Sunday 11 August 2019

Switch the BPF using C# code in MS CRM

Hello All ,

Switching the BPF using c# code in ms crm ,through plugin

I have following scenario's based on one filed value we need to set the BPF , we can use following process but it is obsolete or deprecated in feature it is not going to work .

https://community.dynamics.com/crm/b/crmpowerobjects/posts/change-business-process-flows-using-a-workflow

That is the reason using C# code change BPF(Business Process Flow).

Step 1 :-   My Scenario i have 2 BPF



  •  Carrier Path BPF (logical Name : gitta_carrierpathbpf)  
  •  Carrier Path BPF 1  (logical Name : gitta_carrierpathbpf1) 


Step 2: -  Switch the BPF Based on Text Contains  in the Name .
               
        If name Contains "IT " the  I want Show the "Carrier Path BPF"  other wise switch to " Carrier Path BPF 1 ".

Step 3:- Entity name is "Carrier " ,When ever we create record ,associate record will record  in BPF Entity .

Step 4: - To Switch BPF i am using Plugin code . (we can also use Custom Workflow).


Step 5:- To Switch BPF ,we need to create record in the BPF Entity ,that will automatically switch the BPF.

Step 6: -  First i will Retrieve the    2 BPF records associated with Carrier Entity id ,When ever I create Carrier Entity record ,associate record will be created in BPF .


To retrieve the BPF records


 private  EntityCollection GetCarrierBPF(IOrganizationService service,Guid carrierId)
        {

            QueryExpression queryExpression = new QueryExpression("gitta_carrierpathbpf");
            queryExpression.ColumnSet = new ColumnSet("bpf_name");
            queryExpression.Criteria.AddCondition("bpf_gitta_carrierid", ConditionOperator.Equal, carrierId);
            queryExpression.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 1);
            queryExpression.NoLock = true;

            EntityCollection CarrierBPFPathCollection = service.RetrieveMultiple(queryExpression);
            return CarrierBPFPathCollection;
        }

In the Above code Service is "Organization Service" and "carrierId" is  Newly Created Carrier  record .

"gitta_carrierpathbpf"  Carrier Path BPF logical name

Step 7:-   After 2 BPF records are retrieve using above code .

   var carrierBPFEntityCollection = GetCarrierBPF(service, CarrierId);
   var carrierBPFEntityCollection1 = GetCarrierBPF1(service, CarrierId);

Step 8:- Check for the What is the value in the "Name"
 
              if (carrier.GetAttributeValue<string>("gitta_name")!=null)
                {
                    if (carrier.Attributes["gitta_name"].ToString().Contains("IT"))
                    {
                   

                        if(carrierBPFEntityCollection.Entities.Count ==1)
                        {
                            return;
                        }
                        else if(carrierBPFEntityCollection1.Entities.Count >0)
                        {
                            service.Delete("gitta_carrierpathbpf1", carrierBPFEntityCollection1.Entities[0].Id);
                            createCarrierBPF(service, CarrierId);
                        }
                    }
                    else
                    {
                        if (carrierBPFEntityCollection1.Entities.Count == 1)
                        {
                            return;
                        }
                        else if (carrierBPFEntityCollection.Entities.Count > 0)
                        {
                            service.Delete("gitta_carrierpathbpf", carrierBPFEntityCollection.Entities[0].Id);
                            createCarrier1BPF(service, CarrierId);
                        }
                    }
                 
                }

based on value of name first we are going check record is available in appropriate BPF or not ,if record is not available in the proper BPF entity ,we are going to create record in BPF.

Before that we are going to check other BPF had any record associate with the Carrier entity record ,if record is available in   Other BPF ,we are going to delete first ,after we are going to create.

Step 9 :- Creation of the BPF record code .


 private void createCarrierBPF(IOrganizationService service,Guid carrierid)
        {
            Entity carrierBpf = new Entity("gitta_carrierpathbpf");
            carrierBpf["bpf_gitta_carrierid"] = new EntityReference("gitta_carrier", carrierid);
            service.Create(carrierBpf);
         
        }

Step 10 : Total code is below.

using Microsoft.Xrm.Sdk;
using MSCRMplugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;

namespace MS_CRM_plugins.Demo.Plugins
{
    public class Carrier : PluginBase
    {
        string unsecureString;
        public Carrier(string secure, string unsecure) : base(typeof(Carrier))
        {
            unsecureString= unsecure;

        }

        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new InvalidPluginExecutionException("localContext");
            }
            IPluginExecutionContext Context = localContext.PluginExecutionContext;
            //if (Context.Depth > 1) { return; }
            if (Context.PrimaryEntityName.ToLower() != "gitta_carrier") { return; }
            if (Context.MessageName.ToLower() != "create")
            {
                return;
            }

            IOrganizationService service = localContext.OrganizationService;
            ITracingService trace = localContext.TracingService;
            if ((Context.InputParameters != null) && Context.InputParameters.Count > 0 && Context.InputParameters.Contains("Target") && (Context.InputParameters["Target"] is Entity))
            {
                if(Context.Depth > 2) { return; }
                Entity carrier = Context.InputParameters["Target"] as Entity;
                Guid CarrierId = carrier.Id;
                var carrierBPFEntityCollection = GetCarrierBPF(service, CarrierId);
                var carrierBPFEntityCollection1 = GetCarrierBPF1(service, CarrierId);
                if (carrier.GetAttributeValue<string>("gitta_name")!=null)
                {
                    if (carrier.Attributes["gitta_name"].ToString().Contains("IT"))
                    {
                   

                        if(carrierBPFEntityCollection.Entities.Count ==1)
                        {
                            return;
                        }
                        else if(carrierBPFEntityCollection1.Entities.Count >0)
                        {
                            service.Delete("gitta_carrierpathbpf1", carrierBPFEntityCollection1.Entities[0].Id);
                            createCarrierBPF(service, CarrierId);
                        }
                    }
                    else
                    {
                        if (carrierBPFEntityCollection1.Entities.Count == 1)
                        {
                            return;
                        }
                        else if (carrierBPFEntityCollection.Entities.Count > 0)
                        {
                            service.Delete("gitta_carrierpathbpf", carrierBPFEntityCollection.Entities[0].Id);
                            createCarrier1BPF(service, CarrierId);
                        }
                    }
                 
                }
             
            }
        }

        private  EntityCollection GetCarrierBPF(IOrganizationService service,Guid carrierId)
        {

            QueryExpression queryExpression = new QueryExpression("gitta_carrierpathbpf");
            queryExpression.ColumnSet = new ColumnSet("bpf_name");
            queryExpression.Criteria.AddCondition("bpf_gitta_carrierid", ConditionOperator.Equal, carrierId);
            queryExpression.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 1);
            queryExpression.NoLock = true;

            EntityCollection CarrierBPFPathCollection = service.RetrieveMultiple(queryExpression);
            return CarrierBPFPathCollection;
        }

        private EntityCollection  GetCarrierBPF1(IOrganizationService service, Guid carrierId)
        {
            QueryExpression queryExpression = new QueryExpression("gitta_carrierpathbpf1");
            queryExpression.ColumnSet = new ColumnSet("bpf_name");
            queryExpression.Criteria.AddCondition("bpf_gitta_carrierid", ConditionOperator.Equal, carrierId);
            queryExpression.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 1);
            queryExpression.NoLock = true;

            EntityCollection CarrierBPFPath1Collection = service.RetrieveMultiple(queryExpression);
            return CarrierBPFPath1Collection;
        }

        private void createCarrierBPF(IOrganizationService service,Guid carrierid)
        {
            Entity carrierBpf = new Entity("gitta_carrierpathbpf");
            carrierBpf["bpf_gitta_carrierid"] = new EntityReference("gitta_carrier", carrierid);
            service.Create(carrierBpf);
         
        }

        private void createCarrier1BPF(IOrganizationService service, Guid carrierid)
        {
            Entity carrierBpf = new Entity("gitta_carrierpathbpf1");
            carrierBpf["bpf_gitta_carrierid"] = new EntityReference("gitta_carrier", carrierid);
            service.Create(carrierBpf);
        }

    }

}


Note : - Please Observed above code i am using the Plugin Base ,if you don't about plugin base ,you can use normal IPlugin also.

public class Carrier : IPlugin
{
  above code just replace with small changes . 

}

Step 11: Please Register plugin Post Event  Create of Carrier ( in my case  use your own entity) 

Now create record using console c# code  or OOB On demand Work Flow ,in my case i used on-demand work create carrier path.







Wednesday 31 July 2019

MS CRM Subgrid Filter Using JavaScript

Hello All ,

Why i am writing this below  Post ,I gone through the different post not found suitable answer for Subgird Filter in MS CRM using Javascript

MS CRM  Version : Dynamics 365 Online v 9.0 

 I am using Form-context instead of Xrm.Page why because it is deprecated in V 9.0

Please find below link to under stand the Form Context.

https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/clientapi-form-context


User need check the below check box,to Pass Execution Context


function subgirdFilter(executionContext)
{
var formContext = executionContext.getFormContext(); // get formContext
// Case_Activities is Sub Grid Name
var caseActivities =  formContext.getControl("Case_Activities"); 
    if (caseActivities == null) {
        // Wait one second before recalling the function
        setTimeout(subgirdFilter, 1000);
        return;
    }

var IRCId = formContext.data.entity.getId();
 
  // Build Fetch statement
        var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='activitypointer'>" +
    "<attribute name='subject' />" +
    "<attribute name='ownerid' />" +
    "<attribute name='activitytypecode' />" +
    "<attribute name='statecode' />" +
    "<attribute name='instancetypecode' />" +
    "<attribute name='community' />" +
    "<attribute name='description' />" +
    "<attribute name='activityid' />" +
    "<order attribute='subject' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='isregularactivity' operator='eq' value='1' />" +
      "<filter type='or'>" +
        "<condition attribute='regardingobjectid' operator='eq' uitype='brent_ic_complaintsinformationrequest' value='" + IRCId + "' />" +
      "</filter>" +
    "</filter>" +
    "<link-entity name='email' from='activityid' to='activityid' visible='false' link-type='outer' alias='email_engagement'>" +
      "<attribute name='isemailfollowed' />" +
      "<attribute name='lastopenedtime' />" +
      "<attribute name='delayedemailsendtime' />" +
    "</link-entity>" +
  "</entity>" +
"</fetch>";

  // Update the Subgrid with the new FetchXml and refresh the grid
    if (caseActivities != null)
    {
        caseActivities.getGrid().setParameter("fetchXml",fetchXml);
        caseActivities.refresh();
    }
}

Above code will Work for Filter the "Sub Grid " with Fetch Xml.

Saturday 3 December 2016

500 Error in Web Service or WebMethod in ASP.net or Asmx calling from Ajax or Js Call.

I got  One issues 500 Error  In Web Service in Asp.net ,I tried different Ways ,I am unable to find exact reason why ? That Reason I writing this Post .

In Browser Developer tools we find following error 500 Internal Server Error


Check the Following steps :-

Step 1:- 

    [System.Web.Script.Services.ScriptService]
    public class firstService : System.Web.Services.WebService
    {

     }

Check that Attribute is Given Above Service or Not .

if not you will get Error. Normally if we create the .asmx File by Default this attribute will be in comment mode ,please  un-comment .

Still issues not Resolved? following next Step 

Step 2:- 


        [ScriptMethod(UseHttpGet = false,ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        public  static List<employee>  Employee()
        {

          }


Check your placed the following  attribute or not .

[ScriptMethod(UseHttpGet = false,ResponseFormat = ResponseFormat.Json)]

Bydefault  UseHttpGet is false ,you can write like 

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]


Still is Not Resolved ?

Step 3:-  Check the ajax code  what we write  there 


 $.ajax({
            type: "GET", ---->  Type of Call   // 
            url: "/webServices/firstService.asmx/Employee",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (list) {
                $("#Something").append("<ul id='bullets'></ul>");
                for (i = 0; i < list.d.length; i++) {
                    $("#bullets").append("<li>" + list.d[i].name + ":" + list.d[i].age);
                    
                }
            },
            error: function (e) {
                $("#Something").html("There was an error retrieving records");
            }
        });

We Need to Change the Type of Ajax Call.

  type: "GET", ----> // Issue here we need to Change the following line to " POST"

like  this


 $.ajax({
            type: "POST",
            url: "/webServices/firstService.asmx/Employee",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (list) {
                $("#Something").append("<ul id='bullets'></ul>");
                for (i = 0; i < list.d.length; i++) {
                    $("#bullets").append("<li>" + list.d[i].name + ":" + list.d[i].age);
                    
                }
            },
            error: function (e) {
                $("#Something").html("There was an error retrieving records");
            }
        });


NOW issue is Resolved You can able to call [WebMethod] of Service.