Monthly Archives: December 2013

Call Workflow from Javascript

This is the code needed.


function triggerBulkWorkflowByName(wfName, svid) {
    var wId = getWorkflowId(wfName);
    triggerWorkflow(wId, svid);
}

function getWorkflowId(wfName) {

    var urlPos = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/WorkflowSet?$filter=Name eq '" + wfName + "' and ParentWorkflowId/Id eq null";
    //var urlPos = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/WorkflowSet";

    var id;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        async: false,
        datatype: "json",
        url: urlPos,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data.d.results.length > 0) {
                id = data.d.results[0].WorkflowId;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Error");

        }
    });

    return id;
}

function triggerWorkflow(wfId, entityId) {

    try {
var soapBody = "<soap:Body>" + 
" <Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
 " <Request xsi:type=\'ExecuteWorkflowRequest\'>" +
 " <EntityId>" + entityId + "</EntityId>" +
 " <WorkflowId>" + wfId + "</WorkflowId>" +
 " </Request>" +
 " </Execute>" +
 "</soap:Body>";

/*Wrap the Soap Body in a soap:Envelope.*/
 var soapXml = "<soap:Envelope " +
 " xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' " +
 " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
 " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
 GenerateAuthenticationHeader() +
 soapBody +
 "</soap:Envelope>";

        /* Create the XMLHTTP object for the execute method.*/
        var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        xmlhttp.open("POST", "/MSCRMservices/2007/crmservice.asmx", false);
        xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
        /* Send the XMLHTTP object. */
        xmlhttp.send(soapXml);
    }

    catch (e) {
        alert("An error has occured: " + e.description);
    }

}

Creating Associate Plugin

The Plugin needs to be registered on Post Operation of the Associate Plugin.

Associate Plugin

Associate Plugin

From the Context variable we can obtain the target entity and the associated entities.


namespace Lema.SiteVisits.Plugins
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using Microsoft.Crm.Sdk;
    using Microsoft.Xrm.Sdk;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;

    public class PostSiteCategoryAssociate: 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);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));          

            if (!context.InputParameters.Contains("Relationship")) { return; }
            Relationship relationship = (Relationship)context.InputParameters["Relationship"];
            if (relationship.SchemaName != "mike_mike_sitevisit_mike_sitevisittype") { return; }
            
            if (!context.InputParameters.Contains("Target")) { return; }
            EntityReference target = (EntityReference)context.InputParameters["Target"];
            if (!context.InputParameters.Contains("RelatedEntities")) { return; }
            EntityReferenceCollection related = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];

            //Relationship is a reference to the relationship which this association is working against. i.e. mike_mike_sitevisit_mike_sitevisittype
            //Target is a reference to the primary Entity – i.e. Site Visit
            //RelatedEntities is a set of references pointing to the records to associate with – i.e. site Visits Type

            Guid SiteId = (Guid)target.Id;
            Entity sitev = service.Retrieve("mike_sitevisit", SiteId, new ColumnSet(true));

            string typenames = string.Empty;
            foreach (EntityReference sitetype in related)
            {
                typenames += sitetype.Name + ";";        
            }
            sitev.Attributes["mike_summary"] = typenames;
            service.Update(sitev);             
        }