Connect to your instance via C# for validation – Works for Dynamics 365 latest versions

Hi Folks,

Every now and then when we were struck up with the issues with our code or with any power platform components like Power Automate, we had to definitely understand whether it is working from normal C# console application.

There were tons of articles over the internet and just it’s ophhhh…

So this post is just for a quick reference to connect to Dynamics 365 CE Instance to check if your actual function is returning valid data or not. I have just removed my functions for brevity.

You can just specify your Client Id, Client Secret, Instance URL below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System.ServiceModel;

namespace TestConsole
{
internal class Program
{
static void Main(string[] args)
{

        IOrganizationService orgService = GetOrganizationServiceClientSecret(your client id, your client secret, instance url);
        var response = orgService.Execute(new WhoAmIRequest());//To validate the request

        if(response != null)
        {
            Console.WriteLine("Connected to CRM");

            //Your function here
        }
    }

    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;
        }
    }
}

}

Whenever you want to check any thing from C# Console, I hope this piece code works for connecting to your Dynamics.

Cheers,

PMDY

Top 100 CRM blogs on the Planet for the year 2020

Hi Folks,

I am extremely happy to share that my blog is 75th in the list of best CRM blogs on the planet ranked by Feed spot.

Thank you for the readers and I will continue to contribute to the community through my blog going ahead.

https://blog.feedspot.com/crm_blogs/

Top 100 image from feedspot

Cheers,

PMDY