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



No comments:

Post a Comment