Thursday, October 13, 2011

Convert QueryExpression To FetchXml

Converting fetch xml to query expression and vice-verse was not an easy job for the developers and was very much complicated if you have a complex query with multiple link entities and criteria. Currently CRM 2011 provides the functionality to generate fetch xml using advanced find which could be used within the code with necessary changes. But if we have a query expression which need to be implemented within javascript for client side implementations, then QueryExpressionToFetchXmlRequest will be very useful.

The following example explains a simple conversion of query expression request to fetch xml.

QueryExpression query = new QueryExpression()
EntityName = "product",
ColumnSet = new ColumnSet(false),
Distinct = true,
Criteria = new FilterExpression()
FilterOperator = LogicalOperator.And,
Conditions =
new ConditionExpression("statecode",ConditionOperator.Equal, "0" )

QueryExpressionToFetchXmlRequest fetchxmlrequest = new QueryExpressionToFetchXmlRequest();
fetchxmlrequest.Query = query;

QueryExpressionToFetchXmlResponse queried = (QueryExpressionToFetchXmlResponse)crmservice.Execute(fetchxmlrequest);
string fetchXml = queried.FetchXml;

The below example explains the conversion of generated fetch xml request string to query expression.

FetchXmlToQueryExpressionRequest queryrequest = new FetchXmlToQueryExpressionRequest();
queryrequest.FetchXml = fetchXml;

FetchXmlToQueryExpressionResponse response = (FetchXmlToQueryExpressionResponse)crmservice.Execute(queryrequest);

QueryExpression query = response.Query;

Good Luck!

Friday, July 22, 2011

Using OData Service with Dynamics CRM 2011

Microsoft Dynamics CRM 2011 provides developers with different options to query data. The Open Data Protocol (OData) is one of the Query options provided by Dynamics CRM 2011 and enables the creation of REST-based data services, which allow resources, identified using Uniform Resource Identifiers (URIs) and defined in a data model, to be published and edited by Web clients using simple HTTP messages.

The following lists the query string options defined in the OData protocol that are implemented in the REST endpoint for Microsoft Dynamics CRM.

Option Description
$expand : Directs that related records should be retrieved in the record or collection being retrieved.
$filter : Specifies an expression or function that must evaluate to ‘true’ for a record to be returned in the collection.
$order : Determines what values are used to order a collection of records.
$select : Specifies a sub set of properties to return.
$skip : Sets the number of records to skip before it retrieves records in a collection.
$top : Determines the maximum number of records to return.

The following code illustrates how the OData Service is used to connect and query the data.

raise the request and return the value.
function RetrieveData(url) {

var org = Xrm.Page.context.getOrgUniqueName()
var oDataEndpointUrl = "/" + org + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += url;

var service = GetRequestObject();
if (service != null) {"GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
// alert(service.responseText);
var results = eval('(' + service.responseText + ')').d;
return results;

// Create the XMLHTTP Object
function GetRequestObject() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
catch (ex) {
return null;

// OData Query to get Parent Customer Corporate
function getParentCorporate(contactid) {
var url = "ContactSet?$select=ParentCustomerId&$filter=ContactId eq (guid'" + contactid+ "')";
var vaParentCustomerId = RetrieveData(url);
if (vaParentCustomerId.results != null && vaParentCustomerId.results != "")
return vaParentCustomerId.results[0].ParentCustomerId;
return null;

While building the URI, make sure you use the Schema Name to define the attributes and entities in CRM and the URI is case sensitive.

You can test the URI using the IE by posting the URI and it will return the result on IE.

Hope this helps you all. Good Luck!

Tuesday, April 26, 2011

ISV Button On Click To Process Selected Items in an Aspx page

I was looking through the net for code to get all selected items from the CRM grid view and couldn't find the complete solution. Here I got the code for implementing the solution for an ISV button calling aspx page and getting all selected items from the grid view in Dynamics CRM.

// ISV button added to the customisation and the javascript method calls your aspx page...

< Button Icon="/_imgs/ico/16_send.gif" Url="" JavaScript="function post_to_url(path,param){var myForm = document.createElement('form');myForm.setAttribute('method', 'post'); myForm.setAttribute('action', path); myForm.setAttribute('target','SomePage'); var pInput = document.createElement('input'); pInput.setAttribute('name', 'guids'); pInput.setAttribute('value', param); myForm.appendChild(pInput); document.body.appendChild(myForm);var lValue= 50; var tValue=50;,'SomePage','scrollbars=yes,menubar=no,height=750,width=800,resizable=no,toolbar=no,location=no,status=no,'+'top='+tValue+',left='+lValue); myForm.submit(); document.body.removeChild(myForm);}; var aList = document.all['crmGrid'].InnerGrid.SelectedRecords; if (aList.length > 0) { var guidIds=''; for (j=0; j < aList.length; j++ ) { guidIds += aList[j][0]+','+aList[j][1]+':'; }; post_to_url('/ISV/WebPages/MyCustomPage.aspx',guidIds);};" WinParams="dialogHeight: 2px; dialogWidth: 5px;" WinMode="2" PassParams="1" >

// ASPX page OnLoad
// =================================================
if (Context != null && Context.Request.InputStream.Length > 0)
string[] selectedEntities = GetSelectedEntities(Context);
string guidValue = null;
string[] selectedids = null;
StringBuilder emailList = new StringBuilder();
ViewState["Guids"] = selectedEntities;
foreach (string ids in selectedEntities)
selectedids = ids.Split(new char[] { ',' });
guidValue = selectedids[0];

if (guidValue != null && guidValue != String.Empty)
// Write your code with the guid.


The following code will return you the string array of selected records guid from the CRM Grid.

/// Extract Selected Entities from Context

/// Context
private string[] GetSelectedEntities(HttpContext context)

// Read the Xml data that is passed in the HttpRequest stream.
StreamReader sr = new StreamReader(context.Request.InputStream);
string recordIds = sr.ReadToEnd();
if (string.IsNullOrEmpty(recordIds))
return new string[0];

recordIds = recordIds.Replace("%7B", "{").Replace("%7D", "}").Replace("%3A", ":").Replace("%2C", ",");
return recordIds.Substring(6).Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

Hope this helps. Post me any questions...


Monday, April 11, 2011

Get Associated Entity Code On Dynamics CRM Form

Custom entities created within Dynamics CRM will have different entity code while imported to different Organisations. It is difficult to define the entity code while the deployment is moved from development to testing/UAT and production. Certain cases deployment will be done by the release team who will just follow the instructions rather it would not be easy for them to edit the script file to update the custom entity code.

It is tricky to get this, but the below function will return the entity code on the Form. Make sure the associated entity link is not hidden from the form and will be hidden if required using javascript after getting the entity code.

// ----------------------------------------------------------

// getObjectTypeCode

// This function will return Object type Code from url

function getObjectTypeCode(name, url) {

name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

var regexS = "[\\?&]" + name + "=([^&#]*)";

var regex = new RegExp(regexS);

var results = regex.exec(url);

if (results == null)

return "";


return results[1];


/********************END - getObjectTypeCode function**********/

The following method accepts the name of the

// ----------------------------------------------------------

// getEntityCode

// This function will return Entity Object type Code

function getEntityCode(name) {

//Get Entity url

var navEntity = document.getElementById(name);

if (navEntity != null) {

var img = navEntity.getElementsByTagName("IMG")[0];

//get Entity Object Type Code

var objectTypeCode = getObjectTypeCode('objectTypeCode', img.src); = "none";

if (objectTypeCode != "")

return objectTypeCode;


return "";


return "";


/********************END - getEntityCode function**********/

Disable ISV Button on Dynamics CRM Toolbar

ISV buttons are used to extend certain functionality on Dynamics CRM Tool bars. The id of an ISV button will be different each time the page is refreshed. So its a bit tricky to identify the ISV button and attach functionality or hide or disable it.

The following method will disable the ISV button on the CRM tool bar in an iFrame. This method could be extended to access ISV buttons on the tool bar.

// ----------------------------------------------------------
// DisableIsvButton
// Disable Isv Button on an iFrame
function DisableIsvButton(iframeID, searchText) {

var frame = document.getElementById(iframeID);

var menuItems = frame.contentWindow.document.getElementsByTagName("li");

for (var i = 0; i < menuItems.length; i++) {

if (menuItems[i].id.indexOf("ISV") == 0 && menuItems[i].id.indexOf(searchText) > 0) { menuItems[i].disabled = true; break; }


Hope this helps you...


Display Associated Entity On Dynamics CRM Form IFrames

This blog explains you how to display an associated entity grid on the CRM form. For example if users need to see all the activities associated with a contact on the activities Tab on the Form or on the main Form. This could be achieved using some java script on the form onLoad event and is a supported approach.

This uses 3 different methods which will get the source for the frame, set the styling of the frame and hide or display items on the grid.

// Get the URL and set the Iframe source.
var url = getFrameSource('area_campaign_additional_lead') + "&roleOrd=1";
crmForm.all.IFRAME_Name.src = url;

// This method set the styling for the frame.

// This method do the stuff on CRM Grid to hide/display items.

// ----------------------------------------------------------
// getFrameSource
// Gets the source URL for a frame
function getFrameSource(tabSet) {
if (crmForm.ObjectId != null) {
var oId = crmForm.ObjectId;
var oType = crmForm.ObjectTypeCode;
var security = crmFormSubmit.crmFormSubmitSecurity.value;
return "areas.aspx?oId=" + oId + "&oType=" + oType + "&security=" + security + "&tabSet=" + tabSet;

else { return "about:blank"; }

// ----------------------------------------------------------
// fixStylingInFrameSource
// Waits for the content window of the IFrame to be ready
function fixStylingInFrameSource(iframeID) {
var frame;

if (document.getElementById(iframeID).contentWindow.document.readyState != "complete")
{ window.setTimeout(function() { fixStylingInFrameSource(iframeID) }, 10); }
else {
frame = document.getElementById(iframeID);

// Change the background color to CRM form color = "#eef0f6";

// Remove the left border

frame.contentWindow.document.body.all(0).style.borderLeftStyle = "none";

// Remove padding

frame.contentWindow.document.body.all(0).all(0).all(0).all(0).style.padding = "0px";

// Make the cell the full width of the IFRAME

frame.contentWindow.document.body.all(0).style.width = "100%"

// Show the IFrame = "block";

// ----------------------------------------------------------
// fixStylingInFrameContent
// Waits for the content window of the IFrame to be ready
function fixStylingInFrameContent(iframeID) {
var frame;

if (document.getElementById(iframeID).contentWindow.document.readyState != "complete")
{ window.setTimeout(function() { fixStylingInFrameContent(iframeID) }, 10); }
else {
frame = document.getElementById(iframeID);

// Some sample items on the grid which will be hidden.

var menuItem2 = frame.contentWindow.document.getElementById('gridPrint');

var menuItem3 = frame.contentWindow.document.getElementById('mailMergeTeam');

var menuItem4 = frame.contentWindow.document.getElementById('assignTeam');

var menuItem5 = frame.contentWindow.document.getElementById('moreActions');

if (menuItem2 != null) { = 'none'; }

if (menuItem3 != null) { = 'none'; }

if (menuItem4 != null) { = 'none'; }

if (menuItem5 != null) { = 'none'; }


Good Luck.