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);

linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);

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();
centreList.Add(cr);
}
}

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 = parent.Xrm.Page.data.entity.getId();

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

//Retrieve dynamically the organization’s server url

var serverUrl = document.location.protocol + “//” + document.location.host + “/” + 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’);
else
alert(‘The Case has not any open Activity’);

}

// function to make synchronous oData call

function syncODataCall(odataSelect) {

var request = new XMLHttpRequest();

request.open(“GET”, odataSelect, false);

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

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

request.send();

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,        
                    Principal=teamReference
                },

                Target=new EntityReference(“lead”,recordId)

            };
            service.Execute(grantAccessRequest);

           // Get teamId from below function

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

            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.
https://arvindcsit.wordpress.com/2012/02/26/create-contact-and-share-the-record-which-contains-lookuppicklist-and-string-datatype/

 

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.

Steps:
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.

 

<RibbonDiffXml>

<CustomActions>

<CustomAction Id=”CompanyName.Form.contact.Related.Activities.CustomerVisits.CustomAction” Location=”Mscrm.Form.contact.Related.Activities.Controls._children” Sequence=”41″>

<CommandUIDefinition>

<Button Id=”CompanyName.Form.contact.Related.Activities.CustomerVisits” Command=”CompanyName.Form.contact.Related.Activities.CustomerVisits.Command” Sequence=”15″ ToolTipTitle=”$LocLabels:CompanyName.Form.contact.Related.Activities.CustomerVisits.LabelText” LabelText=”$LocLabels:CompanyName.Form.contact.Related.Activities.CustomerVisits.LabelText” ToolTipDescription=”$LocLabels:CompanyName.Form.contact.Related.Activities.CustomerVisits.Description” TemplateAlias=”isv” Image32by32=”http://<crm&gt;:5555/PuneCRMTest/WebResources/new_customerVisits” Image16by16=”http://<crm&gt;:5555/PuneCRMTest/WebResources/new_AppAdd” />

</CommandUIDefinition>

</CustomAction>

</CustomActions>

<Templates>

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

</Templates>

<CommandDefinitions>

<CommandDefinition Id=”CompanyName.Form.contact.Related.Activities.CustomerVisits.Command”>

<EnableRules />

<DisplayRules />

<Actions>

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

</Actions>

</CommandDefinition>

</CommandDefinitions>

<RuleDefinitions>

<TabDisplayRules />

<DisplayRules />

<EnableRules />

</RuleDefinitions>

<LocLabels>

<LocLabel Id=”CompanyName.Form.contact.Related.Activities.CustomerVisits.Description”>

<Titles>

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

</Titles>

</LocLabel>

<LocLabel Id=”CompanyName.Form.contact.Related.Activities.CustomerVisits.LabelText”>

<Titles>

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

</Titles>

</LocLabel>

</LocLabels>

</RibbonDiffXml>


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.
Steps:
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.
https://arvindcsit.files.wordpress.com/2012/07/sampledata.jpg

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 ContactImport.zip 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.
https://arvindcsit.files.wordpress.com/2012/07/fieldsmapping.jpg
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.

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0c7dcc45-9d41-4e2e-8126-895517b4274c&displayLang=en#SystemRequirements

%d bloggers like this: