Skip to content

Instantly share code, notes, and snippets.

@pawelgradecki
Created July 21, 2017 08:46
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/2effb7af90e5c189c772c6ab317f1177 to your computer and use it in GitHub Desktop.
Save pawelgradecki/2effb7af90e5c189c772c6ab317f1177 to your computer and use it in GitHub Desktop.
Autonumbering in Dynamics365
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");
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); //NOW WE LOCK ALL TRANSACTIONS
var lockedCounter = service.Retrieve("new_lock", blocker.Id, new ColumnSet("new_lastnumber"));
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