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
As David explained, you need to implement locking. There is a "classic" article on this subject:
So, currently, I just have one customized field in case entity, and the problem is that when creating records, duplicates are also created, how can I avoid that?
There are several options re concurrency, with varying levels of robustness. You need to be able to lock some resource to ensure no duplicates. The main options are:
Stay up to date on forum activity by subscribing. You can also customize your in-app and email Notification settings across all subscriptions.
André Arnaud de Cal... 291,228 Super User 2024 Season 2
Martin Dráb 230,056 Most Valuable Professional
nmaenpaa 101,156