DEV Community

Abhilash Panicker
Abhilash Panicker

Posted on

How to connect to D365 CE and stay connected even when token expires

To create a simple console application in C# that connects to Dynamics 365 CE with OAuth and refreshes the token when it expires, follow these steps:

  1. Install the required NuGet packages: Install the following NuGet packages using Package Manager Console in Visual Studio or add them manually through the NuGet Package Manager:
  • Microsoft.IdentityModel.Clients.ActiveDirectory
  • Microsoft.CrmSdk.CoreAssemblies
  • Microsoft.CrmSdk.XrmTooling.CoreAssembly
  1. Create a new C# Console Application in Visual Studio.
    Create a new project and select "Console App (.NET Core)" or "Console App (.NET Framework)".

  2. Replace the contents of Program.cs with the following code:

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;

namespace Dynamics365OAuthApp
{
    class Program
    {
        // Replace with your Dynamics 365 CE instance URL
        private const string ResourceUrl = "https://<your_instance>.crm.dynamics.com";
        // Replace with your Azure AD tenant ID
        private const string TenantId = "<your_tenant_id>";
        // Replace with your Azure AD application client ID
        private const string ClientId = "<your_client_id>";
        // Replace with your Azure AD application client secret
        private const string ClientSecret = "<your_client_secret>";
        private const string AuthorityUrl = "https://login.microsoftonline.com/" + TenantId;

        static void Main(string[] args)
        {
            var service = GetCrmService();
            if (service != null)
            {
                // Add your code to interact with Dynamics 365 CE
            }
            else
            {
                Console.WriteLine("Failed to connect to Dynamics 365 CE.");
            }
        }

        private static IOrganizationService GetCrmService()
        {
            try
            {
                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var credentials = new ClientCredential(ClientId, ClientSecret);
                var authResult = authenticationContext.AcquireTokenAsync(ResourceUrl, credentials).Result;
                var connectionString = $@"
                    ServiceUri={ResourceUrl};
                    AuthType=OAuth;
                    AccessToken={authResult.AccessToken};
                    ";

                var crmService = new CrmServiceClient(connectionString);
                if (crmService.IsReady)
                {
                    return crmService.OrganizationWebProxyClient != null
                        ? (IOrganizationService)crmService.OrganizationWebProxyClient
                        : crmService.OrganizationServiceProxy;
                }
                Console.WriteLine("Failed to connect: " + crmService.LastCrmError);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }

            return null;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Make sure to replace <your_instance>, <your_tenant_id>, <your_client_id>, and <your_client_secret> with your own values.

  1. Run the console application Build and run the console application. If successful, it will connect to Dynamics 365 CE using OAuth and return an instance of IOrganizationService which can be used to interact with the Dynamics 365 CE instance.

When the token expires, the CrmServiceClient will automatically refresh the token using the provided ClientCredential. You do not need to worry about manually refreshing the token.

That's it! You now have a simple console application that connects to Dynamics 365 CE with OAuth and automatically refreshes the token when it expires.

Top comments (0)