Search code examples
c#async-awaitdynamics-crm

How to retrieve Dynamics CRM 365 data asynchronous on server side


I am implementing an Web API which retrieves data from several Microsoft Dynamics CRM 365, aggregates the data and returns it to the caller.

I was wondering if it is possible to retrieve the data from the CRM Organization Service asynchronously. Neither the CrmServiceClient nor the ServiceContext generated by the CrmSvcUtil offery async operations.
Is there no possibility to make async crm query calls?


Solution

  • Http requests to Xrm.WebApi are asynchronous by default, e.g. Xrm.WebApi.retrieveRecord. Examples in the API document I've linked there are written in JavaScript, but you can of course make Http requests to the WebApi from C# too.

    This document demonstrates basic CRUD operations to the WebApi using C# and HttpClient.SendAsync(). Extract:

    string connectionString = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
    
    using (HttpClient client = SampleHelpers.GetHttpClient(
       connectionString,
       SampleHelpers.clientId,
       SampleHelpers.redirectUrl,"v9.0"))
    {
       Console.WriteLine("--Section 1 started--");
       string queryOptions;
       contact1.Add("firstname", "Rafel");
       contact1.Add("lastname", "Shillo");
    
       HttpRequestMessage createrequest1 = new HttpRequestMessage(HttpMethod.Post, 
          client.BaseAddress + "contacts");
       createrequest1.Content = new StringContent(contact1.ToString());
       createrequest1.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
    
       HttpResponseMessage createResponse1 = client.SendAsync(createrequest1, 
       HttpCompletionOption.ResponseHeadersRead).Result;
    
       if (createResponse1.IsSuccessStatusCode)
       {
          Console.WriteLine("Contact '{0} {1}' created.", contact1.GetValue("firstname"), contact1.GetValue("lastname"));
          contact1Uri = createResponse1.Headers.GetValues("OData-EntityId").FirstOrDefault();
          entityUris.Add(contact1Uri);
          Console.WriteLine("Contact URI: {0}", contact1Uri);
       }
    }