Inkey Solution Logo
banner

Blogs

Access the Azure Logic App using Service Bus to connect Microsoft Dynamics 365 from an external website

, September 5, 2018 4346 Views

Using Logic App we can create, update, return list of records etc from the CRM. Today in this blog, I will explain how to access the Azure Logic App using Service Bus from an external website.

First, create a web API to access the Azure Logic App using Service Bus.
Please refer the below link to know in detail how to create the web API to access the Azure Logic App using Service Bus.

Integrate external web resource with Microsoft Dynamics 365 using Azure Service Bus & Logic App

Now, once the web API and the Logic App is ready, we can call the web API from any external website. Below is an example in which I am calling the web API from an aspx web page to create records in Dynamics CRM 365.

The UI of the aspx page will have some text boxes and a button. The user will fill up the text boxes and click on the Submit button. Clicking on the submit button will call the web API to create records in CRM.

For Example:-

protected void btnSubmit_Click(object sender, EventArgs e)
{
      //Add TLS 1.2 Support
      if ((!ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Tls12)))
      {
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
      }
      try
      {
        WorkItem workitem = new WorkItem();

        workitem.FirstName = (String.IsNullOrEmpty(txtFirstName.Text) || txtFirstName.Text == null) ? "" : txtFirstName.Text;
        workitem.LastName = (String.IsNullOrEmpty(txtLastName.Text) || txtLastName.Text == null) ? "" : txtLastName.Text;
        workitem.Address = (String.IsNullOrEmpty(txtAddress.Text) || txtAddress.Text == null) ? "" : txtAddress.Text;

       Dictionary<string, string> result = CallWebApiProtectedByCredAsync(workitem).Result;

        string resultString = string.Join(";", result.Select(x => x.Key + "=" + x.Value).ToArray());
        string[] resultStringArr = resultString.Split(';');
        string status = resultStringArr[0];
        string message = resultStringArr[1];

        lblResult1.Text = status;
        lblResult2.Text = message;
      }
      catch (Exception ex)
      {
        throw ex;
      }
}

In the above code you can see that, we are calling “CallWebApiProtectedByCredAsync” method with all the text box values filled by the user. Now, lets see the definition of CallWebApiProtectedByCredAsync method.

static async Task<Dictionary<string, string>> CallWebApiProtectedByCredAsync(WorkItem workItem)
{
      string authority = "Token endpoint goes here";
      string clientId = "Client ID goes here";
      string secretkey = "Secret key ID goes here";
      string resource = "Azure web API url goes here";

      Dictionary<string, string> result = new Dictionary<string, string>();
      try
      {
        ClientCredential clientCred = new ClientCredential(clientId, secretkey);
        AuthenticationContext authContext = new AuthenticationContext(authority);
        AuthenticationResult token = authContext.AcquireToken(resource, clientCred);
        if (token == null)
        {
          throw new InvalidOperationException("Failed to obtain the token");
        }

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("Azure web API url goes here");
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token.AccessTokenType, token.AccessToken);
        var stringContent = new StringContent(JsonConvert.SerializeObject(workItem), Encoding.UTF8, "application/json");

        //”api/CreateRecordDetails” is the route of your controller method
        HttpResponseMessage httpResponse = client.PostAsync("api/CreateRecordDetails", stringContent).Result;

        if (httpResponse == null)
        {
          throw new InvalidOperationException("Failed to obtain the httpResponse");
        }

        string responseString = await httpResponse.Content.ReadAsStringAsync();
        var json = JsonConvert.DeserializeObject(responseString);
        result.Add("STATUS", httpResponse.StatusCode.ToString());
        result.Add("MESSSGE", json.ToString());

      }
      catch (Exception ex)
      {
        //Need to maintain Exception in Error log.
        throw ex;
      }
      return result;
}

The “CallWebApiProtectedByCredAsync” method requires below details:-

1. Token endpoint

You can get the token endpoint by navigating to Home → App registrations → Endpoints

2. Client ID

You can get the Client ID by navigating to Home → App registrations

3) Secret Key

You can get the Secret key by navigating to Home → App registrations → Click on your app → Settings → Keys

To create a new secret key – add the description, select the expiry date for that secret key & save the form to generate the secret key.

Note the following:
1. Copy the key value. Once you leave the page, you will not be able to retrieve the key.
2. More than one key can be generated.

4) Azure web API URL

You can get the web API URL by navigating to Home → Resource groups → Select your resource group → Select your App service -> Copy the URL

I hope this helps you!!

Happy CRMing.


 

Insert data into Many-to-Many relationship in Dynamics CRM very easily & quickly, using the Drag and drop listbox.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/drag-and-drop-listbox

Create a personal / system view in Dynamics CRM with all the fields on the form/s which you select for a particular entity using the View Creator.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/view-creator

mm

Inkey

INKEY is your solution partner.
Our focus is to deliver you in-time intelligent innovative solutions ("key") for the problems in hand. Maintaining a quality standard right from the inception of a project is our top most priority.

Our team of talented professionals will execute your projects with dedication and excellence. We take ownership and accountability for the effort that goes into meeting our client’s needs.

Years of experience and proven success of delivering innovative custom solutions.

More posts by

3 responses to “Access the Azure Logic App using Service Bus to connect Microsoft Dynamics 365 from an external website”

  1. […] Access the Azure Logic App using Service Bus to connect Microsoft Dynamics 365 from an external webs… […]

  2. PRAVEEN says:

    The first link that you have provided is not accessable.
    can you please help!
    “Integrate external web resource with Microsoft Dynamics 365 using Azure Service Bus & Logic App”

Leave a Reply

Your email address will not be published. Required fields are marked *

The maximum upload file size: 2 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Drop file here

Would you like to digitize your business and put it on the cloud?
Do you need clear, concise reports for your organization?