Generate case title custom value in dynamic crm
Link:https://youtu.be/bisoBaAFIXc You can also check the video on youtube.
Scenario : Once you click on new case. case title should be populate as "2020-01-0001". 2020 is the present year and 01 is the current month and 0001 is the number of case is created.
Create one filed called "currentNumber(data type as a single line of text)" in configuration setting entity.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AutoNumberExample
{
public class CaseAutonumber : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
try
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (context.MessageName.ToLower() != "create" && context.Stage != 20)
{
return;
}
Entity targetEntity = context.InputParameters["Target"] as Entity;
Entity updateAutoNumberConfig = new Entity("cai_configurationsettings");
StringBuilder autoNumber = new StringBuilder();
string current, year, month;
DateTime today = DateTime.Now;
month = today.Month.ToString("00");
year = today.Year.ToString();
QueryExpression qeAutoNumberConfig = new QueryExpression { EntityName = "cai_configurationsettings", ColumnSet = new ColumnSet("cai_currentnumber") };
EntityCollection ecAutoNumber = service.RetrieveMultiple(qeAutoNumberConfig);
if (ecAutoNumber.Entities.Count == 0)
{
return;
}
foreach (Entity entity in ecAutoNumber.Entities)
{
if (ecAutoNumber.Entities.Count > 0)
{
// suffix = entity.GetAttributeValue<string>("cai_suffixnumber");
current = entity.GetAttributeValue<string>("cai_currentnumber");
int tempCurrent = int.Parse(current);
tempCurrent++;
current = tempCurrent.ToString("0000");
updateAutoNumberConfig.Id = entity.Id;
updateAutoNumberConfig["cai_currentnumber"] = current;
service.Update(updateAutoNumberConfig);
autoNumber.Append(year+"-"+month+"-"+ current);
break;
}
}
targetEntity["ticketnumber"] = autoNumber.ToString();
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("An error occured in Autonumber Plugin: " + ex.Message.ToString(), ex);
}
}
}
}
Good 👍
ReplyDelete