Dynamics 365 – Connect to CRM with C#

Advertisements
Advertisements

If you are a Dynamics 365 developer, you might be familiar with the CrmServiceClient class, which is part of the Microsoft.Xrm.Tooling.Connector namespace. This class provides a convenient way to connect to the Dynamics 365 web service and perform various operations using the OrganizationServiceProxy or the OrganizationWebProxyClient.

However, with the recent release of the Microsoft.PowerPlatform.Dataverse.Client NuGet package, there is a new class that you can use to interact with the CRM web service: the ServiceClient class. This class is part of the Microsoft.PowerPlatform.Dataverse.Client namespace and it inherits from the IOrganizationService interface. This means that you can use it to execute any message request that you would normally use with the OrganizationServiceProxy or the OrganizationWebProxyClient.

In this blog post, I will show you how to use the ServiceClient class to connect to the CRM web service and perform some common operations. I will also compare it with the CrmServiceClient class and highlight some of the differences and advantages of using the ServiceClient class.

Prerequisites

To follow along with this blog post, you will need:

How to Connect CRM Using C#

To connect to CRM using the ServiceClient class, you need to pass a connection string as a parameter to the constructor. The connection string should contain the following information:

AuthType: The authentication type to use. For this example, we will use OAuth.

Url: The URL of your CRM environment.

Username: The username of the user who will access CRM.

Password: The password of the user who will access CRM.

RedirectUri: The redirect URI of your app registration in Azure Active Directory.

AppId: The application ID of your app registration in Azure Active Directory.

LoginPrompt: The login prompt behavior to use. For this example, we will use Auto.

Here is an example of a connection string that contains these information:

AuthType=OAuth;Url=https://myorg.crm.dynamics.com;Username=someone@myorg.onmicrosoft.com;Password=mypassword;RedirectUri=http://localhost;AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;LoginPrompt=Auto

You can store this connection string in a configuration file, such as appsettings.json, and read it from there. Alternatively, you can hard-code it in your code, but this is not recommended for security reasons.

To create a ServiceClient instance using this connection string, you can use this code:

using Microsoft.PowerPlatform.Dataverse.Client;
using System;

namespace DataverseServiceClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read the connection string from appsettings.json
            var connectionString = Configuration.GetConnectionString("default");

            // Create a ServiceClient instance using the connection string
            var serviceClient = new ServiceClient(connectionString);

            // Check if the connection is successful
            if (serviceClient.IsReady)
            {
                Console.WriteLine("Connected to CRM successfully!");
            }
            else
            {
                Console.WriteLine("Failed to connect to CRM!");
            }
        }
    }
}

If you run this code, you should see a message indicating whether the connection was successful or not.

Creating a record

To create a record in CRM using the ServiceClient class, you can use the Create method. This method takes an Entity object as a parameter and returns a Guid that represents the ID of the created record.

For example, to create an account record with some attributes, you can use this code:

// Create an account entity with some attributes
var account = new Entity("account");
account["name"] = "Contoso Ltd";
account["telephone1"] = "555-1234";
account["websiteurl"] = "https://www.contoso.com";

// Create the account record using the ServiceClient
var accountId = serviceClient.Create(account);

// Display the ID of the created record
Console.WriteLine($"Created account record with ID: {accountId}");

Retrieving a record

To retrieve a record from CRM using the ServiceClient class, you can use the Retrieve method. This method takes three parameters:

  • The logical name of the entity to retrieve.
  • The ID of the record to retrieve.
  • The column set to specify which attributes to retrieve.

The method returns an Entity object that contains the retrieved attributes.

For example, to retrieve the account record that we created earlier, you can use this code:

// Specify the column set to retrieve
var columnSet = new ColumnSet("name", "telephone1", "websiteurl");

// Retrieve the account record using the ServiceClient
var account = serviceClient.Retrieve("account", accountId, columnSet);

// Display the retrieved attributes
Console.WriteLine($"Retrieved account record with name: {account["name"]}");
Console.WriteLine($"Retrieved account record with phone: {account["telephone1"]}");
Console.WriteLine($"Retrieved account record with website: {account["websiteurl"]}");

Updating a record

To update a record in CRM using the ServiceClient class, you can use the Update method. This method takes an Entity object as a parameter and updates the record with the same ID and entity type as the Entity object.

The Entity object should contain only the attributes that need to be updated. You do not need to specify all the attributes of the record.

For example, to update the website URL of the account record that we retrieved earlier, you can use this code:

// Create an account entity with the ID and the attribute to update
var account = new Entity("account");
account.Id = accountId;
account["websiteurl"] = "https://www.contoso.net";

// Update the account record using the ServiceClient
serviceClient.Update(account);

// Display a confirmation message
Console.WriteLine("Updated account record successfully!");

Deleting a record

To delete a record from CRM using the ServiceClient class, you can use the Delete method. This method takes two parameters:

  • The logical name of the entity to delete.
  • The ID of the record to delete.

For example, to delete the account record that we created and updated earlier, you can use this code:

// Delete the account record using the ServiceClient
serviceClient.Delete("account", accountId);

// Display a confirmation message
Console.WriteLine("Deleted account record successfully!");

Executing a message request

To execute any message request in CRM using the ServiceClient class, you can use the Execute method. This method takes an OrganizationRequest object as a parameter and returns an OrganizationResponse object.

The OrganizationRequest object should contain the name and parameters of the message request that you want to execute. The OrganizationResponse object contains the results and output parameters of the message request.

For example, to execute a WhoAmIRequest, which returns information about the current user and organization, you can use this code:

// Create a WhoAmIRequest object
var whoAmIRequest = new WhoAmIRequest();

// Execute the WhoAmIRequest using the ServiceClient
var whoAmIResponse = (WhoAmIResponse)serviceClient.Execute(whoAmIRequest);

// Display the results of the WhoAmIRequest
Console.WriteLine($"Current user ID: {whoAmIResponse.UserId}");
Console.WriteLine($"Current organization ID: {whoAmIResponse.OrganizationId}");
Console.WriteLine($"Current business unit ID: {whoAmIResponse.BusinessUnitId}");

Comparing with CrmServiceClient

The ServiceClient class is similar to the CrmServiceClient class in many ways. They both inherit from the IOrganizationService interface and they both use connection strings to connect to CRM.

However, there are some differences and advantages of using the ServiceClient class over the CrmServiceClient class. Here are some of them:

  • The ServiceClient class supports .NET Core and .NET 5, while the CrmServiceClient class only supports .NET Framework.
  • The ServiceClient class uses Microsoft.Identity.Client (MSAL) for authentication, while the CrmServiceClient class uses Microsoft.IdentityModel.Clients.ActiveDirectory (ADAL). MSAL is newer and more secure than ADAL and it supports more authentication scenarios.
  • The ServiceClient class has better performance and reliability than the CrmServiceClient class. It uses HttpClient under the hood and it handles retries and timeouts more gracefully.
  • The ServiceClient class has a simpler and cleaner API than the CrmServiceClient.

Conclusion

In summary, the ServiceClient class in the Microsoft.PowerPlatform.Dataverse.Client namespace presents a modern and effective way to connect to the Dynamics 365 web service and carry out operations. It supports .NET Core and .NET 5, using Microsoft.Identity.Client (MSAL) for authentication, which enhances security, performance, and reliability compared to the CrmServiceClient class.

For more in-depth insights and tutorials on Programming or Dynamics 365 and Power Platform features and customization, check out our posts to further enhance your proficiency and maximize the potential of your skills.

Advertisements
Advertisements
Advertisements

Leave a comment

Create a website or blog at WordPress.com