Author Archives: Vikranth

About Vikranth

Vikranth Pandiri has been working with Microsoft Dynamics CRM since v4.0. He has over 10 years of experience in Microsoft CRM, Unified Service Desk and related technologies. He is passionate about learning Microsoft related technologies and interested in participating Microsoft CRM community related activities.

How To – Series 6: How To Use “CustomRule” to Enable/Disable HomePageGrid Buttons- CRM 2011

 

In the earlier post here we have seen how to use <ValueRule> to retrieve a field value from the CRM form and Enable/Disable Custom Button based on that value. What if we want to do the same thing with “HomePageGrid” also like based on a particular value from the selected record in the Grid, Enable/Disable a Custom Button? Can we use <ValueRule> for the same?? The answer is big “No…!!!” Instead, we can use <CustomRule> wherein we can call a JavaScript function to do the required stuff.
For this post also, I am doing required stuff for “HomePageGrid” on top of the following SDK walkthrough: Walkthrough: Add a Custom Button to an Existing Group for a Specific Entity . Below is the result of SDK sample for Account Home Page Grid:
Custom button “Hello Ribbon” will be enabled when only one Account record is selected. Following is the code snippet for that:
<EnableRule Id=”Sample.account.grid.OneSelected.EnableRule”>
  <SelectionCountRule AppliesTo=”SelectedEntity” Maximum=”1″ Minimum=”1″ />
</EnableRule>
Now, let’s consider a scenario where we want to enable the “Hello Ribbon” button when only one Account record is selected and the selected record should have “Fax” value. We will see what are all the steps we need to follow to accomplish this.
Step 1: Retrieve the selected Item’s GUID value
Step2: Use the resultant GUID value to retrieve “Fax” field value using “REST” or “SOAP” calls
Step 1:
Inorder to retrieve selected item’s GUID value, we can use the following:
<CrmParameter Value=”SelectedControlSelectedItemCount” />
<CrmParameter Value=”FirstSelectedItemId” />
The first one returns an array of GUIDs for the selected items and the latter one returns GUID of the first item in the selected items.
<CrmParameter Value=”SelectedControlAllItemCount” />
Using this one we can get a count of selected items.
Step 2:
Use <CustomRule> to call java script function by passing the selected GUID value and it’s count. Following is the code snippet to do that:
            <EnableRule Id=”Sample.account.grid.SelectedRowValueCheck.EnableRule”>
              <CustomRule FunctionName=”IsExist” Library=”$webresource:new_CheckFieldValue.js”>
                <CrmParameter Value=” SelectedControlSelectedItemCount” />
                <CrmParameter Value=”FirstSelectedItemId” />
              </CustomRule>
            </EnableRule>
Here, “FunctionName” refers to Java Script method and “Library” refers to Java Script web resource. And the <CrmParameter> defined will pass it’s returned Value to the <CustomRule>’s function as parameters.
Let’s go define “IsExist” method in “new_CheckFiledValue.js” web resource as follows:
function IsExist(rowscount, firstselectedid) {
    if (rowscount == 1) {
        var ValueExist = ReturnValue(firstselectedid);
        return ValueExist;
    }
    else {
        return false;
    }
}
Observe the “IsExist” function’s prototype. It has two parameters. The first one “rowscount” refers to first <CrmParameter> and the second one referes to second <CrmParameter>. In the definition, I am calling a method “ReturnValue” with “firstselectedid” as the parameter when “rowscount” is 1. If not, returning “false”. In the “ReturnValue” method I am planning to retrieve “Fax” field value based on the GUID from the “firstselectedid” parameter using REST based web service call.
function ReturnValue(firstselectedid) {
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
    var ODATA_Filter = “/AccountSet?$select=Fax&$filter=AccountId/Id eq (guid'” + firstselectedid + “‘)”;
    var jsonEntity = window.JSON.stringify(CRMObject);
    $.ajax({ type: “GET”,
        contentType: “application/json; charset=utf-8”,
        datatype: “json”,
        url: serverUrl + ODATA_ENDPOINT + ODATA_Filter,
        beforeSend: function (XMLHttpRequest) {
             XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
        },
        success: function (data, textStatus, XmlHttpRequest) {
            var faxValue = data[“d”];
            if (faxValue != null)
                return true;
            else
                return false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            return false;
        }
    });
}
This function returns “True” if “Fax” field has value else “False”.
PS: We need to refer “JQuery” and “JSON” libraries in our Java Script web resource to use REST end points. However, I am still struggling to find out how to refer “JQuery” and “JSON” libraries in our Java script web resource as we are not calling the functions as part of any event. Right now, I am working on an “Online” deployment. If it is On-Premise environment, we could easily call “JQuery” and “JSON” libraries as external files the same way we used to do in CRM 4.0. Anyways, I will come back here once I find a solution.
Hope it helps in giving a basic idea on how to use <CustomRule> and how to Enable or Disable HomePageGrid’s Button based on a condition.

How To – Series 5: How To Use “ValueRule” and “OrRule” in Ribbon Customizations – CRM 2011

 

Hello everyone,

 

This is my first blog post on Dynamics CRM 2011. I have been going through Dynamics CRM 2011 SDK and it has fantastic stuff to learn. I went through the Walkthrough: Add a Custom Button to an Existing Group for a Specific Entity Ribbon customization stuff in the SDK and able to do it. In that walkthrough, by using “CrmClientTypeRule” and “FormStateRule” rules custom button on the Form(not HomePageGrid)  has been enabled only for “Web Client” and for “Existing Records”. This is the result of SDK sample:

Now, In this post I would like to add few more things on how to use “ValueRule” and “OrRule” rules with “EnableRules”.

Lets consider, if we want to enable the Custom button only when a specific filed on the form has a value. In that scenario, we can use “ValueRule” which can retrieve a specific field value on the form. Assume that we have to show Custom button only when “Fax” filed has value. In that case we can think of two approaches. One is, if “Fax” field is null then disable the Custom Button and the other one is, if “Fax” field has “anyvalue” then “Enable” the custom button. However, for ribbon customizations we have only “EnableRule”. And certainly “EnableRule” only works with “Equality” condition. So, In order to support different conditions we have one useful attribute called “InvertResult” which negates the result(Instead of looking for “not equal” condition, go with equal condition and use “InvertResult”).

 

Following the piece of code we need to place it under //RibbonDiffXml/RuleDefinitions/EnableRules/EnableRule/

 

            <EnableRule Id=”Sample.account.form.CheckFaxValue.EnableRule”>

<ValueRule Field=”fax” Value=”null” InvertResult=”true”/>
</EnableRule>

Here I have used unique Id for the “EnableRule” which can be used to refer in the “CommandDefinition”. For the “ValueRule”, I have defined three attributes. “Field” refers to the schema name of particular field on the form from which we are trying to retrieve a value. “Value” attribute will hold user given value which will be checked against “Field” attribute’s value for equality. In our case, I decided to go with “null” check condition and “InvertResult”.  So, I have given “null” as the value and for the third attribute “InvertResult”, I have given “true” as the value. Whenever “Fax” filed has value then the returned value from “ValueRule” is “True”(as we are using Invert Result) and “False” if it is “null”.

 

After placing above code, refer the id in the following location //RibbonDiffXml/CommandDefinitions/CommandDefinition/EnableRules as

<EnableRule Id=”Sample.account.form.CheckFaxValue.EnableRule”/>

Now, export the solution and publish it. Below will be the result when Fax doesn’t have any value:

And when “Fax” field has a value:

That’s cool. With single line additional code we can enable/disable custom button based on field value.

Now, I thought of checking with “Option Set” fields and want to whether it considers “Selected Value” or “Selected Text”. Certainly, it is “Selected Value” by default. Below is the piece of code I wrote:

<EnableRule Id=”Sample.account.form.CheckContactValue.EnableRule”>
<ValueRule Field=”address1_addresstypecode” Value=”1″/>
</EnableRule>

<EnableRule Id=”Sample.account.form.CheckFaxValue.EnableRule”>
<ValueRule Field=”fax” Value=”null” InvertResult=”true”/>
</EnableRule>

And
<EnableRule Id=”Sample.account.form.CheckFaxValue.EnableRule”/>
<EnableRule Id=”Sample.account.form.CheckContactValue.EnableRule”/>

Below is the result:

When “Address Type” is selected as “Bill To(Value:1):

 

And when other than “Bill To” is selected:

 

This is fine and as expected. And one more thing we need to observe “EnableRule” placed under  RibbonDiffXml/CommandDefinitions/CommandDefinition/EnableRules are by default uses “and” filter. If I remove “Fax” filed value and keep “Bill To” as the “Address Type”, the custom button will be disabled. Check the below screenshot:

 

So, what if we want to go with “or” condition??? Certainly, we do have “OrRule” which can be used for this purpose. Instead of having two separate “EnableRule” for each “ValueRule”, we can have one “EnableRule” with collection of “ValueRule” under “OrRule”. Below is the piece of code we need to have under //RibbonDiffXml/RuleDefinitions/EnableRules/EnableRule/:

<EnableRule Id=”Sample.account.form.OrRule.EnableRule”>
<OrRule>
<Or>
<ValueRule Field=”fax” Value=”null” InvertResult=”true”/>
</Or>
<Or>
<ValueRule Field=”address1_addresstypecode” Value=”1″/>
</Or>
</OrRule>
</EnableRule>

And refer the “Id” at the following: //CommandDefinitions/CommandDefinition/EnableRules
<EnableRule Id=”Sample.account.form.OrRule.EnableRule”/>

Below is the result with “OrRule”:

 

Now, the question arises what if I have complex query and based on its result custom button should be enabled/disabled??? The answer is, we do have one more feature called “CustomRule” using which we can call a Java Script function and based on the result(should be Boolean) we can enable/disable a custom button. In this coming post I will show how to use that Rule and in which scenarios it will be more useful.

This post gives basic idea on how to use “ValueRule” and “OrRule” in Ribbon Customizations. Hope it helps…!!! J

How To – Series 4: How to make an Associated View IFrame Mandatory

Sometimes, we came across situations to make an Associated View IFrame to be mandatory. However, it is very easy to implement. There are two approaches. First one is, using Java Script to call a web service and check whether current record has at least one associated record. And the second approach is just check whether an IFrame which is used to display associated records has at least one record in it’s grid. The latter approach is very easy to implement and here we go:
1.       In the onSave event of crmForm, just check how many records the IFrame grid has
2.       If the count is less than one, cancel the Save event and alert the user
3.       Set the focus to the “Add Existing Button” of the crmGrid.
function ValidateIFrame()
{
if (crmForm.all.IFRAME_ MyIFrame.readyState == “complete”)
{
if (document.frames(“IFRAME_ MyIFrame”).document.all[‘crmGrid’].InnerGrid.NumberOfRecords < 1)
{
event.returnValue=false;
alert(“Please Select Records”);
var oaddexist=document.frames(‘IFRAME_ MyIFrame’).document.getElementById(‘<id of the add existing button>’);
if(oaddexist)
{
oaddexist.focus();
}
}
}
}
}
if(crmForm.all.IFRAME_MyIFrame)
{
ValidateIFrame();
}

Hope it helps…

Thanks
Vikranth P.

How To – Series 3: How to bulk Activate/Reactivate Dynamics CRM Records using CRM Update Web Service in Java Script

 Today I wish to share with you the frequently needed functionality “how to bulk Activate/Reactivate records on ISV Toolbar button click”.  This involves following simple steps to be performed.
1.       Creating an ISV button on the crmGrid
2.       Retrieving selected record’s GUIDs
3.       Updating the state of the selected records using CRM Update Service
Lets start with creating a Toolbar button on CRM grid. It is simple and straight forward. Just add following lines of code to the respective entity in the ISV.Config.

1.       Creating an ISV button on the “Lead” entity’s crmGrid
<Entity name=”lead”>
          <ToolBar ValidForCreate=”0″ ValidForUpdate=”1″>
            <Button Icon=”/_imgs/ico_18_debug.gif” JavaScript=”alert(“Your JavaScript code will be here”)”>
              <Titles>
                <Title LCID=”1033″ Text=”Reactivate” />
              </Titles>
              <ToolTips>
                <ToolTip LCID=”1033″ Text=”Reactivate” />
              </ToolTips>
            </Button>
          </ToolBar>
</Entity> />

2.       Retrieving selected record’s GUIDs
var selectedrecords = document.all[‘crmGrid’].InnerGrid.SelectedRecords;
var selectedItems = new Array(selectedrecords.length);
for (var r=0; i < selectedrecords.length; i++)
{
 selectedItems[r] = selectedrecords [r][0];
}
                Selectedrecords[r][0] returns guid of the respected selected records
3.       Updating the state of the selected records using CRM Update Service
In order to change/set state of the “Lead” record we have to use “SetStateLeadRequest” class which has following fields EntityId, LeadState and LeadStatus. We need to pass an instance of this class as a request parameter to Execute() method. Check the possible state and status values for “Lead” entity in msdn documentation here
The possible state and status code for “Lead” entity in our requirement is “Open” and “New/Contacted”. We can also give statuscode as “-1” so that respective statuscode will be taken as required.
Below is the MS CRM Update Web Service Method code to reactivate closed leads
var xml = &apos;&apos; +
 &apos;&lt;?xml version=&apos;1.0&apos; encoding=&apos;utf-8&apos;?&gt;&apos; +
 &apos;&lt;soap:Envelope xmlns:soap=&apos;http://schemas.xmlsoap.org/soap/envelope/&apos;
 xmlns:xsi=&apos;http://www.w3.org/2001/XMLSchema-instance&apos;
 xmlns:xsd=&apos;http://www.w3.org/2001/XMLSchema&apos;&gt;&apos;
 +  GenerateAuthenticationHeader()
  + &apos; &lt;soap:Body&gt;&apos;
  +  &apos; &lt;Execute xmlns=&apos;http://schemas.microsoft.com/crm/2007/WebServices&apos;&gt;&apos; +
 &apos; &lt;Request xsi:type=&apos;SetStateLeadRequest&apos;&gt;&apos; + &apos; &lt;EntityId&gt;&apos;+<selectedItemGUID>+&apos;&lt;/EntityId&gt;&apos; + &apos; &lt;LeadState&gt;Open&lt;/LeadState&gt;&apos; + &apos; &lt;LeadStatus&gt;-1&lt;/LeadStatus&gt;&apos; + &apos; &lt;/Request&gt;&apos; + &apos; &lt;/Execute&gt;&apos; + &apos; &lt;/soap:Body&gt;&apos; + &apos;&lt;/soap:Envelope&gt;&apos; + &apos;&apos;;
 var xmlHttpRequest = new ActiveXObject(&apos;Msxml2.XMLHTTP&apos;);
 xmlHttpRequest.Open(&apos;POST&apos;,&apos;/mscrmservices/2007/CrmService.asmx&apos;, false);
 xmlHttpRequest.setRequestHeader(&apos;SOAPAction&apos;,&apos;http://schemas.microsoft.com/crm/2007/WebServices/Execute&apos;);
 xmlHttpRequest.setRequestHeader(&apos;Content-Type&apos;, &apos;text/xml; charset=utf-8&apos;);
 xmlHttpRequest.setRequestHeader(&apos;Content-Length&apos;, xml.length);
 xmlHttpRequest.send(xml);
 var resultXml = xmlHttpRequest.responseXML;
Here I am setting SetStateLeadRequest’s EntityId to selected record’s GUID, LeadState to Open and LeadStatus to -1. This code snippet will does reactivate the specified GUID Lead record.
Now, finally we need to wire above three steps code together so that selected grid records will be reactived when crm grid toolbar’s button is clicked. Below is the final version of the code which you can directly use it in your ISV.config file. Here I kept CRM Update webservice code snippet inside the for loop of selected grid items so that update web service will be called with each selected record’s GUID.
<Entity name=”lead”>
<Grid>
<MenuBar>
<Buttons>
<Button Icon=”/_imgs/ico_18_debug.gif” JavaScript=”var a = document.all[‘crmGrid’].InnerGrid.SelectedRecords; var selectedItems = new Array(a.length); for (var i=0; i &lt; a.length; i++) { selectedItems[i] = a[i][0]; var xml = &apos;&apos; + &apos;&lt;?xml version=&apos;1.0&apos; encoding=&apos;utf-8&apos;?&gt;&apos; + &apos;&lt;soap:Envelope xmlns:soap=&apos;http://schemas.xmlsoap.org/soap/envelope/&apos; xmlns:xsi=&apos;http://www.w3.org/2001/XMLSchema-instance&apos; xmlns:xsd=&apos;http://www.w3.org/2001/XMLSchema&apos;&gt;&apos; + GenerateAuthenticationHeader() + &apos; &lt;soap:Body&gt;&apos; + &apos; &lt;Execute xmlns=&apos;http://schemas.microsoft.com/crm/2007/WebServices&apos;&gt;&apos; + &apos; &lt;Request xsi:type=&apos;SetStateLeadRequest&apos;&gt;&apos; + &apos; &lt;EntityId&gt;&apos;+selectedItems[i]+&apos;&lt;/EntityId&gt;&apos; + &apos; &lt;LeadState&gt;Open&lt;/LeadState&gt;&apos; + &apos; &lt;LeadStatus&gt;-1&lt;/LeadStatus&gt;&apos; + &apos; &lt;/Request&gt;&apos; + &apos; &lt;/Execute&gt;&apos; + &apos; &lt;/soap:Body&gt;&apos; + &apos;&lt;/soap:Envelope&gt;&apos; + &apos;&apos;; var xmlHttpRequest = new ActiveXObject(&apos;Msxml2.XMLHTTP&apos;); xmlHttpRequest.Open(&apos;POST&apos;,&apos;/mscrmservices/2007/CrmService.asmx&apos;, false); xmlHttpRequest.setRequestHeader(&apos;SOAPAction&apos;,&apos;http://schemas.microsoft.com/crm/2007/WebServices/Execute&apos;); xmlHttpRequest.setRequestHeader(&apos;Content-Type&apos;, &apos;text/xml; charset=utf-8&apos;); xmlHttpRequest.setRequestHeader(&apos;Content-Length&apos;, xml.length); xmlHttpRequest.send(xml); var resultXml = xmlHttpRequest.responseXML;} window.crmGrid.Refresh();”>
<Titles>
<Title LCID=”1033″ Text=”Reactivate” />
</Titles>
<ToolTips>
<ToolTip LCID=”1033″ Text=”Reactivate” />
</ToolTips>
</Button>
</Buttons>
</MenuBar>
</Grid>
</Entity>
Hope it helps you…
Vikranth P

How To – Series 2: How to make Phone Number field as CTI integrable or make IFrame look alike Label on Crm Form

There are situations, where you want to display an IFrame which looks like label on crm form. These type of implementations sometimes targets to have CTI integrations with them. Here I want to share with you one of the approaches to implement that. Below is the screenshot of what actually I want to get finally:
Here I am displaying Business phone of the contact in an IFrame which looks like a label on the form.
1.       Create an HTML page with style properties set to as follows:
<html>
<body style=”background-color: #eaf3ff; font-size:0.7em; font-family:Tahoma, Verdana, Arial; font-style:normal”>
</body>
</html>
Here, I am setting background color of the HTML page to be default CRM form’s color(i.e. #eaf3ff), font size to 0.7em(em is preferable than px for IE) and font family to be CRM form’s default i.e Tahoma, Verdana, Arial. So that, our HTML form which will become source for the IFrame will look alike as Crm Fom.
2.       Deploy above HTML page to ISV folder(ISVContactSampleAppBusinessPhone.html).
3.       Create a Section in the crmForm with formatting properties as:
i.                    Layout:  Fixed-width Column
ii.                   Column Format: Two columns(1:1)
So that we can make our IFrame to occupy only one column in the crm form instead entire row.
4.       Create an IFrame and name it as IFRAME_MyBusinessPhone with the following properties
i.                     URL: ISVContactSampleAppBusinessPhone.html
ii.                   Label it as MyBusinessPhone and check it to display label on the form
iii.                  Select Number of rows as “1” and uncheck “Automatically expand to use available space” so that IFrame occupies only one row.
iv.                 Select scrolling as “Never” and uncheck to “Display Border”.
v.                   Add this IFrame to earlier created section.
5.       Go to form onLoad event and add following code:
if(crmForm.all.telephone1.DataValue!=null)
{
document.getElementById(‘IFRAME_MyBusinessPhone_d’).innerHTML='<div style=”margin-top:2px; margin-left:2px”>’+crmForm.all.telephone1.DataValue+'</div>’;
}
else
{
document.getElementById(‘IFRAME_ MyBusinessPhone _d’).innerHTML='<div style=”margin-top:2px; margin-left:2px”></div>’;
}
Here I am giving div style margin as 2px so that it will be in align with IFrame’s label.
Finally, a simple IFrame and a HTML page with few properties set to will make a Magic….!!!!!!

How To – Series 1: How to add/change filter criteria of a Lookup field in Java Script

Hi all… This is my first blog post in How-To Series.

Let’s consider a scenario, where we have three picklist fields on a form and the Lookup filed search criteria is depended on selected picklist values. For an instance, if we have Account Type, Product Type and Call Type as picklists and the requirement is like by the time user clicks on the Lookup filed it should have below as the filter criteria

1. Include only the picklists whose value is selected
2. If none of the picklist is selected then display all active records

Below is the code which needs to be placed in the onLoad of the crmForm. As the fetchxml code needs to be changed as per the user picklist selection, I have declared four variables named param, headparam, tailparam and bodyparam. In which bodyparam content is changing as per the user selection. Finally I am concatenating headparam, bodyparam and tailparam to generate required fetchxml code. I am implementing entire code as a function so that it can be called from the picklist’s onchange events instead copy and pasting entire code each and every place.

crmForm.lookupquery = function xyz() {
var field = crmForm.all.abaxis_lookupid;
    field.lookupbrowse = 1;
    var headparam = “<fetch mapping=’logical’><entity name=’new_myentity’><all-attributes /><filter type=’and’>”;
    var tailparam = “</filter></entity></fetch>”;
    var bodyparam = “”;
    var param = “”;
    if (crmForm.all.new_plproducttype.DataValue != null)
        bodyparam = bodyparam + “<condition attribute=’new_producttype’ operator=’eq’ value='” + crmForm.all.new_plproducttype.DataValue[0].id + ” ‘/>”;
    if (crmForm.all.new_placcounttype.DataValue != null)
        bodyparam = bodyparam + “<condition attribute=’new_accounttype’ operator=’eq’ value='” + crmForm.all.new_placcounttype.DataValue + ” ‘/>”;
    if (crmForm.all.new_plcallfor.DataValue != null)
        bodyparam = bodyparam + “<condition attribute=’new_callfor’ operator=’eq’ value='” + crmForm.all.new_plcallfor.DataValue + ” ‘/>”;
    if (bodyparam == “”)
        bodyparam = “<condition attribute=’statecode’ operator=’eq’ value=’0’/>”;
    param = headparam + bodyparam + tailparam;

    field.AddParam(“search”, param);
}
crmForm.lookupquery();

onChange:
 Add crmForm.lookupquery(); to all the picklist attributes onChange() event so that as soon as a picklist value is changed lookup field filter criteria will also be changed.

Hope it helps you..!!!!

Cheers
VikranthP