简体   繁体   中英

How to connect to dynamics crm with c#?

The Office365 authentication type and OrganizationServiceProxy Connection are now deprecated Link , which variant is the best to create a connection between dynamics 365 Online and c#. do you have any examples.

Personally I suggest to use Client Id & ClientSecret from an Azure App Registration. This method is also compatible with the .NET Core SDK package (still in Alpha https://www.nuget.org/packages/Microsoft.Powerplatform.Cds.Client/ ) as this package does not support username&password authentication.

You can find many tutorials online to use a Client Id & Client Secret, you can start from this one https://blog.magnetismsolutions.com/blog/paulnieuwelaar/2020/04/24/dynamics-365-xrmtooling-connect-with-azure-app-registration-in-c-

You can still use a service account from your AD or over OAuth and a connection over the CRMServiceClient.

Create a connection string in your web.config

 <add key="Dynamics365Test" value="AuthType=AD;Domain=domain;Username=domain\xxx;Password=XXXXX;Url=https://yourcrm.crm.dynamics.com/"/>

or

  <add name="Dynamics365Test" connectionString="AuthType=OAuth;Username=test@contoso.onmicrosoft.com;Password=passcode;Url=https://yourcrm.crm.dynamics.com;AppId=xxx-12ee-xxxe-aaae-xxx91f45987d;RedirectUri=app://xxx-0C36-4500-8xxx-xxx54F2AC97;TokenCacheStorePath=c:\MyTokenCache;LoginPrompt=Auto"/>

As I understand it, there are two primary ways to obtain a user with which to connect to Dynamics 365:

  • Use an existing AD service account and add it to Dynamics. The account will need to have MFA disabled to be used in a non-interactive context. No app registration is needed.
  • Register your app in Azure and create a user principal with client ID/secret or a certificate.

Dynamics 365 data is stored within a Dataverse database, and the available security roles for accessing that data are described here . You'll need to ensure your user is in an appropriate role for data access, such as the 'Service Reader' role if you just need to read entities.

The Power Platform API and OAuth can be used to access the data with .NET. (See Organization Service ). These days ServiceClient is recommended over the older CrmServiceClient . Here's a code sample using the service account approach:

Web.config:

<add name="MyCrmEntities" connectionString="AuthType=OAuth;Username=serviceAccount@company.com;Password=MyPassword;Url=https://appname.crm.dynamics.com;LoginPrompt=Never"/>

Note: Recommendation is to not store the password in plain text as done for this example. Instead, consider encrypting it or storing it in a more secure location.

You can see more connection string parameters here , including client ID/secret if those are relevant for your connection method.

C# (Retrieve a list of all 'Account' entities and output their names):

using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

...

using (ServiceClient service = new 
       ServiceClient(ConfigurationManager.ConnectionStrings["MyCrmEntities"].ConnectionString))
{
    if (service.IsReady)  // successfully connected to environment's Organization service
    {
        QueryExpression queryAccounts = new QueryExpression("account");
        queryAccounts.ColumnSet.AddColumns("name");
        EntityCollection accountResult = service.RetrieveMultiple(queryAccounts);

        foreach (Entity account in accountResult.Entities)
        {
            Console.WriteLine(account.Attributes["name"].ToString());   
        }
    }
}

I can't connect to CRM online with OAuth CrmServiceClient. Whenever I try it times out. I'm going mad with this.!! My test code is below.

Does the user need particular permissions or anything? (.Net version 4.6.2)

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Tooling.Connector; using System;

public partial class c2: System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {

    string ConnectionString = "AuthType=OAuth;Username=xxx@xxx.com;Password=xxx;Url=https://xxx.crm4.dynamics.com;AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;LoginPrompt=Never";

    CrmServiceClient svc = new CrmServiceClient(ConnectionString);

    if (svc.IsReady)
    {
        var myContact = new Entity("contact");
        myContact.Attributes["lastname"] = "Test";
        myContact.Attributes["firstname"] = "User1";
        svc.Create(myContact);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM