[Step By Step] Configure Server-to-Server (S2S) authentication using Azure AD and Application User – Dynamics 365

In this article I am going to explain, what is ‘Application User’ and how it helps to establish using Server-to-Server (S2S) authentication and Azure Active Directory

To explain the S2S authentication simpler, let’s take an integration requirement

  • You have an ASP.Net Web Application
  • You need pull the Contacts from a CRM organization and display in the ASP.Net Web Page

The conventional design approach for the above requirement would be

  • Establish the CRM connection in your ASP.Net page by passing CRM User credentials
  • Make a Retrieve call to CRM
  • Read and bind the Contacts to a grid.

To implement the above design you need to have a paid CRM User credentials to interact with your Dynamics CRM organization.

So what is S2S authentication and how is it different from the legacy integration model we discussed above.

Server-to-Server (S2S) authentication:

  • S2S authentication means you don’t need to use a paid Dynamics 365 user license when you connect to Dynamics 365 tenants.
  • We will use a special user (i.e., Application User)
  • Best part is, you can connect to D365 and make server calls from your application (i.e.,Web/Console) with no Dynamics SDK dlls and no ‘UserID/Password’.

What is this ‘Application User’:

  • ‘Application User’ is a ‘systemuser’ record of type ‘Application User’
  • There is no license fee for the ‘Application User’ account

App User - 14

How an ‘Application User’ account achieve the S2S authentication:

  •  ‘Application User’ with conjunction of Azure Active Directory (Azure AD) will establish S2S authentication.
  • We first generates an ‘Application ID’ in Azure AD which we set in ‘Application User’ in Dynamics.

Lets see the step by step approach to achieve S2S authentication.

  • Pre-requisites:
    • Dynamics 365 instance
    • Azure Subscription with same Office 365 account used for your D365 instance.
  • High Level Steps
    • Generate ‘Application ID’ and ‘Keys’ in ‘Azure’
    • Add a new User in ‘Azure Active Directory’ (Azure AD)
    • Create a new ‘Application User’ in Dynamics 365

Step 1 – Generate ‘Application ID’ and ‘Keys’ in ‘Azure’:

  • Connect to your Azure
  • Go to ‘App registrations’ service

App User - 1

  • Create a ‘New application registration’
    • Note: ‘Sign-on URL’ can be any valid URL.

App User - 2

  • Copy the generated ‘Application ID’ (This is needed while creating ‘Application User’ in CRM)

App User - 3

  • Generate ‘Keys’ (You need the ‘Key’ to establish connection in your Web Application/Console Application)

App User - 4

  • Save the ‘Key’ (Note: You cannot read the key if you move away from the screen)

App User - 5

Step 2 – Add a new User in ‘Azure Active Directory’ (Azure AD):

  • Connect to your Azure
  • Go to ‘Users’ service

App User - 6

  • Create a ‘New User’
    • Note: ‘Password’ auto generates once you save. You don’t need to copy as this is not required further.

App User - 7

  • Once the User saved, copy the ‘User Name’ (This is needed while creating ‘Application User’ in CRM)

App User - 8

Step 3 – Create a new ‘Application User’ in Dynamics 365:

This step we are going to create an ‘Application User’ in D365 by copying the details generated in Azure

  • Connect to Dynamics 365
  • Go to ‘Settings -> Security -> Users
  • Switch the view to ‘Application Users’ and click ‘New’

App User - 9

  • In the ‘New User’ screen
    • Set ‘User Name’ with the ‘User Name’ copied from ‘Azure’
    • Set ‘Application ID’ with the ‘Application ID’ copied from ‘Azure’
    • Save the User and once saved, you notice the auto populated ‘Application ID URI’ and ‘Azure AD Object ID’

App User - 10

  • Assign a ‘Security Role’
    • ‘Security Role’ must be a Custom Security Role and you cannot assign OOB role.
    • For this exercise, you might want to copy any existing OOB Security Role.

All right! We are all set and now its time to test S2S authentication from your console.

S2S Authentication Code Snippet:


  • Install ‘ADAL’ and ‘NewtonSoft’ NuGet packages


using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
private static async Task GetContactsAsync()
// Your Dynamics Web API URL
string api = “”;

AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(api)).Result;

// Set ‘Application ID’ and ‘Key’ generated from Azure
var creds = new ClientCredential(“e4ac3a78-xxxx-403a-a94c-xxxxxxx”, “hEo/xxxxxxxS+LEiYHpxxxxxxxRe8xg0=”);

AuthenticationContext authContext = new AuthenticationContext(ap.Authority);
var token = authContext.AcquireTokenAsync(ap.Resource, creds).Result.AccessToken;

using (HttpClient httpClient = new HttpClient())
httpClient.Timeout = new TimeSpan(0, 2, 0);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, token);

// Retrieve Top 1 Contact
HttpResponseMessage response = await httpClient.GetAsync(api + “/contacts?$top=1”);

// Parse the response
if (response.IsSuccessStatusCode)
JObject contact = JsonConvert.DeserializeObject<JObject>(await response.Content.ReadAsStringAsync());

var contactName = contact.GetValue(“fullname”);


App User - 13



Dynamics 365 Spring Release 2018

Microsoft has released Spring ’18 release notes for Microsoft Business Applications and can be downloaded from here


Refer this link for all latest updates on Dynamics 365

Dynamics Portals – Hide Search Control and clear cache

Other day, we got a requirement to hide the ‘Search’ control from our Custom portal.


Its very easy to achieve by changing a configuration.

Steps to hide Search control:

  • Go to Portals ->Site Settings ->Search/Enabled record
  • By default the ‘Value’ will be ‘true’, to hide the ‘Search’ change to ‘false’


  • Save
  • Refresh the browser and you should not see the ‘Search’ control


What if you are still seeing the ‘Search’ control:

Sometimes for some reason (Mostly due to caching), you wont see the change immediately.

In this case you can either reset portal/clear the server side cache by following steps below.

Reset the Portal:

  • If the change is not taken place for all users you might want to reset the portal.
  • Resetting the portal is not feasible option especially when your portal is being tested, as the end users will experience a snag for sometime.
  • But if the Portal is in Development phase and you can reset from your ‘D365 Admin Center’
    • Go to ‘Admin Center’ -> Applications
    • Select your Portal application and click ‘Manage’


  • Select ‘Portal Actions’ -> Reset


Clear Server Side Cache:

  • You can force the portal to refresh its cache immediately.
  • To clear the server-side cache, sign in to the portal with Administrator web role
  • Navigate to the URL as follows : <Your_portal_URL>/_services/about
    • (i.e., You need to append /_services/about end of your portal URL)
  • Select Clear Cache.
  • Refer this for article more details



Dynamics 365 – Create/Modify Views using App Designer

In this article, I am going to detail, how views can be created or modified using App Designer.

Open ‘App Designer’:

  • To start off, go to ‘My Apps’ by navigating to ‘Settings –> Application –> My Apps’

Views - 1.PNG

  • Open the ‘Sales’ app in ‘App Designer’ by clicking ‘OPEN IN APP DESIGNER’

Views - 2

Add/Edit Views:

Once the ‘App Designer’ loads, lets see how to modify Account’s ‘Active Accounts’ view

  • From the ‘App Designer’ window, under ‘Entity View’ section, select the ‘Views’ tab from ‘Account’ row.
  • On the right side ‘Public Views’ tab, select the View you want to modify (i.e., ‘Active Accounts’ in my case)
  • After selecting the view from right window, back to ‘Views’ tab and expand, open the ‘Active Accounts’ to Edit

Views - 3

  • To add new column, click on ‘Add’ button, choose Primary or Related entity to add the fields from and drag and Drop the column you want.

Views - 4

  • Expand the ‘Filter Criteria’ tab to update the filter

Views - 5

  • To add new view, click ‘Create New’ from your ‘App Designer’

Views - 6

With the ‘App Designer’, you can perform all the view customizations, which you can do with conventional view editor.

Refer article  for more details.


[Code Snippet] Upload file to Azure blob – C#

In this article I am going to provide details and code snippets on how to upload attachment to Azure blob storage from console application.


Below are the prerequisites to run the code snippet and upload the file

  • Azure subscription:You need an Azure subscription as the first  step.
    • You can spin up 30 days trail Azure subscription. Click here
    • Note: You need to share valid credit card details to complete the subscription and you will be charged 2 INR.
  • Storage Account:Add a storage account

Azure - Storage Account

  • Container:
    • Add a Container
    • Copy the Container Name.

Azure - Storage Account - Containers

  • Access Keys:Need the ‘Key’ to connect to Azure Blob from your C# console.
    • Copy and keep below 2 values as shown in screenshot
      • Storage Account Name
      • Key 1

Azure - Storage Account - Keys

  • Nuget package:Add below nuget packages to your console project
      • Microsoft.WindowsAzure.Storage

C# Code Snippet:

// Namespaces

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

private static void AddFileToBlob(){
var accountName = “{Storage Account Name}“; // Refer Prerequisites for value
var keyValue = “{key 1}“; // Refer Prerequisites for value
var useHttps = true;
var connValid = true;

// Establish connection to Azure

var storageCredentials = new StorageCredentials(accountName, keyValue);
var storageAccount = new CloudStorageAccount(storageCredentials, useHttps);
var blobConString = storageAccount.ToString(connValid);

// Retrieve storage account from connection string.
storageAccount = CloudStorageAccount.Parse(blobConString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Set container name
CloudBlobContainer container = blobClient.GetContainerReference(“{Container Name}“); // Refer Prerequisites for value

// Set your blob name; It can be anything
CloudBlockBlob blockBlob = container.GetBlockBlobReference(“{Your desired blob name}“);

// Set your file path which you want to upload to blob
using (var fileStream = System.IO.File.OpenRead(@”D:\ABC.PNG”)) {

Console.WriteLine(“File added to Blob!!!”);


Categories: Azure Tags: ,

D365 – JScript – Deep Insert – Xrm.WebApi

Dynamics 365/Version 9.x has brought new objects to the Xrm client object model.

Deep Insert - 4

One of the new additions to Xrm object  is ‘WebApi’ where you can perform CRUD operations.

WebAPI provides wrappers for all CRUD operations with in the framework so that we dont need to rely on 3rd party helper libraries. For example XrmServiceToolKit

In this article I am going to explain the Deep Insert using the Xrm.WebApi.

What is a ‘Deep Insert’:

  • Deep Insert is a create operation where we create a primary record along with new related records.
  • In simpler words, In a single ‘Create’ server call, we can create Account and related Contact and Opportunity along with a Task.
    • Account (i.e., Primary)
  • Deep Insert - 2
    • and Related
      • Contact (and set Account.PrimaryContact)
      • Opportunity (and associate with created Account)

Deep Insert - 3

  • Below is the syntax

Xrm.WebApi.createRecord(entityLogicalName, data).then(successCallback, errorCallback);


Here is the sample code to create an Account and related records.

function createAccountAndRelated() {
// Define data to create primary (i.e.,Account) and related (i.e.,Contact and Oppoerunity) entity records
var data =
“name”: “XYZ Account”,
“creditonhold”: false,
“address1_latitude”: 47.639583,
“description”: “Creating Account along with new Primary Contact and Opportunity”,
“revenue”: 5000000,
“accountcategorycode”: 1,
“firstname”: “Rajeev”,
“lastname”: “Pentyala”
“name”: “New Opportunity”,
{ “subject”: “Task associated to the new opportunity” }

// create account record
Xrm.WebApi.createRecord(“account”, data).then(
function success(result) {
console.log(“Account created with ID: ” +;
function (error) {

Deep Insert - I


Categories: CRM, Dynamics 365 Tags: ,

D 365 – Set Recommendation on a field using JScript/Business Rule

In this article I am going to detail the steps to set a notification (i.e., Recommendation/Error) to a particular control on the form.

Notifications can be of 2 types; Error or Recommendation.

  • If an ‘Error’ notification set, a red “X” icon appears next to the control. Setting an error notification on a control blocks saving the form.
  • If a ‘Recommendation’ notification set, an “i” icon appears next to the control. A recommendation notification does not block saving the form.

To explain this better, I am taking below scenario

  • If ‘Account Name’ is ‘Microsoft’ recommend to set ‘Ticker Symbol’ to ‘MSFT’

Recommendation - 1

  • From the recommendation, if I click on ‘Apply’, set ‘Ticker Symbol’ to ‘MSFT’

Recommendation - 2

Setting Recommendation using ‘Business Rule’:

Create a new ‘Business Rule’ with below components

Recommendation - BR 2

  • Add a “Condition” flow with condition (If ‘Account Name’ = ‘Microsoft’ AND ‘Ticker Symbol’ <> MSFT)
  • If condition met, add ‘Recommendation’ action
  • Under ‘Recommendation’ action, add sub Action, set ‘Ticker Symbol’ field to ‘MSFT’

Recommendation - BR 1

Setting Recommendation from JScript:

Register this function on form ‘onload’ and ‘onchange’ of ‘Account Name’ field.

function setRecommendationOnAccountName() {
var ctrlAccountName = Xrm.Page.getControl(‘name’);
var accountName =‘name’);
var tickerSymbol =‘tickersymbol’);

// Check condition (If ‘Account Name’ = ‘Microsoft’ AND ‘Ticker Symbol’ <> MSFT)
if (accountName.getValue(‘Microsoft’) && tickerSymbol.getValue() != ‘MSFT’) {
var actionCollection = {
message: ‘Set the Ticker Symbol to MSFT?’,
actions: null

// Add sub Action, set ‘Ticker Symbol’ field to ‘MSFT’ and clear Recommendation
actionCollection.actions = [function () {

// Set the Notification to ‘Account Name’ control
messages: [‘Set Ticker Symbol’],
notificationLevel: ‘RECOMMENDATION’,
uniqueId: ‘notify_account_name’,
actions: [actionCollection]


  • notificationLevel : Valid values are either ERROR or RECOMMENDATION. If nothing specified in object definition, it is set to ERROR by default.