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);

}

CRM Difference between Secure & Unsecure Configuration in Plugin Registration tool

Dear all,

Read original text  from the URL

Secure Configuration of Plugin
Registration tool in CRM
Unsecure Configuration of
Plugin Registration tool in CRM
The Secure Configuration information could be read only by CRM Administrators.(Eg: Restricted data from normal user could be supplied here)
Unsecure configuration information could be read by any user in CRM. Remember its public information (Eg: Parameter strings to be used in plugin could be supplied here)
Imagine that you include a plugin,plugin steps and activate them in asolution. Later solution was exportedas Managed Solution to anotherenvironment. In this scenario, thesupplied Secure configuration  information would NOTbe available in the new environment. The simple  reason behind this is to provide more security to the contents of Secure Configuration.
Imagine that you include a plugin, plugin steps and activate them in a solution. Later solution was exported as Managed Solution to another environment. In this scenario, the supplied Unsecure configuration values would be available in the new environment.

One of the benefits to the plug-in architecture of CRM 4.0 is the ability to store plug-ins in the CRM database so they may be used by multiple CRM servers. This introduces a slight complication regarding the storage of configuration information. Because the plug-in assembly doesn’t reside on the disk the normal method of using a .config file located with the assembly no longer works.
Luckily, the plug-in architecture solves this issue by allowing the developer to supply configuration information for each step executed by the plug-in.
Plug-in Configuration Architecture
As noted in the CRM SDK article, Writing the Plug-in Constructor, when creating your plug-in, you may define a constructor that passes two parameters to your plug-in: unsecure configuration and secure configuration:
   1: public class SamplePlugin : IPlugin
   2: {
   3:   public SamplePlugin(string unsecureConfig, string secureConfig)
   4:   {
   5:   }
   6: }
Both parameters are strings and may contain any configuration data, in any format, that you wish. For the purposes of this discussion, we will only be concerned with the unsecure configuration parameter.
Creating a Configuration Structure
Since most of us are familiar with the XML configuration provided by the standard Properties.Settings structure, I thought it would be a great idea to retain as much of that experience as possible so we can move code from a stand-alone test application to a plug-in with little difficulty.
Using an XML fragment that closely resembles the Settings section found in the .config file of a .Net assembly, we can create a similarly functional system for storing configuration data. Consider the following XML:
   1:
   2:     "RetryCount">
   3:         <value>5</value>
   4:    
   5:     "TaskPrefix">
   6:         <value>This task was created on {0}.</value>
   7:    
   8:     "FirstRun">
   9:         <value>false</value>
  10:    
  11:
As you can see, we have three settings which contain values that we would normally find in our .config file and which are used to configure our assembly. Using the Plug-in Registration Tool, we can add this information to the Unsecure Configuration field when registering a new step, as show by the figure below:

Plug-in Configuration Class
I created a simple class to extract values from an XML document for simple data types such as Guids, strings, Booleans, and integers, given the structure we discussed above:
   1: class PluginConfiguration
   2: {
   3:     private static string GetValueNode(XmlDocument doc, string key)
   4:     {
   5:         XmlNode node = doc.SelectSingleNode(String.Format("Settings/setting[@name='{0}']", key));
   6: 
   7:         if (node != null)
   8:         {
   9:             return node.SelectSingleNode("value").InnerText;
  10:         }
  11:         return string.Empty;
  12:     }
  13: 
  14:     public static Guid GetConfigDataGuid(XmlDocument doc, string label)
  15:     {
  16:         string tempString = GetValueNode(doc, label);
  17: 
  18:         if (tempString != string.Empty)
  19:         {
  20:             return new Guid(tempString);
  21:         }
  22:         return Guid.Empty;
  23:     }
  24: 
  25:     public static bool GetConfigDataBool(XmlDocument doc, string label)
  26:     {
  27:         bool retVar;
  28: 
  29:         if (bool.TryParse(GetValueNode(doc, label), out retVar))
  30:         {
  31:             return retVar;
  32:         }
  33:         else
  34:         {
  35:             return false;
  36:         }
  37:     }
  38: 
  39:     public static int GetConfigDataInt(XmlDocument doc, string label)
  40:     {
  41:         int retVar;
  42: 
  43:         if (int.TryParse(GetValueNode(doc, label), out retVar))
  44:         {
  45:             return retVar;
  46:         }
  47:         else
  48:         {
  49:             return -1;
  50:         }
  51:     }
  52: 
  53:     public static string GetConfigDataString(XmlDocument doc, string label)
  54:     {
  55:         return GetValueNode(doc, label);
  56:     }
  57: }
Putting PluginConfiguration to Work
Once we have our PluginConfiguration class added to our project, we need to modify the plug-in constructor to extract the values from our configuration string:
   1: public SamplePlugin(string unsecureConfig, string secureConfig)
   2: {
   3:     XmlDocument doc = new XmlDocument();
   4:     doc.LoadXml(unsecureConfig);
   5: 
   6:     string TaskPrefix = PluginConfiguration.GetConfigDataString(doc, "TaskPrefix");
   7:     bool FirstRun = PluginConfiguration.GetConfigDataBool(doc, "FirstRun");
   8:     int RetryCount = PluginConfiguration.GetConfigDataInt(doc, "RetryCount");
   9: }
There is no automatic determination of data types so you will need to know which method to use to extract a specific value from the configuration data.

have a glance below for plugin code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using System.Xml;
namespace ReadPluginConfgInPlugins
{
public class PluginConfg : IPlugin
{
private readonly string _unsecureString;
private readonly string _secureString;
public PluginConfg(string unsecureString, string secureString)
{
if (String.IsNullOrWhiteSpace(unsecureString) || String.IsNullOrWhiteSpace(secureString))
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(unsecureString);
Guid DefaultQueueGuid = PluginConfiguration.GetConfigDataGuid(doc, “Contact Guid”);
string ContactFullName = PluginConfiguration.GetConfigDataString(doc, “Full Name”);
int MobileNumber = PluginConfiguration.GetConfigDataInt(doc, “Mobile Number”);
bool Gender = PluginConfiguration.GetConfigDataBool(doc, “Gender 0 refer to Male”);
}
catch (Exception ex)
{
throw new Exception(“SoapException” + ex.Message + “########” + ex.StackTrace + “$$$$Inner Exception” + ex.InnerException);
}
}
}
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// For this sample, execute the plug-in code only while the client is online.
tracingService.Trace(“AdvancedPlugin: Verifying the client is not offline.”);
if (context.IsExecutingOffline || context.IsOfflinePlayback)
return;
// The InputParameters collection contains all the data passed
// in the message request.
if (context.InputParameters.Contains(“Target”) &&
context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
}
}
}
}
For this approach also have a Pros and Cons.
PROS:
  • The step configuration is solution-aware so it will be automatically transported with the plugin step.
CONS:
  • You need to use the plugin registration tool or another application to update the step configuration.
  • The configuration is step-specific so you have to provide it and/or update it for every step even if the value is the same for all the steps (the configuration is on each step instead of the assembly or plugin type).
  • the configuration is just an attribute of the plugin step so you cannot control privileges on the configuration independently from privileges on plugin step entity.
*. Use the plugin step “Secure Configuration”
This is similar to the step Configuration except that the configuration data is stored in a separate entity which can be secured.
PROS:
  • The configuration data can be secured as any other entity using the CRM security model. This is useful when the configuration contains sensitive information such as passwords.
CONS:
  • Secure configuration is not solution aware so you will need to configure it for each environment.
  • You need to use the plugin registration tool or another application to update the step configuration.
  • The configuration is step-specific so you have to provide it and/or update it for every step even if the value is the same for all the steps (the configuration is on each step instead of the assembly or plugin type).
*. Use a Web Resource
You can store configuration information in web resources, for example you might have some XML configuration stored in a web resource and have your plugin read the web resource each time it executes.
PROS:
  • Web resources are solution aware and the GUID is preserved across environments so you can hardcode the web resource GUID in your plugin code. You can transport the web resource and the plugin in the same solution.
  • Can be easily updated using the CRM UI.
CONS:
  • You cannot secure the configuration since it depends on the web resource access privileges and most users will need at least read access to web resources.

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, ...