CRM Crate

How to create an Auto-Number field in Dynamics 365?

We will learn to create an auto-number field in Dynamics 365. Before we start, make sure to subscribe to CRM Crate so that you can stay up to date in the domain of Dynamics 365.

How to create an Auto-Number field in Dynamics 365?

What is an auto-number field?

An auto-number field can be used in Dynamics 365 for automatically generating a unique number for a broad range of different types of entity. With an auto number field, the number for each record will be handled entirely by the system, so there’s no need for you to identify each one as it is created.

Auto-number attributes in Dynamics 365

With the Dynamics 365 CE, you can add an auto-number attribute for any entity (Both system and custom entity). Currently, you can add the attribute programmatically as there is no user interface to add this type of attribute. 

Here you can create an auto-number attribute in the same way you create a string attribute using the StringAttributeMetadata class except that you use the new AutoNumberFormat property. 

Use the AutoNumberFormat property to define a pattern that includes sequential numbers and random strings by composing placeholders, which indicate the length and type of values that are generated.

There are the multiple auto-number formats provided by Microsoft which are explained below.

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

Create an auto-number field in Dynamics 365

There are two ways to create an auto-number attribute in an entity programmatically which is Console Application & Web API.

Using Console Application to create an auto-number attribute –

Use the below .Net Console App code and execute it on your Dynamics 365 CE environment for creating a new auto-number attribute.

using System;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.IO;
using System.Text;
using Microsoft.Xrm.Sdk.WebServiceClient;
using System.Diagnostics;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;

namespace Console_Application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CRM Crate Console Application Started!");

            //Retrieving CRM Essential Information.
            string sEnvironment = System.Configuration.ConfigurationManager.AppSettings["Environment"].ToString(); //Dynamics 365 CE Environment URL
            string sUserKey = System.Configuration.ConfigurationManager.AppSettings["UserKey"].ToString(); //User Login ID
            string sUserPassword = System.Configuration.ConfigurationManager.AppSettings["UserPassword"].ToString(); //User Login Password

            //Creating A Connection String.
            string conn = $@" Url = {sEnvironment};AuthType = OAuth;UserName = {sUserKey}; Password = {sUserPassword};AppId = 51f85479-16tt-4a9e-awat-b2591f75y87d;RedirectUri = app://52145R91-0HTO-4510-8554-080855F2AC97;LoginPrompt=Auto; RequireNewInstance = True";
            Console.WriteLine("Operating Environment : " + sEnvironment);

            //Obtaining CRM Service.
            using (var service = new CrmServiceClient(conn))
            {
                CreateAttributeRequest CRMCrateAutonumberField = new CreateAttributeRequest
                {
                    EntityName = "cc_sampleentity", //Entity Schema Name
                    Attribute = new StringAttributeMetadata
                    {
                        //Define the format of the attribute
                        AutoNumberFormat = "CRMCrate-{SEQNUM:3}-{RANDSTRING:6}", //Specific Auto-Number Format
                        LogicalName = "cc_autonumber1", //Entity Attribute Logical Name
                        SchemaName = "cc_autonumber1", //Entity Attribute Schema Name
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), //Attribute Required Level (Optional / Business Recommended / Mandatory)
                        MaxLength = 100, //Attribute Maximum Lenght
                        DisplayName = new Label("Autonumber Type 1", 1033), //Attribute Form Display Name
                        Description = new Label("Autonumber of the CRM Crate.", 1033) //Attribute Description With Language Code
                    }
                };

                //Execute An Attribute Creation Request
                service.Execute(CRMCrateAutonumberField);
            }
            Console.WriteLine("CRM Crate Console Application Completed!");
            Console.ReadLine();
        }
    }
}

Click on the given link to learn more about connecting the Dynamics 365 environment with console applications- https://www.crmcrate.com/plugin/connecting-to-dynamics-365-crm-using-a-console-application/.

Using Console Application to create an auto-number attribute –

REQUEST - 
POST [Organization URI]/api/data/v9.1/EntityDefinitions(LogicalName='new_widget')/Attributes HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
OData-MaxVersion: 4.0
OData-Version: 4.0

{
 "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
}
RESPONSE - 
HTTP/1.1 204 No Content
OData-Version: 4.0
OData-EntityId: [Organization URI]/api/data/v9.1/EntityDefinitions(402fa40f-287c-e511-80d2-00155d2a68d2)/Attributes(f01bef16-287c-e511-80d2-00155d2a68d2)

Validate the changes in Dynamics 365

Once an auto-number attribute has been created by using any of the above two methods, navigate to the Dynamics 365 form validate the changes as shown below.

Thus, we learned to create an auto-number field in Dynamics 365.

5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
error: CRM Crate Security Engine - Disabled Right Click & Selection!

Congratulations!

Well Done,
Welcome to CRM Crate

Stay tuned with us and get all latest updates and learning in Microsoft CRM and related techonologes.