Create Auto-Number Attribute In Dynamics CRM 365 Using Organization Service + Simple Console Application

With the Dynamics 365 v9, you can add an auto-number attribute for any entity. Currently, you can add the attribute programmatically. There is no user interface to add this type of attribute.

There are actually two ways of doing this one is using c# code which you can use a console application and other being Web API request.

In  this blog, I will cover the 1st one, and by default this blog will also help you in connecting dynamics CRM 365 with console application.


Create a simple console application

 

  1. Open Visual Studio and click on new project and select console application project type and give it a name as “AutoNumber” and click on OK.



  2. From your solution manager , right click on “References” and click on “Manager nuget package”:




  3. In the search box enter the name as “Microsoft.CrmSdk.CoreAssemblies” , when result comes > select an click on install. It will install the dynamics crm core assemblies reference needed in the application.



  4. Now from your solution explorer click on add references and again select “System.Configuration” , “System.ServiceModel“and “System.Runtime.Serialization assmeblies“.


  5. Use below namespaces:
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Crm.Sdk.Messages;
    using System.Configuration;
    using System.Net;
    using System.ServiceModel.Description;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
  6. Copy paste below code in the application:
 IOrganizationService organizationService = null;

            try
            {
                ClientCredentials clientCredentials = new ClientCredentials();
                clientCredentials.UserName.UserName = ConfigurationManager.AppSettings["Username"];
                clientCredentials.UserName.Password = ConfigurationManager.AppSettings["Password"];

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                
                organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri(ConfigurationManager.AppSettings["CRMUrl"]),
                 null, clientCredentials, null);

                if (organizationService != null)
                {
                    Guid userid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;

                    if (userid != Guid.Empty)
                    {
                        Console.WriteLine("Connected to dynamics crm");

                        CreateAttributeRequest widgetSerialNumberAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = "new_autonumber",
                            Attribute = new StringAttributeMetadata
                            {
                                //Define the format of the attribute
                                AutoNumberFormat = "DPR-{SEQNUM:5}-{RANDSTRING:6}-{DATETIMEUTC:yyyyMMddhhmmss}",
                                LogicalName = "new_serialnumber",
                                SchemaName = "new_SerialNumber",
                                RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                                MaxLength = 100, // The MaxLength defined for the string attribute must be greater than the length of the AutoNumberFormat value, that is, it should be able to fit in the generated value.
                                DisplayName = new Label("Serial Number", 1033),
                                Description = new Label("Serial Number of the widget.", 1033)
                            }
                        };
                        organizationService.Execute(widgetSerialNumberAttributeRequest);                      
                        Console.WriteLine("Created the autonumber attribute successfully..");
                    }
                }
                else
                {
                    Console.WriteLine("Failed to Established Connection!!!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught - " + ex.Message);
            }
            Console.ReadKey();
        }

 

        7.  In the code above:

            A. change the entitylogical to the name of the entity where you want to create an autonumber field.  
            B. Give the required logical name of the attribute(which you would like to create).
            C. notice the  code line —-   

AutoNumberFormat = "DPR-{SEQNUM:5}-{RANDSTRING:6}-{DATETIMEUTC:yyyyMMddhhmmss}" 


         In the code above you can actually define what should be the format of your auto number as in example below : 

( Taken from docs.microsoft here : AutoNumber  Format Options)
        
     8. Now in your app.config put below( Insert the correct organization URL , username , password):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="CRMUrl" value="https://organame.api.crm8.dynamics.com/XRMServices/2011/Organization.svc" />
<add key="Username" value="Username" />
<add key="Password" value="Password" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
</configuration>


     9.  Build your console application( right click on solution and click “Build Solution” and then Run(Start) it:
        

    10. If it gets excuted fine , go to your dynamics CRM and open the entity fields from Settings > customizations > customize the system > entityname> fields. You will notice the field is created:
       
    


   11. Customize the form and add this field to the form post which try to create a record in dynamics crm. I have create two records and could see below:

      


 

     12. Note that you can always update this attrubute if it is created incorrectly by using code given here and using the same application we created :  Update AutoNumber attribute


Conclusion:
We can utilize this feature very well for creating an autonumber field in crm. before this we needed created a plugin which will trigger everytime or a workflow with very complex configuration.

Transaction handling:

“SEQNUM” which is The sequential segment is generated by SQL and hence uniqueness is guaranteed by SQL.

In my next blog – we will create an auto number field with more simpler approach of Web API request.



       
 
          

Advertisement

7 thoughts on “Create Auto-Number Attribute In Dynamics CRM 365 Using Organization Service + Simple Console Application

  1. Pingback: CREATE AUTO-NUMBER ATTRIBUTE IN DYNAMICS CRM 365 WEB API + Use POSTMAN with CRM Online – Passion Dynamics

  2. Pingback: CREATE AUTO-NUMBER ATTRIBUTE IN DYNAMICS CRM 365 USING WEB API + Use POSTMAN with CRM Online – Passion Dynamics

  3. Pingback: CREATE AUTO-NUMBER ATTRIBUTE IN DYNAMICS CRM 365 USING WEB API + Use POSTMAN with CRM Online - Microsoft Dynamics CRM Community

  4. seems the property ‘AutoNumberFormat’ is removed from StringAttributeMetadata/AttributeMetadata.. is there any alternative?
    ‘StringAttributeMetadata’ does not contain a definition for ‘AutoNumberFormat’ ConsoleApp1

    Like

    • Hi, No I tested just now it seems to be getting created. You can also try web api to see if you get same result:

      also make sure you have updated dlls :
      using Microsoft.Xrm.Sdk;
      using Microsoft.Xrm.Sdk.Client;
      using Microsoft.Crm.Sdk.Messages;
      using System.Configuration;
      using System.Net;
      using System.ServiceModel.Description;
      using Microsoft.Xrm.Sdk.Messages;
      using Microsoft.Xrm.Sdk.Metadata;

      Like

  5. this working in CRM 2016 on-premise?
    because I did all the steps and the visual s. It did not give me an error, but the field does not appear in the entity

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.