Monday, May 25, 2020

Generic Web API methods for Dynamic CRM in C#


Here are the generalized methods to Create, Retrieve, Update and Delete entity instances in Dynamic CRM using Web API in C#.

It includes method to get httpclient to access Dynamic 365 CRM instance and access token.


Generic Method Definitions for CRUD Operations


// Note : Please provide your Application Id, Client Secret Key, Organization Url and TennantID
//        These parameter can be parameterized, but for simplicity I kept it like that only.
public static async Task<string> GetAccessToken()
{
    var applicationId = "00000000-0000-0000-0000-000000000000";
    var clientSecret = "client-secrete key";
    var organizationUrl = "https://myOrganization.api.crm8.dynamics.com/";
    var aadInstanceUrl = "https://login.microsoftonline.com";
    var tenantId = "00000000-0000-0000-0000-000000000000";

    var clientcred = new ClientCredential(applicationId, clientSecret);
    var authenticationContext = new AuthenticationContext($"{aadInstanceUrl}/{tenantId}");
    var authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);
    return authenticationResult.AccessToken;
}


public static HttpClient GetD365Client()
{
    var accessToken = await GetAccessToken();
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
    client.DefaultRequestHeaders.Add("OData-Version", "4.0");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");

    return client;
}


// Note : Please provide your Organization Url
public static string GetOrganizationAPIUrl()
{
    return "https://myOrganization.crm8.dynamics.com/api/data/v9.1/";
}


public static async Task<string> GetEntity(string entityQuery)
{
    string resultJson = null; // Output variable
    var httpClient = CrmHelper.GetD365Client();           
    string organizationAPIUrl = CrmHelper.GetOrganizationAPIUrl();
           
    var httpResponse = await httpClient.GetAsync(organizationAPIUrl + entityQuery);

    if (httpResponse.IsSuccessStatusCode)
    {
        if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK)
        {
            resultJson = httpResponse.Content.ReadAsStringAsync().Result;                   
        }
    }
    return resultJson;
}


public static async Task<string> updateEntity(string entityUri, object crmEntiyObj)
{
    string entityId = null; // Output variable
    var httpClient = await CrmHelper.GetD365Client();
    string organizationAPIUrl = CrmHelper.GetOrganizationAPIUrl();

    HttpRequestMessage updateEntityReq = 
              new HttpRequestMessage(new HttpMethod("PATCH"), organizationAPIUrl + entityUri);
    updateEntityReq.Content = 
              new StringContent(JsonConvert.SerializeObject(crmEntiyObj), Encoding.UTF8, "application/json");
    HttpResponseMessage httpResponseResult = 
              httpClient.SendAsync(updateEntityReq, HttpCompletionOption.ResponseContentRead).Result;

    if (httpResponseResult != null)
    {
        IEnumerable<string> uri = null;
        httpResponseResult.Headers.TryGetValues("OData-EntityId", out uri);
        if (uri != null)
        {
            entityId = uri.FirstOrDefault().Replace(organizationAPIUrl, "");                   
        }
    }
    return entityId;
}


public async Task<string> createEntity(string entityName, object crmEntiyObj)
{           
    string entityId = null// Output variable
    var httpClient = await CrmHelper.GetD365Client();
    string organizationAPIUrl = CrmHelper.GetOrganizationAPIUrl();
           
    var content = new StringContent(JsonConvert.SerializeObject(crmEntiyObj), Encoding.UTF8, "application/json");
    var httpResponseResult = httpClient.PostAsync(organizationAPIUrl + entityName, content).Result;

    if (httpResponseResult != null)
    {
        IEnumerable<string> uri = null;
        httpResponseResult.Headers.TryGetValues("OData-EntityId", out uri);
        if (uri != null)
        {
            var txtReplacer = organizationAPIUrl + entityName;
            entityId = uri.FirstOrDefault().Replace(txtReplacer, "").Replace("(", "").Replace(")", "");                   
        }
    }
    return entityId;
}


RETRIEVE operation demo:
Please refer here to know more about making canonical for Crm Entity and sending the response in a user-friendly format which other consumer or business can understand. 





5 comments:

Anonymous said...

var accessToken = await GetAccessToken();

throws error.

K said...
This comment has been removed by the author.
cheap erectile dysfunction pills online said...

Oh my goodness! Incredible article dude! Thanks, However I am going through problems with your RSS. I don't know the reason why I am unable to subscribe to it. Is there anybody else having the same RSS issues? Anyone that knows the solution can you kindly respond? Thanks!!

ed pills said...

Hi there to every one, the contents present at this web page are really remarkable for people experience, well, keep up the nice work fellows.

Unknown said...

Hi,
Thanks for sharing this great post. I was wondering if you can share the CrmHelper code with us.

Thanks!