Dynamics 365





Monday, July 15, 2013

Random Number Generation through plug-in in MS Dynamics 2011

The Requirement is to generate a Unique Random Auto-generated Number while creating a record in Custom Prospect entity.

public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service =  (IOrganizationService)factory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                int count = 0;
                if (entity.LogicalName == "new_prospect")
                {
                    // A Prospect number attribute should not already exist because
                    // it is system generated.
                

                    if (entity.Attributes.Contains("new_prospectnumber") == false)
                    {
                        // Create a new Prospect number attribute, set its value, and add
                        // the attribute to the entity's attribute collection.
                        Random rndgen = new Random();
                        entity.Attributes.Add("new_prospectnumber", rndgen.Next().ToString());
                        entity.Attributes.Add("new_updatecounter", count.ToString());
                      
                    }
                    else
                    {
                        // Throw an error, because Prospect numbers must be system generated.
                        // Throwing an InvalidPluginExecutionException will cause the error message
                        // to be displayed in a dialog of the Web application.
                        throw new InvalidPluginExecutionException("The Prospect number can only be set by the system.");
                    }
                }
            }
        }