Call third party webapi from plugin using secure/ unsecure configuration (Sample C# code)

 Call third party webapi from plugin using secure/ unsecure configuration (Sample C# code)

Reference

Sample Code 1:

using Microsoft.Xrm.Sdk;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Xml;

namespace Thirdpartycallpluginconfig
{
    //<Data> <key>bf48d51a9722aba723c923c2fa4e476d</key>  <url>http://apilayer.net/api/live</url> </Data>
    public class thirdpartywebapicall : IPlugin
    {
        private readonly string _configSettings;
        private readonly string _key;
        private readonly string _url;

        public thirdpartywebapicall(string configurationSettings)
        {
            if (!string.IsNullOrWhiteSpace(configurationSettings))
            {
                try
                {
                    _configSettings = configurationSettings;
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(_configSettings);
                    _key = doc.SelectSingleNode("Data/key").InnerText;
                    _url = doc.SelectSingleNode("Data/url").InnerText;
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("configs not found" + ex.InnerException.ToString());
                }
            }
        }

        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            var ent = (Entity)context.InputParameters["Target"];

            HttpClient client = new HttpClient();
            var query = $"access_key={_key}&currencies=EUR,GBP,CAD,PLN &source=USD&format=1";

            var request = (HttpWebRequest)WebRequest.Create(_url + "?" + query);
            request.Method = "GET";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            var content = string.Empty;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(stream))
                    {
                        content = sr.ReadToEnd();
                    }
                }
            }
            var parsedResponseJSON = JObject.Parse(content);
            var CurrenciesJSON = parsedResponseJSON["quotes"];

            var parsedCurrenciesJSON = JObject.Parse(CurrenciesJSON.ToString());
            var USDTOEUR = parsedCurrenciesJSON["USDEUR"];

            //add a note
            Entity Note = new Entity("annotation");
            Note["objectid"] = new EntityReference("contact", ent.Id);
            Note["objecttypecode"] = 2;
            Note["subject"] = "Latest Currency Exchange Data";
            Note["notetext"] = "USDEUR : " + USDTOEUR +" " + _url + "?" + query + " " + content;
            service.Create(Note);

        }

    }
}

Sample Code 2:

public class WebApiSample : IPlugin
{
  public void Execute(IServiceProvider serviceProvider)
  {
    // getting the pipeline context.
    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    var ent = (Entity) context.InputParameters[“Target”];

    var accessToken = GetTokenWithoutADAL().GetAwaiter().GetResult();
    var accountJson = RetrieveAccounts(accessToken).GetAwaiter().GetResult();

    ent[“vvbv_description”] = accountJson;
  }

  private async Task<string> GetTokenWithoutADAL() //ADAL (Active directory authentication library)
  {
    string azureAdDomain = “xrmforyou62.onmicrosoft.com”;
    string loginUrl = $”https
      : // login.microsoftonline.com/{azureAdDomain}/oauth2/token”;
        string resource = “https
      : // xrmforyou62.crm.dynamics.com”;
        string clientId = “9a3590d8 - c89e - 4de5 - bb50 - 8dfa3d9796a9”;
    string clientSecret = “<put your client secret here>”;

    HttpClient client = new HttpClient();
    var postData = $”client_id = { clientId }& client_secret = {clientSecret}& resource = { resource }& grant_type = client_credentials”;

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, loginUrl);
    request.Content = new StringContent(postData, Encoding.UTF8);
    request.Content.Headers.Remove(“Content - Type”);
    request.Content.Headers.TryAddWithoutValidation(“Content - Type”, $”application / x - www - form - urlencoded”);

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    var responseMessage = await client.SendAsync(request);
    var jsonResponseString = await responseMessage.Content.ReadAsStringAsync();
    var jsonContent = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResponseString);

    return jsonContent[“access_token”];
  }

  private async Task<string> RetrieveAccounts(string token)
  {
    string webApiUrl = “https
      : // xrmforyou62.api.crm.dynamics.com/api/data/v9.1″;
        string url = $”{ webApiUrl } / accounts? $select = name”;

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(“Bearer”, token);
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    HttpResponseMessage response = await client.GetAsync(url);
    string jsonContent = await response.Content.ReadAsStringAsync();

    return jsonContent;
  }
}


No comments:

Post a Comment