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

No comments:

Loading...