Tag: Autonumber in crm

CREATE AUTO-NUMBER ATTRIBUTE IN DYNAMICS CRM 365 USING WEB API + Use POSTMAN with CRM Online

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. 

I have in my other blog showed how you can achieve this using C#(console application) : CREATE AUTO-NUMBER ATTRIBUTE IN DYNAMICS CRM 365 USING ORGANIZATION SERVICE + SIMPLE CONSOLE APPLICATION

In this blog I am going to show you how you can achieve this using a simple WebApi request, By default this blog will also help you to learn and see how you can use postman to connect with dynamics 365 online to perform certain WEBAPI operations as we will be suing postman to fire a web api request.

  1. If you don’t already have POSTMAN, download desktop application here it here : POSTMAN Desktop Client  or simply add a chrome extension : Chrome Extension . In my case I am using a chrome extension. Launch the application and select Action as “POST”:

  2. Enter below URL in the next url section:
    https://%5BOrganizationURL%5D/api/data/v9.1/EntityDefinitions(LogicalName=’EntityLogicalName’)/Attributes/ 
    Enter the correct organization url and entity logical name on which you need to create an auto number field.

  3. Now click on “Headers” and add below:
     
  4. Now click on “Body” tab and select “raw” option:
  5. Enter below Json request in the editor:
     
{
 "AttributeType": "String",
 "AttributeTypeName": {
  "Value": "StringType"
 },
 "Description": {
  "@odata.type": "Microsoft.Dynamics.CRM.Label",
  "LocalizedLabels": [
   {
    "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",
    "Label": "Serial Number of the widget.",
    "LanguageCode": 1033
   }
  ]
 },
 "DisplayName": {
  "@odata.type": "Microsoft.Dynamics.CRM.Label",
  "LocalizedLabels": [
   {
    "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",
    "Label": "Serial Number",
    "LanguageCode": 1033
   }
  ]
 },
 "RequiredLevel": {
  "Value": "None",
  "CanBeChanged": true,
  "ManagedPropertyLogicalName": "canmodifyrequirementlevelsettings"
 },
 "SchemaName": "new_AutoNumber",
 "AutoNumberFormat": "WID-{SEQNUM:5}-{RANDSTRING:6}-{DATETIMEUTC:yyyyMMddhhmmss}",
 "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata",
 "FormatName": {
  "Value": "Text"
 },
 "MaxLength": 100
}

       6. change the “SchemaName” of the field as per your need in my case its “new_AutoNumber” and also you can change the AutoNumberFormat as we discussed in the last post : : CREATE AUTO-NUMBER ATTRIBUTE IN DYNAMICS CRM 365 USING ORGANIZATION SERVICE + SIMPLE CONSOLE APPLICATION

    7. Okay its starting to look really good. but here comes the important part how do we setup the authentication – to do this click on “Authorization” Tab and select Type as “OAuth 2.0”:
    

    8. When you select Type as “OAuth 2.0” you have option to “Generate Access Token”

      

    9.Click on Generate New Access Token:
       

    10. Enter Details as below : 

      Token Name : Desires Name i.e dynamics crm Online

      AuthURLhttps://login.windows.net/common/oauth2/authorize?resource=%5Byour dynamics crm plain URL i,e https://passion4dynamicscrm.crm8.dynamics.com%5D

     Access Token URL : https://login.microsoftonline.com/common/oauth2/token 

     Client ID : follow this blog i have created to get client id of your dynamics CRM : REGISTER DYNAMICS CRM APP WITH AZURE FOR OAUTH 2.0 AUTHENTICATION

   11. Now click on Request Access token, you will be asked to login to your dynamics CRM, after successful login you will have a screen below:

     Select the token which we have setup and change “Add token to” to Header and click on “Use Token” which will add this to headers.

   

    13.  we are all set to execute our request , so click on “Send” , if everything was setup properly you will get success with no response:
     

   14. Open you dynamics CRM and navigate to Settings > Customizations > Customize the system > entity name > fields and notice the field has been created:
       

   15. Go ahead and put this field on the form and create some records.

     

   There you go! I hope this helps! Please feel free to let me know if you face any issues during this operation.

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.



       
 
          

How to Create Auto- Number Fields

Requirement for creating an auto number field is very common & achieving them used to be very difficult or unsupported(using third party tools) . Now with Dynamics CRM 365, you can create an auto-number attribute very easily.

At this moment its not available in the UI , you will have to do it programmatically but its  very less and easy code.

following the format which can be achieved :

AutoNumberFormat value Example value
CAR-{SEQNUM:3}-{RANDSTRING:6} CAR-123-AB7LSF
CNR-{RANDSTRING:4}-{SEQNUM:4} CNR-WXYZ-1000
{SEQNUM:6}-#-{RANDSTRING:3} 123456-#-R3V
KA-{SEQNUM:4} KA-0001
{SEQNUM:10} 1234567890
QUO-{SEQNUM:3}#{RANDSTRING:3}#{RANDSTRING:5} QUO-123#ABC#PQ2ST
QUO-{SEQNUM:7}{RANDSTRING:5} QUO-0001000P9G3R
CAS-{SEQNUM:6}-{RANDSTRING:6}-{DATETIMEUTC:yyyyMMddhhmmss} CAS-002000-S1P0H0-20170913091544
CAS-{SEQNUM:6}-{DATETIMEUTC:yyyyMMddhh}-{RANDSTRING:6} CAS-002002-2017091309-HTZOUR
CAS-{SEQNUM:6}-{DATETIMEUTC:yyyyMM}-{RANDSTRING:6}-{DATETIMEUTC:hhmmss} CAS-002000-201709-Z8M2Z6-110901

lets see how this can be done , in this example i am giving my custom organization entity a serial auto numbered field. you can do this both by C# code or Webapi :

C#

CreateAttributeRequest widgetSerialNumberAttributeRequest = new CreateAttributeRequest

            {
             EntityName = "new_organization",
             Attribute = new StringAttributeMetadata
                {

                    //Define the format of the attribute

                    AutoNumberFormat = "ORG-{SEQNUM:3}-{RANDSTRING:6} ",
                    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 Microsoft.Xrm.Sdk.Label("Serial Number", 1033),
                    Description = new Microsoft.Xrm.Sdk.Label("Serial Number of the widget.", 1033)
                }

            };
            crmService.Execute(widgetSerialNumberAttributeRequest);

As you can see in my request i have given AutoNumberFormat  as ORG-{SEQNUM:3}-{RANDSTRING:6} from the List.

in case you need the full code:

using System;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Metadata;

using Microsoft.Xrm.Sdk.Messages;



amespace Microsoft.Crm.Sdk.Samples

    {

        public class FollowupPlugin : IPlugin

        {
            public void Execute(IServiceProvider serviceProvider)
            {
                //Extract the tracing service for use in debugging sandboxed plug-ins.
                ITracingService tracingService =

                    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
               // Obtain the execution context from the service provider.

                IPluginExecutionContext context = (IPluginExecutionContext)
                    serviceProvider.GetService(typeof(IPluginExecutionContext));
            

            CreateAttributeRequest widgetSerialNumberAttributeRequest = new CreateAttributeRequest
            {

                EntityName = "new_organization",
                Attribute = new StringAttributeMetadata

                {
                    //Define the format of the attribute
                    AutoNumberFormat = "ORG-{SEQNUM:3}-{RANDSTRING:6}  ",
                    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 Microsoft.Xrm.Sdk.Label("Serial Number", 1033),
                    Description = new Microsoft.Xrm.Sdk.Label("Serial Number of the widget.", 1033)
                }
            };

            crmService.Execute(widgetSerialNumberAttributeRequest);
       }

    }

WebAPI

{
 "AttributeType": "String",
 "AttributeTypeName": {
  "Value": "StringType"
 },

 "Description": {
  "@odata.type": "Microsoft.Dynamics.CRM.Label",
  "LocalizedLabels": [
   {
   "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",
    "Label": "Serial Number of the widget.",
   "LanguageCode": 1033
   }
  ]
 },

 "DisplayName": {
  "@odata.type": "Microsoft.Dynamics.CRM.Label",
  "LocalizedLabels": [
   {
    "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",
    "Label": "Serial Number",
    "LanguageCode": 1033
   }
  ]
 },

 "RequiredLevel": {
  "Value": "None",
  "CanBeChanged": true,
  "ManagedPropertyLogicalName": "canmodifyrequirementlevelsettings"
 },

 "SchemaName": "new_SerialNumber",
 "AutoNumberFormat": "WID-{SEQNUM:5}-{RANDSTRING:6}-{DATETIMEUTC:yyyyMMddhhmmss}",
 "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata",
 "FormatName": {
  "Value": "Text"
},
 "MaxLength": 100
}

 

You just have to pass certain headers in the API request such as Content -Type , Application as JSON and the authentication.

Once you have done this – you will see a a new field as new_serialnumber has been created in the system under new entity. Few things:

  1. Put the field on the form
  2. it will be a locked field
  3. it will generate a new number everytime you click on save

it will be something like below:

Untitled

 

I hope this helps!