Skip to content

Instantly share code, notes, and snippets.

@pawelgradecki
Created July 21, 2017 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawelgradecki/12c670a09e8d71a40bcb31042f8d11b9 to your computer and use it in GitHub Desktop.
Save pawelgradecki/12c670a09e8d71a40bcb31042f8d11b9 to your computer and use it in GitHub Desktop.
Corrected Autonumbering in Dynamics 365
namespace TransactionPlugin
{
public class Autonumber : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var pluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = factory.CreateOrganizationService(null);
var target = pluginContext.InputParameters["Target"] as Entity;
var qExpression = new QueryExpression("new_lock");
qExpression.ColumnSet = new ColumnSet("new_name", "new_lastnumber");
qExpression.Criteria.AddCondition("new_name", ConditionOperator.Equal, "Counter");
var results = service.RetrieveMultiple(qExpression);
var counter = results.Entities.First();
var blocker = new Entity("new_lock");
blocker.Id = counter.Id;
blocker["new_name"] = "Counter";
service.Update(blocker);
var qExpression2 = new QueryExpression("new_lock");
qExpression2.ColumnSet = new ColumnSet("new_lastnumber");
qExpression2.Criteria.AddCondition("new_name", ConditionOperator.Equal, "Counter");
var rmRequest = new RetrieveMultipleRequest();
rmRequest.Query = qExpression2;
var lockedResults = (RetrieveMultipleResponse)service.Execute(rmRequest);
var lockedCounter = lockedResults.EntityCollection.Entities.First();
var currentNumber = lockedCounter.GetAttributeValue<int>("new_lastnumber");
target["accountnumber"] = $"{++currentNumber}";
var counterUpdater = new Entity("new_lock");
counterUpdater.Id = counter.Id;
counterUpdater["new_lastnumber"] = currentNumber;
service.Update(counterUpdater);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment