Thursday 21 July 2016

Check/Get user security role in CRM using C# Code

Hi,

Sometimes, we get the requirement to check the security role of the user in code and doing some business operation.

Here is the C# code for getting security role of the user.

QueryExpression queryExpression = new QueryExpression();
queryExpression.EntityName = "role"; //role entity name
ColumnSet cols = new ColumnSet();
cols.AddColumn("name"); //We only need role name
queryExpression.ColumnSet = cols;
ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values.Add(userID);
//system roles
LinkEntity lnkEntityRole = new LinkEntity();
lnkEntityRole.LinkFromAttributeName = "roleid";
lnkEntityRole.LinkFromEntityName = "role"; //FROM
lnkEntityRole.LinkToEntityName = "systemuserroles";
lnkEntityRole.LinkToAttributeName = "roleid";
//system users
LinkEntity lnkEntitySystemusers = new LinkEntity();
lnkEntitySystemusers.LinkFromEntityName = "systemuserroles";
lnkEntitySystemusers.LinkFromAttributeName = "systemuserid";
lnkEntitySystemusers.LinkToEntityName = "systemuser";
lnkEntitySystemusers.LinkToAttributeName = "systemuserid";
lnkEntitySystemusers.LinkCriteria = new FilterExpression();
lnkEntitySystemusers.LinkCriteria.Conditions.Add(ce);
lnkEntityRole.LinkEntities.Add(lnkEntitySystemusers);
queryExpression.LinkEntities.Add(lnkEntityRole);
EntityCollection entColRoles = service.RetrieveMultiple(queryExpression);
if (entColRoles != null && entColRoles.Entities.Count > 0)
{
     foreach (Entity entRole in entColRoles.Entities)
     {
         if (entRole.Attributes["name"].ToString().ToLower() == "<Your rolename>")
         {
 
         }
     }
}

Hope this helps.

--
Happy CRM'ing
Gopinath

Wednesday 20 July 2016

Associate/Disassociate plugin messages in CRM

Hi,

Most of the times to fulfill our requirement, we will creating N:N relation ship between the entities. Sometimes, we might need to perform some business logic which relating two records. For implementing we will have to write plugins and register them on "Associate" message.
 

Here is something interesting, the Associate and Disassociate messages behave little different that other messages.

When we register a plugin on Associate or Disassociate message, we have to leave Primary and Secondary entities as 'None'. As we haven't specified any entities, the plugin triggers on all Associate/Disassociate operations. We need to check few conditions to let the Association happen only between required entities.

Here is the sample which is like template for Associate/Disassociate message.

EntityReference targetEntity = null;
string strRelationshipName = string.Empty;
EntityReferenceCollection relatedEntities = null;
EntityReference relatedEntity = null;
if (pluginContext.MessageName == "Associate")
{
    // Get the "Relationship" Key from context
    if (pluginContext.InputParameters.Contains("Relationship"))
    {
        strRelationshipName = pluginContext.InputParameters["Relationship"].ToString();
    }
    // Check the "Relationship Name" with your intended one
    if (strRelationshipName != "<YOUR RELATION NAME>")
    {
         return;
    }
    // Get Entity 1 reference from "Target" Key from context
    if (pluginContext.InputParameters.Contains("Target") && pluginContext.InputParameters["Target"] is EntityReference)
    {
        targetEntity = (EntityReference)pluginContext.InputParameters["Target"];
    }
    // Get Entity 2 reference from "RelatedEntities" Key from context
    if (pluginContext.InputParameters.Contains("RelatedEntities") && pluginContext.InputParameters["RelatedEntities"] is EntityReferenceCollection)
    {
        relatedEntities = pluginContext.InputParameters["RelatedEntities"] as EntityReferenceCollection;
        relatedEntity = relatedEntities[0];
    }
}

Hope this helps.

--
Happy CRM'ing
Gopinath

Wednesday 13 July 2016

Retrieve associated records (N:N related) in CRM

Hi,

In CRM, many times we create N:N relationship between 2 entities. When ever we do this, CRM internally creates an intermediate entity with 3 fields.

1) Primary key field of newly created entity.
2) First entity Primary Key field
3) Second entity Primary Key field


In my example, I have two entities called Books and Authors. One book can be written by multiple authors and one author can write multiple books.

Here is the code to retrieve Books written by Author 'Gopinath'

string strFirstEntity = "books";
string strSecondEntity = "authors";
string strRelationshipEntityName = "books_authors";
QueryExpression query = new QueryExpression(strFirstEntity);
query.ColumnSet = new ColumnSet(true);
LinkEntity linkEntity1 = new LinkEntity(strFirstEntity, strRelationshipEntityName, "books", "booksid", JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity(strRelationshipEntityName, strSecondEntity, "authors", "authorsid", JoinOperator.Inner);
linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);
// Add condition to match the Author name with "Gopinath"
linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, "Gopinath"));
EntityCollection collRecords = iService.RetrieveMultiple(query);

Hope this helps.

--
Happy CRM'ing

Gopinath

Solution Segmentation - Add only required things to the solution in CRM 2016

Hi,

Today, I have started working on CRM 2016 and got a chance to explore Solution Enhancements. Most of the times we wanted to include only the changes we did in an entity in the solution instead of including entire solution just for a small change. For example, you have added a field to the contact entity etc...

Till CRM 2015 we have to import complete Contact entity in the target environment.  The problem with this is when we add the contact entity, all the fields, forms, relationships, keys and etc.. even thought we are expecting only one field change..

In CRM 2016, we can do this. For example, if we have made changes to a field and we want to move this change to target environment.

Here are the steps to include only the changes we did on the entity.

Create a Solution.
Click on Add Existing and select Contact entity.
You will be popped with a window to select Forms, Views, Charts, Fields etc..
That's the magic, now you can navigate through each of the tabs and just select the components you have changed.
If you expand and see the components, you will see only the things which are added by you but the complete entity information.

Suppose If you forget to some of the components in the same entity, you can click on 'Add SubComponents' and the required things to the same solution.

You can also choose whether you would like to add Entity Metadata by checking the Flag on the window. When this checkbox is checked it will add all the metadata information in the XML like EntityColor, AuditEnabled etc.. you can see all the details in the XML file.

Hope this helps.
--
Happy CRM'ing

Gopinath

Wednesday 6 July 2016

Retrieve record using Web API – CRM 2016

Hi,

We all know with CRM 2016 we should use Web API instead of oData in JavaScript. Here is the sample code for creating a record using Web API.


function getPrimaryContact() {
    var clientUrl = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
    req.open("GET", encodeURI(clientUrl + "/api/data/v8.0/contacts?$select=fullname,emailaddress1&$filter=fullname eq 'I am the Primary Contact'"), true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                var data = JSON.parse(this.response);
                var dat = data.value;
                // Loop through ‘Contact’ result set
                for (var i = 0; i < dat.length; i++) {
                    // Get ‘Contact ID’ from Contact record.
                    var contactId = dat[i].contactid;
                    var emailAddress = dat[i].emailaddress1;
                    if (contactId) {
                        Xrm.Utility.alertDialog("Email Address : " + emailAddress);
                        // Xrm.Utility.alertDialog("Contact ID : " + contactId);
                    }
                }
            }
            else {
                var error = JSON.parse(this.response).error;
                alert("Error retrieving contact – " + error.message);
            }
        }
    };
    req.send();
}

Hope this helps.
--
Happy CRM'ing

Gopinath

Monday 4 July 2016

Create record and its related record using Web API – CRM 2016

Hi,
We all know with CRM 2016 we should use Web API instead of oData in JavaScript. Here is the sample code for creating a record using Web API.This has some good things, we can create the related records and set them as look up values if we do not have the values.

function createAccount() {
    var clientUrl = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest()
    req.open("POST", encodeURI(clientUrl + "/api/data/v8.0/accounts"), true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Prefer", "odata.include-annotations=*");

    // Set Account Object
    var objAccount = {};
    objAccount.name = "My Account";
    objAccount.creditonhold = false;
    objAccount.accountcategorycode = 1;
    objAccount.revenue = 123456;
    // account["abc_approvaldate"] = new Date();

    // Create new Contact and Set as ‘Primary Contact’
    objAccount.primarycontactid = {};
    objAccount.primarycontactid.firstname = "I am the Primary";
    objAccount.primarycontactid.lastname = "Contact";

    // Set existing Contact as ‘Primary Contact’
    // objAccount[‘primarycontactid@odata.bind’] = "/contacts(" + { contact GUID } + ")";

    //convert JSON object to string
    var body = JSON.stringify(objAccount);


    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                var accountUri = this.getResponseHeader("OData-EntityId");
                // Get Account GUID
                var accountID = accountUri.split(/[()]/);
                accountID = accountID[1];
                Xrm.Utility.alertDialog("Created Account ID : " + accountID);
            }
        }
    };
    req.send(body);
}


Hope this helps.
--
Happy CRM'ing
Gopinath