Friday, 19 January 2018

Clone Opportunity Record Using Action in CRM Online 365

I came up with a task of cloning opportunity records on click of a button in Opportunity Form.
Below procedures I have followed :
1. Added button in Opportunity form using Ribbon Workbench.
2.Create an action in CRM with input parameter & output parameter like below:
2. Below Scripts, I kept on the button :

function executeCustomActionSynchronous(entityId, entityCollectionName, actionName, parameters, isGlobalAction) {
    debugger;
    var query = "";
    var req = "";
    var response = {};
    stringParameterCheck(actionName, "XrmUtilities.webAPI.executeCustomActionSynchronous requires the actionName parameter is a string.");
    if (!isNullOrUndefined(isGlobalAction) && isGlobalAction !== true) {
        entityId = entityId.replace("{", "").replace("}", "");
        stringParameterCheck(entityId, "XrmUtilities.webAPI.executeCustomAction requires the e entityId parameter is a string.");
        stringParameterCheck(entityCollectionName, "XrmUtilities.webAPI.executeCustomAction requires the entityCollectionName parameter is a string.");
        query = entityCollectionName + "(" + entityId + ")/Microsoft.Dynamics.CRM." + actionName;
    }
    else {
        query = actionName;
    }
    req = new XMLHttpRequest();
    req.open("POST", getWebAPIPath() + query, false);
    setRequestHeaders(req, false);
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            switch (this.status) {
                case 200:
                    response.status = true;
                    response.results = JSON.parse(this.response);
                    break;
                case 204:
                    response.status = true;
                    break;
                case 1223:
                    response.status = true;
                    break;
                default:
                    response.status = false;
                    response.error = JSON.parse(this.response).error;
            }
        }
    };
    req.send((!isNullOrUndefined(parameters)) ? JSON.stringify(parameters) : null);
    return response;
};
function isNullOrUndefined(value) {
    return (typeof (value) === "undefined" || value === null);
};
function getWebAPIPath() {
    return getClientUrl() + "/api/data/v8.1/";
};
function getClientUrl() {
    var clientUrl = context().getClientUrl();
    return clientUrl;
};
function context() {
    ///<summary>
    /// Private function to the context object.
    ///</summary>
    ///<returns>Context</returns>
    var oContext = null;
    if (!isNullOrUndefined(window.parent.Xrm)) {
        oContext = window.parent.Xrm.Page.context;
    }
    else if (!isNullOrUndefined(window.GetGlobalContext)) {
        oContext = window.GetGlobalContext();
    }
    else if (!isNullOrUndefined(Xrm)) {
        oContext = Xrm.Page.context;
    }
    else {
        throw new Error("Context is not available.");
    }
    return oContext;
};
function stringParameterCheck(parameter, message) {
    if (typeof parameter !== "string") {
        throw new Error(message);
    }
};
function setRequestHeaders(req, includeFormattedValues, customHeaders) {
    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");
    if (!(!isNullOrUndefined(includeFormattedValues) && includeFormattedValues === false)) {
        req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
    }
    var arrayName = [];
    if (!(customHeaders && customHeaders.constructor === arrayName.constructor)) {
        customHeaders = [];
    }
    customHeaders.forEach(function (h) {
        switch (h.key) {
            case "Accept":
            case "Content-Type":
            case "OData-MaxVersion":
            case "OData-Version":
            case "Prefer":
                break;
            default:
                req.setRequestHeader(h.key, h.value);
        }
    });
};
function copyOpportunityRecord() {
    debugger;
    var opportunityId = Xrm.Page.data.entity.getId();
    var parameters =
    {
        ActionType: opportunityId.toString()
    };
    var Result = executeCustomActionSynchronous(opportunityId, "opportunities", "ags_CopyOpportunityAction", parameters, false)
    var id = Result.results.OppId;
    var options = { openInNewWindow: true };
    Xrm.Utility.openEntityForm("opportunity", id,null,options);
}

3. Below plugin 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);
            try
            {
                tracingService.Trace("Checking plugin");
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
                {
                    EntityReference opportunity = (EntityReference)context.InputParameters["Target"];
                    string opportunityId = context.InputParameters["ActionType"].ToString();
                    tracingService.Trace("Check Action Parameter" + opportunityId);
                    Guid id = Guid.Parse(opportunityId);
                    Guid newOpportunityId = CreateOpportunityRecord(service, id);
                    //tracingService.Trace(id);
                    context.OutputParameters["OppId"] = newOpportunityId.ToString();
                    tracingService.Trace("Successfully Created");
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("An Error occurred in plugin.", ex);
            }
        }
          /// <summary>
          /// Create Opportunity Record
          /// </summary>
          /// <param name="service"></param>
          /// <param name="id"></param>
          /// <returns></returns>
        private Guid CreateOpportunityRecord (IOrganizationService service, Guid id)
        {
            Entity oppEntity = service.Retrieve("opportunity", id, new ColumnSet(true));
            oppEntity.Attributes.Remove("opportunityid");
            oppEntity.Attributes.Remove("createdon");
            oppEntity.Attributes.Remove("modifiedon");
            oppEntity.Attributes.Remove("modifiedby");
            Entity opportunity = new Entity("opportunity");
            opportunity.Attributes = oppEntity.Attributes;
            return service.Create(opportunity);
        }
4. Registered the dll file in plugin registration tool & here I took message as my action which i have created on opportunity.

Hope it will helps !!



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 !!