Created
July 21, 2017 08:46
-
-
Save pawelgradecki/2effb7af90e5c189c772c6ab317f1177 to your computer and use it in GitHub Desktop.
Autonumbering in Dynamics365
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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