Wednesday 30 August 2017

Deactivate Child Records When Parent Record Gets Deactivated Using Plugin in CRM

In my earlier post I have already written about cascade deactivate records using plugin.But this article is for deactivating child records once parent record gets deactivated.

Here I have Account lookup field present on Event Entity form. Once account record gets deactivated then it should deactivate related event record.Below screenshot follows :



1. Below code I wrote :

public void Execute(IServiceProvider serviceProvider)
       {
           ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
           IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
           IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
           IOrganizationService service = factory.CreateOrganizationService(context.UserId);

           if (context.InputParameters.Contains("EntityMoniker") && context.InputParameters["EntityMoniker"] is EntityReference)
           {
               var entity = (EntityReference)context.InputParameters["EntityMoniker"];
               var state = (OptionSetValue)context.InputParameters["State"];
               var status = (OptionSetValue)context.InputParameters["Status"];

               if(state.Value==1)
               {
                   QueryExpression event= new QueryExpression { EntityName = "ags_event", ColumnSet = new ColumnSet(true) };
                   event.Criteria.AddCondition("ags_account", ConditionOperator.Equal, entity.Id);
                   event.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
                   EntityCollection retrieveEvent = service.RetrieveMultiple(event);

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

               }
               if (state.Value == 0)
               {
                   QueryExpression event= new QueryExpression { EntityName = "ags_event", ColumnSet = new ColumnSet(true) };

                   event.Criteria.AddCondition("ags_account", ConditionOperator.Equal, entity.Id);
                   event.Criteria.AddCondition("statecode", ConditionOperator.Equal, 1);
                   EntityCollection retrieveEvent = service.RetrieveMultiple(event);


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

2. Register the plugin With message SetStateDynamicEntity on Account Entity.


Below Screenshots You can see :


 
Hope it may helps !!



Tuesday 29 August 2017

Cascade Deactivate Related Records Using Plugin in CRM

Today came up with a task regarding how we can deactivate related child records once parent record is getting deactivated.Below Screenshot shared :
 
Here My Requirement is : In Account entity i have lookup field with Event Entity(Parent Record).
Once Event record gets deactivated then related child records(Account Record) associated with Event entity must be deactivated.
I have done using c# plugin code.

1. Please find the below code :

public void Execute(IServiceProvider serviceProvider)
       {
           ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
           IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
           IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
           IOrganizationService service = factory.CreateOrganizationService(context.UserId);

           if (context.InputParameters.Contains("EntityMoniker") && context.InputParameters["EntityMoniker"] is EntityReference)
           {
               var entity = (EntityReference)context.InputParameters["EntityMoniker"];
               var state = (OptionSetValue)context.InputParameters["State"];
               var status = (OptionSetValue)context.InputParameters["Status"];

               if(entity.LogicalName=="ags_event" && state.Value==1)
               {
                   QueryExpression account = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet("accountid", "ags_event") };
                   account.Criteria.AddCondition("ags_event", ConditionOperator.Equal, entity.Id);
                   account.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
                   EntityCollection retrieveAccount = service.RetrieveMultiple(account);

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

               }
               if (state.Value == 0)
               {
                   QueryExpression account = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet("accountid", "ags_event") };

                   account.Criteria.AddCondition("ags_event", ConditionOperator.Equal, entity.Id);
                   account.Criteria.AddCondition("statecode", ConditionOperator.Equal, 1);
                   EntityCollection retrieveAccount = service.RetrieveMultiple(account);


                   if (retrieveAccount.Entities.Count > 0)
                   {
                       foreach (var a in retrieveAccount.Entities)
                       {
                           SetStateRequest accountRequest = new SetStateRequest();
                           accountRequest.EntityMoniker = new EntityReference(a.LogicalName, new Guid(a.Id.ToString()));
                           accountRequest.State = new OptionSetValue(0);
                           accountRequest.Status = new OptionSetValue(-1);
                           service.Execute(accountRequest);
                       }
                   }
               }
           }
       }
2. Register this c# code on setStateDynamicEntity Message using Plugin Registration Tool.



Hope it would be helpful to someone !!

Friday 11 August 2017

Dynamically disable fields getting from external files based on Option sets Values in CRM

This blog is for dynamically how we can disable the fields in CRM Using external files based on condition.
I am maintaining all the fields in XML file, which we want to disable, see the below one :

<?xml version="1.0" encoding="utf-8" ?>
<CaseEntity>
  <DisableFields>
    <name>ags_customer</name>
  </DisableFields>
  <DisableFields>
    <name>ags_casetype</name>
  </DisableFields>
  <DisableFields>
    <name>ags_subcategory</name>
  </DisableFields>
  <DisableFields>
    <name>ags_casepriority</name>
  </DisableFields>
</CaseEntity>


Create Web resource with XML type the above one.
Add Javascript with the below one :

function ReadXml() {
    alert("Hello");
    var xmlPath = "../WebResources/ags_ExternalXMLFile.xml";
    $.ajax({
        type: "GET",
        url: xmlPath,
        dataType: "xml",
        success: parseXML
    });
}
function parseXML(xml) {
    $(xml).find("DisableFields").each(function () {

        var fieldName = $(this).find("name").text();
        var optValue = Xrm.Page.getAttribute("ags_externalsystem").getValue();
        if (optValue == 283210000) {
            alert("Hi");
            Xrm.Page.getControl(fieldName).setDisabled(true);
        }
        else {
            alert("Error");
            Xrm.Page.getControl(fieldName).setDisabled(false);
        }
    });
}
Here, using ajax calling the XML file based on option sets value disabling the fields which are defined in XML file.

Hope it would be useful !!
Happy Coding !!

Display CRM Records in CRM portal 365 Using Liquid

I came up with a task to show crm entity records in Portal using liquid.













Here how I have done :
1. Get fetch XML records from an Advanced find in CRM & Create Web Template in the portal with below code :

<script src="cdn.datatables.net/.../jquery.dataTables.min.js"></script>
<script src="cdn.datatables.net/.../dataTables.bootstrap.min.js"></script>
<script>
$(document).ready(function(){
    $('#grid').DataTable();
});
</script>
<table class="table table-striped table-bordered" id="grid" cellspacing="0" style="width:90%; margin-left: 107px;">
    <thead>
      <tr>
        <th>Name</th>
        <th>Passport Number</th>
        <th>Address</th>
        <th>Emergency Contact No</th>
        <th>Created On</th>
      </tr>
    </thead>
    <tbody>
      {% if user%}
      {% fetchxml fetch_query %}
          <fetch mapping="logical" returntotalrecordcount="true">
                    <entity name="ags_event">
                        <attribute name="ags_eventid" />
                        <attribute name="ags_name" />
                        <attribute name="createdon" />
                        <attribute name="ags_address" />
                        <attribute name="ags_passportnumber" />
                        <attribute name="ags_emergencycontactno" />
                        <order attribute="ags_name" descending="false" />
                     
                    </entity>
                </fetch>
                {% endfetchxml %}
                {% assign result = fetch_query.results.entities %}
                {% for item in result %}
                <tr>                
                    <td>{{item.ags_name}}</td>
                    <td>{{item.ags_passportnumber}}</td>
                    <td>{{item.ags_address}}</td>
                    <td>{{item.ags_emergencycontactno}}</td>
                    <td>{{item.createdon}}</td>
                </tr>
                {% endfor %}
                {% else %}
                <tr>
                    <td>No Records Found</td>
                </tr>
                {% endif %}
            </tbody>
        </table>

In above fetch query, you can put your query & here I am using the bootstrap grid (Instead of this we can use Jqgrid also ).In later I will write blogs on this.

2. Now, Create Page template by taking this web template. Then Create Web Page with this page template & set the web page under primary navigation Page in Portal side.

Hope it would be helpful to someone !!