Thursday, June 17, 2010

Formatting datetime in workflows with custom workflow activity in Microsoft Dynamics CRM 4.0

I've found one weird thing in workflows - when you insert datetime value inside text field you can't format it. Result of such inserting:




I decided to develop custom activity which will give possibility to format those output.
This activity has two inputs - datetime value to format (CrmDateTime property) and format (string property) and one output - formatted datetime (string). Code of custom action:

using System;
using System.Text;
using System.Collections.Generic;
using System.Workflow.Activities;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Sdk;

namespace DateTimeFormatting
{
[CrmWorkflowActivity("Formats date time with required format", "Formatting Routines")]
public class FormatDateTime : SequenceActivity
{
protected override System.Workflow.ComponentModel.ActivityExecutionStatus Execute(System.Workflow.ComponentModel.ActivityExecutionContext executionContext)
{
string result = string.Empty;

if (!string.IsNullOrEmpty(DateFormat) && datetime != null)
{
result = DateTime.Parse(datetime.Value).ToString(DateFormat);
}

Result = result;

return ActivityExecutionStatus.Closed;
}

public static DependencyProperty DateFormatProperty = DependencyProperty.Register("DateFormat", typeof(string), typeof(FormatDateTime));

[CrmInput("Format of DateTime")]
public string DateFormat
{
get
{
return (string)base.GetValue(DateFormatProperty);
}
set
{
base.SetValue(DateFormatProperty, value);
}
}

public static DependencyProperty datetimeProperty = DependencyProperty.Register("datetime", typeof(CrmDateTime), typeof(FormatDateTime));

[CrmInput("DateTime to format")]
public CrmDateTime datetime
{
get
{
return (CrmDateTime)base.GetValue(datetimeProperty);
}
set
{
base.SetValue(datetimeProperty, value);
}
}

public static DependencyProperty ResultProperty = DependencyProperty.Register("Result", typeof(string), typeof(FormatDateTime));

[CrmOutput("Formatted DateTime")]
public string Result
{
get
{
return (string)base.GetValue(ResultProperty);
}
set
{
base.SetValue(ResultProperty, value);
}
}

}
}


Following screenshots show how to use this action:
1. Insert this action before using the result of formatting:


2. Click "Set Properties" button to insert datetime and format:


3. Fill "Format of DateTime" and "DateTime to Format" fields:


4. Add some workflow step formatted datetime to be used (for example sending email):





Save step and save and publish workflow. Result of work of this workflow:


Sourcecode: