Friday, April 26, 2013

How to refresh grid from an open record in MSCRM 2011

This is a simple single line of code


window.parent.opener.document.getElementById("crmGrid").control.refresh();
 
In case the above line does not work another way to achieve the same is the code of line below where we are calling the click event of the refresh button on the crm grid

window.parent.opener.document.getElementById("grid_refresh").click();


Convert from one time zone to another time zone - convert Source DateTime to UTC and will then convert UTC timezone to destination timezone code




The function below will first convert Source DateTime to UTC and will then convert UTC timezone to destination timezone code


  

# region "ConvertFromSourceTimeZoneToDestinationTimeZone"

/// <summary>
       
/// </summary>

/// <param name="sourceDateTime"></param>

/// <param name="sourceTimeZoneCode"></param>

/// <param name="destinationTimeZoneCode"></param>

/// <param name="organizationServ"></param>

/// <returns></returns>

private DateTime ConvertFromSourceTimeZoneToDestinationTimeZone(DateTime sourceDateTime, int sourceTimeZoneCode, int destinationTimeZoneCode, IOrganizationService organizationServ)



{

DateTime destinationDateTime = DateTime.UtcNow;

try



{

//Convert Source DateTime to UTC

UtcTimeFromLocalTimeRequest utcFromLocalRequest = new UtcTimeFromLocalTimeRequest();



utcFromLocalRequest.LocalTime = sourceDateTime;

utcFromLocalRequest.TimeZoneCode = sourceTimeZoneCode;

UtcTimeFromLocalTimeResponse utcFromLocalResponse = (UtcTimeFromLocalTimeResponse)organizationServ.Execute(utcFromLocalRequest);

//Convert UTC DateTime to Destination TimeZone

LocalTimeFromUtcTimeRequest localFromUtcRequest = new LocalTimeFromUtcTimeRequest();



localFromUtcRequest.UtcTime = utcFromLocalResponse.UtcTime;

localFromUtcRequest.TimeZoneCode = destinationTimeZoneCode;

LocalTimeFromUtcTimeResponse localFromUtcResponse = (LocalTimeFromUtcTimeResponse)organizationServ.Execute(localFromUtcRequest);



destinationDateTime = localFromUtcResponse.LocalTime;

}

catch (FaultException<OrganizationServiceFault>)



{

throw;



}

catch (Exception)



{

}

return destinationDateTime;



}

# endregion

Get User Local Time From UTC Time in MSCRM 2011

The following piece of code will return user's local time from utc time , the user time zone will be retrieved by another function which I have posted in another of my blogs , iam pasting the code here also for making it easy to understand
 
 
 

        private DateTime GetUserLocalTimeFromUTCTime(IOrganizationService service, DateTime utcDate, Guid userId)

        {

            Entity loggedInUser = null;

            int timeZoneCode = 0;

            DateTime returnDateTime = DateTime.UtcNow;

            try

            {

                loggedInUser = GetUserTimeZone(service, userId);

                if (loggedInUser != null && loggedInUser.Attributes.Contains("timezonecode"))

                {

                    timeZoneCode = ((int)loggedInUser.Attributes["timezonecode"]);

                }

                LocalTimeFromUtcTimeRequest request = new LocalTimeFromUtcTimeRequest();

                request.UtcTime = utcDate;

                request.TimeZoneCode = timeZoneCode;

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

                returnDateTime = response.LocalTime;

                return returnDateTime;

            }

            catch (FaultException<OrganizationServiceFault>)

            {

                //return UtcNow when the corresponding userId doesn't have any local time zone settings (for example "Network Service")

                //throw;

                return returnDateTime;

            }

            catch (Exception)

            {

                //return UtcNow when the corresponding userId doesn't have any local time zone settings (for example "Network Service")

                //throw;

                return returnDateTime;

            }

        }

 
 
 
 
        private Entity GetUserTimeZone(IOrganizationService service, Guid userId)
        {
            try
            {
 
                RetrieveUserSettingsSystemUserRequest request = new RetrieveUserSettingsSystemUserRequest();
                request.ColumnSet = new ColumnSet("timezonecode");
                request.EntityId = userId;
                RetrieveUserSettingsSystemUserResponse response = (RetrieveUserSettingsSystemUserResponse)service.Execute(request);
                return response.Entity;
            }
            catch (FaultException<OrganizationServiceFault>)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
 
 

     

How to retrieve user time zone in MSCRM 2011

Following is the piece of code that could be used to retrieve the user's timezone code.



 private Entity GetUserTimeZone(IOrganizationService service, Guid userId)

        {

            try

            {

 

                RetrieveUserSettingsSystemUserRequest request = new RetrieveUserSettingsSystemUserRequest();

                request.ColumnSet = new ColumnSet("timezonecode");

                request.EntityId = userId;

                RetrieveUserSettingsSystemUserResponse response = (RetrieveUserSettingsSystemUserResponse)service.Execute(request);

                return response.Entity;

            }

            catch (FaultException<OrganizationServiceFault>)

            {

                throw;

            }

            catch (Exception)

            {

                throw;

            }

        }

Thursday, April 25, 2013

How to color Code a grid in CRM 2011


The following code will color code the grid based on a field; I am using a field to set the value of an incoming email. The value of the field “Unread” is checked to set the color of the record to red every time a new email arrives it updates the field on the record which in turn turns the record red.

function ColorGridByNewEmail() {

   //debugger;

    var indexPriority = 0;

   // var indexSRStatus = 0;

    var iColumns = 0;

 

    if (window.document.getElementById('gridBodyTable') != null) {

        var gridBar = window.document.getElementById('gridBodyTable');

        if (gridBar != null && gridBar != "undefined") {

            var headers = gridBar.getElementsByTagName('TH');

            //Total no. of columns in the view

            iColumns = headers.length;

            for (var iL = 0; iL < headers.length; iL++) {

                var header = headers[iL];

                switch (header.innerText) {

                    case "Email":

                        indexPriority = iL;

                        break;

                    default:

                        break;

                }

            }

        }

        if (indexPriority != 0) {

            //Get the Grid records

            var oItems = window.document.getElementById('gridBodyTable');

            _iTotalRecords = oItems.rows.length - 1;

            oItems.rows[0].style.display = 'none';

            for (var i = 1; i < oItems.rows.length; i++) {

                var cellPriority = oItems.rows[i].cells[indexPriority];

                //var cellSRStatus = oItems.rows[i].cells[indexSRStatus];

                if (cellPriority != null) {

                    //Case Status = Unassigned, Response Received, and Change Request

                    //Make the grid row "RED" color

                    if (cellPriority.innerText == "Unread") {

                        oItems.rows[i].style.color = 'red';

                        for (var iHeadLoop = 0; iHeadLoop < iColumns; iHeadLoop++) {

                            if (oItems.rows[i].cells[iHeadLoop].children[0] != null && oItems.rows[i].cells[iHeadLoop].children[0] != 'undefined' && oItems.rows[i].cells[iHeadLoop].children[0] != undefined) {

                                if (oItems.rows[i].cells[iHeadLoop].children[0].children[0] != null && oItems.rows[i].cells[iHeadLoop].children[0].children[0] != 'undefined' && oItems.rows[i].cells[iHeadLoop].children[0].children[0] != undefined) {

                                    if (oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0] != null && oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0] != 'undefined' && oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0] != undefined) {

                                        if (oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0].children[0] != null && oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0].children[0] != 'undefined' && oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0].children[0] != undefined) {

                                            oItems.rows[i].cells[iHeadLoop].children[0].children[0].children[0].children[0].style.color = 'red';

                                        }

                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

 

    }

}

 

This piece of code is called by an enable/disable rule of a button placed on the ribbon “colorcode” as shown in the image below. Also we need to place the field based on which this color coding has to be done on all the views where we need to show the color coding

I am using a visual ribbon editor to call the “ColorGridByNewEmail” function on an enable/disable rule as shown in the image below.Please change the library name as per your own web resource where you place the “ColorGridByNewEmail” function.
 
 

Friday, April 12, 2013

Update record using OData and JQuery in CRM 2011


The following function could be used to update records in json/ajax.This could be useful in scenario where we want to update some records in the background

function updateRecord(id, entityObject, odataSetName) {

    //debugger;

    var jsonEntity = window.JSON.stringify(entityObject);

    // Get Server URL

    var serverUrl = Xrm.Page.context.getServerUrl();

    //The OData end-point

    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //Asynchronous AJAX function to Update a CRM record using OData

    $.ajax({

        type: "POST",

        contentType: "application/json; charset=utf-8",

        datatype: "json",

        data: jsonEntity,

        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",

        beforeSend: function (XMLHttpRequest) {

            //Specifying this header ensures that the results will be returned as JSON.

            XMLHttpRequest.setRequestHeader("Accept", "application/json");

            //Specify the HTTP method MERGE to update just the changes you are submitting.

            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");

        },

        success: function (data, textStatus, XmlHttpRequest) {

            //alert('Updated successfully');

        },

 

        error: function (XmlHttpRequest, textStatus, errorThrown) {

            if (XmlHttpRequest && XmlHttpRequest.responseText) {

                alert("Error while updating " + odataSetName + " ; Error – " + XmlHttpRequest.responseText);

            }

        }

    });

 

}

 

The above function can be called in the following manner, for eg. if I want to call this function to update a picklist/optionset value on the incident entity

var caseId = Xrm.Page.data.entity.getId();

var incidentObj = new Object();

incidentObj.fieldname_optionsettypeoffield = { Value: 1 };

updateRecord(caseId, incidentObj, "IncidentSet");

 

Note: This will require json2 and jquery1.4.1.min.js to be preloaded on your form as shown below