CRUD Operations on Dynamics 365 CRM Tables with ODATA API

What is Issue?

Performing CRUD operation on Dynamics 365 CRM using API (Rest/ODATA) from other applications.

The Reason-

While performing integration of other application with CRM, creating custom Web API and webservice is having much efforts in terms of time and development. Microsoft already made developers job easy by providing the ODATA API available for their products. How to consume that API in other applications.

Solution-

While performing integration of other application with CRM, rather than creating the custom API or webservice, we can utilize ODATA APIs that can be consumed with the OAuth 2.0 authentication.

Lets take .net application which is consuming ODATA API.

Some time we don’t want to include any third party dll due to some environmental restrictions. so the sample code added below is using only system libraries.

(In case of Json serialization, you can utilize Newtonsoft.Json to avoid the classes to be written manually)

Create records using ODATA API-

#region Create API Call
        /// <summary>
        /// Create the entity Record using API Call
        /// </summary>
        /// <param name="entityname">entity Name</param>
        /// <param name="entity">entity Object with parameter values</param>
        /// <returns></returns>
        public string CreateAPI(string entityname, object entity)
        {
            string funResponse = null;
            string query = entityname;
            string crmRestQuery = apiUrl + query;

            try
            {
                using (MemoryStream streamOpportunitySerialize = new MemoryStream())
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(entity.GetType());
                    ser.WriteObject(streamOpportunitySerialize, entity);
                    streamOpportunitySerialize.Position = 0;
                    StreamReader srOpportunity = new StreamReader(streamOpportunitySerialize);
                    string objectJSON = srOpportunity.ReadToEnd();
                    objectJSON = objectJSON.Replace("_odata_bind", "@odata.bind");

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, crmRestQuery);
                    //add header parameters
                    request.Headers.Add("Authorization", "Bearer " + oauthToken);
                    request.Content = new StringContent(objectJSON);
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                    HttpResponseMessage response = httpClient.SendAsync(request).Result;
                    string responseString = response.Content.ReadAsStringAsync().Result;

                    if (response.IsSuccessStatusCode)
                    {
                        string _recordUrl = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
                        string[] splitRetrievedData = _recordUrl.Split('[', '(', ')', ']');
                        funResponse = splitRetrievedData[1];
                    }
                    else
                        funResponse = responseString;

                }
            }
            catch (Exception ex)
            {
                funResponse = ex.Message;
            }
            return funResponse;
        }
        #endregion

Update records using ODATA API-

  #region Update API Call
        /// <summary>
        /// Update the entity record using API Call
        /// </summary>
        /// <param name="entityname">entity name</param>
        /// <param name="entityid">entity id</param>
        /// <param name="entity">entity Object with parameter values</param>
        /// <returns></returns>
        public string UpdateAPI(string entityname, string entityid, object entity)
        {
            string funResponse = null;
            string query = entityname + "(" + entityid + ")";
            string crmRestQuery = apiUrl + query;
            try
            {
                using (MemoryStream streamOpportunitySerialize = new MemoryStream())
                {

                    DataContractJsonSerializer ser = new DataContractJsonSerializer(entity.GetType());
                    ser.WriteObject(streamOpportunitySerialize, entity);
                    streamOpportunitySerialize.Position = 0;
                    StreamReader srOpportunity = new StreamReader(streamOpportunitySerialize);
                    string objectJSON = srOpportunity.ReadToEnd();
                    objectJSON = objectJSON.Replace("_odata_bind", "@odata.bind");

                    HttpMethod method = new HttpMethod("PATCH");
                    HttpRequestMessage request = new HttpRequestMessage(method, crmRestQuery);
                    //add header parameters
                    request.Headers.Add("Authorization", "Bearer " + oauthToken);
                    request.Headers.Add("If-Match", "*");      //preventing creation of new record if no record found with ID
                    request.Content = new StringContent(objectJSON);
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                    HttpResponseMessage response = httpClient.SendAsync(request).Result;
                    string responseString = response.Content.ReadAsStringAsync().Result;
                    if (response.IsSuccessStatusCode)
                    {
                        funResponse = "Sucessfully Updated Record!!";
                    }
                    else
                        funResponse = responseString;
                }
            }
            catch (Exception ex)
            {
                funResponse = ex.Message;
            }
            return funResponse;
        }
        #endregion

Delete records using ODATA API-

#region Delete API Call
        /// <summary>
        /// Delete the entity Record using API Call
        /// </summary>
        /// <param name="entityname">entity Name</param>
        /// <param name="entityid">Entity id</param>
        /// <returns></returns>
        public string DeleteAPI(string entityname, string entityid)
        {
            string funResponse = null;
            string query = entityname + "(" + entityid + ")";
            string crmRestQuery = apiUrl + query;

            try
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, crmRestQuery);
                //add header parameters
                request.Headers.Add("Authorization", "Bearer " + oauthToken);
                request.Headers.Add("Accept", "application/json; charset=utf-8");

                HttpResponseMessage response = httpClient.SendAsync(request).Result;
                string responseString = response.Content.ReadAsStringAsync().Result;
                if (response.IsSuccessStatusCode)
                    funResponse = "Deleted!!!";
                else
                    funResponse = responseString;
            }
            catch (Exception ex)
            {
                funResponse = ex.Message;
            }
            return funResponse;
        }
        #endregion

Retrieve Single record using ODATA API-

 /// <summary>
        /// Retrieve single using API Call
        /// </summary>
        /// <param name="entityPluralName">entity Name</param>
        /// <param name="entityId">entity id</param>
        /// <param name="entityObject">blank entity object</param>
        /// <param name="selectColumns">select columns to retrieve in API Call</param>
        /// <returns>Object of entity</returns>
        public object RetrieveSingle(string entityPluralName,string entityId,object entityObject, string selectColumns=null)
        {
            string query = "("+entityId+")";
            if (selectColumns != null) {
                query += "?$select=" + selectColumns;
            }
            string crmRestQuery = apiUrl + entityPluralName + query;
            try
            {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, crmRestQuery);
                    //add header parameters
                    request.Headers.Add("Prefer", "odata.include-annotations=\"*\"");//for formatted values
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/XML"));
                    request.Headers.Add("Authorization", "Bearer " + oauthToken);

                    //send request
                    HttpResponseMessage response = httpClient.SendAsync(request).Result;
                    string responseString = response.Content.ReadAsStringAsync().Result;
                    responseString = FormatResponse(responseString);

                    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseString)))
                    {
                        // Deserialization from JSON  
                        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(entityObject.GetType());
                    entityObject = (object)deserializer.ReadObject(ms);
                    }
                    
            }
            catch (Exception ex){ throw ex; }
            return entityObject;
        }

Retrieve Multiple records using ODATA API-

  /// <summary>
        /// Retrieve multiple using Fetch XML in API Call
        /// </summary>
        /// <param name="entityPluralName">entity name</param>
        /// <param name="fetchXML">fetchXML string</param>
        /// <returns>List of retrieved Objects</returns>
        public List<RetrieveOpportunity> RetrieveMultiple(string entityPluralName, string fetchXML)
        {
            fetchXML = fetchXML.Replace("<fetch", "<fetch {0} ");
            int page = 1;
            var cookie = string.Format("page='{0}'", page);
            string xml = string.Format(fetchXML, cookie);
            string crmRestQuery = apiUrl + entityPluralName + "?fetchXml=" + xml;
            List<RetrieveOpportunity> lstOpties = new List<RetrieveOpportunity>();
            bool isDone = false;
            try
            {
                while (isDone == false)
                {
                    isDone = true;
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, crmRestQuery);
                    //add header parameters
                    request.Headers.Add("Prefer", "odata.include-annotations=\"*\"");//for formatted values
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/XML"));
                    request.Headers.Add("Authorization", "Bearer " + oauthToken);

                    //send request
                    HttpResponseMessage response = httpClient.SendAsync(request).Result;
                    string responseString = response.Content.ReadAsStringAsync().Result;
                    responseString = FormatResponse(responseString);

                    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseString)))
                    {
                        // Deserialization from JSON  
                        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(APIResult));
                        APIResult apiResult = (APIResult)deserializer.ReadObject(ms);

                        if (!string.IsNullOrEmpty(apiResult.Microsoft_Dynamics_CRM_fetchxmlpagingcookie))
                        {
                            isDone = false;
                            page++;

                            //retrieve pagingCookie value
                            string xmlVal = WebUtility.UrlDecode((WebUtility.UrlDecode((string)apiResult.Microsoft_Dynamics_CRM_fetchxmlpagingcookie)));
                            int Start = xmlVal.IndexOf("pagingcookie=\"", 0) + "pagingcookie=\"".Length;
                            int End = xmlVal.IndexOf("\" istracking=\"False\"", Start);

                            //proccess the pagingCookie value to support in API URL
                            string strVal = xmlVal.Substring(Start, End - Start).Replace("<", "%26lt;").Replace(">", "%26gt;").Replace("\"", "%26quot;").Replace("'", "%26apos;").Replace("&", "%26amp;");
                            cookie = string.Format("page='{0}' paging-cookie='{1}'", page, strVal);

                            //modify the query for next page with paging cookie
                            xml = string.Format(fetchXML, cookie);
                            crmRestQuery = apiUrl + entityPluralName +"?fetchXml=" + xml;

                        }
                        if (!string.IsNullOrEmpty(apiResult.odata_nextLink))
                        {
                            isDone = false;
                            crmRestQuery = apiResult.odata_nextLink;
                        }

                        if (lstOpties == null || lstOpties.Count == 0)
                        {
                            lstOpties = apiResult.value;
                        }
                        else
                        {
                            lstOpties.AddRange(apiResult.value);
                        }
                    }
                }
            }
            catch (Exception ex) {
                throw ex;
            }
            return lstOpties;
        }

        public List<RetrieveOpportunity> RetrieveMultiple(string entityPluralName, string selectColumns,string filterConditions=null, string orderby=null,bool returnCount=false)
        {
           string query= "?$select=" + selectColumns;
            if (filterConditions != null) {
                query += "&$filter=" + filterConditions;
            }
            if (orderby != null) {
                query += "&$orderby=" + orderby;
            }
            if (returnCount == true) {
                query += "&$count=true";
            }

            string crmRestQuery = apiUrl + entityPluralName +  query;
            List<RetrieveOpportunity> lstOpties = new List<RetrieveOpportunity>();
            bool isDone = false;
            try
            {
                while (isDone == false)
                {
                    isDone = true;
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, crmRestQuery);
                    //add header parameters
                    request.Headers.Add("Prefer", "odata.include-annotations=\"*\"");//for formatted values
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/XML"));
                    request.Headers.Add("Authorization", "Bearer " + oauthToken);

                    //send request
                    HttpResponseMessage response = httpClient.SendAsync(request).Result;
                    string responseString = response.Content.ReadAsStringAsync().Result;
                    responseString = FormatResponse(responseString);

                    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseString)))
                    {
                        // Deserialization from JSON  
                        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(APIResult));
                        APIResult apiResult = (APIResult)deserializer.ReadObject(ms);
                        
                        if (!string.IsNullOrEmpty(apiResult.odata_nextLink))
                        {
                            isDone = false;
                            crmRestQuery = apiResult.odata_nextLink;
                        }

                        if (lstOpties == null || lstOpties.Count == 0)
                        {
                            lstOpties = apiResult.value;
                        }
                        else
                        {
                            lstOpties.AddRange(apiResult.value);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return lstOpties;
        }

Some common Methods in above Code –

  #region Local variables
        /// <summary>
        /// Local Variables
        /// </summary>
        private string clientID, secretKey, resource, oauthToken, apiUrl, tokenURL;
        private HttpClient httpClient;

        /// <summary>
        /// Constructor to initialize the variables
        /// </summary>
        public Operations()
        {
            apiUrl = "https://mscrm16tech.crm8.dynamics.com/api/data/v8.2/";
            clientID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
            secretKey = "asdasdxzxczdsdaasda";
            resource = "https://mscrm16tech.crm8.dynamics.com";
            tokenURL = "https://login.microsoftonline.com:443/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/token/";
        }
        #endregion 
 #region Generate Bearer Token
        /// <summary>
        /// Function to generate Bearer token OAuth2.0 using client id and secret
        /// </summary>
        /// <returns>access token</returns>
        public string GetBearerToken()
        {
            oauthToken = null;
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.Proxy = WebRequest.GetSystemWebProxy();
            clientHandler.Proxy.Credentials = CredentialCache.DefaultCredentials; // or new NetworkCredential("username","password","DOMAIN");
            clientHandler.UseProxy = true;
            httpClient = new HttpClient(clientHandler);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpContent requestContent = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"grant_type","client_credentials"},
                {"client_id",clientID},
                {"client_secret",secretKey},
                {"resource",resource}
            }
            );
            HttpResponseMessage response = httpClient.PostAsync(tokenURL, requestContent).Result;
            String responseString = response.Content.ReadAsStringAsync().Result;
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseString)))
            {
                // Deserialization from JSON  
                DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BearerToken));
                BearerToken token = (BearerToken)deserializer.ReadObject(ms);
                oauthToken = token.access_token;
            }

            return oauthToken;
        }
        #endregion
#region Common Methods
       public string FormatResponse(string responseString) {
            responseString = responseString.Replace("@odata.etag", "odata_etag");
            responseString = responseString.Replace("@OData.Community.Display.V1.FormattedValue", "_OData_Community_Display_V1_FormattedValue");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.associatednavigationproperty", "_Microsoft_Dynamics_CRM_associatednavigationproperty");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.lookuplogicalname", "_Microsoft_Dynamics_CRM_lookuplogicalname");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.lookuplogicalname", "_Microsoft_Dynamics_CRM_lookuplogicalname");
            responseString = responseString.Replace("@odata.context", "odata_context");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.totalrecordcount", "Microsoft_Dynamics_CRM_totalrecordcount");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded", "Microsoft_Dynamics_CRM_totalrecordcountlimitexceeded");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.fetchxmlpagingcookie", "Microsoft_Dynamics_CRM_fetchxmlpagingcookie");
            responseString = responseString.Replace("@Microsoft.Dynamics.CRM.morerecords", "Microsoft_Dynamics_CRM_morerecords");
            responseString = responseString.Replace("@odata.nextLink", "odata_nextLink");
            return responseString;
        }
        #endregion

Sample Class for Json Serialization in API Calls-

This class is not needed in you are using Newtonsoft.Json library.

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace ODATA_API
{
    [DataContract]
    public class BearerToken
    {
        [DataMember]
        public string token_type;
        [DataMember]
        public string expires_in;
        [DataMember]
        public string ext_expires_in;
        [DataMember]
        public string expires_on;
        [DataMember]
        public string not_before;
        [DataMember]
        public string resource;
        [DataMember]
        public string access_token;
    }

    [DataContract]
    public class CreateUpdateOpportunity {
        [DataMember]
        public string name;
        [DataMember]
        public string estimatedclosedate;
        [DataMember]
        public string parentaccountid_odata_bind;
        [DataMember]
        public decimal estimatedvalue;
        [DataMember]
        public string transactioncurrencyid_odata_bind;
    }
    [DataContract]
    public class RetrieveOpportunity
    {
        [DataMember]
        public string _odata_context;
        [DataMember]
        public string _odata_etag;
        [DataMember]
        public string estimatedclosedate_OData_Community_Display_V1_FormattedValue;
        [DataMember]
        public string estimatedclosedate;
        [DataMember]
        public string estimatedvalue_OData_Community_Display_V1_FormattedValue;
        [DataMember]
        public string estimatedvalue;
        [DataMember]
        public string estimatedvalue_base_OData_Community_Display_V1_FormattedValue;
        [DataMember]
        public string estimatedvalue_base;
        [DataMember]
        public string name;
        [DataMember]
        public string _parentaccountid_value_OData_Community_Display_V1_FormattedValue;
        [DataMember]
        public string _parentaccountid_value;
        [DataMember]
        public string opportunityid;
        [DataMember]
        public string _transactioncurrencyid_value_OData_Community_Display_V1_FormattedValue;
        [DataMember]
        public string _transactioncurrencyid_value;
    }

    [DataContract]
    public class APIResult
    {
        [DataMember]
        public string odata_context;
        [DataMember]
        public int Microsoft_Dynamics_CRM_totalrecordcount;
        [DataMember]
        public bool Microsoft_Dynamics_CRM_totalrecordcountlimitexceeded;
        [DataMember]
        public string Microsoft_Dynamics_CRM_fetchxmlpagingcookie;
        [DataMember]
        public bool Microsoft_Dynamics_CRM_morerecords;
        [DataMember]
        public string odata_nextLink;
        [DataMember]
        public List<RetrieveOpportunity> value;
    }

}

Calling the Above methods Sample-

static void Main(string[] args)
        {
            Operations ops = new Operations();
            Console.WriteLine("Started!!");
            Console.WriteLine(ops.GetBearerToken());
            
            CreateUpdateOpportunity entity = new CreateUpdateOpportunity();

            entity.transactioncurrencyid_odata_bind = "/transactioncurrencies(c63ba581-6bc6-e811-a96f-000d3af04fb0)";
            entity.estimatedvalue = 1000;
            entity.estimatedclosedate = "2021-01-01";
            entity.name = "Generated From C# Code";
            entity.parentaccountid_odata_bind = "/accounts(3b3b7c71-61d2-ea11-a813-000d3af0205e)";
            //create record
            string recordGuid = ops.CreateAPI("opportunities", entity);
            Console.WriteLine(recordGuid);
           
            //update record
            entity.name = "Generated From CSharp Code";
            Console.WriteLine(ops.UpdateAPI("opportunities", recordGuid, entity));

            //retrieve record
            RetrieveOpportunity retrieveOpportunity = new RetrieveOpportunity();
            retrieveOpportunity =(RetrieveOpportunity)ops.RetrieveSingle("opportunities", recordGuid,retrieveOpportunity);
            Console.WriteLine(retrieveOpportunity.name);

            //delete Record
            Console.WriteLine(ops.DeleteAPI("opportunities", recordGuid));


            Console.Read();
        }

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

Get SharePoint Document details for particular record in MS CRM using FetchXML

What is Issue?

There are many cases while implementing MS CRM where clients ask to perform some operation in MS CRM based on the document uploaded in SharePoint. But how to get SharePoint document details in MS CRM other than “Documents” associated view? If you try to fetch records using advanced find or querying sharepointdocument entity directly, it will show you error. So how we can query and get the document details using code either from client side or server side?

The Reason-

MS CRM Supports only the associated view for Document i.e. sharepointdocument entity. MS CRM do not support direct querying on all sharepointdocument.

Solution-

There is a way to fetch SharePoint document details for particular record in MS CRM.

If you try to query on Document entity in MS CRM using Advanced find you will get the error-” SharePoint document entity does not support any view other than associated view”.

Now this seems trouble to get sharepoint document details. Don’t worry, as error itself says, the sharepoint document does not support any view other than associated view, We can keep building query in advance find itself.

Suppose I want to get documents details for one of my Opportunity in MS CRM , So I am building the query in the following way-
1. Look for : Document
2.Use Saved View :All Sharepoint Documents
3.If you want, you can edit the columns
4. Select Regarding(Opportunity) contains data
5. Select sub query for opportunity record(for which you want to get details)

If you click on results, it will still show you same error. Don’t worry, download the fetchXML for the query we built.

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="sharepointdocument">
    <attribute name="documentid" />
    <attribute name="fullname" />
    <attribute name="relativelocation" />
    <attribute name="sharepointcreatedon" />
    <attribute name="filetype" />
    <attribute name="absoluteurl" />
    <attribute name="modified" />
    <attribute name="sharepointmodifiedby" />
    <attribute name="title" />
    <attribute name="readurl" />
    <attribute name="editurl" />
    <attribute name="author" />
    <attribute name="sharepointdocumentid" />
    <attribute name="ischeckedout" />
    <attribute name="locationid" />
    <attribute name="iconclassname" />
    <order attribute="relativelocation" descending="false" />
    <link-entity name="opportunity" from="opportunityid" to="regardingobjectid" link-type="inner" alias="ad">
      <filter type="and">
        <condition attribute="opportunityid" operator="eq" value="{83779C3E-xxxx-xxxx-xxxx-0CD3BEAFE160}" />
      </filter>
    </link-entity>
  </entity>
</fetch>

When I tried to use the fetchXML in Javascript query, I got the Sharepoint Document details in json as below-

As sharepoint document entity supports only associated view, it requires regarding object to query. So if you try to remove and link-entity tag from fetchXML, it will not return any record in response.

Now we have fetchXML which we can utilize in Javascript or C# based on requirement.

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

Generating Early Bound Classes and simple Entity Classes MS CRM

What is Issue?

While developing the CRM, when we have to go through coding part, we need to create Early-bound classes for some specific entities. But CrmSvcUtil.exe provides us the Early Bound classes for all the entities available in CRM.
Second scenario- we don’t want this much of complicated classes, Only want to add simple Entity classes. But it might become very lengthy and time consuming task to add the fields in class one by one.

The Reason-

Creating Early bound classes for particular entities is not possible using CrmSvcUtil.exe directly and creating simple entity classes is lengthy and time consuming task.

Solution-

To create early bound classe using CrmSvcUtil.exe, please refer blog – Generate Early Bound Classes for selected entities using CrmSvcUtil.exe in MS CRM

OR

you can use the tool created by mscrm16Tech as below-
It provides both the options like creating Simple CRM entity classes or to Use CrmSvcUtil.exe to generate early bound classes for selected entities only.

When you install and open the application in your system you will get below window which will help you in configuration of MS CRM connection and database connection if needed.

AppScreen1

After configuring the app and clicks on OK, Select the application “Create Early-Bound Classes” in next window  –

App2Screen0

Now you can load the available entities in connected CRM Organization. Please use below image for reference-

App2Screen In case you are using windows 10 and trying to generate Early Bound classes using CrmSvcUtil.exe, you need to make sure following feature is enabled on your windows-
>Control Panel Programs and Features – Turn Windows feature On or Off
->.NetFramework 4.8 Advanced Services
-> WCF Services
->HTTP Activation (Please enable if not)

App2Screen1

Please follow the images to work with the app.

You can download app Here- MSCRM16Tech Tool

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

 

Get Excel Report or Create Database table Directly from FetchXML file

What is Issue?

The creating report or database table using complex fetchXML and getting records more than 5000.

The Reason-

It is difficult to get data directly from MS CRM without any coding or using third party tool .

Solution-

Here is the new tool created by mscrm16tech which allows you to save data in excel sheet from MS CRM or helps you to create Database table with the display names available in MS CRM. These reports and data dump minimizes the developer efforts.

When you install and open the application in your system you will get below window which will help you in configuration of MS CRM connection and database connection if needed.

AppScreen1

After configuring the app and clicks on OK, you will get below window –

AppScreen2

Please follow the images to work with the app.

You can download app Here- FetchApp by MSCRM16Tech

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

 

Date Time issue due to different Timezone of User in MS CRM

What is Issue?

Working with date time field is most challenging task in MS CRM. Many times user sees the Date time in record which is different on the email he received or on some where it is populated and he reports the issue. Date time on the records should be consistent through out the MS CRM application. If record is used on some other entity or web-resource with that date time field, It should be exactly matching to the actual date time on record which is visible to user.

The Reason-

The reason behind this issue on timezone of the user and CRM application. At the time of execution of some server side code, it will always give you the date time in CRM server timezone. And if CRM application is going to used wordwide or from multiple timezones these date time fields might show mismatch data.

Solution-

One solution for this is to make all the user time zone similar to the server timezone. But when any javascript populates some date time field this might cause wrong date time.

Example: User is working from India and the Crm Server is placed in UK. User sets his timezone to UK timezone. but if any javascript is populating current date and time in record it will be Indian time which will be +5.30 hrs ahead. This data created is wrong at this time.

Another solution is to handle this date time things in code itself.

In Code we can perform following steps-

  1. Get user’s personal setting like – date time form, timezone information, locale informtion.
  2. Convert date time according to user setting.
  3. format this date time in user setting format.
  4. Set this updated date time on your desired place.

Now in both server side and client side how to handle it?

Server side code

Server side you need only 2 requests –

  1. LocalTimeFromUtcTimeRequest
  2. UtcTimeFromLocalTimeRequest

And UserSettings entity for Timezone Code.

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;

namespace TestConsoleApp
{
    class TestLogic
    {
        int? _timeZoneCode = 83;
        public void YourLogic(IOrganizationService service, Object parameter = null) {
            //get user's timezone-
            _timeZoneCode = RetrieveUsersTimeZoneCode(service);
            
            //datetime Value 
            DateTime scheduledStartDate=DateTime.Now;
            Console.WriteLine(scheduledStartDate.ToString());
         
            //Convert to User Local Time
            DateTime dt =scheduledStartDate.ToUniversalTime();
            DateTime UserLocalTime=RetrieveLocalTimeFromUTCTime(service, dt,_timeZoneCode);

            //convert to server Time
            DateTime serverTime =RetrieveUTCTimeFromLocalTime(service, UserLocalTime, _timeZoneCode);
            
            Console.Read();
        }

        public int? RetrieveUsersTimeZoneCode(IOrganizationService service, EntityReference user = null)
        {

            ConditionExpression cd = null;
            if (user == null)
                cd = new ConditionExpression("systemuserid", ConditionOperator.EqualUserId);
            else
                cd = new ConditionExpression("systemuserid", ConditionOperator.Equal, user.Id);

            var currentUserSettings = service.RetrieveMultiple(
            new QueryExpression("usersettings")
            {
                ColumnSet = new ColumnSet("localeid", "timezonecode"),
                Criteria = new FilterExpression
                {
                    Conditions = { cd }
                }
            }).Entities[0].ToEntity();
            return (int?)currentUserSettings.Attributes["timezonecode"];
        }

        public DateTime RetrieveLocalTimeFromUTCTime(IOrganizationService service, DateTime utcTime, int? timeZoneCode)
        {
            if (!timeZoneCode.HasValue)
                return utcTime;

            var request = new LocalTimeFromUtcTimeRequest
            {
                TimeZoneCode = timeZoneCode.Value,
                UtcTime = utcTime.ToUniversalTime()
            };

            var response = (LocalTimeFromUtcTimeResponse)service.Execute(request);

            return response.LocalTime;
        }

        public DateTime RetrieveUTCTimeFromLocalTime(IOrganizationService service, DateTime localTime, int? timeZoneCode)
        {
            if (!timeZoneCode.HasValue)
                return DateTime.Now;

            var request = new UtcTimeFromLocalTimeRequest
            {
                TimeZoneCode = timeZoneCode.Value,
                LocalTime = localTime
            };

            var response = (UtcTimeFromLocalTimeResponse)service.Execute(request);
            return response.UtcTime;
        }
    }
}

Client side code

In Javascripts, You need to play around UserSettings, LanguageLocale, TimezoneDefinition entities.

//array of all unique timezone offsets
var allTimeZones = { "(GMT+01:00)": "Africa/Algiers", "(GMT+02:00)": "Europe/Tirane", "(GMT+03:00)": "Europe/Mariehamn", "(GMT+04:00)": "Asia/Yerevan", "(GMT+04:30)": "Asia/Kabul", "(GMT+05:00)": "Antarctica/Mawson", "(GMT+05:30)": "Asia/Kolkata", "(GMT+05:45)": "Asia/Kathmandu", "(GMT+06:00)": "Antarctica/Vostok", "(GMT+06:30)": "Indian/Cocos", "(GMT+07:00)": "Antarctica/Davis", "(GMT+08:00)": "Antarctica/Casey", "(GMT+08:45)": "Australia/Eucla", "(GMT+09:00)": "Asia/Dili", "(GMT+09:30)": "Australia/Adelaide", "(GMT+10:00)": "Antarctica/DumontDUrville", "(GMT+10:00)": "Australia/Brisbane", "(GMT+10:30)": "Australia/Lord_Howe", "(GMT+11:00)": "Antarctica/Macquarie", "(GMT+12:00)": "Antarctica/McMurdo", "(GMT+12:45)": "Pacific/Chatham", "(GMT+13:00)": "Pacific/Enderbury", "(GMT+14:00)": "Pacific/Kiritimati", "(GMT-01:00)": "Atlantic/Cape_Verde", "(GMT-02:00)": "America/Noronha", "(GMT-02:30)": "America/St_Johns", "(GMT-03:00)": "Antarctica/Palmer", "(GMT-04:00)": "America/Anguilla", "(GMT-05:00)": "America/Eirunepe", "(GMT-06:00)": "America/Belize", "(GMT-07:00)": "America/Creston", "(GMT-08:00)": "Pacific/Pitcairn", "(GMT-09:00)": "Pacific/Gambier", "(GMT-09:30)": "Pacific/Marquesas", "(GMT-10:00)": "Pacific/Rarotonga", "(GMT-11:00)": "Pacific/Pago_Pago", "(GMT)": "Africa/Lome" };

//call this function to get user date in concerted format.
var GetTimeInCurrentUserZoneAndFormat=function(xrm,new_startdate) {
    //example : I have fetched new_startdate using REST Api and  new_startdate = 2019-08-30T10:00:00+01:00  
    var d = new Date(new_startdate);
    //step 1: Get user Date and Time format which he selected in Personal settings of CRM
    var dtFormat = GetDateandTimeSettingsOfUser(xrm);
    //step 2: convert Date to user local date.
    var userLocalDate = convertTimetoSpecificTimeZone(xrm, dtFormat.timeZone, dtFormat.localeId)
    // step 3: now convert date time format in user format 
    var convertedDateTime = ConvertDateInFormat(d, dtFormat.dateformat, dtFormat.dSeparator, dtFormat.timeFormat, dtFormat.tSeparator);

    return convertedDateTime; 
}

//get user's personal setting 
var GetDateandTimeSettingsOfUser = function (xrm) {
    var recordId = xrm.Page.context.getUserId();
    recordId = recordId.replace(/[{}]/g, "");
    var format = { dateformat: null, dSeparator: null, timeFormat: null, tSeparator: null, timeZone: null, localeId: null };
    var req = new XMLHttpRequest();
    req.open("GET", xrm.Page.context.getClientUrl() + "/api/data/v9.0/usersettingscollection?$select=dateformatstring,dateseparator,timeformatstring,timeseparator,localeid,timezonecode&$filter=systemuserid eq " + recordId, false);
    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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    format.dateformat = results.value[i]["dateformatstring"];
                    format.dSeparator = results.value[i]["dateseparator"];
                    format.timeFormat = results.value[i]["timeformatstring"];
                    format.tSeparator = results.value[i]["timeseparator"];
                    format.localeId = results.value[i]["localeid"];
                    format.timeZone = results.value[i]["timezonecode"];
                }
            }
            else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
    return format;
}

//start converting time to user local time
var convertTimetoSpecificTimeZone = function (xrm, date, _timezonecode, _localeid) {
    var timeZoneName = getTimeZoneStandartName(xrm, _timezonecode);
    var localeCode = getLocaleCode(xrm, _localeid);

    var GMTCode = timeZoneName.uiName.substring(0, 11);


    var newDate = date.toLocaleString(localeCode, { timeZone: allTimeZones[GMTCode] });

    return newDate;

}
var getTimeZoneStandartName = function (xrm, _timezoneCode) {
    var TimeZoneName = { standardName: "Greenwich Standard Time", uiName: "(GMT+00:00) Monrovia, Reykjavik" }
    var req = new XMLHttpRequest();
    req.open("GET", xrm.Page.context.getClientUrl() + "/api/data/v9.0/timezonedefinitions?$select=standardname,timezonecode,userinterfacename&$filter=timezonecode eq " + _timezoneCode, false);
    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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    TimeZoneName.standardName = results.value[i]["standardname"];
                    TimeZoneName.uiName = results.value[i]["userinterfacename"];
                }
            } else {
                xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
    return TimeZoneName;
}


var getLocaleCode = function (xrm, _localeId) {
    var code = "en-us";
    var req = new XMLHttpRequest();
    req.open("GET", xrm.Page.context.getClientUrl() + "/api/data/v9.0/languagelocale?$select=code,localeid&$filter=localeid eq " + _localeId, false);
    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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    code = results.value[i]["code"];
                    var localeid = results.value[i]["localeid"];
                    var localeid_formatted = results.value[i]["localeid@OData.Community.Display.V1.FormattedValue"];
                }
            } else {
                xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
    return code;
}

//to convert date time in particular format use the below function
//You can add more cases if you required more formats.	
var ConvertDateInFormat = function (date, dateFormat, dateSeperator, timeformat, timeSeperator) {
    if (dateFormat === void 0) { dateFormat = "M/d/yyyy"; }
    if (dateSeperator === void 0) { dateSeperator = "/"; }
    if (timeformat === void 0) { timeformat = "HH:mm"; }
    if (timeSeperator === void 0) { timeSeperator = ":"; }
    var daysShortW = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var daysLongW = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var monthLongW = ["January", "February", "March", "April", "May", "june", "July", "August", "September", "October", "November", "December"];
    var monthShortW = ["Jan", "Feb", "Mar", "Apr", "May", "jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
    var M = date.getMonth();
    var dd = date.getDate();
    var y = date.getFullYear();
    var day = date.getDay();
    var H = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    var ms = date.getMilliseconds();
    var formatedDateTime = date.toLocaleString();
    var formattedDateString = "";
    var formattedTimeString = "";
    switch (dateFormat) {
        case "MM/dd/yyyy":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var month = "" + (M + 1);
            if (month.length < 2)
                month = '0' + month;
            formattedDateString = [month, dt, "" + y].join(dateSeperator);
            break;
        case "dd/MM/yyyy":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var month = "" + (M + 1);
            if (month.length < 2)
                month = '0' + month;
            formattedDateString = [dt, month, "" + y].join(dateSeperator);
            break;
        case "M/d/yyyy":
            formattedDateString = ["" + (M + 1), "" + dd, "" + y].join(dateSeperator);
            break;
        case "dd/MMM/yy":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var year = "" + y;
            year = year.substring(2, 4);
            formattedDateString = [dt, monthShortW[M], year].join(dateSeperator);
            break;
        case "M/d/yy":
            var year = "" + y;
            year = year.substring(2, 4);
            formattedDateString = ["" + (M + 1), "" + dd, year].join(dateSeperator);
            break;
        case "d/M/yy":
            var year = "" + y;
            year = year.substring(2, 4);
            formattedDateString = ["" + dd, "" + (M + 1), year].join(dateSeperator);
            break;
        case "MM/dd/yy":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var month = "" + (M + 1);
            if (month.length < 2)
                month = '0' + month;
            var year = "" + y;
            year = year.substring(2, 4);
            formattedDateString = [month, dt, year].join(dateSeperator);
            break;
        case "dd/MM/yy":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var month = "" + (M + 1);
            if (month.length < 2)
                month = '0' + month;
            var year = "" + y;
            year = year.substring(2, 4);
            formattedDateString = [dt, month, year].join(dateSeperator);
            break;
        case "yy/MM/dd":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var month = "" + (M + 1);
            if (month.length < 2)
                month = '0' + month;
            var year = "" + y;
            year = year.substring(2, 4);
            formattedDateString = [year, month, dt].join(dateSeperator);
            break;
        case "yyyy/MM/dd":
            var dt = "" + dd;
            if (dt.length < 2)
                dt = '0' + dt;
            var month = "" + (M + 1);
            if (month.length < 2)
                month = '0' + month;
            formattedDateString = ["" + y, month, dt].join(dateSeperator);
            break;
    }
    var hours = "" + H;
    if (hours.length < 2)
        hours = "0" + hours;
    var minutes = "" + m;
    if (minutes.length < 2)
        minutes = "0" + minutes;
    switch (timeformat) {
        case "HH:mm":
            formattedTimeString = [hours, minutes].join(timeSeperator);
            break;
        case "H:mm":
            formattedTimeString = ["" + H, minutes].join(timeSeperator);
            break;
        case "hh:mm tt":
            var td = hours + ":" + minutes + ":00";
            formattedTimeString = this.timeConvertToAMPM(td, "hh:mm tt");
            break;
        case "h:mm tt":
            var td = hours + ":" + minutes + ":00";
            formattedTimeString = this.timeConvertToAMPM(td, "h:mm tt");
            break;
    }
    if (formattedDateString != "") {
        if (formattedTimeString != "")
            formatedDateTime = formattedDateString + " " + formattedTimeString;
        else
            formatedDateTime = formattedDateString;
    }
    else {
        if (formattedTimeString != "")
            formatedDateTime = formattedTimeString;
    }
    return formatedDateTime;
}

//convert time string to AMPM format
var timeConvertToAMPM = function (time, format) {
    var patt = new RegExp("^([01]?[0-9]|2[0-3]):?[0-5][0-9](:[0-5][0-9])?$");
    var res = patt.test(time);
    if (res) { // If time format correct
        var H = +time.substr(0, 2);
        var h = (H % 12) || 12;
        var hour = "" + h;
        var ampm = H < 12 ? "AM" : "PM";
        if (format == "hh:mm tt")
            if (hour.length < 2)
                hour = "0" + hour;
        time = hour + time.substr(2, 3) + " " + ampm;
    }
    return time;
};

Hope this will help…

Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech