Press "Enter" to skip to content

Parse JSON string for CRM Dynamics 365 received in Azure Function

Bilal Marzouk 0

Parsing the json from crm dynamics received from Azure function is not that easy Cause we have many entities , so it need to be generic for all entities .

When plugin triggers and invokes a WebHook, three types of data received in the request i.e. Query String, Header Data and Request Body. The Request body contains a string that represents the JSON value of the RemoteExecutionContext class. This class defines the contextual information sent to a remote service endpoint at run-time. Below code snippet reads the content from the HttpRequestMessage and converts the received JSON string to proper deserializable JSON string.

in our example i will take the most diffcult entity the email because it has some HTML in email body so let is start:

First Step will be to get our request body string:

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

Second) so now we have the string and we need now to well formated to be easy to read by code and first step will be to clea HTMl tags so here how to clear crm dynamics 365 email body from html tags :

   public static string StripHTML(string input)
    {
        var result = Regex.Replace(input, "<br>|</br>", " ");
        result = Regex.Replace(result, "<.*?>| |\n|\\\\u000|\\\\u", string.Empty);
        result = Regex.Replace(result, "<(.|\n)*?>", string.Empty);
        return Regex.Replace(result, "\r", " ");
    }



Third step )we have Format the json cause the recieved json it is not well formed :

 public static string FormatJson(string str)
    {
        var indent = 0;
        var quoted = false;
        var sb = new StringBuilder();
        for (var i = 0; i < str.Length; i++)
        {
            var ch = str[i];
            switch (ch)
            {
                case '{':
                case '[':
                    sb.Append(ch);
                    if (!quoted)
                    {
                        sb.AppendLine();
                        Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
                    }
                    break;
                case '}':
                case ']':
                    if (!quoted)
                    {
                        sb.AppendLine();
                        Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
                    }
                    sb.Append(ch);
                    break;
                case '"':
                    sb.Append(ch);
                    bool escaped = false;
                    var index = i;
                    while (index > 0 && str[--index] == '\\')
                        escaped = !escaped;
                    if (!escaped)
                        quoted = !quoted;
                    break;
                case ',':
                    sb.Append(ch);
                    if (!quoted)
                    {
                        sb.AppendLine();
                        Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
                    }
                    break;
                case ':':
                    sb.Append(ch);
                    if (!quoted)
                        sb.Append(" ");
                    break;
                default:
                    sb.Append(ch);
                    break;
            }
        }
        return sb.ToString();
    }

now we have to option either we create an dynamic object and get the felds from dynamics like

        log.LogInformation("C# HTTP trigger function processed a request.");
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        requestBody = StripHTML(requestBody);                  
        string resultJson = FormatJson(requestBody);         
        log.LogInformation("remoteExecutionContext start");         
        dynamic data = Newtonsoft.Json.Linq.JObject.Parse(resultJson);
        return data.PrimaryEntityId;


or we can also to cast RemoteExecutionContext and then get our felds from here :


  requestBody = StripHTML(requestBody);
  string resultJson = FormatJson(requestBody);
  log.LogInformation("remoteExecutionContext start");
  var remoteExecutionContext = 
  DeserializeJsonString<Microsoft.Xrm.Sdk.RemoteExecutionContext>(resultJson);

   Microsoft.Xrm.Sdk.Entity targetEntity = 
  (Microsoft.Xrm.Sdk.Entity)remoteExecutionContext.InputParameters["Target"];
   EntityReference phoneNumber = targetEntity.Attributes["phonenumber"] as 
    EntityReference;
          

Leave a Reply

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