Monday, July 28, 2014

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();

Tuesday, July 8, 2014

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