Monday 2 December 2013

Read Sub-Grid cell value MS CRM 2013 !!!

Here is sample code to get sub grid cell value in MS CRM 2013.

function GetSubGridCellValues() {
    if (document.getElementById("SubGridName")) {
        var grid = document.getElementById("SubGridName").control;
        var ids = gridControl.get_allRecordIds();
        for (i = 0; i < ids.length; i++) {
            alert(gridControl.getCellValue('fullname', ids[i]));
        }
    }
    else {
        setTimeout("GetSubGridCellValues();", 2500);
    }


}

Saturday 23 November 2013

Attach OnClick event in Sub grid Records MS CRM 2013 Using JavaScript !!!

Sometimes we have requirements to attach click event to sub-grid. So we could read selected record data and do the stuffs.

Here is sample code to attach click event to sub grid :

function ReadSelectedSubGridRecords() {
    if (document.getElementById("SubGridName")) {
        var grid = document.getElementById("SubGridName").control;
        for (var rowNo = 0; rowNo < grid.get_selectedRecords().length; rowNo++)
            alert(grid.get_selectedRecords()[rowNo].Name);
    }
}

function Form_OnLoad() {
    if (document.getElementById("SubGridName")) {
        var grid = document.getElementById("SubGridName");
        // Google chrome
        if (grid.addEventListener) {
            grid.addEventListener('click', ReadSelectedSubGridRecords, false);
            // IE
        } else if (grid.attachEvent) {
            grid.attachEvent('onclick', ReadSelectedSubGridRecords);
        }

    }
    else {
        setTimeout("Form_OnLoad();", 2000);
    }
}

Attach Form_OnLoad function to form OnLoad event handler !!!

Read Selected Sub grid Records MS CRM 2013 Using JavaScript !!!

Sometimes we have requirements to play with selected sub-grid records using client side scripting.
Here is same code to read selected sub-grids records :

function ReadSelectedSubGridRecords() {
        if (document.getElementById("SubGridName")) {
        var grid = document.getElementById("SubGridName").control;
        for (var row = 0; row < grid.get_selectedRecords().length; row++)
            alert(grid.get_selectedRecords()[row].Name);
    }
}


Read SubGrid Records MS CRM 2013 using JavaScript !!!

Many times we have requirements to read sub grid records and do subtotal or some others stuff with grid data. Here is same code to retrieve entire rows and columns from SubGrid.

function RetrieveSubGridRecords() {
    if (document.getElementById("SubGridName")) {
        var grid = document.getElementById("SubGridName").control;
        for (var rowNo = 0; rowNo < grid.GetRecordsFromInnerGrid().length; rowNo++)
            for (var cellNo = 0; cellNo < grid.GetRecordsFromInnerGrid()[rowNo][3].cells.length; cellNo++)
                alert(grid.GetRecordsFromInnerGrid()[rowNo][3].cells[cellNo].outerText);
    }
    else {
        setTimeout("RetrieveSubGridRecords();", 2500);
    }

}


Hope it helps. J

Wednesday 13 November 2013

Retrieve account record based on account Id using SOAP request MS CRM 2011 !!!

Here is the same to code to get account record based on account Id using SOAP request.

function ExecuteRequest(_XML, Message) {
try {
var _ResultXML = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", Xrm.Page.context.getServerUrl() + "/XRMServices/2011/Organization.svc/web", false);
xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/" + Message);
xmlhttp.send(_XML);
_ResultXML = xmlhttp.responseXML;
var errorCount = _ResultXML.selectNodes('//error').length;
if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
_ResultXML = null;
return _ResultXML;
}
else {
return _ResultXML;
}
}
catch (Err) {
alert(Err);
return;
}
}

function GetAccountName() {
var request = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<s:Body>" +
"<Retrieve xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
"<entityName>account</entityName>" +
"<id>44b1719c-4440-e311-8fae-00221960bc47</id>" +
"<columnSet xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
"<a:AllColumns>false</a:AllColumns>" +
"<a:Columns xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
"<b:string>name</b:string>" +
"<b:string>accountnumber</b:string>" +
"</a:Columns>" +
"</columnSet>" +
"</Retrieve>" +
"</s:Body>" +
"</s:Envelope>";
var _ResultXML = ExecuteRequest(request, "Retrieve");

var _AccountName = _ResultXML.selectSingleNode("//a:Attributes").selectSingleNode("//b:value").text;
return _AccountName;
}

You could call GetAccountName function to get account name like :
Var _Name= GetAccountName();


You could also pass accountId as parameter to GetAccountName function.

Thursday 31 October 2013

Read user privileges using RetrieveUserPrivilegesRequest through JavaScript !!!

There is a very common requirement in dynamics CRM to hide some optionset values based on some other entity’s privileges. We have a requirement to hide approval option from status field in case entity if current user doesn’t have write permission for waiver rights entity.

Here is code sample :

// function call
RetrieveUserPrivileges("37DC5BE0-B813-E311-9A5C-00221960BC47", "prvWriteNew_waiverrights");

// function definition
function RetrieveUserPrivileges(_UserId, _PrivilegeName) {
    try {
        var _RequestMain = "";
        _RequestMain += "      <request i:type=\"b:RetrieveUserPrivilegesRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
        _RequestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        _RequestMain += "          <a:KeyValuePairOfstringanyType>";
        _RequestMain += "            <c:key>UserId</c:key>";
        _RequestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + _UserId + "</c:value>";
        _RequestMain += "          </a:KeyValuePairOfstringanyType>";
        _RequestMain += "        </a:Parameters>";
        _RequestMain += "        <a:RequestId i:nil=\"true\" />";
        _RequestMain += "        <a:RequestName>RetrieveUserPrivileges</a:RequestName>";
        _RequestMain += "      </request>";

        // Get privilegeid based on Name
        var d = fncLookupValueFromEntity("privilege", "name", _PrivilegeName, "", "", "privilegeid");
        var flag = false;
        if (d != null) {

            var _RestultXml = XrmServiceToolkit.Soap.Execute(_RequestMain);

            if ($(_RestultXml).find("b\\:RolePrivilege").length > 0) {

                $(_RestultXml).find("b\\:RolePrivilege").each(function () {
                    //inner loop
                    $(this).find("b\\:PrivilegeId").each(function () {

                        var _PrivilegeId = $(this).text();

                        if (_PrivilegeId.toString().toLowerCase() == d.toLowerCase()) {
                            flag = true;

                        }
                    });
                });
            }
            else if ($(_RestultXml).find("RolePrivilege").length > 0) {

                $(_RestultXml).find("RolePrivilege").each(function () {
                    //inner loop
                    $(this).find("PrivilegeId").each(function () {

                        var _PrivilegeId = $(this).text();

                        if (_PrivilegeId.toString().toLowerCase() == d.toLowerCase()) {
                            flag = true;
                        }

                    });
                });


            }
            // If there user don't have Privilege remove status option
            flag == false && Xrm.Page.ui.controls.get("statuscode").removeOption(100000)

        }




    }
    catch (ex) {
        alert(ex.message);
    }

}


function fncLookupValueFromEntity(a, b, c, d, e, g) {
    var m = "";
    "" != d && (m = "<condition attribute='" + d + "' value='" + e + "' operator='eq'/>");
    var fetchXml = "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
                      "<entity name='" + a + "'>" +
                      "<attribute name='" + g + "'/>" +
                      "<filter type='and'>" +
                      "<condition attribute='" + b + "' value='" + c + "' operator='eq'/>" + m +
                      "</filter></entity></fetch>";

    a = XrmServiceToolkit.Soap.Fetch(fetchXml);

    if (a.length > 0) {
        if (a[0].attributes[g] != null) {
            return a[0].attributes[g].value;
        }
    }
    return null
}


Note: Please attach Jquery web resource/library on Form libraries list.

Wednesday 23 October 2013

Show closed and open activities counter in left navigation !!!

One of your client want to have activities counters in record left navigation for activities and closed activities.

Code sample:

function ActivitiesRecordCounter() {

if (formType != CREATEFORM) {
// Get opened record all activites
var fetchXml = "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
"<entity name='activitypointer'>" +
"<attribute name='activitytypecode'/>" +
"<attribute name='subject'/>" +
"<attribute name='statecode'/>" +
"<filter type='and'>" +
"<condition attribute='regardingobjectid' value='" + Xrm.Page.data.entity.getId() + "' operator='eq'/>" +
"</filter></entity></fetch>";

var _Activities = XrmServiceToolkit.Soap.Fetch(fetchXml);
var c = 0;
var d = 0;
// Count all activites
for (var i = 0; i < _Activities.length; i++) {
switch (_Activities[i].attributes.statecode.formattedValue) {
case "Open":
c++;
break;
case "Scheduled":
c++;
break;
case "Completed":
d++;
break;
case "Canceled":
d++;
}
}
null != Xrm.Page.ui.navigation.items.get("navActivities") && Xrm.Page.ui.navigation.items.get("navActivities").setLabel(Xrm.Page.ui.navigation.items.get("navActivities").getLabel() + '(' + c + ')');
null != Xrm.Page.ui.navigation.items.get("navActivityHistory") && Xrm.Page.ui.navigation.items.get("navActivityHistory").setLabel(Xrm.Page.ui.navigation.items.get("navActivityHistory").getLabel() + '(' + d + ')');
}
}


Attach the above function to Onload event Handler.








.

Please download XrmServiceToolkit from CodePlex.











Tuesday 22 October 2013

Read all Notes having attachment related to case entity !!!


Here is the sample code.

public static EntityCollection GetAllNotes(Guid CaseId, IOrganizationService _service)
{
EntityCollection results = null;
try
{

QueryExpression _Query = new QueryExpression
{
EntityName = "annotation",
ColumnSet = new ColumnSet("filename", "documentbody", "filesize", "mimetype","isdocument"),
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,

Conditions =
{
new ConditionExpression
{
AttributeName = "objectid",
Operator = ConditionOperator.Equal,
Values = { CaseId }
},
new ConditionExpression
{
AttributeName = "isdocument",
Operator = ConditionOperator.Equal,
Values = { true }
},
}
}
};

results = _service.RetrieveMultiple(_Query);

}
catch (Exception Ex)
{
Console.Write(Ex.Message);
if (Ex.InnerException != null)
{
Console.WriteLine(Ex.InnerException.Message);
Console.ReadLine();
}
}
return results;

}