Featured

Cascade Deactivate Related Record using C# plugin CRM 2011


Hi all ,

In this article I would like to explain how to De-Activate child records (Related records) when parent record status gets changed.

  • In my Scenario I am taking Account entity, which consists of related Contact record in Left navigation.
  • I would like to De-Activate all list of contact associated with Account.

Cascade Deactivates Record CRM 2011

  • List of contact Associated with Parent Account

2

#region  De-Activate Related Contact Associated with Account Record

    //Note for  Active record  state value = 1 .
   // For In - Active record  State value = 0 .

  /// Check weather state value == 1.
         if (state.Value == 1)
            {
                    /// querry expression to retrieve related Contact associated to Account.
                    QueryExpression contact = new QueryExpression { EntityName = "contact", ColumnSet = new ColumnSet("contactid", "parentcustomerid") };
                    contact.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, Account.Id);

                    // Check weather statecode of the record are Active
                    contact.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
                    EntityCollection Retrievecontact = service.RetrieveMultiple(contact);

                    if (Retrievecontact.Entities.Count > 0)
                    {

                        foreach (var a in Retrievecontact.Entities)
                        {
                            SetStateRequest contactsetStateReq = new SetStateRequest();
                            contactsetStateReq.EntityMoniker = new EntityReference(a.LogicalName, new Guid(a.Id.ToString()));
                            contactsetStateReq.State = new OptionSetValue(1);
                            contactsetStateReq.Status = new OptionSetValue(-1);
                            service.Execute(contactsetStateReq);
                        }

                    }

                }
    #endregion
  • De – Active Parent Record

3

  • Related child contact record status gets updated to In-Active. When Parent Account record gets In-Active

5

#region Re-Activate In-Active Contact Records

   /// Check weather state value == 0. For In active records
        if (state.Value == 0)
          {
    /// querry expression to retrieve related Contact associated to Account.
       QueryExpression contact = new QueryExpression { EntityName = "contact", ColumnSet = new ColumnSet("contactid", "parentcustomerid") };
         contact.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, Account.Id);

      // Check weather statecode of the record are In-Active
        contact.Criteria.AddCondition("statecode", ConditionOperator.Equal, 1);
          EntityCollection Retrievecontact = service.RetrieveMultiple(contact);

       if (Retrievecontact.Entities.Count > 0)
                    {

                        foreach (var a in Retrievecontact.Entities)
                        {
                            SetStateRequest contactsetStateReq = new SetStateRequest();
                            contactsetStateReq.EntityMoniker = new EntityReference(a.LogicalName, new Guid(a.Id.ToString()));
                            contactsetStateReq.State = new OptionSetValue(0);
                            contactsetStateReq.Status = new OptionSetValue(-1);
                            service.Execute(contactsetStateReq);
                        }
          }
          }
  #endregion
  • Re- Activate Account Record to Active State

6

  • Related Contact Record status gets Updated to Active .

8

Plugin Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//CRM SDK Namespace
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;

namespace Sample
{
    public class Cascade : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)
              serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains("EntityMoniker") && context.InputParameters["EntityMoniker"] is EntityReference)
            {

                //Parent Entity (Account)
                EntityReference Account = (EntityReference)context.InputParameters["EntityMoniker"];

                //Capturing record  State & Status
                OptionSetValue state = (OptionSetValue)context.InputParameters["State"];
                OptionSetValue status = (OptionSetValue)context.InputParameters["Status"];

                #region De-Activate Related Contact Associated with Account Record

                //Note for  Active record  state value = 1 .
                // For In - Active record  State value = 0 .

                /// Check weather state value == 1.
                if (state.Value == 1)
                {
                    /// querry expression to retrieve related Contact associated to Account.
                    QueryExpression contact = new QueryExpression { EntityName = "contact", ColumnSet = new ColumnSet("contactid", "parentcustomerid") };
                    contact.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, Account.Id);

                    // Check weather statecode of the record are Active
                    contact.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
                    EntityCollection Retrievecontact = service.RetrieveMultiple(contact);

                    if (Retrievecontact.Entities.Count > 0)
                    {

                        foreach (var a in Retrievecontact.Entities)
                        {
                            SetStateRequest contactsetStateReq = new SetStateRequest();
                            contactsetStateReq.EntityMoniker = new EntityReference(a.LogicalName, new Guid(a.Id.ToString()));
                            contactsetStateReq.State = new OptionSetValue(1);
                            contactsetStateReq.Status = new OptionSetValue(-1);
                            service.Execute(contactsetStateReq);
                        }

                    }

                }
                #endregion

                ///<Re Activate Relate record when Parent record status gets Activated>

                #region Re-Activate In-Active Contact Records

                /// Check weather state value == 0. For In active records
                if (state.Value == 0)
                {
                    /// querry expression to retrieve related Contact associated to Account.
                    QueryExpression contact = new QueryExpression { EntityName = "contact", ColumnSet = new ColumnSet("contactid", "parentcustomerid") };
                    contact.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, Account.Id);

                    // Check weather statecode of the record are In-Active
                    contact.Criteria.AddCondition("statecode", ConditionOperator.Equal, 1);
                    EntityCollection Retrievecontact = service.RetrieveMultiple(contact);

                    if (Retrievecontact.Entities.Count > 0)
                    {

                        foreach (var a in Retrievecontact.Entities)
                        {
                            SetStateRequest contactsetStateReq = new SetStateRequest();
                            contactsetStateReq.EntityMoniker = new EntityReference(a.LogicalName, new Guid(a.Id.ToString()));
                            contactsetStateReq.State = new OptionSetValue(0);
                            contactsetStateReq.Status = new OptionSetValue(-1);
                            service.Execute(contactsetStateReq);
                        }

                    }

                }
                #endregion
            }
        }
    }
}

  • Register your plugin Message = SetStateDynamicEntity
  • Primary Entity = Account
  • Post Operation

9

Hope This Help You . . . 

Expected value between 1 and 1 inclusive. Dynamic CRM 365


Recently we had an issue while trying to Query Retrieve Multiple for (Audit Entity) ,

Error Message: ” Expected value between 1 and 1 inclusive”.

Root Cause: Microsoft has moved Audit table to Cosmo DB, due to which Distinct & Aggregate, Group by function are no more supported from retrieve multiple query.

Fix: Remove distinct , aggregate , group by in your retrieve multiple query will resolve your issue.

Retrieve Lookup & Option set value from web api mscrm


Hello Experts ,

To retrieve Look up   ( Id  ) from Web api , usually we will be declaring Schema Name ,

But in Web api , there is an minor change in syntax.

Instead of Schema Name we need to declare like below forma.

_prefix_attributename_value. 

Eg: _new_accountid_value

To retrieve Look up (Name , Logical Name ) We need to add below syntax in our Web api Request.

req.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);

 

Sample Code For Reference.

Comments : Below example , will retrieve value from lead entity

  • Look Up
  • Money
  • Date Time
  • Option set
  • Decimal

var req = new XMLHttpRequest();

req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/leads()?$select=_accountid_value,budgetamount,_contactid_value,_customerid_value,emailaddress1,modifiedon,salesstage", false);

req.setRequestHeader("OData-MaxVersion", "4.0");

req.setRequestHeader("OData-Version", "4.0");

req.setRequestHeader("Accept", "application/json");

req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

<strong>req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");</strong> 

req.onreadystatechange = function() {

if (this.readyState === 4) {

req.onreadystatechange = null;

if (this.status === 200) {

var result = JSON.parse(this.response);

var _accountid_value = result["_accountid_value"];

var _accountid_value_formatted = result["_accountid_value@OData.Community.Display.V1.FormattedValue"];

var _accountid_value_lookuplogicalname = result["_accountid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

var budgetamount = result["budgetamount"];

var budgetamount_formatted = result["budgetamount@OData.Community.Display.V1.FormattedValue"];

var _contactid_value = result["_contactid_value"];

var _contactid_value_formatted = result["_contactid_value@OData.Community.Display.V1.FormattedValue"];

var _contactid_value_lookuplogicalname = result["_contactid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

var _customerid_value = result["_customerid_value"];

var _customerid_value_formatted = result["_customerid_value@OData.Community.Display.V1.FormattedValue"];

var _customerid_value_lookuplogicalname = result["_customerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

var emailaddress1 = result["emailaddress1"];

var modifiedon = result["modifiedon"];

var salesstage = result["salesstage"];

var salesstage_formatted = result["salesstage@OData.Community.Display.V1.FormattedValue"];

} else {

Xrm.Utility.alertDialog(this.statusText);

}

}

};

req.send();

To make it simple , use
CRM REST Builder
  which will generate the complete code, and you can save your time  😉 😉 😉

Make All Fields ReadOnly in CRM Form


will this work for 2016 ?
is above mentioned reference are default available in crm 2015 and above ??

Microsoft Dynamic xRM

Some case you want to set read only for all field in the forms. It will take time to set field by field. This is small tip for marking all field as read only in MS CRM form.

/// <reference path=”rbei_PACrm.Sdk.js” />

/// <reference path=”../PACRM2011/XrmPageTemplate.js” />

function MarkAllFieldReadOnly() {

Xrm.Page.ui.controls.forEach(function (control, index) {

try{

control.setDisabled(true);

}

catch (e)

{

}

});

}

Hope it will be useful for someone.

View original post

Webresource content size is too big. Microsoft Dynamics CRM ERROR CODE 0x8004F114


We may face an Issue ” Webresource content size is too big.” while importing a solution from one environment to another environment. Microsoft Dynamics CRM ERROR CODE 0x8004F114

To fix it ,
Goto –> Settings –> Administrator –> System Settings –>Email (Tab)
Set file size limit for attachments
Provide Maximum file size (in kilobytes) = 5,120

Untitled
Note: If you reduce Maximum file size, CRM will not allow to upload / Import Notes attachement & Webresource (html, javascript , image , xml) where file greater than mentioned file kilobytes.

Hope this helps you..

Retrieve CRM Views Records using c# Plugin


Dynamics CRM 365

Hi ,

If we need to retrieve CRM Records based on Entity Views in Plugin (c#).

  • In CRM we have 2 tables , saved Query , User Query.

In Saved Query

  • Default Entity Based query
  • [ Eg: Account Entity à Views Active Views , In Active Views ,Etc.].
  • My Personal Views [Eg: User Personal Views ]

In User Query

  • User based views , Team Based Views.
  • In both the entity [ saved Query , User Query ] we have following fields
  • View Id = Unique View Id for both entity [ saved Query , User Query]
  • View Name = Name of the view
  • Fetchxml = A string field which stores the fetch xml query where we need add condition etc.
  • Query Type = Type of the query [eg 0 , 2]
  • Sample Code . .

Similarly

Retrieve  User Query Records

Thanks 🙂

View original post

Retrieve CRM Views Records using c# Plugin


Hi ,

If we need to retrieve CRM Records based on Entity Views in Plugin (c#).

  • In CRM we have 2 tables , saved Query , User Query.

In Saved Query

  • Default Entity Based query
  • [ Eg: Account Entity à Views Active Views , In Active Views ,Etc.].
  • My Personal Views [Eg: User Personal Views ]

In User Query

  • User based views , Team Based Views.
  • In both the entity [ saved Query , User Query ] we have following fields
  • View Id = Unique View Id for both entity [ saved Query , User Query]
  • View Name = Name of the view
  • Fetchxml = A string field which stores the fetch xml query where we need add condition etc.
  • Query Type = Type of the query [eg 0 , 2]
  • Sample Code . .

Retrieve  saved Query Records

Guid ViewId = new Guid("GUID OF VIEW");

var savedQueryFetchXml = (from q in orgContext.CreateQuery("savedquery")

where (Guid)q["savedqueryid"] == ViewId // We can pass Name of the view [Eg:(string)q["name"] = "VIEW NAME"
&& (string)q["fetchxml"] != null

select q["fetchxml"]).FirstOrDefault();

 

Similarly

Retrieve  User Query Records


var UserQueryFetchXml = (from q in orgContext.CreateQuery("userquery")

where (Guid)q["userqueryid"] == ViewId
&& (string)q["fetchxml"] != null

select q["fetchxml"]).FirstOrDefault();

Thanks 🙂

Interact Wcf Service With Microsoft Dynamics Crm Plugin


Hi ,

in my previous post I have explained how to interact WCF Services with Microsoft Dynamics CRM.
In this post I would like to explain how to invoke the Wcf services with CRM service using plugin c#.

• For calling external wcf services within our crm service, we can generate WCF Client Class similar to our early bound class generation.

Goto Visual Studio Tools –> Developer Command

• Use Svcutil.exe and map to the desired location where your client code has to get generated.

Type the following command : svcutil.exe followed by language type , Early Bound class Name.cs , Hosted Url of your WCF Application
svcutil.exe /language:cs /out:CreateLead.cs http://****:8081/Service1.svc

Generate WCF

Add the generated CreateLead.cs class in your application and the namespace reference in your plugin class file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Net;
using System.ServiceModel;
using CreateLead;  // Generated WCF Class
namespace Crm_Plugin
{
    public class WCF_Integration : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            //<snippetFollowupPlugin1>
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
            //</snippetFollowupPlugin1>

            //<snippetFollowupPlugin2>
            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
            Entity entity = (Entity)context.InputParameters["Target"];

               // Invoke  WCF SERVICE
                BasicHttpBinding myBinding = new BasicHttpBinding();
                myBinding.Name = "BasicHttpBinding_IService1";
                myBinding.Security.Mode = BasicHttpSecurityMode.None;
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress endPointAddress = new EndpointAddress("http://******:8080/Service1.svc");

                ChannelFactory<IService1> SerFactor = new ChannelFactory<IService1>(myBinding, endPointAddress);
                IService1 chanl = SerFactor.CreateChannel();

// Passing Parameter to the Wcf Class CreateLead
string Result =chanl.CreateLead(entity.GetAttributeValue<string>("firstname").ToString(), entity.GetAttributeValue<string>("lastname").ToString(), entity.GetAttributeValue<string>("emailaddress1").ToString());
                SerFactor.Close();
            }
        }
    }
}

* Note ,
i have registered my plugin in pre create Contact Entity .
Passing [ First Name , Last Name , Email Address ] 3 parameters to out CreateLead WCF Method .