Featured image of post Extract New Record GUID from Dynamics 365 Customer Engagement Create Web API Request (C#)

Extract New Record GUID from Dynamics 365 Customer Engagement Create Web API Request (C#)

Typically, when working with a database/application to programmatically create new records, it is desirable for us to return some information relating to any newly created records; this would typically take the form of a Globally Unique Identifier (GUID), primary key value or something else that uniquely identifies the record in question. Doing this may be useful for several reasons:

  • By returning this type of data, we can implicitly confirm that the record has been created successfully, as such a value would not exist otherwise.
  • There may be some additional operations that need to be carried out against the new record, post-creation. By returning its unique identifier, we can carry out such activities without any further impediment and do not need to rely on a separate retrieval operation to obtain this property.
  • The unique identifier may be required elsewhere within our application. For example, we may want to store the unique identifier within a separate system, to satisfy any current/future data integration requirements.

Dynamics 365 Customer Engagement (D365CE) is no different in this regard, and you traditionally may have had to devote some effort to accommodate this scenario. Fortunately, if you are working with tools such as Jason Lattimer’s CRM REST Builder, a lot of the hassle involved here becomes virtually non-existent, as you can very quickly generate code snippets that not only perform your entire create record operation but also return the records GUID after the transaction has completed successfully. An example of the type of code that the tool can generate is seen below:

var entity = {};
entity.name = "CRM Chap";

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            var uri = this.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));

In this example, lines 14-17 of the snippet handle the process of returning the newly created records GUID, with some specific steps required to ensure this renders nicely. This is because D365CE returns the newly created record as part of a complete URL by default (e.g. the above example, unmodified, would return something like https://mycrminstance.crm11.dynamics.com/api/data/v9.1/accounts(711cd182-0f90-e911-a97b-002248014773)). Therefore, a Regular Expression (RegEx) is used to strip out all of the URL components and, instead, supply us with the record GUID as part of the newEntityId variable. VERY handy and another reason why we should all be thanking Jason for building such an amazing tool.

While this is all well and good if you are working with the Web API using JScript, there may be other programming languages that you wish to utilise alongside D365CE’s Web API. A natural example of this is C# and, fortunately, there are also code samples freely available to help simplify development. However, these samples do not implement the same kind of transformation that Jason’s tool very kindly does by default. So how can we replicate this functionality using C#? Thanks mostly to the excellent Regular Expression engine built directly into .NET, the task of porting across similar functionality to C# is greatly simplified. By adding a using System.Text.RegularExpressions; statement to the top of our C# class file, we can then use the following three lines of code to extract out the CRM record GUID as a string value (where entityUri is the same URL example shown above):

Regex rx = new Regex(@"\(([^)]+)\)");
Match match = rx.Match(entityUri);
string entityID = match.Value;

From there, we could then look to cast the entityID string into a Guid data type to, for example, associate the record to another within the application, update our external application system, print it out to a log file/console window…the possibilities are endless! What matters the most is that we can get something unique that identifies our newly created D365CE record and all it took was a few lines of code in C# - which is always nice. 🙂

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy