Dynamics CRM Plugin for Beginners
Name: Autonumbering
Details - Create Case ID in ADDMMYYYYHHMMSSMSSXYZ
Where
A- Prefix
DD-Date in DD format
MMYYYYHHMMSS Month, Year, Hour, Second of createdon
MSS- Millisecond
XYZ - Random Number
Logic:
Name: Autonumbering
Details - Create Case ID in ADDMMYYYYHHMMSSMSSXYZ
Where
A- Prefix
DD-Date in DD format
MMYYYYHHMMSS Month, Year, Hour, Second of createdon
MSS- Millisecond
XYZ - Random Number
Logic:
- Generate Random Number using Random().Next() message
- Convert Random Number to String
- Get the first three from random number using Substring()method
- Get the attribute created on and convert to DateTime
- Convert the time to local time and convert to String (with DDMMYYYYHHMMSSMSS format)
- Append and assign the value to the desired attribute
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk;
namespace Auto_Number_SDK
{
public class CaseNumber:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
try
{
Entity incident = context.InputParameters["Target"] as Entity;
var number = new Random().Next().ToString();
var rnum = number.Substring(0, 3);
var time = ((DateTime)incident.Attributes["createdon"]).ToLocalTime().ToString("ddMMyyyyHHmmssfff");
incident.Attributes["ticketnumber"] = "A" + time+rnum;
}
catch (Exception ex)
{
tracingService.Trace("CaseNumber: {0}", ex.ToString());
throw;
}
}
}
}