Connecting to Dynamics 365 using C#

3 min read

Summary

There are multiple methods for connecting to Microsoft Dynamics from a command line application. Here are a list of a few methods.

Using Xrm.Client (deprecated)

Works for Dynamics CRM 2015, 2016 on-premise.

using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Xrm;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRM_Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            //Simplified Connection: https://msdn.microsoft.com/en-us/library/gg695810.aspx
            CrmConnection crmConnection = CrmConnection.Parse("Url=http://crm/beta; Domain=MyDomainName; Username=Administrator; Password=MyPassword;");
            OrganizationService service = new OrganizationService(crmConnection);
            XrmServiceContext context = new XrmServiceContext(service);

            var allisonBrown = new Xrm.Contact
            {
                FirstName = "Allison",
                LastName = "Brown",
                Address1_Line1 = "23 Market St.",
                Address1_City = "Sammamish",
                Address1_StateOrProvince = "MT",
                Address1_PostalCode = "99999",
                Telephone1 = "12345678",
                EMailAddress1 = "allison.brown@example.com"
            };

            context.AddObject(allisonBrown);
            context.SaveChanges();

        }
    }
}

Using Xrm.tooling v8.1 D365

Works for Dynamics 365 Online (period of 2018 & 2019) version 8.1.

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

namespace Dynamics365.Connections
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var connectionString = @"AuthType = Office365; 
                Url = https://[org].crm4.dynamics.com/;Username=[username];Password=[password]";
                CrmServiceClient conn = new CrmServiceClient(connectionString);

                IOrganizationService service;
                service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName = "account"
                };
                RetrieveEntityResponse retrieveAccountEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
                EntityMetadata AccountEntity = retrieveAccountEntityResponse.EntityMetadata;

                Console.WriteLine("Account entity metadata:");
                Console.WriteLine(AccountEntity.SchemaName);
                Console.WriteLine(AccountEntity.DisplayName.UserLocalizedLabel.Label);
                Console.WriteLine(AccountEntity.EntityColor);

                Console.WriteLine("Account entity attributes:");
                foreach (object attribute in AccountEntity.Attributes)
                {
                    AttributeMetadata a = (AttributeMetadata)attribute;
                    Console.WriteLine(a.LogicalName);
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            { }
        }
    }
}

Using Xrm.tooling v9.1 D365

The snippet illustrates connecting to an on-premise environment. Other authentication types can be found here:

AuthenticationType or AuthTypeSpecifies the authentication type to connect to Dynamics 365 Customer Engagement (on-premises). Valid values are: ADIFD (AD FS enabled), OAuth, or Office365.

– AD and IFD are permitted for Dynamics 365 Customer Engagement (on-premises) instances only.
– OAuthCertificate, and ClientSecret are permitted for Dynamics 365 Customer Engagement (on-premises) and Common Data Service instances. For on-premises, ADFS 3.x+ and App\Client Id registration with ADFS is required for OAuthCertificate and ClientSecret types.
– Office365 is permitted for Common Data Service instances only.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Net;

namespace Dynamics365.Connections
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                string envcon = @"AuthType = AD; Url = http://192.168.0.30/exp01/;Domain=cedomain;Username=serviceaccount;Password=CC%******";
                CrmServiceClient conn = new CrmServiceClient(envcon);
                //var service = (IOrganizationService)conn.OrganizationWebProxyClient ?? conn.OrganizationServiceProxy;

                IOrganizationService service;
                service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName = "account"
                };
                RetrieveEntityResponse retrieveAccountEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
                EntityMetadata AccountEntity = retrieveAccountEntityResponse.EntityMetadata;

                Console.WriteLine("Account entity metadata:");
                Console.WriteLine(AccountEntity.SchemaName);
                Console.WriteLine(AccountEntity.DisplayName.UserLocalizedLabel.Label);
                Console.WriteLine(AccountEntity.EntityColor);

                Console.WriteLine("Account entity attributes:");
                foreach (object attribute in AccountEntity.Attributes)
                {
                    AttributeMetadata a = (AttributeMetadata)attribute;
                    Console.WriteLine(a.LogicalName);
                }

                Console.ReadLine();
            }
            catch (Exception ex)
            { }

            Console.ReadLine();
        }
    }
}

You must be logged in to post a comment.