Tuesday, August 28, 2012

How to add custom button in entity? and how to set custom rules for the added buttons in MS CRM 2011?




Use the below defined XML code to add custom button and set custom rules.

      <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="vps.Form.quote.MainTab.Actions.Button.Approve.CustomAction" Location="Mscrm.Form.quote.MainTab.Actions.Controls._children" Sequence="20">
            <CommandUIDefinition>
              <Button Id="vps.Form.quote.MainTab.Actions.Button.Approve" Command="vps.Form.quote.MainTab.Actions.Button.Approve.Command" LabelText="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Approve.LabelText" ToolTipTitle="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Approve.LabelText" ToolTipDescription="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Approve.ToolTip" TemplateAlias="o1" Image16by16="$webresource:new_approved16" Image32by32="$webresource:new_approved32" />
            </CommandUIDefinition>
          </CustomAction>
          <CustomAction Id="vps.Form.quote.MainTab.Actions.Button.Reject.CustomAction" Location="Mscrm.Form.quote.MainTab.Actions.Controls._children" Sequence="30">
            <CommandUIDefinition>
              <Button Id="vps.Form.quote.MainTab.Actions.Button.Reject" Command="vps.Form.quote.MainTab.Actions.Button.Reject.Command" LabelText="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Reject.LabelText" ToolTipTitle="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Reject.LabelText" ToolTipDescription="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Reject.ToolTip" TemplateAlias="o1" Image16by16="$webresource:new_reject16" Image32by32="$webresource:new_reject32" />
            </CommandUIDefinition>
          </CustomAction>
          <CustomAction Id="vps.Form.quote.MainTab.Actions.Button.Seek.CustomAction" Location="Mscrm.Form.quote.MainTab.Actions.Controls._children" Sequence="10">
            <CommandUIDefinition>
              <Button Id="vps.Form.quote.MainTab.Actions.Button.Seek" Command="vps.Form.quote.MainTab.Actions.Button.Seek.Command" LabelText="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Seek.LabelText" ToolTipTitle="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Seek.LabelText" ToolTipDescription="$LocLabels:vps.Form.quote.MainTab.Actions.Button.Seek.ToolTip" TemplateAlias="o1" Image16by16="$webresource:new_seekdiscount16" Image32by32="$webresource:new_seekdiscount32" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="vps.Form.quote.MainTab.Actions.Button.Approve.Command">
            <EnableRules>
              <EnableRule Id="vps.Form.quote.CheckApprovalDiscountPercentageValue.EnableRule" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="vps.Form.quote.CheckApprovalDiscountPercentageValue.DisplayRule" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction Library="$webresource:new_vpsquote" FunctionName="approvediscountrequest" />
            </Actions>
          </CommandDefinition>
          <CommandDefinition Id="vps.Form.quote.MainTab.Actions.Button.Reject.Command">
            <EnableRules>
              <EnableRule Id="vps.Form.quote.CheckRejectDiscountPercentageValue.EnableRule" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="vps.Form.quote.CheckRejectDiscountPercentageValue.DisplayRule" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction Library="$webresource:new_vpsquote" FunctionName="rejectdiscountrequest" />
            </Actions>
          </CommandDefinition>
          <CommandDefinition Id="vps.Form.quote.MainTab.Actions.Button.Seek.Command">
            <EnableRules>
              <EnableRule Id="vps.Form.quote.CheckDiscountPercentageValue.EnableRule" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="vps.Form.quote.CheckDiscountPercentageValue.DisplayRule" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction Library="$webresource:new_vpsquote" FunctionName="seekapprovalfordiscount" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules>
            <DisplayRule Id="vps.Form.quote.CheckApprovalDiscountPercentageValue.DisplayRule">
              <FormStateRule State="Create" InvertResult="true" />
            </DisplayRule>
            <DisplayRule Id="vps.Form.quote.CheckDiscountPercentageValue.DisplayRule">
              <FormStateRule State="Create" InvertResult="true" />
            </DisplayRule>
            <DisplayRule Id="vps.Form.quote.CheckRejectDiscountPercentageValue.DisplayRule">
              <FormStateRule State="Create" InvertResult="true" />
            </DisplayRule>
          </DisplayRules>
          <EnableRules>
            <EnableRule Id="vps.Form.quote.CheckApprovalDiscountPercentageValue.EnableRule">            
              <CustomRule Library="$webresource:new_vpsquote" FunctionName="CustomRuleForApproveReject" Default="true" />
            </EnableRule>
            <EnableRule Id="vps.Form.quote.CheckDiscountPercentageValue.EnableRule">
              <ValueRule Field="discountpercentage" Value="null" InvertResult="true" />
              <CustomRule Library="$webresource:new_vpsquote" FunctionName="QuoteDiscountOnChange" Default="true" />
            </EnableRule>
            <EnableRule Id="vps.Form.quote.CheckRejectDiscountPercentageValue.EnableRule">            
              <CustomRule Library="$webresource:new_vpsquote" FunctionName="CustomRuleForApproveReject" Default="true" />
            </EnableRule>
          </EnableRules>
        </RuleDefinitions>
        <LocLabels>
          <LocLabel Id="vps.Form.quote.MainTab.Actions.Button.Approve.LabelText">
            <Titles>
              <Title languagecode="1033" description="Approve Discount" />
            </Titles>
          </LocLabel>
          <LocLabel Id="vps.Form.quote.MainTab.Actions.Button.Approve.ToolTip">
            <Titles>
              <Title languagecode="1033" description="Approve discount request" />
            </Titles>
          </LocLabel>
          <LocLabel Id="vps.Form.quote.MainTab.Actions.Button.Reject.LabelText">
            <Titles>
              <Title languagecode="1033" description="Reject Discount" />
            </Titles>
          </LocLabel>
          <LocLabel Id="vps.Form.quote.MainTab.Actions.Button.Reject.ToolTip">
            <Titles>
              <Title languagecode="1033" description="Reject discount request" />
            </Titles>
          </LocLabel>
          <LocLabel Id="vps.Form.quote.MainTab.Actions.Button.Seek.LabelText">
            <Titles>
              <Title languagecode="1033" description="Seek Discount" />
            </Titles>
          </LocLabel>
          <LocLabel Id="vps.Form.quote.MainTab.Actions.Button.Seek.ToolTip">
            <Titles>
              <Title languagecode="1033" description="Seek approval for discount" />
            </Titles>
          </LocLabel>
        </LocLabels>
      </RibbonDiffXml>


How to Create WorkFlow Activity and the use of Output parameters in MS CRM 2011?


Use the following line of code to create complete workflow activity with two output parameters.

1) Open Visual Studio 2010 ID.
2) Open New Project.
3) Select Class Library Template.
4) Go to Properties of Project
5) Set Framework 4
6) Sign the assembly.
7) Copy the below lines of code and paste.
8) Register Work Flow Activity using the plugin registration tool.
9) Create workflow.
10) To debug the workflow activity code connect it with crmAsyn process.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Collections.ObjectModel;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;
using System.Collections;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities.Rules;

namespace CRM2011WFA
{
    public sealed class FeasibilityTask : CodeActivity
    {
        [Output("ManagerMailId")]
        [Default("Not Found")]
        public OutArgument ManagerMailId { get; set; }

        [Output("Manager")]
        [Default("7B1C0F8D-8425-E111-906B-00155D00A500", "systemuser")]
        [ReferenceTarget("systemuser")]
        public OutArgument Manager { get; set; }

        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingservice = executionContext.GetExtension();
            IWorkflowContext context = executionContext.GetExtension();
            IOrganizationServiceFactory servicefactory = executionContext.GetExtension();
            IOrganizationService service = servicefactory.CreateOrganizationService(context.UserId);

            tracingservice.Trace("Feasibility Task Start");

            #region Variables
            bool IsTaskExist = false;
            Guid FRequestId = context.PrimaryEntityId;
            #endregion Variables

            #region Check Task Already Exist for the selected Feasibility Request for admin user
            tracingservice.Trace("Retrieve the task using QueryByAttribute");
            QueryByAttribute query = new QueryByAttribute();
            query.Attributes.AddRange(new string[] { "regardingobjectid", "subject" });
            query.ColumnSet = new ColumnSet(new string[] { "subject" });
            query.EntityName = "task";
            query.Values.AddRange(new object[] { FRequestId, "Check Feasibility" });

            tracingservice.Trace("Executing the Query for entity {0}", query.EntityName);


            //Execute using a request to test the OOB (XRM) message contracts
            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            Collection entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
            if (1 != entityList.Count)
            {
                tracingservice.Trace("The CHeck Feasibility Not Exists");
                IsTaskExist = false;
                //throw new InvalidPluginExecutionException("Query did not execute correctly");
            }
            else
            {
                tracingservice.Trace("Casting the Task from RetrieveMultiple to strong type");
                Entity retrievedTask = entityList[0];
                if (retrievedTask.Id != Guid.Empty)
                {
                    IsTaskExist = true;
                }
            }

            #endregion Check Task Already Exist for the selected Feasibility Request for admin user

            #region Create Task for the selected Feasibility Request for admin user
            Guid OpportunityId = Guid.Empty;
            if (!IsTaskExist)
            {
                if (context.InputParameters != null)
                {
                    OpportunityId = SerializeParamCollection(context.InputParameters);
                }
            }
            #endregion Create Task for the selected Feasibility Request for admin user

            #region Get Business Unit ID of the Opportunity
            Guid BUId = Guid.Empty;
            if (OpportunityId != Guid.Empty)
            {
                tracingservice.Trace("Retrieve the BUID using Opportunity");
                QueryByAttribute queryBU = new QueryByAttribute();
                queryBU.Attributes.AddRange(new string[] { "opportunityid" });
                queryBU.ColumnSet = new ColumnSet(new string[] { "owningbusinessunit" });
                queryBU.EntityName = "opportunity";
                queryBU.Values.AddRange(new object[] { OpportunityId });

                tracingservice.Trace("Executing the Query for entity {0}", queryBU.EntityName);

                //Execute using a request to test the OOB (XRM) message contracts
                RetrieveMultipleRequest requestBU = new RetrieveMultipleRequest();
                requestBU.Query = queryBU;
                Collection entityListBU = ((RetrieveMultipleResponse)service.Execute(requestBU)).EntityCollection.Entities;
                if (1 != entityListBU.Count)
                {
                    tracingservice.Trace("BUID Not Exists");
                }
                else
                {
                    tracingservice.Trace("Casting the Opportunity from RetrieveMultiple to strong type");
                    Entity retrievedOpp = entityListBU[0];
                    if (retrievedOpp.Id != Guid.Empty)
                    {
                        BUId = ((EntityReference)retrievedOpp["owningbusinessunit"]).Id;
                    }
                }
            }

            #endregion Get Business Unit ID of the Opportunity

            #region Find Admin User in The Opportunity Business Unit ID
            Guid TaskOwner = Guid.Empty;
            if (BUId != Guid.Empty)
            {
                TaskOwner = FindAdminUser(service, BUId);
                if (TaskOwner != Guid.Empty)
                {
                    #region Create task for feasibility request
                    Entity task = new Entity("task");
                    task["subject"] = "Check Feasibility";
                    task["regardingobjectid"] = new EntityReference("new_feasibilityrequest", FRequestId);
                    task["ownerid"] = new EntityReference("systemuser", TaskOwner);
                    task["description"] = "Please check the Feasibility for this opportunity";
                    Guid TaskID = service.Create(task);

                    #region Get and set Manager & Manager Mail ID in Output parameters
                    QueryExpression qe = new QueryExpression();
                    qe.EntityName = "systemuser";
                    qe.ColumnSet = new ColumnSet(true);

                    qe.LinkEntities.Add(new LinkEntity("systemuser", "systemuser", "systemuserid", "parentsystemuserid", JoinOperator.Inner));
                    ConditionExpression ce = new ConditionExpression("systemuserid", ConditionOperator.Equal, new Object[] { TaskOwner });
                    qe.Criteria.AddCondition(ce);

                    EntityCollection ec = service.RetrieveMultiple(qe);

                    if (ec.Entities.Count > 0)
                    {
                        foreach (Entity act in ec.Entities)
                        {
                            Manager.Set(executionContext, new EntityReference("systemuser", new Guid(act.Attributes["systemuserid"].ToString())));
                            ManagerMailId.Set(executionContext, act.Attributes["internalemailaddress"].ToString());
                        }
                    }
                    else
                        ManagerMailId.Set(executionContext, "Not Found");
                    #endregion Get and set Manager & Manager Mail ID in Output parameters

                    #endregion Create task for for easibility request
                }
                else
                {
                    ManagerMailId.Set(executionContext, "Not Found");
                }
            }
            else
            {
                ManagerMailId.Set(executionContext, "Not Found");
            }
            #endregion Find Admin User in The Opportunity Business Unit ID

        }

        private static Guid FindAdminUser(IOrganizationService service, Guid BUId)
        {
            Guid adminUserId = Guid.Empty;

            QueryExpression qe = new QueryExpression();
            qe.EntityName = "systemuser";
            ColumnSet columns = new ColumnSet();
            columns.AddColumn("systemuserid");
            columns.AddColumn("fullname");
            qe.ColumnSet = columns;

            LinkEntity leRole = new LinkEntity("systemuser", "systemuserroles", "systemuserid", "systemuserid", JoinOperator.Inner);
            LinkEntity le = new LinkEntity("systemuserroles", "role", "roleid", "roleid", JoinOperator.Inner);

            ConditionExpression ce = new ConditionExpression("name", ConditionOperator.Equal, new Object[] { "Admin User" });
            ConditionExpression cebu = new ConditionExpression("businessunitid", ConditionOperator.Equal, new Object[] { BUId });

            le.LinkCriteria = new FilterExpression();
            le.LinkCriteria.AddCondition(ce);
            le.LinkCriteria.AddCondition(cebu);

            leRole.LinkEntities.Add(le);
            qe.LinkEntities.Add(leRole);

            EntityCollection ec = service.RetrieveMultiple(qe);
            if (ec.Entities.Count > 0)
            {
                foreach (Entity act in ec.Entities)
                {
                    adminUserId = new Guid(act["systemuserid"].ToString());
                }
            }
            else
            {
                Guid ParentBunitid = GetParentBU(service, BUId);
                if (ParentBunitid != Guid.Empty)
                {
                    adminUserId = FindAdminUser(service, ParentBunitid);
                }
            }

            return adminUserId;
        }

        private static Guid GetParentBU(IOrganizationService service, Guid BUId)
        {
            Guid ParentBUID = Guid.Empty;
            QueryByAttribute queryBU = new QueryByAttribute();
            queryBU.Attributes.AddRange(new string[] { "businessunitid" });
            queryBU.ColumnSet = new ColumnSet(new string[] { "parentbusinessunitid" });
            queryBU.EntityName = "businessunit";
            queryBU.Values.AddRange(new object[] { BUId });

            //Execute using a request to test the OOB (XRM) message contracts
            RetrieveMultipleRequest requestBU = new RetrieveMultipleRequest();
            requestBU.Query = queryBU;
            Collection entityListBU = ((RetrieveMultipleResponse)service.Execute(requestBU)).EntityCollection.Entities;
            if (entityListBU.Count != 0)
            {
                Entity retrievedOpp = entityListBU[0];
                if (retrievedOpp.Id != Guid.Empty)
                {
                    ParentBUID = retrievedOpp.Id;
                }
            }
            return ParentBUID;
        }

        private static string SerializeEntityImageCollection(EntityImageCollection entityImageCollection)
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair entityImage in entityImageCollection)
            {
                sb.Append(Environment.NewLine);
                sb.Append(entityImage.Key + ": " + SerializeEntity(entityImage.Value));
            }
            return sb.ToString();
        }

        private static string SerializeParameterCollection(ParameterCollection parameterCollection)
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair parameter in parameterCollection)
            {
                if (parameter.Value != null && parameter.Value.GetType() == typeof(Entity))
                {
                    Entity e = (Entity)parameter.Value;
                    sb.Append(parameter.Key + ": " + SerializeEntity(e));
                }
                else
                {
                    sb.Append(parameter.Key + ": " + parameter.Value + "; ");
                }
            }
            return sb.ToString();
        }

        private static string SerializeEntity(Entity e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Environment.NewLine);
            sb.Append(" LogicalName: " + e.LogicalName);
            sb.Append(Environment.NewLine);
            sb.Append(" EntityId: " + e.Id);
            sb.Append(Environment.NewLine);
            sb.Append(" Attributes: [");
            foreach (KeyValuePair parameter in e.Attributes)
            {
                sb.Append(parameter.Key + ": " + parameter.Value + "; ");
            }
            sb.Append("]");
            return sb.ToString();
        }

        private Guid SerializeParamCollection(ParameterCollection parameterCollection)
        {
            Guid oppid = new Guid();
            foreach (KeyValuePair parameter in parameterCollection)
            {
                if (parameter.Value != null && parameter.Value.GetType() == typeof(Entity))
                {
                    Entity e = (Entity)parameter.Value;
                    oppid = OpportunityId(e);
                    break;
                }
            }
            return oppid;
        }

        private Guid OpportunityId(Entity e)
        {
            Guid oppid = new Guid();
            foreach (KeyValuePair parameter in e.Attributes)
            {
                if (parameter.Key == "new_opportunity_new_feasibilityrequid")
                {
                    oppid = ((EntityReference)(parameter.Value)).Id;
                    break;
                }
            }

            return oppid;
        }
    }
}

Thursday, August 23, 2012

Call WebService using Javascript Soap request.

Use the following line of code to access webservice in Javascript

function WSRetrieveMultipleByMultipleCondition(crmEntity, resultAttribute, queryAttributeandValue) {
var resultXml,arrayqueryAttribute,xmlAttributeandValue,arrayresultAttribute,xmlresultAttribute;
arrayqueryAttribute = queryAttributeandValue.split(",");
    for (var i = 0; i < arrayqueryAttribute.length; i++) {
        var Attribute,Value,arrayAttributeandValue;
        AttributeandValue=arrayqueryAttribute[i].split("|");
        Attribute=AttributeandValue[0];
        Value=AttributeandValue[1];       
        xmlAttributeandValue +=""+
        ""+Attribute+""+
        "Like"+
        ""+
        ""+Value+""+
        "
"+
        "
"
    }

arrayresultAttribute = resultAttribute.split(",");
    for (var i = 0; i < arrayresultAttribute.length; i++) {
        var AttributeName;
        AttributeName=arrayresultAttribute[i];
        xmlresultAttribute +="" + AttributeName + ""
    }   
   
var oXMLSoapMsg = ""+
"" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader().toString()+
""+
""+
"" xsi:type='q1:QueryExpression'>"+
""+crmEntity+""+
""+
""+
xmlresultAttribute+
"
"+
"
"+
"false"+
""+
"And"+
""+
xmlAttributeandValue +
"
"+
"
"+
"
"+
"
"+
"
"+
"
";
var oXMLHTTPReq = new ActiveXObject("Msxml2.XMLHTTP");
oXMLHTTPReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
oXMLHTTPReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
oXMLHTTPReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
oXMLHTTPReq.setRequestHeader("Content-Length", oXMLSoapMsg.length);
oXMLHTTPReq.send(oXMLSoapMsg);
resultXml = oXMLHTTPReq.responseXML;

var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0){
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
else{
    return resultXml;
}
}

//You can call the above function using the below line of code
function UserRole(checkrolename)
{
    //Get Current User Roles RoleID
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    var roleidName='';
    for (var i = 0; i < currentUserRoles.length; i++) {
        var userRoleId = currentUserRoles[i];
        var resultAttribute, queryAttributeandValue;
        resultAttribute="name";
        queryAttributeandValue="roleid|"+userRoleId;
        var resultXml=WSRetrieveMultipleByMultipleCondition("role",resultAttribute,queryAttributeandValue);
        var buNodes = resultXml.selectNodes("//BusinessEntity/q1:name");
        var NodeExist = buNodes.length;
        if (NodeExist >=1)
        {
            //alert('Role Name - ' + buNodes[0].text);
            roleidName= buNodes[0].text;
            if(roleidName==checkrolename)
            {break;}
        }
    }
    return roleidName;
}

How to Create a parent child optionSet/PickList in MS CRM 2011?

To make a Parent Child OptionSet or PickList in MS CRM 2011 use the following line of code:

Also You can change values in second OptionSet based on first OptionSet Value

function PicklistOneOnchange() {
    var picklistOneName = "new_healthplantype"; //name of the first picklist
    var picklistTwoName = "new_healthinsuranceplan";  //name of the picklist with dynamic values
   
    var picklistOne = Xrm.Page.getControl(picklistOneName);
    var picklistOneAttribute = picklistOne.getAttribute();
   
    var picklistTwo = Xrm.Page.getControl(picklistTwoName);
    var picklistTwoAttribute = picklistTwo.getAttribute();
       
       var picklistOneSelectedOption = picklistOneAttribute.getSelectedOption();
   
    var picklistOneSelectedText = "";   
    if (picklistOneSelectedOption != null)
    {
        picklistOneSelectedText = picklistOneSelectedOption.text;
    }

    //This "if" statement stores the original values from the dynamic picklist.
    //Very important if the user hasn't made a selection on the first picklist or if the selection changes
    if (picklistTwo.flag == true)
    {
        picklistTwo.clearOptions();
        var origOptions = picklistTwo.originalPicklistValues;
       
        for (var i = origOptions.length - 1; i >= 0; i--)
        {
            if(origOptions[i].text != "")
            {
                picklistTwo.addOption(origOptions[i]);
            }
        }       
    }
    else
    {       
        picklistTwo.originalPicklistValues = picklistTwoAttribute.getOptions();
        picklistTwo.flag = true;
    }

    if (picklistOneSelectedText != null && picklistOneSelectedText != "")
    {       
        var picklistTwoOptions = picklistTwoAttribute.getOptions();
        for (var i = picklistTwoOptions.length - 1; i >= 0; i--) { 
           
            if (picklistTwoOptions[i].value != null && picklistTwoOptions[i].value != "") {
                var optionText = picklistTwoOptions[i].text;
                var optionValue = picklistTwoOptions[i].value;
               
                //BEGIN: If the picklist is set to HMO
                if(picklistOneSelectedText == "HMO")
                {                           
                    //Remove these values
                    if (optionText == "PPO 500" || optionText == "PPO 750" || optionText == "POS Silver" || optionText == "POS Gold")
                    {
                        picklistTwo.removeOption(optionValue);
                    }

                }
                //END: HMO Selection
               
                //BEGIN: If the picklist is set to PPO
                if(picklistOneSelectedText == "PPO")
                {
                    //Remove these values
                    if (optionText == "HMO 5K" || optionText == "HMO 7K" || optionText == "POS Silver" || optionText == "POS Gold")
                    {
                        picklistTwo.removeOption(optionValue);
                    }

                }           
                //END: PPO Selection
               
                //BEGIN: If the picklist is set to POS
                if(picklistOneSelectedText == "POS")
                {
                    //Remove these values
                    if (optionText == "HMO 5K" || optionText == "HMO 7K" || optionText == "PPO 500" || optionText == "PPO 750")
                    {
                        picklistTwo.removeOption(optionValue);
                    }

                }       
                //END: POS Selection
            }
        }
    }
   
}

How to make Read Only Tab in CRM? How to Make read only all the attribute in a specified Tab?

Use the following line of code to make all the fields within a tab as read only or disabled.

// get the div element corresponding to tab, first tab would have index tab0, second as tab1 and so on ..
var el=document.getElementById('tab2')

// create a recursive function to Disable Attributes
function toggleDisabled(el) {
try {
el.disabled = el.disabled ? false : true;
}
catch(E){}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}

// create a recursive function to Enable Attributes
function toggleEnabled(el) {
try {
el.disabled = el.disabled ? true : false;
}
catch(E){}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleEnabled(el.childNodes[x]);
}
}
}

Wednesday, August 22, 2012

JavaScript to hide left navigation from form in CRM 2011

Question: How to Hide Left Navigation?
Answer: Here in CRM 2011 two options are available to hide left navigation Item pane

Option 1:

  • Open CRM form customization screen
  • Click on “Form Properties” button in  ”Form” tab
  • Go to “Display” tab and uncheck “Show navigation items” (Refer screen below)
  • Save & Publish

After this setting “Open” the form and you will get form without “Navigation” section 

Option 2:

Left navigation item pane divided in multiple categories, all are listed here

1 hide the left navigation pane

document.getElementById(“crmNavBar”).parentElement.style.display = “none”;

after hiding the crmform’s content panel moves to left
to set it back to full width set the colspan
document.getElementById(“tdAreas”).parentElement.parentElement.parentElement.parentElement.colSpan = 2;

hide the related section and the table below it.


document.getElementById(“crmFormNavSubareas”).parentElement.style.display = “none”;
document.getElementById(“crmFormNavSubareas”).parentElement.parentElement.previousSibling.style.display = “none”;


hide the section Item


Xrm.Page.ui.navigation.items.get(“navActivities”).setVisible(false);
Xrm.Page.ui.navigation.items.get(“navActivityHistory”).setVisible(false);

Monday, August 20, 2012

How to write code in JavaScript for an entity quote in MS CRM 2011 or 4.0

var managerguid='nomanager';
var rolesDiscountvalue=0,quotediscountvalue=0;
function QuoteOnLoad()
{
    if(crmForm.FormType==2)//form updated
    {
            if(!CurrentandQuoteUsersareEqual())
            {
//alert('update form');
                Xrm.Page.ui.controls.get("discountpercentage").setDisabled(true);
                Xrm.Page.ui.controls.get("discountamount").setDisabled(true);
                Xrm.Page.ui.controls.get("freightamount").setDisabled(true);
                /*Hide Activate quote button*/
                HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
            }
            quotediscountvalue=Xrm.Page.data.entity.attributes.get("discountpercentage").getValue();            if(quotediscountvalue == null || quotediscountvalue == 0)
            {
                disablecustomdiscount(true);//disable fields               
            }
    }
}

function Enablecustomdiscount(boolvalue)
{
    Xrm.Page.ui.controls.get("new_approvaldiscount").setDisabled(boolvalue);
    Xrm.Page.ui.controls.get("new_reasonfordiscountap").setDisabled(boolvalue);
    Xrm.Page.ui.controls.get("new_approvaldiscountamount").setDisabled(boolvalue);   
}

function disablecustomdiscount(boolvalue)
{
    Xrm.Page.ui.controls.get("new_approvaldiscount").setDisabled(boolvalue);
    Xrm.Page.ui.controls.get("new_reasonfordiscountrequest").setDisabled(boolvalue);
    Xrm.Page.ui.controls.get("new_reasonfordiscountap").setDisabled(boolvalue);
    Xrm.Page.ui.controls.get("new_approvaldiscountamount").setDisabled(boolvalue);   
}

function CurrentandQuoteUsersareEqual()
{
    var LoggedInUserGUID = Xrm.Page.context.getUserId();
    var QuoteOwnerGUID = Xrm.Page.data.entity.attributes.get("ownerid").getValue()[0].id;
    if(GuidsAreEqual(LoggedInUserGUID,QuoteOwnerGUID))// if both are equal
    {
        return true;
    }
    else
    {
        return false;
    }
}

function QuoteDiscountOnChange()
{
//alert('QuoteDiscountOnChange');
//debugger;
   quotediscountvalue=Xrm.Page.data.entity.attributes.get("discountpercentage").getValue();     
   rolesDiscountvalue=GetCurrentUserRoleDiscountValue();
   if(rolesDiscountvalue>=quotediscountvalue)
   {
//alert('1');
       //Valid discount value  (Enable Approve and Reject Discount Button)
        if(CurrentandQuoteUsersareEqual())
        {
            disablecustomdiscount(true);//disable fields
        }
        else if(!CurrentandQuoteUsersareEqual() && (Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()=='Pending' || Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()=='Rejected'))
        {
//alert('11');
            /*Hide Activate quote button*/
            HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
                                                                Enablecustomdiscount(false);
                                                                Xrm.Page.ui.controls.get("new_reasonfordiscountrequest").setDisabled(true);
        }
        return false;//disable
   }
   else if(rolesDiscountvalue<quotediscountvalue && Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()==null)
   {
//alert('2');
        //InValid discount value  (Enable Approve and Reject Discount Button)
        alert('Your quote discounted % is more then that specified discount for you! If you required this % please save the quote and click seek for discount.');
/*Hide Activate quote button*/
        HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
        Xrm.Page.ui.controls.get("new_reasonfordiscountap").setDisabled(true);
        return true;//enable
   }
   else if(rolesDiscountvalue<quotediscountvalue && Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()=='Pending')
   {
//alert('3');
       //Invalid discount value (Disable Approve and Reject Discount Button)
/*Hide Activate quote button*/
        HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
       disablecustomdiscount(true);//disable fields
        return false;//disable
   }
   else if(Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()=='Approved')
   {
//alert('4');
       //Invalid discount value (Disable Approve and Reject Discount Button)       
        return false;//disable
   }
   else
   {
//alert('5');

        return true;//enable
   }  
}

function CustomRuleForApproveReject()
{
//debugger;
//alert('CustomRuleForApproveReject');
   if(Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()=='Pending')
   {
//alert('-1');
        /*Hide Activate quote button*/
         HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
                     var LoggedInUserGUID = Xrm.Page.context.getUserId();
                     var QuoteOwnerGUID = Xrm.Page.data.entity.attributes.get("ownerid").getValue()[0].id;
    if(GuidsAreEqual(LoggedInUserGUID,QuoteOwnerGUID))// if both are equal
    {
//alert('-11');
                          return false;//disable
    }
    else
    {
//alert('-12');
        return true;//enable
    }

   }
   else if(Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()=='Approved')
   {
//alert('-2');
                                           if(!CurrentandQuoteUsersareEqual())
        {
            /*Hide Activate quote button*/
            HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
        }
        else
        {
            /*Show Activate quote button*/
            ShowRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");           
        }
        Xrm.Page.data.entity.attributes.get("discountpercentage").setValue(Xrm.Page.data.entity.attributes.get("new_approvaldiscount").getValue());
        Xrm.Page.getAttribute("discountpercentage").setSubmitMode("always");
        return false;//disable
   }
   else
   {
//alert('-3');
        quotediscountvalue=Xrm.Page.data.entity.attributes.get("discountpercentage").getValue();     
        rolesDiscountvalue=GetCurrentUserRoleDiscountValue();
        if(CurrentandQuoteUsersareEqual() && quotediscountvalue>rolesDiscountvalue)
        {
//alert('-31');
                                                                 Enablecustomdiscount(true);
                                                                 Xrm.Page.ui.controls.get("new_reasonfordiscountrequest").setDisabled(false);
            /*Hide Activate quote button*/
            HideRibbonButton("quote|NoRelationship|Form|Mscrm.Form.quote.ActivateQuote-Large");
        }
       return false;//disable
   }  
}

function HideRibbonButton(nameOfButton)
{
    if (window.top.document.getElementById(nameOfButton) != null){
        window.top.document.getElementById(nameOfButton).style.display='none';
    }
}

function ShowRibbonButton(nameOfButton)
{
    if (window.top.document.getElementById(nameOfButton) != null){
        window.top.document.getElementById(nameOfButton).style.display='block';
    }
}

function seekapprovalfordiscount()
{
    var _return = window.confirm('Are you sure you want to seek approval?');
    if(_return)
    {
        if(Xrm.Page.data.entity.attributes.get("new_reasonfordiscountrequest").getValue()== null)
        {
             alert('Plese Specify reason for quote discount request.');
             Xrm.Page.ui.controls.get("new_reasonfordiscountrequest").setFocus();
             //event.returnValue = false;
        }
        else
        {              
            if(Xrm.Page.data.entity.attributes.get("new_approvalstatus").getValue()!='Pending')
            {
                Xrm.Page.data.entity.attributes.get("new_approvalstatus").setValue("Pending");
                Xrm.Page.getAttribute("new_approvalstatus").setSubmitMode("always");
                //Create Discount Approval Task
                                                                                      CreateQuoteApprovalTask();
                                                                                      Xrm.Page.getAttribute("new_reasonfordiscountrequest").setSubmitMode("always");
                                                                                      Xrm.Page.data.entity.save();
                alert('The quote discount request Escalated for approval');
            }
        }         
    }       
 }

function approvediscountrequest()
{
      var userName;
    var _return = window.confirm('Are you sure you want to approved the discount?');
    if(_return)
    {
          if(Xrm.Page.data.entity.attributes.get("new_reasonfordiscountap").getValue() == null)
          {
            alert('Plese Specify reason for discount Approval.');
            Xrm.Page.ui.controls.get("new_reasonfordiscountap").setFocus();
            //event.returnValue = false;
          }
          else
          {
            if(Xrm.Page.data.entity.attributes.get("new_approvaldiscount").getValue()!=null)
            {
                Xrm.Page.data.entity.attributes.get("new_approvalstatus").setValue("Approved");
                Xrm.Page.getAttribute("new_approvalstatus").setSubmitMode("always");
                var UserGUID = Xrm.Page.context.getUserId();
                var resultXml=WSRetrieveMultipleByCondition("systemuser","fullname","systemuserid",UserGUID);
                var buNodes = resultXml.selectNodes("//BusinessEntity/q1:fullname");
                var NodeExist = buNodes.length;
                if (NodeExist >=1)
                {
                //alert('user Name - ' + buNodes[0].text);
                userName= buNodes[0].text;
                }
                SetLookupValue("new_quoteapprovedbyid",UserGUID,userName,"systemuser");
                closeOpenTask();
                Xrm.Page.data.entity.save();   
                alert('The quote discount request approved');
          }
          else
          {
            alert('Please specify Approval Discount Percent value or amount.');
          }
        }
    }                   
 }

function rejectdiscountrequest()
{
    var userName='';
    var _return = window.confirm('Are you sure you want to reject the discount?');
    if(_return)
    {
          if(Xrm.Page.data.entity.attributes.get("new_reasonfordiscountap").getValue() == null)
          {
            alert('Plese Specify reason for discount rejection.');
            Xrm.Page.ui.controls.get("new_reasonfordiscountap").setFocus();
            //event.returnValue = false;
          }
          else
          {
        Xrm.Page.data.entity.attributes.get("new_approvalstatus").setValue("Rejected");
        Xrm.Page.getAttribute("new_approvalstatus").setSubmitMode("always");
        var UserGUID = Xrm.Page.context.getUserId();
                                          var resultXml=WSRetrieveMultipleByCondition("systemuser","fullname","systemuserid",UserGUID);
var buNodes = resultXml.selectNodes("//BusinessEntity/q1:fullname");
            var NodeExist = buNodes.length;
if (NodeExist >=1)
            {
                //alert('user Name - ' + buNodes[0].text);
                userName= buNodes[0].text;
            }
SetLookupValue("new_quoterejectedbyid",UserGUID,userName,"systemuser");
closeOpenTask();
            Xrm.Page.data.entity.save();
        alert('The quote discount request rejected');
          }
    }
 }

function GetCurrentUserRoleDiscountValue()
 {
    //Get Current User Roles RoleID
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    var Discount=0;
    for (var i = 0; i < currentUserRoles.length; i++) {
        var userRole = currentUserRoles[i];
        var resultXml=WSRetrieveMultipleByCondition("new_rolediscount","new_maximumdiscount","new_securityroleid",userRole);
        var buNodes = resultXml.selectNodes("//BusinessEntity/q1:new_maximumdiscount");
        var NodeExist = buNodes.length;
        if (NodeExist >=1)
        {
            //alert('Discounted percentage - ' + buNodes[0].text);
            Discount= buNodes[0].text;           
            break;
        }
    }
    return Discount;
}

function ExecuteQuery(RoleId)
 {
    var serverUrl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
// Creating the Odata Endpoint
    var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    var retrieveReq = new XMLHttpRequest();
    var Odata = oDataPath + "/new_rolediscountSet?$select=new_maximumdiscount&$filter=new_securityroleid eq guid'" + RoleId + "'";
    retrieveReq.open("GET", Odata, false,"raman.goswami","globaL7&");
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.send();
    //retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };
     if (retrieveReq.readyState == 4) {
        var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
        var EmailAddress = retrieved.results[0].new_maximumdiscount;
        //alert(EmailAddress);
     }


   // var oDataEndpointUrl = "https://net2011.4crm.in:444/net2011/XRMServices/2011/OrganizationData.svc/";
 }


function retrieveReqCallBack(retrieveReq) {
    if (retrieveReq.readyState == 4) {
        var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
        var EmailAddress = retrieved.results[0].new_maximumdiscount;
        //alert(EmailAddress);
     }
}

function WSRetrieveMultipleByCondition(crmEntity, resultAttribute, queryAttribute, queryValue) {
var resultXml;
var oXMLSoapMsg = ""+
"" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader().toString()+
""+
""+
"" xsi:type='q1:QueryExpression'>"+
""+crmEntity+""+
""+
""+
""+resultAttribute+""+
"
"+
"
"+
""+
""+
""+
""+
""+
""+queryAttribute+""+
""+
""+
""+queryValue+""+
"
"+
"
"+
"
"+
"
"+
"
"+
"
"+
"
"+
"
";
var oXMLHTTPReq = new ActiveXObject("Msxml2.XMLHTTP");
oXMLHTTPReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
oXMLHTTPReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
oXMLHTTPReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
oXMLHTTPReq.setRequestHeader("Content-Length", oXMLSoapMsg.length);
oXMLHTTPReq.send(oXMLSoapMsg);
resultXml = oXMLHTTPReq.responseXML;

var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0){
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
else{
    return resultXml;
}
}

function SetLookupValue(fieldName,id,name,entityType)
{
    if(fieldName != null)
    {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
        Xrm.Page.getAttribute(fieldName).setSubmitMode("always");  // Need Changes
    }
}

function GuidsAreEqual(guid1, guid2) {
    var isEqual = false;

    if (guid1 == null || guid2 == null) {
        isEqual = false;
    } else {
        isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
    }

    return isEqual;
}

function CreateQuoteApprovalTask()
{
//debugger;
    var LoggedInUserGUID = Xrm.Page.context.getUserId();
    var QuoteOwnerGUID = Xrm.Page.data.entity.attributes.get("ownerid").getValue()[0].id;
    quotediscountvalue=Xrm.Page.data.entity.attributes.get("discountpercentage").getValue();
    GetTaskManagerID(LoggedInUserGUID,quotediscountvalue);
                     if(managerguid!=null)
    {
        CreateSeekTask(managerguid,LoggedInUserGUID);
    }
}

function GetTaskManagerID(LoggedInUserGUID,qtdiscountvalue)
{
    var managerid=GetManagerId(LoggedInUserGUID);
    if(managerid!='')
    {
        //Get User Roles RoleID
        var resultXml = GetUserRoles(managerid);
        var NameNodes = resultXml.selectNodes("//BusinessEntity/q1:roleid");
        if(NameNodes.length > 0)
        {
            for( i = 0; i < NameNodes.length; i++)
            {
                var roleid = NameNodes[i].text;
                var resultXmlRoleDiscount=WSRetrieveMultipleByCondition("new_rolediscount","new_maximumdiscount","new_securityroleid",roleid);
                var buNodes = resultXmlRoleDiscount.selectNodes("//BusinessEntity/q1:new_maximumdiscount");
                var NodeExist = buNodes.length;
                if (NodeExist >=1)
                {
                    var Discount= buNodes[0].text;
                    if(qtdiscountvalue<=Discount)
                    {
                        managerguid = managerid;
                        break;
                    }
                    else
                    {
                        GetTaskManagerID(managerid,qtdiscountvalue);
                    }               
                }
            }
        }
    }
                     else
    {
        managerguid ='nomanager';
    }
}

function GetManagerId(LoggedInUserGUID)
{
    var managerid='';
    var resultXmlsystemuser=WSRetrieveMultipleByCondition("systemuser","parentsystemuserid","systemuserid",LoggedInUserGUID);
    var buNodessystemuser = resultXmlsystemuser.selectNodes("//BusinessEntity/q1:parentsystemuserid");
    var NodeExistsystemuser = buNodessystemuser.length;
    if (NodeExistsystemuser >=1)
    {
        //alert('Manager Id - ' + buNodessystemuser[0].text);
        managerid= buNodessystemuser[0].text;
    }
    return managerid;
}

function GetUserRoles(EqualUserId) 

 var xml = ""+
"" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader().toString()+  
 " <soap:Body>" + 
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + 
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" + 
 " <q1:EntityName>role
" + 
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + 
 " <q1:Attributes>" + 
 " <q1:Attribute>name" + 
 " <q1:Attribute>roleid" +
 " " + 
 " " + 
 " <q1:Distinct>false" + 
 " <q1:LinkEntities>" + 
 " <q1:LinkEntity>" + 
 " <q1:LinkFromAttributeName>roleid" + 
 " <q1:LinkFromEntityName>role" + 
 " <q1:LinkToEntityName>systemuserroles" + 
 " <q1:LinkToAttributeName>roleid" + 
 " <q1:JoinOperator>Inner" + 
 " <q1:LinkEntities>" + 
 " <q1:LinkEntity>" + 
 " <q1:LinkFromAttributeName>systemuserid" + 
 " <q1:LinkFromEntityName>systemuserroles" + 
 " <q1:LinkToEntityName>systemuser" + 
 " <q1:LinkToAttributeName>systemuserid" + 
 " <q1:JoinOperator>Inner" + 
 " <q1:LinkCriteria>" + 
 " <q1:FilterOperator>And" + 
 " <q1:Conditions>" + 
 " <q1:Condition>" + 
 " <q1:AttributeName>systemuserid" + 
  " <q1:Operator>Equal" +
 ""+
 ""+EqualUserId+""+
 "
"+ 
 " " + 
 " " + 
 " " + 
 " " + 
 " " + 
 " " + 
 " " +
 " " + 
 " " + 
 " " + 
 "" + 
 ""; 
 
 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
 
 xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false); 
 xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple"); 
 xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); 
 xmlHttpRequest.setRequestHeader("Content-Length", xml.length); 
 xmlHttpRequest.send(xml); 
 
 var resultXml = xmlHttpRequest.responseXML; 
 var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0){
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
else{
    return resultXml;
}
}

function CreateSeekTask(MangerID,CreatedByID)
{
//debugger;
var CurrentQuoteID = Xrm.Page.data.entity.attributes.get("quotenumber").getValue();
    var attributesandvalues="subject|Discount Approval Request for "+ CurrentQuoteID + ",regardingobjectid|"+Xrm.Page.data.entity.getId()+",statecode|Open";
    var returnXML=WSRetrieveMultipleByMultipleCondition("task","activityid",attributesandvalues);
    var nodecount = returnXML.selectNodes("//BusinessEntity/q1:activityid");
    if(nodecount.length==0)
    {   
    var xml = ""+
"" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader().toString()+ 
    "  <soap:Body>" +
    "    <Create xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "      <entity xsi:type=\"task\">" +
    "        <description>Your Discount Approval is Required for the Quote "+ CurrentQuoteID + "
" +
    "        <ownerid>" + MangerID + "" +
    "        <regardingobjectid type=\"quote\">" + Xrm.Page.data.entity.getId() + "" +
    "         <subject>Discount Approval Request for "+ CurrentQuoteID + "" +
    "         <createdby>" + CreatedByID + "" +
    "      " +
    "    " +
    "  " +
    "" +
    "";

    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Create");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);

    var resultXml = xmlHttpRequest.responseXML;
}
}

function GenerateQuoteDiscountValuePercent()
{
    var valueinpercent=0;
    var discountamount=Xrm.Page.data.entity.attributes.get("discountamount").getValue();
                     if(discountamount!=null)
                     {
        var totallineitemamount=Xrm.Page.data.entity.attributes.get("totallineitemamount").getValue();
        valueinpercent=    (discountamount/totallineitemamount)*100;
        Xrm.Page.data.entity.attributes.get("discountpercentage").setValue(valueinpercent);
        Xrm.Page.getAttribute("discountpercentage").setSubmitMode("always");
   
        Xrm.Page.data.entity.attributes.get("discountamount").setValue(0);
        Xrm.Page.getAttribute("discountamount").setSubmitMode("always");
                      }
}

function GenerateQuoteDiscountValuePercentbyManager()
{
var valueinpercent=0;
    var approvaldiscountamount=Xrm.Page.data.entity.attributes.get("new_approvaldiscountamount").getValue();
    if(approvaldiscountamount!=null)
    {
        rolesDiscountvalue=GetCurrentUserRoleDiscountValue();   
        var totallineitemamount=Xrm.Page.data.entity.attributes.get("totallineitemamount").getValue();
        valueinpercent=    (approvaldiscountamount/totallineitemamount)*100;
        if(valueinpercent<=rolesDiscountvalue)
        {
            Xrm.Page.data.entity.attributes.get("new_approvaldiscount").setValue(valueinpercent);
            Xrm.Page.getAttribute("new_approvaldiscount").setSubmitMode("always");
           
            Xrm.Page.data.entity.attributes.get("new_approvaldiscountamount").setValue(0);
            Xrm.Page.getAttribute("new_approvaldiscountamount").setSubmitMode("always");
        }
        else
        {
            alert('Your quote discounted amount is more then that specified discount for you!');
            //event.returnValue=false;
        }
    }
}

function WSRetrieveMultipleByMultipleCondition(crmEntity, resultAttribute, queryAttributeandValue) {
var resultXml,arrayqueryAttribute,xmlAttributeandValue;
arrayqueryAttribute = queryAttributeandValue.split(",");
    for (var i = 0; i < arrayqueryAttribute.length; i++) {
        var Attribute,Value,arrayAttributeandValue;
        AttributeandValue=arrayqueryAttribute[i].split("|");
        Attribute=AttributeandValue[0];
        Value=AttributeandValue[1];       
        xmlAttributeandValue +=""+
        ""+Attribute+""+
        ""+
        ""+
        ""+Value+""+
        "
"+
        "
"
    }
   
var oXMLSoapMsg = ""+
"" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader().toString()+
""+
""+
"" xsi:type='q1:QueryExpression'>"+
""+crmEntity+""+
""+
""+
""+resultAttribute+""+
"
"+
"
"+
""+
""+
""+
""+
xmlAttributeandValue +
"
"+
"
"+
"
"+
"
"+
"
"+
"
";
var oXMLHTTPReq = new ActiveXObject("Msxml2.XMLHTTP");
oXMLHTTPReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
oXMLHTTPReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
oXMLHTTPReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
oXMLHTTPReq.setRequestHeader("Content-Length", oXMLSoapMsg.length);
oXMLHTTPReq.send(oXMLSoapMsg);
resultXml = oXMLHTTPReq.responseXML;

var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0){
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
else{
    return resultXml;
}
}

function closeOpenTask()
{
debugger;
    var CurrentQuoteID = Xrm.Page.data.entity.attributes.get("quotenumber").getValue();
    var currentuserid=Xrm.Page.context.getUserId();
    var attributesandvalues="subject|Discount Approval Request for "+ CurrentQuoteID + ",regardingobjectid|"+Xrm.Page.data.entity.getId()+",statecode|Open,ownerid|"+currentuserid+"";
    var returnXML=WSRetrieveMultipleByMultipleCondition("task","activityid",attributesandvalues);
    var nodecount = returnXML.selectNodes("//BusinessEntity/q1:activityid");
    if(nodecount.length!=0)
    {
        //close the task
        for (var i = 0; i < nodecount.length; i++)
        {
            var taskid= nodecount[i].text;
            SetStateTaskRequest(taskid);
            //SetLookupValue("modifiedby",currentuserid,ModifiedBy,"systemuser");
        }
    }
}

function SetStateTaskRequest(taskid)
{
var xml = ""+
"" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
GenerateAuthenticationHeader().toString()+
"  <soap:Body>" +
"    <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"      <Request xsi:type=\"SetStateTaskRequest\">" +
"        <EntityId>" + taskid + "
" +
"        <TaskState>Completed" +
"        <TaskStatus>-1" +
"      " +
"    " +
"  " +
"" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
alert(resultXml.xml);

}

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...