Hi, I am working on a simple auto numbering plugin for case number on case entity. The format should be "yyyymmxxxx" and xxxx is the incremental number. I am wondering how to handle the concurrency, for example, when multiple users generate case number at the same time. I attached the sample code as below:
IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; int maxNumber; if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity entity = (Entity)context.InputParameters["Target"]; if (entity.LogicalName == "incident") { if (entity.Attributes.Contains("caseid") == false) { string fetchxml = @"<fetch version='1.0' output-format='xml-platform' distinct='false' mapping='logical'> <entity name='incident'> <attribute name='caseid'/> </entity> </fetch>"; EntityCollection ec = service.RetrieveMultiple(new FetchExpression(fetchxml)); List<int> list = new List<int>(); foreach (var c in ec.Entities) { if (c.Attributes.ContainsKey("caseid")) { list.Add(int.Parse(c.Attributes["caseid"].ToString())); } } maxNumber = list.Max(); entity.Attributes.Add("caseid", Autonumbering(maxNumber)); } } } private string Autonumbering(int caseNumber) { string caseid = string.Empty; string year = DateTime.Now.Year.ToString(); string month = DateTime.Now.ToString("MM"); if (year == caseNumber.ToString().Substring(0, 4)) { if (month == caseNumber.ToString().Substring(4, 2)) { caseid = year + month + (caseNumber + 1).ToString().Substring(6, 4); } else { caseid = year + month + "0001"; } } else { caseid = year + month + "0001"; } return caseid; }
*This post is locked for comments