Thursday, June 18, 2020

Retrieve data from CRM using Azure clientId/clientSecret

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Configuration;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Organization;
using System.ServiceModel;
using System.Net;
using Microsoft.Crm.Sdk.Messages;
using System.Collections.Generic;
using System.Data;
using System.Runtime.InteropServices;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text;
using System.Net.Http.Headers;

namespace CustomCode
{
    public class AzureRetrieveCall
    {
        public static void Main(string[] args)
        {
            //you will get some An unhandled exceptions of type 'System.AggregateException' occurred in mscorlib.dll
            //{ "An error occurred while sending the request."}
            //Hresult -2146233088
            //if you wont specify SecurityProtocol
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var contacts = CrmRequest(HttpMethod.Get, "https://ORGNAME.api.crm.dynamics.com/api/data/v9.1/contacts")
               .Result.Content.ReadAsStringAsync();
            // Similarly you can make POST, PATCH & DELETE requests  
        }
        public static async Task<HttpResponseMessage> CrmRequest(HttpMethod httpMethod, string requestUri, string body = null)
        {
            // Acquiring Access Token  
            var accessToken = await AccessTokenGenerator();

            var client = new HttpClient();
            var message = new HttpRequestMessage(httpMethod, requestUri);

            // OData related headers  
            message.Headers.Add("OData-MaxVersion", "4.0");
            message.Headers.Add("OData-Version", "4.0");
            message.Headers.Add("Prefer", "odata.include-annotations=\"*\"");

            // Passing AccessToken in Authentication header  
            message.Headers.Add("Authorization", $"Bearer {accessToken}");

            // Adding body content in HTTP request   
            if (body != null)
                message.Content = new StringContent(body, UnicodeEncoding.UTF8, "application/json");

            return await client.SendAsync(message);
        }
        public static async Task<string> AccessTokenGenerator()
        {
            string clientId = ""; // Your Azure AD Application ID  
            string clientSecret = ""; // Client secret generated in your App  
            string authority = "https://login.microsoftonline.com/APPTENANTID"; // Azure AD App Tenant ID  
            string resourceUrl = "https://ORGNAME.crm.dynamics.com"; // Your Dynamics 365 Organization URL  

            var credentials = new ClientCredential(clientId, clientSecret);
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
            var result = await authContext.AcquireTokenAsync(resourceUrl, credentials);
            return result.AccessToken;
        }

    }
}

No comments:

Post a Comment