OData Query to retrieve records based on record Guid

To retrieve the record based on Guid, below is the small code snippet to use.

function getRecordFromGuid() {
    var resultData = null;
    var uniqueId =RecordGuid;
    var oDataEndpointUrl = "http://yourservername/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "new_tempSet?&";

    oDataEndpointUrl += "$select=new_name&$filter=new_tempid eq guid'" + uniqueId + "'";
    $.ajax({
        type: "GET",
        url: oDataEndpointUrl,
        //data: jsonAccount,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function result(data) {
            resultData = data.d.results;

        },
        async: false,
        error: function (xhr, textStatus, errorThrown) {
            errorCallback(this._errorHandler(xhr));

        }
    });

    if (resultData != null)
        return resultData;
    else
        return null;
}





You may like below posts

Improving MS CRM Performance

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

OData Query to retrieve records based on picklist value

There may a scenario to retrieve records using a picklist value throug OData query. Below is the small piece of code to retrieve the same.

function GetRecordsBasedonPicklistValue() {
    var plateType = 427345000;//Picklist value
    var oDataEndpointUrl = "http://youservername/xrmservices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "new_itemtypeSet?&";
    oDataEndpointUrl += "$select=new_name&$filter=new_picklistype/Value eq " + plateType;
    $.ajax({
        type: "GET",
        url: oDataEndpointUrl,
        //data: jsonAccount,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function result(data) {
            resultData = data.d.results;
        },
        async: false,
        error: function (xhr, textStatus, errorThrown) {
            errorCallback(this._errorHandler(xhr));
        }
    });
    if (resultData != null)
        return resultData;
    else
        return null;
}



You may like below posts

Improving MS CRM Performance

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

An Unexpected error occured while using RetrieveEntityRequest in MS CRM 2013

"An unexpected error occurred".

This error is really frustrating, this will not give any clue on why this error is occurring.

It took half day to resolve my issue. My project development server has MS CRM 2013 and SIT server has MS CRM 2013 with SP1.

On my development server, we have used RetrieveEntityRequest to read metadata of an entity and it is working fine. So we have moved the code to SIT and started throwing an error as "An unexpected error occurred".

This error is occuring because of Microsoft.Xrm.sdk.dll is older version when deployed the code on SIT server.

So to resolve the issue, we have to rebuild the code with the server version dlls and deploy it. In this case, I have taken Microsoft.Xrm.sdk.dll from SIT server, rebuild the code and deployed.

Now it is started working.

Even after you made the above changes, there are chances of your code may not work because of older version of dlls might be installed in GAC.

If this is the case, uninstall older version of dll and install newer version of dll in GAC.

Hopefully, this solution may save few people's half day time.

Happy coding.....


You may like below posts

Improving MS CRM Performance

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

Improving MS CRM Performance

Performance on MS CRM is always a crucial thing and we may follow different ways to achieve the performance thing. Below is the one more approach we can improve the performance bit more.
In IIS setting of a website where MS CRM is hosted, there we can change the Output Cache property. By changing this property to true, initially any entity record load may take bit time; later on it will open the records in much lesser time. This is quite a good approach to improve the performance.
Below screenshot explains where to change the output Cache settings

Open IIS, click on Microsoft Dynamics CRM site-> On Right side Panel click on Feature View-> Configuration Editor









































(source of below description: MSDN)
What is omitVaryStart:
Gets or sets a value indicating whether the vary header is enabled.


true if the vary header is enabled; otherwise, false. The default is false.

The vary header indicates the request-header fields that the server uses to determine which of multiple cached responses are sent in response to a client request. The default for the OmitVaryStar property is false. By default, ASP.NET sends the vary header in all POST requests, as well as in all GET-request query strings. If the OmitVaryStar is true, ASP.NET omits the vary header when returning the response for cached pages, provided that the GET request to a response is cached with no VaryByCustom property and thePOST request to a response is cached with no VaryByParam property and no VaryByCustom property.




You may like below posts

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

Performance Center in MS CRM 2013

To analyse the performance of a CRM form, SP1 of MS CRM 2013 introduced performance center. It will gives you the detailed information on how much time form is taking to load.

To open Performance Center on CRM, press  Ctrl+Shift+Q




Note: This tool only displays with CRM 2013 once you have Service Pack 1.


You may like below posts

Improving MS CRM Performance

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015


IME Mode in MS CRM

Creating OrganizationService in MS CRM

Mostly creation of an organization service can be done in two ways.

1. Using user credentails
2. Using Network credentials.

1. Creating an organization service using credentials:

            OrganizationUri = new Uri(ConfigurationManager.AppSettings["OrgURL"].ToString());
            HomeRealmUri = null;
            Credentials = new ClientCredentials();
            Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username","password","domain");
            DeviceCredentials = new ClientCredentials();
            _serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, DeviceCredentials);
            _service = (IOrganizationService)_serviceProxy;

2. Creating organization service with Network credentials.

            OrganizationUri = new Uri(ConfigurationManager.AppSettings["OrgURL"].ToString());
            HomeRealmUri = null;
            Credentials = new ClientCredentials();
            Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            DeviceCredentials = new ClientCredentials();
            _serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, DeviceCredentials);
            _service = (IOrganizationService)_serviceProxy;

Note: Generally if you are using Network credentials for creating organization service, you may not able to create the organization service because of web service or aspx pages on different servers or on different port with in the same server.

Network credentials will work only if you hosted your custom pages on same server and same port where CRM hosted.

Hosting custom pages on CRM port is unsupported in MS CRM 2013.

1. If you hosted custom pages on different port, so you have to use user credentials (1st approach) to create an organization service. If you use this approach, you may face an issue on security roles. Because you are creating an organization service using particular credentials(Service Credentials, System Administrator or any one's) security roles will work according to the credentials we have used.
2. If you hosted the custom pages on same port where MS CRM 2013 hosted, according to MS CRM 2013 it is unsupported.




You may like below posts

Improving MS CRM Performance

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

Calculated Field in Dynamics CRM 2015

So far in Dynamic CRM 2013, If we want to calculate data in different fields we have to write down our own JavaScript method to calculate it. But CRM 2015 has introduces new concept called Calculate fields.

I would like to walk you through step by step with an example on this concept.

Ex: Here I would like to calculate an employee salary with few salary components like basic, variable, deductions.

I have created Basic, Variable and Deduction fields as Decimal number like any other fields.

Here Total field should be created with bit different. CRM 2015 has Field Type along with Data Type as shown in below screen



While creating you have to set the Field Type as "Calculated" and click on Edit button, on edit button click itself it will create the field first and navigate you to Calculate field screen. This field will be looks like below.



And write down you logic there on the screen.



Here, whenever you set field type as Calculated field then it will be read only and value will be reflected on save of the form.



















Hide command bar and Navigation bar in MS CRM 2013

MS CRM 2013 has good look and feel but only the draw back is it is taking time to load a form because of Navigation bar and Command bars are taking time to load.

So, with SP1 release, Microsoft provided a feature of hiding Command bar and Navigation bar. We may get a scenarios like form doesn't require Command bar or Navigation bar. Only thing we need to do is pass below parameters on from URL as shown below.

navbar:
Controls whether the navigation bar is displayed and whether application navigation is available using the areas and subareas defined in the sitemap.
on:
The navigation bar is displayed. This is the default behavior if the navbar parameter is not used.
off :
The navigation bar is not displayed. People can navigate using other user interface elements or the back and forward buttons.
entity :
On an entity form, only the navigation options for related entities are available. After navigating to a related entity, a back button is displayed in the navigation bar to allow returning to the original record.

cmdbar:
Controls whether the command bar is displayed.
true :
The command bar is displayed. This is the default.
false :
The command bar is hidden.

IME Mode in MS CRM


While creating fields in MS CRM we come across certain type called IME Mode in form as shown below. So What is IME Mode?
















An IME is a program that enables users to enter complex characters and symbols, such as Japanese Kanji characters, using a standard keyboard.



Members
NameValueDescription
Active2Specifies that the IME mode is active.
Auto0Specifies that the IME mode is chosen automatically.
Disabled3Specifies that the IME mode is disabled.
Inactive1Specifies that the IME mode is inactive.


Note: Microsoft Dynamics CRM 2013 Update Rollup 2 

  • When you set IME mode on an attribute on an entity to ACTIVE, the IME mode is not honored
    • This occurs with Single Line of Text, Multiple Lines of Text, and other attributes that are bound to input elements or text area elements

Customize Search Bar


Search bar on any entity will works with defaults attributes set by respective view. We  can add or remove filtered columns to the view as show as below.













You may like below posts

Improving MS CRM Performance

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

Dynamics CRM 2013 Keyboard Shortcuts

Most useful short cuts in MS CRM 2013

1. Ctrl + S or Shift + F12 --> Save form
2. Alt + S --> Save and Close
3. Esc --> Cancel command, or close selected list or dialog box
4. Ctrl + D --> Delete the record (when forms are in Edit mode)
5. Ctrl + Shift +S --> Save and then open a new form (Save and New) (when forms are in Edit mode)
6. Alt + Down Arrow --> Open the lookup menu with the most recently used items in alphabetical order
7. Ctrl + Shift+ 2 --> Open the list menu (when forms are in Edit mode)
8. Ctrl + Enter --> Open a record found in lookup with forms in Read-optimized mode
9. Alt +Shift +N --> Add a step in the business process editor
10. Ctrl + Shift + 3 --> Tab to the Navigation Pane



You may like below posts

Retrieving updated Value from a Field

Using Xrm.Page.getAttribute("your field name").getValue() we can retrieve the CRM field value. But there are some scenarios, this line of code will give wrong or old value.

Ex. Write something on Subject field and click immediately on button (Webresource button), on onclick of it, try to retrieve the value of this field. It will not give you the update value. After a couple of hours effort found a way to get the updated value in this scenario.

On button click event change the focus to button click event then save the form. Then try to retrieve the field. It will give  you the updated values.

function ButtonClick()
{
Xrm.Page.ui.controls.get("new_button").setFocus();
window.Xrm.Page.data.entity.save();
Xrm.Page.getAttribute("subject").getValue()
}

Get User RoleName in MS CRM using Javascript

In MS CRM user roles plays very crucial role in project requirements. Using Javascript we can get the role of an user and write logic accordingly as per the roles.

Below is the code snippet to get role of an user. This function will returns true if the user role is 'System Administrator' or else it will returns false.

//Check login User has 'System Administrator' role
function CheckUserRole() {
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
         var userRoleId = currentUserRoles[i];
    var userRoleName = GetRoleName(userRoleId);
        if (userRoleName == "System Administrator") {
            return true;
        }
    }
    return false;
}
 
//Get Rolename based on RoleId
function GetRoleName(roleId) {
    //var serverUrl = Xrm.Page.context.getServerUrl();
    var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
    var roleName = null;
    $.ajax(
        {
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                roleName = data.d.results[0].Name;
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
        }
    );
    return roleName;
}

Update record using OData in MS CRM

One of important and difficult thing I have faced was updating record through OData. So I would like to give you a small code snippet which I am using for update.

Ex: Assume that I have to update name and salary of an employee record. So my code snippet for this scenario would be like below.

var updateEmpRecord = new Object();
                updateEmpRecord.fullname = 'Steve Smith';
                updateEmpRecord.new_age = '28';
                var jsonEntity = window.JSON.stringify(updateEmpRecord);
                var empGuid="DCD5DBFB-0666-DC11-A%D9-0003FF9CE217";
                var ODATA_ENDPOINT="http://" + window.parent.location.host + "/" + window.parent.Xrm.Page.context.getOrgUniqueName() + "/XRMServices/2011/OrganizationData.svc/";
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    url: ODATA_ENDPOINT + "/new_employeeSet" + "(guid'" + empGuid + "')",
                    data: jsonEntity,
                    beforeSend: function (XMLHttpRequest) {
                        //Specifying this header ensures that the results will be returned as JSON.
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                        XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
                    },
                    success: function (data, textStatus, XmlHttpRequest) {
                        //write your logic
                    },
 
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
 
                    }
 
                });

Retrieve Host and Organization name dynamically in MS CRM through JavaScript

While we are writing any OData query in MS CRM, we have to retrieve the host and orgnization urls dynamically so that when ever code moves to staging or production, code will works withoug any modifications.

To retrieve host :

var host = location.host;

Organization Name:

var org= Xrm.Page.context.getOrgUniqueName();

Bulk Insert and Bulk Update in MS CRM

Create a record and update a record is very crucial in CRM. There may be a scenario where we need to create or update no. of records at a time. Rather than doing that individually we can do that as Bulk with the below process.

Ex: Consider I need to create 10 records at a time for a requirement. So we need to add those 10 entities to EntityCollection..

EntityCollection entitiesToCreate = new EntityCollection(); //Assume that i have added 10 entites to this collection

var multipleInsertRequest = new ExecuteMultipleRequest()
{
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

// Add a CreateRequest for each entity to the request collection.
foreach (var entity in entitiesToCreate.Entities)
{
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleInsertRequest.Requests.Add(createRequest);
}

ExecuteMultipleResponse multipleInsertResponse = (ExecuteMultipleResponse)service.Execute(multipleInsertRequest );


Similarly to update multiple records:

EntityCollection entitiesToUpdate = new EntityCollection(); //Assume that i have added 10 entites to this collection

var multipleUpdateRequest = new ExecuteMultipleRequest()
                {
                    // Assign settings that define execution behavior: continue on error, return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    },
                    // Create an empty organization request collection.
                    Requests = new OrganizationRequestCollection()
                };

                // Add a UpdateRequest for each entity to the request collection.
                foreach (var entity in entitiesToUpdate.Entities)
                {
                    UpdateRequest updateRequest = new UpdateRequest { Target = entity };
                    multipleUpdateRequest.Requests.Add(updateRequest);
                }

                // Execute all the requests in the request collection using a single web method call.
                ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleUpdateRequest);


Associate and Disassociate Many to Many relationship records using C# in Microsoft Dynamics CRM 2011

Below code used to associate and disassociate records for Many to Many relationship through C#.

For ex: If there we have created Many to Many relationship between Contact and Account. The association of records will be like below.

                   
                    AssociateRequest request = new AssociateRequest();
                    EntityReference moniker1 = new EntityReference("contact", new Guid(contactGuid));
                    EntityReference moniker2 = new EntityReference("account", new Guid(businessGuid));
                    EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
                    relatedEntities.Add(moniker1);
                    request.Target = moniker2;
                    request.RelatedEntities = new EntityReferenceCollection { moniker1 };
                    request.Relationship = new Relationship("crisp_account_contact");
                    service.Associate(moniker2.LogicalName, moniker2.Id, request.Relationship, relatedEntities);

To Disassociate the record:

            AssociateRequest request = new AssociateRequest();
            EntityReference moniker1 = new EntityReference("contact", new Guid(contactGuid));
            EntityReference moniker2 = new EntityReference("account", new Guid(businessGuid));

            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
            relatedEntities.Add(moniker1);
            request.Target = moniker2;
            request.RelatedEntities = new EntityReferenceCollection { moniker1 };
            request.Relationship = new Relationship("crisp_account_contact");
            service.Disassociate(moniker2.LogicalName, moniker2.Id, request.Relationship, relatedEntities);

To retrieve the records associated between Account and Contact use fetchXml as below.
string fetchXml = @"<fetch version='1.0' " +
                           "output-format='xml-platform' " +
                           "mapping='logical'>" +
                           "<entity name='contact'>" +
                           "<filter type='and'>" +
                               "<condition attribute='statecode' operator='eq' value='0'/>" +
                           "</filter>" +
                           "<link-entity name='crisp_account_contact' from='contactid' to='contactid' visible='false' intersect='true'>" +
                             "<filter type='or'>" +
                               "<condition attribute='accountid' operator='eq' value='" + businessId + "'/>" +
                             "</filter>" +
                          "</link-entity>" +
                          "</entity>" +
                           "</fetch>";

           EntityCollection  entityCollection = service.RetrieveMultiple(new FetchExpression(fetchXml));



You may like below posts

Improving MS CRM Performance

Performance Center in MS CRM 2013

date and time field behavior in MS CRM

Upsert in MSCRM

Locking mechanism in MS CRM

Ticker Symbol Field in MS CRM

Themes in MS CRM

Enable Tracing in MS CRM

Calculated Field in Dynamics CRM 2015

IME Mode in MS CRM

Use JavaScript in Dynamics CRM to Set the Value in Read-Only Field on a Form

By default CRM will not allow you save the data assigned to readonly field. For that we have use below javascript code snippet to make this work.

For ex new_amount is the readonly field in your form. So to save the data assigned to it use the below code snippet

function SetSubmitForAmountField()
{
Xrm.Page.getAttribute("new_amount").setSubmitMode("always");
}


You have to call this function on onsave of your form as shown below.

Featured Post

Improving MS CRM Performance

Performance on MS CRM is always a crucial thing and we may follow different ways to achieve the performance thing. Below is the one more a...