Search This Blog

Thursday, September 16, 2021

Call Dynamics 365 Online Webapi in c#

private static string serviceUri = "https://crmdemo.crm.dynamics.com";
private static string redirectUrl = "https://crmdemo.api.crm.dynamics.com/api/data/v9.2/";
private const string Authority = "https://login.microsoftonline.com/d034267c-c30c-4ccf-b0e7-f03149844f21";  // Tenant Id after app registration
private const string clientId = "17802964-c859-410a-a908-76bc97fbe4cd";     // Client ID after app registration

private const string userName = "username";
private const string password = "password";

 

Call Token methods:

string bearerToken = Task.Run(async () => await GetAuthToken()).Result;   // Get bearer token

Get Token Method

        public static async Task<string> GetAuthToken()
        {
            AuthenticationResult result = null;
            try
            {
                AuthenticationContext authContext = new AuthenticationContext(Authority, false);
                UserCredential cred = new UserPasswordCredential(userName, password);
                result = await authContext.AcquireTokenAsync(serviceUri, clientId, cred);
            }
            catch (Exception ex)
            {
                throw;
            }
            return result.AccessToken;
        } 



Retrieve Accounts

        public static void RetrieveAccounts(string authToken)
        {
            HttpClient httpClient = null;
            httpClient = new HttpClient();
            //Default Request Headers needed to be added in the HttpClient Object
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            //Set the Authorization header with the Access Token received specifying the Credentials
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

            httpClient.BaseAddress = new Uri(redirectUrl);
            var response = httpClient.GetAsync("accounts?$select=name&$top=5").Result;
            if (response.IsSuccessStatusCode)
            {
                var accounts = response.Content.ReadAsStringAsync().Result;
                var jRetrieveResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
                foreach (var data in collContacts.value)
                {
                    Console.WriteLine("Contact Name – " + data.name.Value);
                }
            }        
        }

 

Call Create Record Method

string statusss = Task.Run(async () => await CreateRecord(bearerToken)).Result;

Create Record Method

        private static async Task<string> CreateRecord(string authToken)
        {
            JObject acc = new JObject { };
            acc["name"] = "Test1";
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(serviceUrl + "/api/data/v9.2/"),
                Timeout = new TimeSpan(0, 2, 0)
            };
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

            // Add this line for TLS complaience
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "accounts")
            {
                Content = new StringContent(acc.ToString(), Encoding.UTF8, "application/json")
            };
            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return "204";
            }
            return "";
        }

No comments:

Post a Comment