Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, March 23, 2016

Sample WebAPI Methods for MSCRM 2016

function InitiateAPICalls() {
    var resp = ExecuteAPIRequest("accounts"); //Ajax Request
    var resp1 = ExecuteXmlRequestToAPI("accounts"); //XMLHttpRequest

}


function result(resultArray, error) {
    this.results = resultArray;
    this.error = error;
}
function ExecuteAPIRequest(query) {
    var resultArray = null;
    var errorMessage = null;
    $.ajax(
    {
        type: "GET",
        url: Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" +query,
        async: false,
        headers: { "Accept": "application/json", "Content-Type": "application/json;charset=utf-8", "OData-MaxVersion": "4.0", "OData-Version": "4.0" }
    })
    .done(function (Httpresponse) {
        resultArray = Httpresponse.value;
    })
    .fail(function (Httpresponse) {
        var errors = JSON.parse(Httpresponse.responseText);
        if (errors.error)
            errorMessage = "There was an error executing the request. " + Httpresponse.status + " " + Httpresponse.statusText +". " + errors.error.message;
    })
    .always(function (Httpresponse) {
    });
    return new result(resultArray,errorMessage);
}

function ExecuteXmlRequestToAPI(query) {
    var resultArray = null;
    var errorMessage = null;
    var req = new XMLHttpRequest()
    var resultArray = null;
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/"+ query, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onerror = function (error) {
        throw new Error("There was an error executing the request. " + req.status + " " + error.message);
    }
    var response = req.send();
    if (req.status == 200) {
        var results = JSON.parse(req.response);
        resultArray = results.value;
    }
    else {
        var errors = JSON.parse(req.response);
        if (errors.error)
            errorMessage = "There was an error executing the request. " + req.status + " " +req.statusText+ ". "+ errors.error.message;
    }
    return new result(resultArray,errorMessage);
}

Friday, April 3, 2015

Knockout


Knockout Click Binding:

<td>
<a data-bind="text:title,click:$parent.openRecord"/>
</td>

if you use href in "a" tag, the function wont be called.

Inside your view model,

var self = this;
self.openRecord = function (record) { // Write your code here for click operation };


Knockout Dirty flag:


Create new ko object :
ko.dirtyFlag = function (root, isInitiallyDirty) { var result = function () { }, _initialState = ko.observable(ko.toJSON(root)), _isInitiallyDirty = ko.observable(isInitiallyDirty); result.isDirty = ko.computed(function () { return _isInitiallyDirty() || _initialState() !== ko.toJSON(root); }); result.reset = function () { _initialState(ko.toJSON(root)); _isInitiallyDirty(false); }; return result; };


In your view model, you can use the flag like this:
var isDirty = false; //set to true to load your item as Dirty.
  self.dirtyFlag = new ko.dirtyFlag(this, isDirty);

To check for a specific item in your Model as dirty or not,
        self.quantitydirtyFlag = new ko.dirtyFlag(self.quantity, isDirty);

        self.dirtyItems = ko.computed(function () {
        self.isDirty = ko.computed(function () {

            return ko.utils.arrayFilter(self.items(), function (item) {
                return item.dirtyFlag.isDirty();
            });
        }, self);

            return self.dirtyItems().length > 0;

        }, self);


you can check for whether the item is dirty or not by,

record.dirtyFlag.isDirty()
for the specific item,
record.quantitydirtyFlag.isDirty()

Dirty flag original reference here.




Wednesday, August 13, 2014

Parse Json Date to Date Object

Parse jsondate in JavaScript to a Date Object:
Below are two methods I use  
Method 1:
var jsonDate = "/Date(1224043200000)/"
var value = new Date(parseInt(jsonDate.substr(6)));

Method 2:
var jsonDate = "/Date(1224043200000)/"
var value = new Date(parseInt(jsonDate.replace(/(^.*\()|([+-].*$)/g, '')));
if you want in "mm/dd/yyyy" format, use this along with the above script
var dat = value.getMonth()+ 1 + "/" + value.getDate()+ "/" +value.getFullYear();

Friday, January 31, 2014

Ajax request from HTML to CRM2011/ CRM2013

var requestmain = fetchxml;

 $.ajax(
            {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: serverurl + "/XRMServices/2011/Organization.svc/web",
                async: false,
                data: requestMain,
                headers: { "Accept": "application/xml, text/xml, */*", "Content-Type": "text/xml; charset=utf-8", "SOAPAction": "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/RetrieveMultiple" }

            })
            .done(function (XMLHttpRequest) {
                var strResponse = GetXmlValue(XMLHttpRequest.childNodes[0]);
                xmlDoc = $.parseXML(strResponse);
            })
            .fail(function (XMLHttpRequest) {
                alert("Error retrieving accounts using fetch xml");
            })
            .always(function (XMLHttpRequest) {
            });

function GetXmlValue(value) {
    if (value.xml == undefined) {
        return (new XMLSerializer()).serializeToString(value);
    }
    return value.xml;
}
 

Friday, August 24, 2012

open link url inside a div/iframe

<html>
<head>
<script type="text/javascript">

function  showPage (which) {
    document.getElementById('xrmforms').innerHTML = '<' + 'iframe id="crmpage" src="' + which + '"width="100%" height="600px;" scrolling="auto"></iframe>';

}

</script>

</head>
<body>
<a href="http://www.google.com" onclick="showPage(this.href);return false;">Click here</a>


<div id="xforms">
</div>

</body>
</html>








Replace certain character JavaScript

To replace certain characters in javascript:

In this example, i'm replacing '&' with '&amp;' in the entire string.


function formatTexts(linkText) {
    var patt1 = /&/g;
    var patt1replStr = "&amp;";

    var matchPatt = linkText.match(patt1);

    var pattformat = /&amp;/g;
    var matchformatted = "";
    if (matchPatt != null && matchPatt.length > 0) {
        while (matchformatted.length < matchPatt.length) {
            linkText = linkText.replace(linkText.match(patt1)[0], patt1replStr);
            matchformatted = linkText.match(pattformat);
        }
    }
    return linkText;
}

HtmlEncoding in Javascript


Often when executing fetchxml in javascript or when creating tables throught javascript, you would face the error because the values are not htmlencoded.


function htmlEncode(value) {
    return $('<div/>').text(value).html();
}
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}


This encodes the default characters that have to be encoded.
For more details:
http://support.microsoft.com/kb/316063

Hide CrmNavBar and CrmRibbon through javascript

//This toggles ribbon visibility, but doesnt move the form area up
window.top.document.getElementById("minimizeribbon").fireEvent("onclick");


// Hide the Ribbon toolbar and move the form Content area to the top of the window.
window.top.document.getElementById("crmTopBar").style.display = "none";
window.top.document.getElementById("crmContentPanel").style.top = "0px"; //

//default values for showing ribbon and moving content area below ribbon

window.top.document.getElementById("crmTopBar").style.display = "";
window.top.document.getElementById("crmContentPanel").style.top = "135px"; //



// Hide Left Hand Nav bar / pane
document.getElementById("crmNavBar").parentElement.style.display = "none";
document.getElementById("tdAreas").parentElement.parentElement.parentElement.parentElement.colSpan = 2;



// Hide the Breadcrumb and Record Set Toolbar
document.getElementById("recordSetToolBar").parentElement.style.display = "none";

// Hide the Form Footer Bar
document.getElementById("crmFormFooter").parentElement.style.display = "none";




Thursday, March 8, 2012

Sample Odata Query CRM2011


function GetCity()
{
var serverUrl = "http://"+window.location.host+"/" + Xrm.Page.context.getOrgUniqueName();
  var id = Xrm.Page.getAttribute("new_courtid").getValue();
if(id!=null)
{
    var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

    var retrieveReq = new XMLHttpRequest();
//replace with your odata query
    var Odata = ODataPath + "/AccountSet?$select=new_city&$filter=accountId eq guid'" + id[0].id + "'";
    retrieveReq.open("GET", Odata, true);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };
    retrieveReq.send();
}
}

function retrieveReqCallBack(retrieveReq) {

    if (retrieveReq.readyState == 4 /* complete */) {
        if (retrieveReq.status == 200) {
            var retrieved = JSON.parse(retrieveReq.responseText).d;
//replace attribute name as in the query
            var city= retrieved.results[0]["new_city"];
            Xrm.Page.data.entity.attributes.get('new_city').setValue(city.Value);
        }
        else {
            errorHandler(retrieveReq);
            alert("Unable to Retrieve City");
        }
    }
}

Friday, June 10, 2011

Date as per User Settings


//*********************************************************************
//**  DEFAULT DUE DATE:  UPON LOAD OF THE FORM, FOR CREATE ONLY, WE 
//**  SET THE DUE DATE TO THE CURRENT DATE AND TIME FOR THE CRM USER.
//*********************************************************************
var result = new Date();
if(crmForm.FormType ==1 )
{

fetchUserTime();
crmForm.all.scheduledend.DataValue = result;
}
//**************** **************************************
//*****************Get Current User ************************
//*******************************************************
function getCurrentUser()
{
//Create the XML that will fetch the required info.
var XMLRequest = "" + 
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + GenerateAuthenticationHeader() +
" <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>systemuser</q1:EntityName>" + 
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + 
" <q1:Attributes>" + 
" <q1:Attribute>systemuserid</q1:Attribute>" + 
" <q1:Attribute>fullname</q1:Attribute>" + 
" </q1:Attributes>" + 
" </q1:ColumnSet>" + 
" <q1:Distinct>false</q1:Distinct>" + 
" <q1:Criteria>" + 
" <q1:FilterOperator>And</q1:FilterOperator>" + 
" <q1:Conditions>" + 
" <q1:Condition>" + 
" <q1:AttributeName>systemuserid</q1:AttributeName>" + 
" <q1:Operator>EqualUserId</q1:Operator>" + 
" </q1:Condition>" + 
" </q1:Conditions>" + 
" </q1:Criteria>" + 
" </query>" + 
" </RetrieveMultiple>" + 
" </soap:Body>" + 
"</soap:Envelope>" + 
"";
try
{
//Create Http request object
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", XMLRequest.length);
xmlHttpRequest.send(XMLRequest);

//Store the response which would be XML
var Result = xmlHttpRequest.responseXML;

/*
The return is of type "BusinessEntity" if you were using similar code one server side.
Hence we need to select node of type "BusinessEntity"

In our case It should be not more one than one node
*/
var BusinessEntityNodes = Result.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

// Check If data was retrived
if (BusinessEntityNodes.length != 0)
{
    var BusinessEntityNode = BusinessEntityNodes[0]; 
    var SystemUserId = BusinessEntityNode.selectSingleNode("q1:systemuserid");
    var FullName = BusinessEntityNode.selectSingleNode("q1:fullname");
    var SystemUserId = (SystemUserId == null) ? null : SystemUserId.text;
    var FullName = (FullName == null) ? null : FullName.text;
}
return SystemUserId ;
}
catch (e)
{
alert(e.message);
}

}
//****************************************************************************
//***********************Fetch User Time in CRM**********************************
//****************************************************************************
function fetchUserTime()
{
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
"  <soap:Header>" + 
"    <CrmAuthenticationToken xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + 
"      <AuthenticationType xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">0</AuthenticationType>" + 
"      <OrganizationName xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">"+ORG_UNIQUE_NAME +"</OrganizationName>" + 
"      <CallerId xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">00000000-0000-0000-0000-000000000000</CallerId>" + 
"    </CrmAuthenticationToken>" + 
"  </soap:Header>" + 
"  <soap:Body>" + 
"      <Request xsi:type=\"RetrieveUserSettingsSystemUserRequest\" ReturnDynamicEntities=\"true\">" + 
"        <EntityId>"+getCurrentUser()+"</EntityId>" + 
"        <ColumnSet xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:ColumnSet\">" + 
"          <q1:Attributes>" + 
"            <q1:Attribute>timezonebias</q1:Attribute>" + 
"          </q1:Attributes>" + 
"        </ColumnSet>" + 
"      </Request>" + 
"    </Execute>" + 
"  </soap:Body>" + 
"</soap:Envelope>" + 
"";

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;
//Create an XML document that can be parsed.
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
oXmlDoc.async = false;
oXmlDoc.loadXML(resultXml.xml);
//Value the user is interesed in in string form
var times = oXmlDoc.getElementsByTagName("Property");
var difference = Number(times[0].text);

//And the result - Date object
var gmtday= result.getUTCDate();
var gmtmonth = result.getUTCMonth();
gmtmonth=gmtmonth;
var gmtYear = result.getUTCFullYear();
var gmthours = result.getUTCHours();
var gmtminutes = result.getUTCMinutes();

result.setFullYear(gmtYear);
result.setMonth(gmtmonth);
result.setDate(gmtday);
result.setHours(gmthours);
result.setMinutes(gmtminutes);
result.setMinutes ( result.getMinutes() - difference);
}

//********************************************************************
//***************End of Fetch User Time**********************************
//********************************************************************

Wednesday, April 13, 2011

filtered lookup in Jscript


crmForm.all.new_subcategoryid.AddParam("search","<fetch mapping='logical'><entity name='new_casesubcategory'><filter><condition attribute='new_categoryid' operator='eq' value='" + crmForm.all.new_categoryid.DataValue[0].id + "' /></filter></entity></fetch>");

Friday, April 1, 2011

set activityparty onload of crmform


var lookupItem1 = new Array();
lookupItem1[0] = new LookupControlItem ('303232C2-3622-E011-895A-0003FFD4167C',8,'Dr. RK Sharma')
lookupItem1[1] = new LookupControlItem ('50511D55-F422-E011-82C2-0003FFD4167C',2,'John Chen')
crmForm.all.requiredattendees.DataValue = lookupItem1 ;

Wednesday, March 2, 2011

format integer field -- value without commas


if(crmForm.all.new_test1.DataValue!=null){
crmForm.all.new_test1.value = crmForm.all.new_test1.DataValue;
}

Friday, November 26, 2010

Read QueryString in Jscript

function PageQuery( q )
{
    if( q.length > 1 ) this.q = q.substring( 1, q.length );
    else this.q = null;
    this.keyValuePairs = new Array();
    if( q )
    {
        for( var i=0; i < this.q.split( "&" ).length; i++ )
        {
            this.keyValuePairs[i] = this.q.split( "&" )[i];
        }
    }
    this.getKeyValuePairs = function() { return this.keyValuePairs; }
    this.getValue = function( s )
    {
        for( var j=0; j < this.keyValuePairs.length; j++ )
        {
            if( this.keyValuePairs[j].split( "=" )[0] == s )
            return this.keyValuePairs[j].split( "=" )[1];
        }
        return false;
    }
    this.getParameters = function()
    {
        var a = new Array( this.getLength() );
        for( var j=0; j < this.keyValuePairs.length; j++ )
        {
            a[j] = this.keyValuePairs[j].split( "=" )[0];
        }
        return a;
    }
    this.getLength = function() { return this.keyValuePairs.length; }
}


function queryString( key )
{
    var page = new PageQuery( window.location.search );
    return unescape( page.getValue( key ) );
}

alert(queryString('id'));

This will provide the record Guid as alert, reading the value from queryString.

Thursday, November 25, 2010

Restrict Future date in CRM and restrict save event

To avoid future date in a date field in CRM Form and restrict save in such cases:

var today = new Date();

var filledDate = crmForm.all.new_testdate.DataValue;

if(filledDate > today)
{
   alert('filled in date is a future date. please enter appropriate date.');

 event.returnValue = false;
     return false;
}


To restrict save of crmfrom, we need to execute the following script onsave of the form.

 event.returnValue = false;
     return false; // if this line is not added, the rest of the script that follows this will get executed. 

Thursday, November 18, 2010

Retrieve roles of loggedin user in Jscript

var roleName="SalesRep";


var isSalesrep = UserHasRole(roleName);





function UserHasRole(roleName)
{
var oXml = GetCurrentUserRoles();
                     var found = false;
                     if(oXml != null)
{
var roles = oXml.selectNodes("//BusinessEntity/q1:name");
if(roles != null)
{

for( i = 0; i < roles.length; i++)
{
if(roles[i].text == roleName)
{
found = true;
return found;
}
}

}
}
return found;
}
function GetCurrentUserRoles()
{
var xml = "" + 


"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 


"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + 


GenerateAuthenticationHeader() + 


" <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:EntityName>" + 


" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + 


" <q1:Attributes>" + 


" <q1:Attribute>name</q1:Attribute>" + 


" </q1:Attributes>" + 


" </q1:ColumnSet>" + 


" <q1:Distinct>false</q1:Distinct>" + 


" <q1:LinkEntities>" + 


" <q1:LinkEntity>" + 


" <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" + 


" <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" + 


" <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" + 


" <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" + 


" <q1:JoinOperator>Inner</q1:JoinOperator>" + 


" <q1:LinkEntities>" + 


" <q1:LinkEntity>" + 


" <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" + 


" <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" + 


" <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" + 


" <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" + 


" <q1:JoinOperator>Inner</q1:JoinOperator>" + 


" <q1:LinkCriteria>" + 


" <q1:FilterOperator>And</q1:FilterOperator>" + 


" <q1:Conditions>" + 


" <q1:Condition>" + 


" <q1:AttributeName>systemuserid</q1:AttributeName>" + 


" <q1:Operator>EqualUserId</q1:Operator>" + 


" </q1:Condition>" + 


" </q1:Conditions>" + 


" </q1:LinkCriteria>" + 


" </q1:LinkEntity>" + 


" </q1:LinkEntities>" + 


" </q1:LinkEntity>" + 


" </q1:LinkEntities>" + 


" </query>" + 


" </RetrieveMultiple>" + 


" </soap:Body>" + 


"</soap:Envelope>" + 


"";
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;
                     return(resultXml);
}

To get the loggedin user id through Jscript

   var userId=getCurrentUser().toString ().toLowerCase();
   userId=userId.replace('{','').replace('}','').toLowerCase();






function getCurrentUser()
{
    var systemUserId="";
    if(AUTHENTICATION_TYPE==0)//
    {
        var soapBody = "<soap:Body>"+"<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+"<Request xsi:type='WhoAmIRequest' />"+"</Execute></soap:Body>";
        var soapXml = "<soap:Envelope "+"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' "+"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "+"xmlns:xsd='http://www.w3.org/2001/XMLSchema'>";
        soapXml += "<soap:Header><CrmAuthenticationToken xmlns='http://schemas.microsoft.com/crm/2007/WebServices'><AuthenticationType xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>0</AuthenticationType><OrganizationName xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>"+ORG_UNIQUE_NAME+"</OrganizationName><CallerId xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>00000000-0000-0000-0000-000000000000</CallerId></CrmAuthenticationToken></soap:Header>";
        soapXml += soapBody;
        soapXml += "</soap:Envelope>";
        // Create the XMLHTTP object for the execute method.
        var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        xmlhttp.open("POST", "/mscrmservices/2007/CrmService.asmx", false);
        xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
        //Send the XMLHTTP object.
        xmlhttp.send(soapXml);
        // Create an XML object to parse the results.
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.loadXML(xmlhttp.responseXML.xml);
        // Get the user's ID.
        var userid = xmlDoc.getElementsByTagName("UserId")[0].childNodes[0].nodeValue;
        systemUserId=userid;
    }
    else
    if(AUTHENTICATION_TYPE==2)//IFD
    {
        //Create the XML that will fetch the required info.
        //You can inspect this web service call using a tool called FIDDLER.
        var XMLRequest = "" + 
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
        "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + GenerateAuthenticationHeader() +
        " <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>systemuser</q1:EntityName>" + 
        " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + 
        " <q1:Attributes>" + 
        " <q1:Attribute>systemuserid</q1:Attribute>" + 
        " <q1:Attribute>fullname</q1:Attribute>" + 
        " </q1:Attributes>" + 
        " </q1:ColumnSet>" + 
        " <q1:Distinct>false</q1:Distinct>" + 
        " <q1:Criteria>" + 
        " <q1:FilterOperator>And</q1:FilterOperator>" + 
        " <q1:Conditions>" + 
        " <q1:Condition>" + 
        " <q1:AttributeName>systemuserid</q1:AttributeName>" + 
        " <q1:Operator>EqualUserId</q1:Operator>" + 
        " </q1:Condition>" + 
        " </q1:Conditions>" + 
        " </q1:Criteria>" + 
        " </query>" + 
        " </RetrieveMultiple>" + 
        " </soap:Body>" + 
        "</soap:Envelope>" + 
        "";


        try
        {
            //Create Http request object
            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", XMLRequest.length);
            xmlHttpRequest.send(XMLRequest);
            //Store the response which would be XML
            var Result = xmlHttpRequest.responseXML;
            /*
            The return is of type "BusinessEntity" if you were using similar code one server side.
            Hence we need to select node of type "BusinessEntity"
            In our case It should be not more one than one node
            */
            var BusinessEntityNodes = Result.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");


            // Check If data was retrived
            if (BusinessEntityNodes.length != 0)
            {
                var BusinessEntityNode = BusinessEntityNodes[0]; 
                var SystemUserId = BusinessEntityNode.selectSingleNode("q1:systemuserid");
                var FullName = BusinessEntityNode.selectSingleNode("q1:fullname");
                var SystemUserId = (SystemUserId == null) ? null : SystemUserId.text;
                var FullName = (FullName == null) ? null : FullName.text;
            }
               systemUserId=SystemUserId ;
        }
        catch (e)
        {
            alert(e.message);
        }
    }//Else for IFD end
    systemUserId=systemUserId.replace('{','');
    systemUserId=systemUserId.replace('}','');
    systemUserId=systemUserId.toLowerCase();
    return systemUserId
}