Plugin to generate auto ID

Now let's write a plugin to generate an auto ID. Generating an auto ID in Microsoft CRM is a very common requirement. So we are going to write a generic plugin to generate an auto ID for any entity. We have created an Auto ID Setup entity, which we will use to create the entity record for which we need to generate an auto ID. We will specify the entity name and auto ID field name, and we will use this information in our plugin to set the auto ID.

First we will create an Auto ID Setup entity record that will provide an entity name, auto ID field, and start number for generating an issue ID. Create an auto ID setup record and enter the following information:

  • Name: new_issue
  • Auto ID Field: new_issuenumber
  • Start with: You can enter any number as a starting point
  • Increment By: Enter any positive number
  • Prefix: If you want to add a prefix before the issue ID, you can use this field

In Chapter 4, Implementing Business Logic through Plugin, we used Developer Toolkit to write a plugin. In this chapter, I will explain how to write a plugin without using Developer Toolkit. Perform the following steps to create a plugin assembly in Visual Studio 2010:

  1. Start Visual Studio 2010 and go to File | New | Project | Visual C#.
  2. Select the Class Library template and name it Generate_AutoID.
  3. Rename Class1.cs as AutoID.cs.
  4. Go to the Signing tab and check the Sign the assembly checkbox.
  5. Right-click on the Project folder and select Add Reference... to add a reference for the following assemblies:
    • Microsoft.xrm.sdk
    • System.Runtime.Serialization
  6. Open the AutoID.cs file.
  7. Add the following using directive to our class:
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
  8. We need to write the following two functions in our class apart from the main plugin Execute function:
    • GetAutoIDSetupDetails: This function is used to get details from the Auto ID Setup entity
    • GetAutoNumber: This function is used to generate an auto ID number

First, we need to write a function to get auto ID setup details. This is required to read the Start With number, to assign an issue number, and increment it with the value present in the Increment By field. Our query expression should look like the following code snippet:

Entity Autoidsetup = null;
            QueryExpression _Query = new QueryExpression
            {
                EntityName = "new_autoidsetup",
                ColumnSet = new ColumnSet("new_incrementby", "new_prefix", "new_startwith", "new_name", "new_autoidsetupid", "new_autoidfield"),
                Criteria =
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName="new_name",
                                Operator=ConditionOperator.Equal,
                                Values={EntityName}
                            }
                        }
                }
            };
            EntityCollection EntitiesColleciton = service.RetrieveMultiple(_Query);
if (EntitiesColleciton.Entities.Count > 0)
            {
                Autoidsetup = EntitiesColleciton.Entities.First();
            }
            return Autoidsetup;

Tip

As we are using the late bound programming style here, we need to make sure that we are using the logical name of the fields.

In the previous method, we have used the QueryExpression class to query the Auto ID Setup entity to read a record based on the entity name in which the current plugin is being executed. Once we get the result, we need to get the first entity object from the entity collection and return it to the calling function.

After getting an auto ID number, we need to assign that number to the Issue Number field. We want to generate the auto ID at the time of record creation so that we have an option to register our plugin as either precreate or postcreate. If we will register our plugin as postcreate, we need to write an update request to update Auto ID Field after record creation. But if we register our plugin as precreate, we can inject the Auto ID Field property in the property bag of the entity before record creation; so, we are going to register our plugin as precreate. Let's add our Execute method in our plugin class, where we can get a plugin context to get entity information and add an attribute to the entity property collection. Our code should look as follows:

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            Entity PrimaryEntity;
            if (context.InputParameters.Contains("Target") &&
            context.InputParameters["Target"] is Entity)
            {  
                PrimaryEntity = (Entity)context.InputParameters["Target"];
            }
            else
            { return; }
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.MessageName == "Create")
                {
                    Entity Autosetupdetails = GetAutoIDSetupDetails(PrimaryEntity.LogicalName, service);
                    if (Autosetupdetails != null)
                    {
                        if (Autosetupdetails.Contains("new_autoidfield"))
                        {
                            string AutoIDFieldName = Autosetupdetails["new_autoidfield"].ToString();
                            PrimaryEntity.Attributes.Add(AutoIDFieldName, GetAutoNumber(service, Autosetupdetails).ToString());
                        }
                     }
                    else
                        return;
                }

In the preceding code, we have retrieved the primary entity from the context and passed the entity name to the GetAutoIDSetupDetails function to fetch the Auto ID Setup entity record based on the entity name. If it returns a record, we will use that record to generate our auto ID; otherwise we will cancel the execution of the plugin by returning a control.

You can find complete code under CodeGenerate_AutoID for this chapter.

Perform the following steps to build a plugin assembly and register it using the plugin registration tool:

  1. Open PluginRegistration.exe and connect to your organization, as shown in the following screenshot:
    Plugin to generate auto ID
  2. Once you are connected to your organization, it will display all the plugins registered for your organization.
  3. Navigate to Register and select the Register New Assembly option, as shown in the following screenshot:
    Plugin to generate auto ID
  4. Browse your assembly using the default settings.
  5. Click on Register Selected Plugins.
  6. Select your plugin assembly and navigate to Register | Register New Step. We need to use the information shown in the following screenshot when registering the Create step:
    Plugin to generate auto ID
  7. After registration, the plugin assembly should look like the following screenshot:
    Plugin to generate auto ID
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.149