Archive

Posts Tagged ‘Dynamics 365’

[Code Snippet] Authenticate and Perform Operations using D365 Web API and C#

September 18, 2018 3 comments

As a continuation to my last article Different ways to connect authenticate dynamics 365 , lets see how to Authenticate Dynamics Web API using C#.

Note: Be mindful that this approach is different than connecting to Dynamics 365 using Microsoft.XRM.Tooling.Connector dll approach. This article explains how to connect to D365 using Web API which is no SDK .dll approach.

Pre-requisites:

  • Dynamics 365 subscription. Go for 30 days trail if not already have one.
  • Register an App in “Azure Active Directory” and get ‘Application ID’ and other parameters.
  • Visual Studio Console application

Steps to Register App in “Azure Active Directory”:

We need to register an application with Microsoft Azure Active Directory so that it can connect to the Microsoft Dynamics 365 server, authenticate using OAuth, and access the web services.

WebAPI_Snippet2

  • From the “Azure Active Directory admin center’, select ‘App registrations’ -> New application registration

WebAPI_Snippet3

  • Provide below details
    • Name – Provide name of the App. Can be any name minimum of 4 characters.
    • Application Type – Choose ‘Native’ as we are going to call Web API from Console application
    • Sign-on URL – Can be a valid URL. This you need to pass in the Console application.

WebAPI_Snippet4

  • Click ‘Create’ to complete the App creation
  • Post creation, open the App and copy the ‘Application ID’ which you need in Console application.

WebAPI_Snippet5

  • Click on ‘Settings’ -> Required Permissions -> Add ‘Dynamics CRM Online’ -> Enable the permission as below

WebAPI_Snippet6

  • Finally, select the App, click on ‘Endpoints’ and copy ‘OAuth 2.0 Authorization Endpoint‘ which you would need in Console Application.

WebAPI_Snippet7

Steps to connect to D365 WebAPI from Console Application:

After registering App in ‘Azure Active Directory’ now its time to connect to D365 Web API from Console Application.

  • Create a new C# Console Application project
  • Add below 2 Nuget packages to the project
    • Newtonsoft.Json
    • Microsoft.IdentityModel.Clients.ActiveDirectory

WebAPI_Snippet8

Code Snippet:

In the ‘Program.cs’ file add below

  • Add Using Namespaces:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;

  • Add Global Variables:

// O365 User Name and Password
private const string userName = “rajeevpentyala@exploreSept18.onmicrosoft.com”;
private const string password = “YourPasswordHere”;
// D365 Application Url
private const string serviceUrl = “https://exploresept18.crm.dynamics.com”;
// Azure APP Application Id
private const string applicationId = “1549b5b3-XXXX-XXXX-94be-7a8eeaf3e081”;
// Redirct Uri specified during registration of application
private const string RedirectUri = “https://localhost”;
// OAuth 2.0 Authorization Endpoint copied from Azure APP
private const string authorityUri = “https://login.microsoftonline.com/9e3039aa-XXXX-XXXX-80e1-f67d40bd01cf/oauth2/authorize”;

private static AuthenticationResult authResult = null;

  • Main Method:

private static void Main(string[] args){

// Code to connect to D365
var credentials = new UserPasswordCredential(userName, password);
var context = new AuthenticationContext(authorityUri);
authResult = context.AcquireTokenAsync(serviceUrl, applicationId, credentials).Result;

// Call CRUD operations

// Task.WaitAll(Task.Run(async () => await ExecuteWhoAmI()));
// Task.WaitAll(Task.Run(async () => await CreateRecord()));
// Task.WaitAll(Task.Run(async () => await RetrieveContacts()));

}

  • Code to call WhoAmIRequest:

private static async Task ExecuteWhoAmI(){
var httpClient = new HttpClient{
BaseAddress = new Uri(serviceUrl),
Timeout = new TimeSpan(0, 2, 0)
};
httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, authResult.AccessToken);

// Add this line for TLS complaience
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

// Call WhoAmI
var retrieveResponse = await httpClient.GetAsync(“api/data/v9.0/WhoAmI”);
if (retrieveResponse.IsSuccessStatusCode){
var jRetrieveResponse = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);

var currUserId = (Guid)jRetrieveResponse[“UserId”];
var businessId = (Guid)jRetrieveResponse[“BusinessUnitId”];

Console.WriteLine(“My User Id – ” + currUserId);
Console.WriteLine(“My User Id – ” + businessId);
Console.ReadLine();
}
}

  • Code to Retrieve Records:

private static async Task RetrieveContacts(){
var httpClient = new HttpClient{
BaseAddress = new Uri(serviceUrl),
Timeout = new TimeSpan(0, 2, 0)
};
httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, authResult.AccessToken);

// Add this line for TLS complaience
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

// Retrieve Contacts
var retrieveResponse = await httpClient.GetAsync(“api/data/v9.0/contacts”);
if (retrieveResponse.IsSuccessStatusCode){
var jRetrieveResponse = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);

dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());

foreach (var data in collContacts.value){
Console.WriteLine(“Contact Name – ” + data.fullname.Value);
}

Console.ReadLine();
}
}

WebAPI_Snippet1

  • Code to Create Record:

private static async Task CreateRecord(){
JObject contact1 = new JObject{
{ “firstname”, “Peter” },
{ “lastname”, “Cambel” },
{ “annualincome”, 80000 }
};

contact1[“jobtitle”] = “Junior Developer”;

var httpClient = new HttpClient{
BaseAddress = new Uri(serviceUrl + “/api/data/v9.0/”),
Timeout = new TimeSpan(0, 2, 0)
};
httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, authResult.AccessToken);

// Add this line for TLS complaience
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, “contacts”){
Content = new StringContent(contact1.ToString(), Encoding.UTF8, “application/json”)
};

HttpResponseMessage response = await httpClient.SendAsync(request);if (response.StatusCode == HttpStatusCode.NoContent) //204 {
Console.WriteLine(“POST succeeded, entity created!”);
//optionally process response message headers or body here, for example:
var entityUri = response.Headers.GetValues(“OData-EntityId”).FirstOrDefault();

// Update the Contact record
Task.WaitAll(Task.Run(async () => await UpdateRecord(entityUri)));

// Delete the contact record
Task.WaitAll(Task.Run(async () => await DeleteRecord(entityUri)));
}
else{
Console.WriteLine(“Operation failed: {0}”, response.ReasonPhrase);
throw new CrmHttpResponseException(response.Content);
}
}

  • Code to Update Record:

private static async Task UpdateRecord(string contactUri){
JObject contact1Add = new JObject{
{ “annualincome”, 80000 },
{ “jobtitle”, “Junior Developer” }
};

var httpClient = new HttpClient{
BaseAddress = new Uri(serviceUrl + “/api/data/v9.0/”),
Timeout = new TimeSpan(0, 2, 0)
};

httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, authResult.AccessToken);

HttpRequestMessage updateRequest1 = new HttpRequestMessage(new HttpMethod(“PATCH“), contactUri){
Content = new StringContent(contact1Add.ToString(), Encoding.UTF8, “application/json”)
};
HttpResponseMessage updateResponse1 = await httpClient.SendAsync(updateRequest1);

if (updateResponse1.StatusCode == HttpStatusCode.NoContent) //204 {
//Console.WriteLine(“Contact ‘{0} {1}’ updated with job title” +
// ” and annual income.”, contactUri.GetValue(“firstname”),
// contactUri.GetValue(“lastname”));
}
else{
Console.WriteLine(“Failed to update contact for reason: {0}”, updateResponse1.ReasonPhrase);
throw new CrmHttpResponseException(updateResponse1.Content);
}

}

  • Code to Delete Record:

private static async Task DeleteRecord(string contactUri){
var httpClient = new HttpClient{
BaseAddress = new Uri(serviceUrl + “/api/data/v9.0/”),
Timeout = new TimeSpan(0, 2, 0)
};

httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, authResult.AccessToken);

var response = httpClient.DeleteAsync(contactUri).Result;
if (response.IsSuccessStatusCode) //200-299 {
Console.WriteLine(“Contact has been deleted!!!”);
}
else if (response.StatusCode == HttpStatusCode.NotFound) //404 {
//Entity may have been deleted by another user or via cascade delete.
}
else //Failed to delete {
Console.WriteLine(“Error while deletion; Message: ” + response.Content);
}
}

🙂

Advertisement

D 365 Development – Different ways to connect/authenticate Dynamics 365

September 17, 2018 1 comment

There was a question posted on my blog by a Dynamics 365 newbie developer on how to authenticate to Dynamics 365 online from his console application.

In this article I am going to detail various ways to connect to Dynamics 365.

Option 1 – Connect using Dynamics 365 SDK assemblies:

  • You need Dynamics 365 SDK assemblies, If you are creating plug-ins, custom workflow activities, or custom XAML workflows and performing operations (i.e., Create/Update/Execute/Retrieve)
  • Refer Steps to create a basic plug-in
  • Download the latest SDK assemblies from nuget.

Option 2 – Connect using XRM Tooling assemblies:

  • If you are building .Net applications (i.e., Console/Web/Windows) use the XRM Tooling assemblies to connect to the Dynamics Application.
  • XRM tooling enables you to connect to your Dynamics 365 instance by using connection strings.
  • Refer article for different types of Connection strings based on your Dynamics deployment (i.e., One-prem/IFD/Office 365 etc..)
  • Below is the sample code to connect to your instance from Console:

Prerequisites:

  • Download the latest SDK assemblies from nuget in your console application.
  • Make sure you refer below .dlls in your console class file.
    • using Microsoft.Xrm.Sdk;
    • using Microsoft.Xrm.Tooling.Connector;

App.Config:

// Add below Connection string to your console’s App.config file

<connectionStrings>

<add name=”Xrm” connectionString=”Url=https://{orgname}.crm.dynamics.com; Username=rajeevpentyala@yourdomain.onmicrosoft.com; Password=XXXXXXX;authtype=Office365;Timeout=20″ />

</connectionStrings>

Code:

// Declare the Service Variables

private static OrganizationServiceProxy _serviceProxy;

private static IOrganizationService _service;

// Read the connection string configured in App.config file

var connectionString = ConfigurationManager.ConnectionStrings[“Xrm”].ConnectionString;

var crmConn = new CrmServiceClient(connectionString);

using (_serviceProxy = crmConn.OrganizationServiceProxy) {

_service = _serviceProxy;

var reqWhoAmI = new WhoAmIRequest();

var resp = (WhoAmIResponse)_service.Execute(reqWhoAmI);

var buID = resp.OrganizationId.ToString();

var userID = resp.UserId.ToString();

}

  • Refer my post on steps to connect to D 365 using Xrm.Tooling.Connector

Option 3 – Connect using Dynamics 365 Web API:

  • What if you want to connect to Dynamics from a Non- .NET applications (i.e., Java/PHP applications), the solution is Web API.
  • Web API provides development experience that can be used across a wide variety of programming languages, platforms, and devices.
  • Web API uses no DLL approach; Unlike above 2 approaches (i.e., XRM Tooling/SDK Assemblies), you don’t need to refer assemblies to connect to Web API.
  • There are 3 different ways to connect to Web API
    1. Using JavaScript in from Dynamics web resources (i.e., Jscript files, HTML, Ribbon). We don’t need to include any authentication code as the logged-in user is already authenticated by the application.
    2. If your Dynamics 365 is On-premise, you can authenticate Web API by passing User’s network credentials.
    3. If your Dynamics 365 is Online or IFD, you must use OAuth to connect.
  • Refer this article on steps to connect to Web API.
  • Web API is very convenient to use and test.
  • With Postman tool you can connect to Web API and perform operations. Refer article

Below is the Flow diagram gives idea on when to use which option among the 3 options:

WebAPI_Connect.PNG

🙂

Categories: CRM, Dynamics 365 Tags: , ,

PowerApps – Create an ‘Account’ in Dynamics 365 from App using Flow

August 13, 2018 1 comment

If you are new to PowerApps, please go through my previous blog

In this post, lets build an App with an Account Form and create the record in Dynamics 365.

PA_Flow_5

Prerequisite:

  • You must have a PowerApps account. Refer blog for details.
  • Create a Microsoft Flow with logic to create an Account record in Dynamics 365
  • Build an App and trigger Flow

Steps to create Flow:

  • Login to PowerApps Portal
  • Navigate to Business Logic -> Flows -> Create from blank

PA_Flow_1

  • In the new Flow screen, Choose Action, select ‘Dynamics 365’

PA_Flow_7

  • Select ‘Create a new record’ from Actions.
  • Now we need to put place holders in the fields which we pass data from PowerApp.
  • To add a place holder to ‘Account Name’ field, select the field, in ‘Dynamics content’ window, click on ‘Ask in PowerApps‘ button.
    • A new place holder will get added to ‘Account Name’ field.

PA_Flow_2

  • I repeated the above step for ‘Main Phone’ and ‘Description’ fields.

PA_Flow_3

  • Rename the Flow to CreateAccount and Save

Invoke Flow from PowerApp:

  • To know, how to create a new App and add controls to form, refer my earlier blog
  • To trigger the Flow, select the ‘Create’ button, go to ‘Action -> Flows’
  • From the ‘Data’ window, select the flow created in above section (i.e.,CreateAccount)

PA_Flow_4

  • On ‘OnSelect’ event of button, trigger the Flow ‘CreateAccount’ by calling ‘Run’ method and passing the 3 placeholder parameters.
    • CreateAccount.Run(txtName.Text,txtDesc.Text,txtMobile.Text)
  • Thats it, now its time to test the App

Test the App:

  • Press F5
  • Set the values and click ‘Create’

PA_Flow_5

  • Open the D365 App and you should see new ‘Account’ record.

PA_Flow_6

Refer my earlier article to build an App using Excel as Data Source.

🙂

Code Snippet – Execute Dynamics 365 WhoAmIRequest in Azure Function

July 15, 2018 1 comment

Azure Function is a serverless compute service that enables you to run code on-demand without having to explicitly provision or manage infrastructure.

We can leverage ‘Azure Functions’ in Dynamics 365 to build robust integrations.

Scenario:

Lets take a scenario, where your Customer has a Facebook page and complaints posted on page should get created as ‘Case’ records in your Dynamics application.

In the above scenario,

  • Connecting to Facebook and retrieving Posts can be achieved using ‘Logic Apps’ Facebook connector
  • Now creating Posts as ‘Cases’ in Dynamics can be done by creating an ‘Azure Function’ with Case create logic and invoke it from ‘Logic App’

In this article, I will walk you through the steps to establish connection to D365 and  execute ‘WhoAmIRequest’ from ‘Azure Functions’.

Steps to create Azure Function:

  • Refer my previous article for steps to create Azure Function.

Prerequisites to Connect to D365 From Azure Function:

  • We would need ‘CRM SDK’ nuget packages in Azure Function to establish connection with D365.
  • Below are steps to add nuget packages to ‘Azure Function’
    • Connect to ‘Advanced tools(Kudu)‘ from ‘Function Apps -> Platform features
    • WhoAmi_1
    • Click on ‘Debug Console -> CMD’
    • WhoAmi_2
    • From the folder explorer, navigate to ‘site -> wwwroot‘ folder
    • Open the folder with your Azure Function name
      • Since my function name is ‘WhoAmI’ and I got the ‘WhoAmI’ folder under ‘wwwroot
    • WhoAmi_3
    • To refer nuget packages, we have to create a new file by name ‘project.json’
    • WhoAmi_4
    • Add below package references
    • WhoAmi_5
    • Save
  • Add URL and Credential details of ‘D365’ to ‘Application Settings’ of ‘Azure Function’
    • Navigate to ‘Function Apps -> Platform features -> Application Settings’
    • WhoAmi_6
    • Add the URL, UserId, Password details.
    • AzFunc_5

Code Snippet:

Once you have the Prerequisites ready, below is the code snippet to execute ‘WhoAmIRequest’

using System.Net;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk.Messages;
using System.Configuration;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
try{
log.Info(“Inside Try”);

ClientCredentials userCredentials = new ClientCredentials();
var userName = ConfigurationManager.AppSettings[“Crm_UserName”];
var password = ConfigurationManager.AppSettings[“Crm_Password”];
var Crm_UniqueOrgUrl = ConfigurationManager.AppSettings[“Crm_UniqueOrgUrl”];
userCredentials.UserName.UserName = userName;
userCredentials.UserName.Password = password;

log.Info(“userName – “+userName);
log.Info(“password – “+password);

var service = new OrganizationServiceProxy(new Uri(Crm_UniqueOrgUrl + “/XRMServices/2011/Organization.svc”), null, userCredentials, null);
service.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

WhoAmIRequest reqWhoAmI = new WhoAmIRequest();
WhoAmIResponse resp = (WhoAmIResponse)service.Execute(reqWhoAmI);
var buID = resp.OrganizationId.ToString();
var userID = resp.UserId.ToString();

log.Info(“Business Unit Id – “+buID);}
catch(Exception ex)
{
log.Info(“Exception – “+ex.Message);
}

return req.CreateResponse(HttpStatusCode.OK, “Successfully made call to D365.”);
}

Run and Test the Code:

  • Click on ‘Run’ and expand ‘Logs’ section to track the logs.

WhoAmi_7

🙂

 

Dynamics 365 – Read Auditing

One of the much awaited features ‘Read Access Audit‘ is being roll out in the latest version of Dynamics 365 online.

Enable ‘Read’ Audit:

  • Connect to your Dynamics 365 application.
  • To enable Audit, choose Settings > Administration > System Settings > Auditing tab

Read Audit

Access Audit Data:

  • Audit data can be viewed by connecting to the Office 365 Security and Compliance Center.
  • Connect to https://protection.office.com > Search & investigation > Audit log search and select the Dynamics 365 activities tab

Read Audit Reports

Refer this article for more info.

🙂

Dynamics 365 – Broken ‘Notes’ control on the form and Fix

If you have upgraded to latest Dynamics 365 version or subscribed for 30 days trail and could not add a note or attachments in ‘Notes’ tab on form, this fix is for you.

Problem statement:

  • Could not add a Note or add attachment from ‘Notes’ control on form.
  • ‘Notes’ panel rendering as below with no ‘Enter a Note’ option

Notes-1

  • It seems product issue and will be fixed in future updates.

Fix worked for me:

There is no documented fix for this, however below steps worked for me.

  • Open the entities ‘Customization Form’ which you have problem with.
  • Double click and open the ‘Notes’ tab

Notes-4

  • Under ‘Web Client Properties’, select ‘Default tab’ property as highlighted below.

Notes-3

  • Save & Publish
  • Go back to the form and refresh.
  • You should see option to add Note.

Notes-2

🙂

 

D365 – Troubleshoot and Fix connectivity issues – ‘Microsoft Support and Recovery Assistant for Office 365’ tool

April 23, 2018 1 comment

Recently, I came across a Microsoft Support and Recovery Assistant for Office 365 tool from Microsoft to troubleshoot and fix Office 365 connectivity issues. Download

This tool can fix many problems for you, or it can tell you how to fix them yourself with guided steps.

Tool - 3

It helped me fixing my Dynamics 365 free trail connectivity issue and Outlook connectivity issue.

Usage:

  • Download and open the .exe

Tool

  • Pick the App you have problem with.

Tool - 2

🙂

 

IntelliSense in Jscript/TypeScript file – Dynamics 365

April 16, 2018 1 comment

In this article, lets see how to configure intellisence with XRM syntaxes in your Jscript/TypeScript files.

To enable IntelliSence, you need to install xrm npm package to your Visual Studio.

Steps to install NPM package:

  • To install npm package, you need to download and install a Visual Studio extension : Package Installer

Intelli - 5

  • Post installation, from your Visual Studio, select ‘Quick Install Package’ from Menu

Intelli - 6

  • From the popup,
    • Select ‘npm’ in the dropdown
    • In the textbox, type ‘@types/xrm
    • Click on ‘Install’

Intelli - 7

  • Post package installation, refresh the project and you should see a new folder ‘node_modules
    • Note: If you dont get the ‘node_modules’ folder, check your project’s physical location and add the folder to your Visual Studio project.

Intelli - 8

  • In above screen, ‘TypeScript’ is my project name and post above steps, I got the ‘node_modules’ project.

Enable IntelliSence in your Jscript/TypeScript file:

  • Open your script file
  • Drag and drop the ‘index.d.ts’ file from ‘node_modules’ folder on to your script file.
    • Alternatively you can also this syntax
      • /// <reference path=“../node_modules/@types/xrm/index.d.ts />

Intelli - 1

  • Start typing ‘Xrm’ and you should see the syntaxes.

Notes:

  • Those who are wondering what is a npm, it is a package manager for the JavaScript programming language.
  • www.npmjs.com hosts thousands of free packages to download and use.

 

Dynamics CE – Demystify ‘Auto Number’

April 6, 2018 3 comments

Auto Number‘ feature is available with Dynamics 365 (online) and V9.x versions. With this feature we are no longer dependent on 3rd party ISV solutions for Auto numbering.

Auto Number - 2

In this article I am going to cover a few use cases of Auto Number fields.

How to create an Auto Number field:

As of the date, we can either create a new ‘Auto number’ field or convert an existing field to ‘Auto Number’ only programmatically (i.e., using SDK call).

Creation of an ‘Auto Number’ from Application will be included in next releases.

Lets see how to create a brand new ‘Auto Number’ field and convert an existing ‘Single Line Of Text’ field to ‘Auto Number’ along with few key points.

[Code Snippet] Create a NEW auto number field:

Below is the sample code to create a new Auto Number field ‘new_studentnumber‘ in a custom entity ‘new_student

var studentNumberAttributeRequest = new CreateAttributeRequest{
EntityName = “new_student“,
Attribute = new StringAttributeMetadata{
//Define the format of the attribute
AutoNumberFormat = “STD-{SEQNUM:4}”,
// Set fields Logical and Schema Name
LogicalName = “new_studentnumber“,
SchemaName = “new_studentnumber“,
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
MaxLength = 100,
// Set fields Display Name and Description
DisplayName = new Label(“Student ID”, 1033),
Description = new Label(“Student ID”, 1033)
}
};
_serviceProxy.Execute(studentNumberAttributeRequest);

  • Make sure you ‘Publish‘ customization’s from Application after executing the code.

[Code Snippet] Convert EXISTING field to an auto number field:

Below is the sample code to convert OOB ‘new_name’ field to auto number field in the custom entity ‘new_student‘.

Important note:

  • Field you are converting has to be of type ‘Single Line Of Text’.
  • If you pass a different type of field (Ex- Whole number), code will not throw any exception but no auto number logic will get attached to the field.

// First retrieve the Attribute Metadata
var attributeRequest = new RetrieveAttributeRequest{
EntityLogicalName = “new_student”,
// Pass the attribute name
LogicalName = “new_name”,
RetrieveAsIfPublished = true
};

// Retrieve attribute response
var attributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

// Now modify the retrieved auto-number attribute
var retrievedAttributeMetadata = attributeResponse.AttributeMetadata;
// Set the auto numbering format
retrievedAttributeMetadata.AutoNumberFormat = “STD-{SEQNUM:3}-{RANDSTRING:6}”;

// Update the auto-number attribute
var updateRequest = new UpdateAttributeRequest{
Attribute = retrievedAttributeMetadata,
EntityName = “new_student”,
};

// Execute the request
_serviceProxy.Execute(updateRequest);

  • Make sure you ‘Publish‘ customization’s from Application after executing the code.

Key Points:

  • Auto number fields will be Read-only and you cannot override the value from Form.
  • But you can override the value from code using SDK Insert call.
  • As you would notice below, Even though the ‘Name’ is an Auto number field, I could create a ‘Student’ record from code by setting ‘Name’ to ‘Rajeev’.  If you dont set a ‘Name’ field value from code, system would populate the auto number.

Auto Number - 1

  • In a single Entity, you can have multiple auto number type fields with the same format.
  • You can alter the auto number format of a field at any point of time by using ‘UpdateAttributeRequest’ SDK call (Refer 2nd code snippet above).
  • In the Auto number format, use ‘Random String’ tag (i.e., {RANDSTRING:number}) which help you to avoid duplicates or collisions, especially when offline clients trying to create auto-numbers.
    • For example, CNR-{RANDSTRING:4} format will generate an auto number with a random string of 4 character length (i.e., ‘CNR-WXYZ‘)

Auto Number - 3

  • The random string placeholders are optional.You can include more than one random string placeholder in an Auto Number Format.

🙂