Search code examples
c#azure-functions.net-6.0dynamics-365dataverse

Accessing DataVerse data and running SQL statements against it from C# code on .NET 6 (Azure Function)


I'm working with Dynamics365 CE in the cloud. I'm trying to run some rather involved queries that I've built up as SQL scripts (using the wonderful "SQL-4-CDS" plugin for the XrmToolBox).

Now I know I can connect to the Dataverse data store through the TDS endpoint (if enabled - it is in my case), and from SSMS, it works just fine:

Server Name    = myorg.crm4.dynamics.com,5558
Authentication = Azure Active Directory - Password
User Name      = my company e-mail

I can connect to Dataverse, and run my queries - all is great.

Now I'd like to do the same from C# code (running on .NET 6) that I'm writing, that should end up being an Azure Function in the end - so it's a "server-to-server", behind-the-scenes, no interactive login context kind of scenario.

I can connect to Dataverse via the TDS endpoint using this connection string - as long as I'm running the app interactively - as me, in my user context:

Server=myorg.crm4.dynamics.com,5558;Authentication=Active Directory Password;Database=my_dbname;User Id=my_email;Password=my_pwd;

However - this won't work with a server-to-server "daemon"-style setup.

Since I'm using .NET 6 (for the Azure Function), and since I want to run some custom SQL statements, I cannot use the "CRM XRM Client" tooling (with the IOrganizationService classes) - I need to use straight ADO.NET - any idea would I could define an ADO.NET compatible connection string, that would use a Client ID and Client Secret (which I both have at my disposal)?

I've tried a great many values for the Authentication=...... setting - but none have worked so far. Any place I can find a complete list of the supported values for this connection string parameter?

Thanks for any help or pointers!


Solution

  • I know it's an old question, but in case it's still helpful to anyone: you should be able to use the SqlConnection.AccessToken property to authorize your connection to the TDS Endpoint. To get the access token you'd need to use your application user client ID & secret to obtain the token.

    You can also use the SQL 4 CDS ADO.NET provider - once you've created the ServiceClient from the Dataverse SDK, pass that to the Sql4CdsConnection constructor:

    using var con = new Sql4CdsConnection(service);
    using var cmd = con.CreateCommand();
    cmd.CommandText = "SELECT ...";