Retrieve data from N-N relationship in CRM

Sharing a sample code to retrieve data from N-N relationship in CRM. We have a trainer profile which have N-N relationship with Centre that means one trainer can visit to multiple centre and one centre can be assigned to multiple trainers. Here we are trying to retrieve list of centres associated with particular trainer.

List<Centre> centreList = new List<Centre>();
QueryExpression query = new QueryExpression(“mc_centre”);
query.ColumnSet = new ColumnSet(new string[] { “mc_centreid”, “mc_name” });

LinkEntity linkEntity1 = new LinkEntity(“mc_centre”, “mc_mc_trainer_mc_centre”, “mc_centreid”, “mc_centreid”, JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity(“mc_mc_trainer_mc_centre”, “mc_trainer”, “mc_trainerid”, “mc_trainerid”, JoinOperator.Inner);


linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression(“mc_trainerid”, ConditionOperator.Equal, new Guid(trainerId)));

EntityCollection centreCollection = service.RetrieveMultiple(query);
if (centreCollection.Entities.Count > 0)
foreach (var centre in centreCollection.Entities)
Centre cr = new Centre();
cr.centreId = centre.Attributes[“mc_centreid”].ToString();
cr.centreName = centre.Attributes[“mc_name”].ToString();

return centreList

Check open activity related case using oData query

Sharing below code which returns some value using oData query. This function will check if there is any open activity related to Incident entity.

function CheckOpenActivity() {

var Id =;

var IncidentId = Id.substring(1, 37);

//Retrieve dynamically the organization’s server url

var serverUrl = document.location.protocol + “//” + + “/” + Xrm.Page.context.getOrgUniqueName();

var ODATA_ENDPOINT = “/xrmservices/2011/OrganizationData.svc”;

var ODATA_EntityCollection = “/IncidentSet?$select=IncidentId,Incident_ActivityPointers/ActivityId,Incident_ActivityPointers/StateCode&$expand=Incident_ActivityPointers”;

var ODATA_Filter1 = “&$filter=IncidentId eq guid'” + IncidentId + “‘”;

var oDataRequestUrl = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Filter1;

var result = syncODataCall(oDataRequestUrl);

var isOpenActivity = ProcessReturnedEntities(result);

if (isOpenActivity)
alert(‘The Case has open Activity’);
alert(‘The Case has not any open Activity’);


// function to make synchronous oData call

function syncODataCall(odataSelect) {

var request = new XMLHttpRequest();“GET”, odataSelect, false);

request.setRequestHeader(“Accept”, “application/json”);

request.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);


var objJQuery = jQuery.parseJSON(request.responseText);

return objJQuery.d


function ProcessReturnedEntities(d) {

var hasRelated = false;

if (d.results[0] != null) {

var activities = d.results[0].Incident_ActivityPointers;

if (activities != null) {

if (activities.results.length > 0) {

$.each(activities.results, function (index) {

if (activities.results[index].StateCode.Value == ‘0’) {

hasRelated = true;
return hasRelated;


} else {
hasRelated = false;
return hasRelated;

} else {
hasRelated = false;
return hasRelated;
return hasRelated;


Hope this help you.

Share Entity record with Team

          Below is the sample code to share entity record with team in MS CRM 2011

            var teamReference = new EntityReference(“team”, teamId);
            var grantAccessRequest = new GrantAccessRequest
                PrincipalAccess = new PrincipalAccess
                    AccessMask=AccessRights.ReadAccess | AccessRights.WriteAccess,        

                Target=new EntityReference(“lead”,recordId)


           // Get teamId from below function

private Guid GetTeamId(string teamName,OrganizationService service)
            Guid teamId=Guid.Empty;
            QueryByAttribute query = new QueryByAttribute();
            ColumnSet cols = new ColumnSet();

            query.ColumnSet = cols;
            query.AddAttributeValue(“name”, teamName);
            query.EntityName = “team”; 

            EntityCollection entityCollection = (EntityCollection)service.RetrieveMultiple(query);              
            if (entityCollection.Entities.Count > 0)
                    Entity entity =entityCollection.Entities[0];
                    teamId = entity.Id;
            return teamId;          


I have already posted the same for CRM 4.0. Please find the reference link below.


Add button in existing group of Ribbon

Let’s say, we want to add a custom button in Activity group of Contact and on click it will open a window to create CustomerVisits (new_customervisit) record which is a custom activity.

Follow the below steps to create a button in existing group.
Step #1 Create a new solution say TestSolution.
Step #2 Open newly created TestSolution and the entity on which you want to button.I have added contact entity.
Step #3 Publish All Customization
Step #4 Export the TestSolution for editing.
Step #5 Open customization.xml file from exported solution for editing.
Step #6 Find out RibbonDiffXml tag and replace the code from <RibbonDiffXml> to </RibbonDiffXml>With below code.




<CustomAction Id=”” Location=”” Sequence=”41″>


<Button Id=”” Command=”” Sequence=”15″ ToolTipTitle=”$” LabelText=”$” ToolTipDescription=”$” TemplateAlias=”isv” Image32by32=”http://<crm&gt;:5555/PuneCRMTest/WebResources/new_customerVisits” Image16by16=”http://<crm&gt;:5555/PuneCRMTest/WebResources/new_AppAdd” />





<RibbonTemplates Id=”Mscrm.Templates”></RibbonTemplates>



<CommandDefinition Id=””>

<EnableRules />

<DisplayRules />


<Url Address=”http://<crm&gt;:5555/PuneCRMTest/main.aspx?etn=new_customervisit&amp;pagetype=entityrecord” PassParams=”false” WinParams=”0″ />





<TabDisplayRules />

<DisplayRules />

<EnableRules />



<LocLabel Id=””>


<Title languagecode=”1033″ description=”CustomerVisits Description” />



<LocLabel Id=””>


<Title languagecode=”1033″ description=”CustomerVisits” />





Step #7 Save the customization.xml file.
Step #8 Zip the all three files (cutomiztion, solution and [Content_Types]) and import into CRM
Step #9 Remove the contact entity from TestSolution.
Step #10 Delete the solution TestSolution.

Import attachment into MS CRM 2011 entity

Let’s say we want to attach some documents in Contact entity records. We can use out of box Import Data Tool to upload data/attachments into MS CRM 2011.To import attachment into particular record we need to identify a unique key for the record(let’s say for contact entity, it’s contact id i.e. GUID or any field which is unique).

Below is the step by step procedure to import attachment for contact’s record.
Prepare Source Data:

Step #1 Go to Data Management ->Templates for Data Import -> Select Note and click on Download.
Step #2 Edit the downloaded template as shown below.

Description of Columns:
Title: This would be Title of attached file.
File Name: File name of the attachment.
Mime Type: Type of attachment like text/plain.
Regarding:  Reference of record’s field name. In my case I have selected Contact’s Full Name.
Document: Document Id of attached file.
Owner: Owner name must be the CRM user.
Description: Description of file.

Step #3 Build the folder structure for attachments and data file:
Below are some guidelines for file size and folder structure.

If you want to Import multiple files in one Import session, you can .zip them together. A .zip file can include files of .csv, .xml, or .txt file types. All files in a single compressed file must be of the same file type.

The .zip file must confirm to one of these folder structure:

  • .zip file having the files and optional attachment folder directly in it:-
    • Attachments (Folder)
    • <File1>
    • <File2>
    • <File3>

Note: By default, the maximum size of the files you can import is 8 megabytes (MB). This means:

  • Any .csv, .txt, or .xml file must not exceed 8 MB.
  • Any individual file inside the .zip file must not exceed 8 MB and the total size of the .zip file, including the Attachment folder, must not exceed 32 MB.

You can choose any of the above file formats and give it as an input to the Import Data wizard. The delimited .txt, .csv, or XML Spreadsheet 2003 format files can be easily created by using Microsoft Office Excel.

In my case, I followed this “ZIP folder that contain data files and one Attachment folder directly under root” i.e.

  • ContactImport(Zip file name)
    • Attachments(folder)
    • Note.xml

Step #4 Import the file using Import Data feature (Data Management ->Imports).
Step #5 Click Next
Step#6 Select “SampleDataMap” and Click Next.
Step#7 Select “Note” for Microsoft Dynamics CRM Record Types and Click Next.
Step#8 Select mapping fields from CRM Fields as shown below and Click Next.
Step#8 Clicks on Next.
Step#9 Select Allow Duplicates “No”  and Click Submit.
You can write Data map Name for future import.
Step#9 Data has been submitted for import. It may take time based on size of data.

Step#10 Please check the contact record for attachment.

What’s new in Microsoft Dynamics CRM 2011?

1.) New application features

  • Visualization. On demand graphical charts for many record types.
  • Improved user interface that includes the Office Ribbon design and more streamlined forms.
  • Connections. A new feature for establishing relationships between records.
  • Recurring activities. Schedule activities, such as appointments, that repeat.
  • Queue enhancements.
  • Auditing. To enable record level auditing, go to System Settings under Settings, click the Auditing tab, and then click Enable.
  • Field level security. Manage user and team permissions to read, create, or write information in secured fields.
  • Solutions. Solutions are packages of software that you can install or remove from your Microsoft Dynamics CRM organization.

2.) Sandbox Processing Service

The Sandbox Processing Service server role enables an isolated environment to allow for the execution of custom code, such as plug-ins. This isolation reduces the possibility of custom code affecting the operation of the organizations in the Microsoft Dynamics CRM deployment.

3.) Claims-based authentication support

Using federation identity technology such as AD FS 2.0 (formerly known as “Geneva”), Microsoft Dynamics CRM supports claims-based authentication. This technology helps simplify access to applications and other systems by using an open and interoperable claims-based model that provides simplified user access and single sign-on to applications on-premises, cloud-based, and even across organizations. For more information about the claims-based authentication model, see Identity and Access Management.

4.) Add or remove a server role

You can now install individual server roles by using the Microsoft Dynamics CRM Server Setup Wizard. Similarly, you can add a server role, or change or remove installed server roles from Programs and Features in Control Panel.

5.)    SharePoint documentation management

SharePoint documentation management lets you view Microsoft Dynamics CRM data in Microsoft SharePoint. This is an optional feature that you can configure in the Settings area of the Microsoft Dynamics CRM Web application.

For More details, Please download CRM 2011 Implementation Guide from below link.

%d bloggers like this: