Implementing Console App in Dynamics CRM Using Azure Application ID And Secret Key

Introduction

While working on projects over Dynamics CRM, we get multiple situations wherein we need to validate the code and various functionalities offered by code, and for that developing a console application is always an advantage to developer. It's a one-time activity that assists a developer in multiple ways including,

  • Validation of existing code and functionalities
  • Unit Testing the code
  • Debugging of Plugins and Custom Workflows
  • More efficient - method of code development as developer saves a lot of time building the assembly and registering the same in an environment

In this article, I will be sharing with you steps to register the Dynamics CRM application in Azure Active Directory and then generate a secret key that can be used in connection string while connecting to Dynamics CRM Application.

Steps

Login to Portal.Azure.com and open the Active Directory.

Register the Application in Azure Portal.

Open the Added Application and now need to grant the API permissions to the same.

Need to connect to Dynamics CRM API.

Once we are connected to Dynamics CRM API, we need to grant the Admin Consent to the same, or in other words, we are granting approval for its usage.

Now, this application has to be registered or we can say a user needs to be created in Dynamics CRM using the same Application ID.



Now once the application user has been created in Dynamics CRM we need to grant required roles and permissions to the user, allowing the user to perform the required set of actions in the application while being connected to application through Console Application.

And yes the important aspect is to generate the client secret key in Azure following the below steps.

Steps to use the above generated code in Console Application.

Sample code to connect to Dynamics CRM using the Application ID and Value.

namespace ConsoleApp {
    public class Program {
        public static void Main(string[] args) {
            IOrganizationService orgService = GetOrganizationServiceClientSecret("11e428dd-7153-42bb-9988-a08eebfdd86a", "qu27Q~Xq6MMD_NiEb8NnV6Yl2qPOnpQIfH~eK", "https://org53e65b9b.crm.dynamics.com");
            var response = orgService.Execute(new WhoAmIRequest());
        }
        public static IOrganizationService GetOrganizationServiceClientSecret(string clientId, string clientSecret, string organizationUri) {
            try {
                var conn = new CrmServiceClient($ @ "AuthType=ClientSecret;url={organizationUri};ClientId={clientId};ClientSecret={clientSecret}");
                return conn.OrganizationWebProxyClient != null ? conn.OrganizationWebProxyClient : (IOrganizationService) conn.OrganizationServiceProxy;
            } catch (Exception ex) {
                Console.WriteLine("Error while connecting to CRM " + ex.Message);
                Console.ReadKey();
                return null;
            }
        }
    }
}