Friday, 30 August 2013

CRM 2011 Open New or Existing Entity using Java Script

function OpenExistingRecord(entityName, recordId) {
        

        //window.open("/main.aspx?etn=" + entityName + "&pagetype=entityrecord&id=%7B" + recordId + "%7D");
        //Xrm.Utility.openEntityForm(entityName, recordId); 
        return href = "/main.aspx?etc=2&etn=" + entityName + "&pagetype=entityrecord&id=%7B" + recordId + "%7D";
       
    }


//Open New Entity form with prefilled values for fields

Sample 1:
var params = {
    regardingobjectid: referenced record id,
    regardingobjectidtype: referenced record type name,
    regardingobjectidname: referenced record display name
};

Xrm.Utility.openEntityForm("task", null, params);

Sample 2:
var params = {
    pId: referenced record id,
    pType: referenced record type code,
    pName: referenced record display name
};

Xrm.Utility.openEntityForm("task", null, params);

 Sample 3:

//Set features for how the Case form window will appear
var features = "location=no,menubar=no,status=no,toolbar=no";
 
//Pop the Case record
window.open("/main.aspx?etn=incident&pagetype=entityrecord&id=" + GuidValue, "_blank", features, false);


Sample 4:

//Collect values from the existing CRM form that you want to default onto your new record
var CallerGUID = Xrm.Page.data.entity.attributes.get("from").getValue()[0].id;
var CallerName = Xrm.Page.data.entity.attributes.get("from").getValue()[0].name; 
 
//Set the parameter values
var extraqs = "&title=New Case";
extraqs += "&customerid=" + CallerGUID;
extraqs += "&customeridname=" + CallerName;
extraqs += "&customeridtype=contact"; 
 
//Set features for how the window will appear
var features = "location=no,menubar=no,status=no,toolbar=no"; 
 
//Pop the window
window.open("/main.aspx?etn=incident&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);




Sample 5:


//Open a new account record
Xrm.Utility.openEntityForm("account"); 
 
//Open an existing account record
Xrm.Utility.openEntityForm("account","A85C0252-DF8B-E111-997C-00155D8A8410"); 
 
//Open a new account record with a specific form and setting default values
var parameters = {};
parameters["formid"] = "b053a39a-041a-4356-acef-ddf00182762b";
parameters["name"] = "Test";
parameters["telephone1"] = "(425) 555-1234";
Xrm.Utility.openEntityForm("account", null, parameters);
 
//Open a new contact record, move it to the top left corner of the screen, and set the size of the window
var newWindow = Xrm.Utility.openEntityForm("contact");
newWindow.moveTo(0,0);
newWindow.resizeTo(800,600);






Wednesday, 24 July 2013

CRM 2011 Convert HTML text into Plain Text

private string ConvertHtmltoText(string source)
  {
   try
    {

      string result;
      // Remove HTML Development formatting
      // Replace line breaks with space
      // because browsers inserts space
      result = source.Replace("\r", " ");
      // Replace line breaks with space
      // because browsers inserts space
      result = result.Replace("\n", " ");
      // Remove step-formatting
      result = result.Replace("\t", string.Empty);
      // Remove repeating spaces because browsers ignore them
      result = Regex.Replace(result,@"( )+", " ");

      // Remove the header (prepare first by clearing attributes)
      result = Regex.Replace(result,@"<( )*head([^>])*>", "<head>",RegexOptions.IgnoreCase);
result = Regex.Replace(result,@"(<( )*(/)( )*head( )*>)", "</head>",RegexOptions.IgnoreCase);
result = Regex.Replace(result,"(<head>).*(</head>)", string.Empty,RegexOptions.IgnoreCase);

 // remove all scripts (prepare first by clearing attributes)
 result = Regex.Replace(result,@"<( )*script([^>])*>", "<script>",RegexOptions.IgnoreCase);
 result = Regex.Replace(result,@"(<( )*(/)( )*script( )*>)", "</script>",RegexOptions.IgnoreCase);
              
result = Regex.Replace(result,@"(<script>).*(</script>)", string.Empty,RegexOptions.IgnoreCase);

 // remove all styles (prepare first by clearing attributes)
 result = Regex.Replace(result,@"<( )*style([^>])*>", "<style>",RegexOptions.IgnoreCase);
  result = Regex.Replace(result,@"(<( )*(/)( )*style( )*>)", "</style>",RegexOptions.IgnoreCase);
  result = Regex.Replace(result,"(<style>).*</style>)",string.Empty,RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags
                result = Regex.Replace(result,@"<( )*td([^>])*>", "\t",RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags
                result = Regex.Replace(result,@"<( )*br( )*>", "\r",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"<( )*li( )*>", "\r",RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place
                // if <P>, <DIV> and <TR> tags
                result = Regex.Replace(result,@"<( )*div([^>])*>", "\r\r",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"<( )*tr([^>])*>", "\r\r",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"<( )*p([^>])*>", "\r\r",RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,
                // comments etc - anything that's enclosed inside < >
                result = Regex.Replace(result,@"<[^>]*>", string.Empty,RegexOptions.IgnoreCase);

                // replace special characters:
                result = Regex.Replace(result,@" ", " ",RegexOptions.IgnoreCase);

                result = Regex.Replace(result,@"&bull;", " * ",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&lsaquo;", "<",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&rsaquo;", ">",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&trade;", "(tm)",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&frasl;", "/",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&lt;", "<",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&gt;", ">",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&copy;", "(c)",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,@"&reg;", "(r)",RegexOptions.IgnoreCase);
              
                result = Regex.Replace(result,@"&(.{2,6});", string.Empty,RegexOptions.IgnoreCase);

               

                // make line breaking consistent
                result = result.Replace("\n", "\r");

                // Remove extra line breaks and tabs:
                // replace over 2 breaks with 2 and over 4 tabs with 4.
                // Prepare first to remove any whitespaces in between
                // the escaped characters and remove redundant tabs in between line breaks
                result = Regex.Replace(result,"(\r)( )+(\r)", "\r\r",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,"(\t)( )+(\t)", "\t\t",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,"(\t)( )+(\r)", "\t\r",RegexOptions.IgnoreCase);
                result = Regex.Replace(result,"(\r)( )+(\t)", "\r\t",RegexOptions.IgnoreCase);
                // Remove redundant tabs
                result = Regex.Replace(result,"(\r)(\t)+(\r)", "\r\r",RegexOptions.IgnoreCase);
                // Remove multiple tabs following a line break with just one tab
                result = Regex.Replace(result,"(\r)(\t)+", "\r\t",RegexOptions.IgnoreCase);
                // Initial replacement target string for line breaks
                string breaks = "\r\r\r";
                // Initial replacement target string for tabs
                string tabs = "\t\t\t\t\t";
                for (int index = 0; index < result.Length; index++)
                {
                    result = result.Replace(breaks, "\r\r");
                    result = result.Replace(tabs, "\t\t\t\t");
                    breaks = breaks + "\r";
                    tabs = tabs + "\t";
                }

                // That's it.
                return result;
            }
            catch
            {
             
                return source;
            }
        }


Wednesday, 10 July 2013

Get Html Webresource control value in Crm 2011 javascript


Here "WebResource_CboComponent" is webresource name and "CboComponent" is html control name in the html page.

the html page looks like below

<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE></TITLE><LINK rel=stylesheet type=text/css href="/_common/styles/fonts.css.aspx?lcid=1033"><LINK rel=stylesheet type=text/css href="/_common/styles/global.css.aspx?lcid=1033"><LINK rel=stylesheet type=text/css href="/_common/styles/select.css.aspx?lcid=1033">
<SCRIPT type=text/javascript src="../ClientGlobalContext.js.aspx"></SCRIPT>

<SCRIPT type=text/javascript src="json2.js"></SCRIPT>

<SCRIPT type=text/javascript src="jquery161min.js"></SCRIPT>

<SCRIPT type=text/javascript src="FetchXMLUtil.js"></SCRIPT>
<SCRIPT type=text/javascript src="XrmServiceToolkit.js"></SCRIPT>

<SCRIPT type=text/javascript src="../New_chargeitem_main_library.js"></SCRIPT>

<SCRIPT language=javascript type=text/javascript>

    var Quantity = 0;
    function window.onload() {
        //alert("Onload");
        var _oServices;
        var _sServerUrl = GetGlobalContext().getServerUrl();
       
        var new_chargeid = window.parent.Xrm.Page.getAttribute("new_chargeid").getValue();
     
        var fFetch = "fetch Query";
         _oServices = new FetchUtil(_sServerUrl);
        var oEntity = _oServices.Fetch(fFetch, ComponentsCallBack);
    }
    function ComponentsCallBack(results) {


        var _lookupItems = new Array();
        document.getElementById("CboComponent").length = 0;
        if (results.length != 0) {
            var Select = document.getElementById("CboComponent");
            for (i = 0; i < results.length; i++) {

                option = document.createElement("option");
                option.text = results[i].attributes.new_name.value;
                option.value = results[i].attributes.new_componentid.value.toLowerCase();
                option.title = "Components";
                Select.add(option, i);
            }

            // Select.selectedIndex = -1;
            var lookup = new Array();

             lookup = window.parent.Xrm.Page.getAttribute("new_componentid").getValue();
             if (Select != null && lookup != null) {
                 var id = lookup[0].id.toLowerCase().replace('{', '').replace('}', '');
                 Select.value = id;
                 //window.parent.GetComponentRecord(id);
                 window.parent.GetInclusiveQuantity();
               }else {
                 Select.selectedIndex = -1;
            }

          
        }
    }
 
   function addComponent() {
        //alert("On change Event");
        var Select = document.getElementById("CboComponent");
        if (Select !=null && Select.selectedIndex >= 0) {
            var compID = Select.options[Select.selectedIndex].value;
           
            if (compID != null) {
               var unitprice = window.parent.Xrm.Page.getAttribute("new_componentunitprice");
                if (unitprice != undefined)
                    unitprice.setValue(null);
                window.parent.GetComponentRecord(compID);
               
            }
        }

    }

    function ComponentLookup() {
       // alert("ComponentLookup");
        window.parent.document.getElementById('new_componentid').click();

    }

  </SCRIPT>

<META charset=utf-8></HEAD>
<BODY>
<TABLE cellSpacing=0 cellPadding=0 width="100%">
<TBODY>
<TR>
<TD style="WIDTH: 100%"><SELECT style="WIDTH: 100%" id=CboComponent onchange=addComponent()  class=ms-crm-SelectBox></SELECT> </TD>
</TR></TBODY></TABLE>

</BODY></HTML>


 In the Entity form load(where we used the above html page as webresource in the form) we can access the control from below code

function ToggleFormFields(disable) {
var Select = Xrm.Page.getControl("WebResource_CboComponent").getObject().
contentWindow.window.document.getElementById("CboComponent");

   if(Select!=null)
        Select.disabled =disable;

}


Friday, 5 July 2013

CRM 2011 Javascript Fetch XML synchronous or asynchronous using FetchUtil


Using helper function to execute FetchXML request is great.

FetchUtil.js:

/// <summary>FetchUtil.js</summary>
var XMLHTTPSUCCESS = 200;
var XMLHTTPREADY = 4;
function FetchUtil(sOrg, sServer) {
    this.org = sOrg;
    this.server = sServer;
    if (sOrg == null) {
        if (typeof (ORG_UNIQUE_NAME) != "undefined") {
            this.org = ORG_UNIQUE_NAME;
        }
    }
    if (sServer == null) {
        this.server = window.location.protocol + "//" + window.location.host;
    }
}
FetchUtil.prototype._ExecuteRequest = function (sXml, sMessage, fInternalCallback, fUserCallback) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", this.server + "/XRMServices/2011/Organization.svc/web", (fUserCallback != null));
    xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
    xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (fUserCallback != null) {
        //asynchronous: register callback function, then send the request.
        var crmServiceObject = this;
        xmlhttp.onreadystatechange = function () { fInternalCallback.call(crmServiceObject, xmlhttp, fUserCallback) };
        xmlhttp.send(sXml);
    }
    else {
        //synchronous: send request, then call the callback function directly
        xmlhttp.send(sXml);
        return fInternalCallback.call(this, xmlhttp, null);
    }
}
FetchUtil.prototype._HandleErrors = function (xmlhttp) {
    /// <summary>(private) Handles xmlhttp errors</summary>
    if (xmlhttp.status != XMLHTTPSUCCESS) {
        var sError = "Error: " + xmlhttp.responseText + " " + xmlhttp.statusText;
        alert(sError);
        return true;
    } else {
        return false;
    }
}
FetchUtil.prototype.Fetch = function (sFetchXml, fCallback) {
    /// <summary>Execute a FetchXml request. (result is the response XML)</summary>
    /// <param name="sFetchXml">fetchxml string</param>    /// <param name="fCallback" optional="true" type="function">(Optional) Async callback function if specified. If left null, function is synchronous </param>
    var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    request += "<s:Body>";
    request += '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">' +
'<request i:type="b:RetrieveMultipleRequest" ' +
'<b:KeyValuePairOfstringanyType>' +
'<c:key>Query</c:key>' +
'<c:value i:type="b:FetchExpression">' +
'<b:Query>';
    request += CrmEncodeDecode.CrmXmlEncode(sFetchXml);
    request += '</b:Query>' +
'</c:value>' +
'</b:KeyValuePairOfstringanyType>' +
'</b:Parameters>' +
'<b:RequestId i:nil="true"/>' +
'<b:RequestName>RetrieveMultiple</b:RequestName>' +
'</request>' +
'</Execute>';
    request += '</s:Body></s:Envelope>';
    return this._ExecuteRequest(request, "Fetch", this._FetchCallback, fCallback);
}
FetchUtil.prototype._FetchCallback = function (xmlhttp, callback) {
    ///<summary>(private) Fetch message callback.</summary>
    //xmlhttp must be completed
    if (xmlhttp.readyState != XMLHTTPREADY) {
        return;
    }
    //check for server errors
    if (this._HandleErrors(xmlhttp)) {
        return;
    }
    var sFetchResult = xmlhttp.responseXML.selectSingleNode("//a:Entities").xml;
    var resultDoc = new ActiveXObject("Microsoft.XMLDOM");
    resultDoc.async = false;
    resultDoc.loadXML(sFetchResult);
    //parse result xml into array of jsDynamicEntity objects
    var results = new Array(resultDoc.firstChild.childNodes.length);
    for (var i = 0; i < resultDoc.firstChild.childNodes.length; i++) {
        var oResultNode = resultDoc.firstChild.childNodes[i];
        var jDE = new jsDynamicEntity();
        var obj = new Object();
        for (var j = 0; j < oResultNode.childNodes.length; j++) {
            switch (oResultNode.childNodes[j].baseName) {
                case "Attributes":
                    var attr = oResultNode.childNodes[j];
                    for (var k = 0; k < attr.childNodes.length; k++) {
                        // Establish the Key for the Attribute
                        var sKey = attr.childNodes[k].firstChild.text;
                        var sType = '';
                        // Determine the Type of Attribute value we should expect
                        for (var l = 0; l < attr.childNodes[k].childNodes[1].attributes.length; l++) {
                            if (attr.childNodes[k].childNodes[1].attributes[l].baseName == 'type') {
                                sType = attr.childNodes[k].childNodes[1].attributes[l].text;
                            }
                        }
                        switch (sType) {
                            case "a:OptionSetValue":
                                var entOSV = new jsOptionSetValue();
                                entOSV.type = sType;
                                entOSV.value = attr.childNodes[k].childNodes[1].text;
                                obj[sKey] = entOSV;
                                break;
                            case "a:AliasedValue":
                                var entRef = new jsEntityReference();
                                entRef.guid = attr.childNodes[k].childNodes[1].childNodes[2].childNodes[0].text;
                                entRef.logicalName = attr.childNodes[k].childNodes[1].childNodes[2].childNodes[1].text;
                                entRef.name = attr.childNodes[k].childNodes[1].childNodes[2].childNodes[2].text;
                                obj[attr.childNodes[k].childNodes[1].childNodes[0].text] = entRef;
                                break;
                            case "a:EntityReference":
                                var entRef = new jsEntityReference();
                                entRef.type = sType;
                                entRef.guid = attr.childNodes[k].childNodes[1].childNodes[0].text;
                                entRef.logicalName = attr.childNodes[k].childNodes[1].childNodes[1].text;
                                entRef.name = attr.childNodes[k].childNodes[1].childNodes[2].text;
                                obj[sKey] = entRef;
                                break;
                            default:
                                var entCV = new jsCrmValue();
                                entCV.type = sType;
                                entCV.value = attr.childNodes[k].childNodes[1].text;
                                obj[sKey] = entCV;
                                break;
                        }
                    }
                    jDE.attributes = obj;
                    break;
                case "Id":
                    jDE.guid = oResultNode.childNodes[j].text;
                    break;
                case "LogicalName":
                    jDE.logicalName = oResultNode.childNodes[j].text;
                    break;
                case "FormattedValues":
                    var foVal = oResultNode.childNodes[j];
                    for (var k = 0; k < foVal.childNodes.length; k++) {
                        // Establish the Key, we are going to fill in the formatted value of the already found attribute
                        var sKey = foVal.childNodes[k].firstChild.text;
                        jDE.attributes[sKey].formattedValue = foVal.childNodes[k].childNodes[1].text;
                    }
                    break;
            }
        }
        results[i] = jDE;
    }
    //return entities
    if (callback != null) callback(results);
    else return results;
}
function jsDynamicEntity(gID, sLogicalName) {
    this.guid = gID;
    this.logicalName = sLogicalName;
    this.attributes = new Object();
}
function jsCrmValue(sType, sValue) {
    this.type = sType;
    this.value = sValue;
}
function jsEntityReference(gID, sLogicalName, sName) {
    this.guid = gID;
    this.logicalName = sLogicalName;
    this.name = sName;
    this.type = 'EntityReference';
}
function jsOptionSetValue(iValue, sFormattedValue) {
    this.value = iValue;
    this.formattedValue = sFormattedValue;
    this.type = 'OptionSetValue';
}
//setting CRM fields
function SetLookupField(res, fieldName) {
    if (res[0].attributes[fieldName] != null) {
        SetLookupValue(fieldName, res[0].attributes[fieldName].id, res[0].attributes[fieldName].name, res[0].attributes[fieldName].logicalName);
    }
}
function SetNumberField(res, fieldName) {
    if (res[0].attributes[fieldName] != null) {
        Xrm.Page.getAttribute(fieldName).setValue(parseFloat(res[0].attributes[fieldName].value));
    }
}
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);
    }
}





Synchronous Call Sample :


function FetchData(contactid) {
    var _oService;
    var _sOrgName = "";
    var _sServerUrl = Xrm.Page.context.getServerUrl();
    var sFetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='contact'>" +
  "<attribute name='fullname' />" +
   "<filter type='and'>" +
  "<condition attribute='contactid' operator='eq'   value='" + contactid+ "' />" +
  "</filter>" +
  "</entity>" +
  "</fetch>"
    _oService = new FetchUtil(_sOrgName, _sServerUrl);
    var res = _oService.Fetch(sFetch);

var fullName=res[0].attributes["fullname"].value;
}



Asynchronous Call Sample :


function FetchData(contactid) {
    var _oService;
    var _sOrgName = "";
    var _sServerUrl = Xrm.Page.context.getServerUrl();
    var sFetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='contact'>" +
  "<attribute name='fullname' />" +
   "<filter type='and'>" +
  "<condition attribute='contactid' operator='eq'   value='" + contactid+ "' />" +
  "</filter>" +
  "</entity>" +
  "</fetch>"
    _oService = new FetchUtil(_sOrgName, _sServerUrl);

//The below line will be difference
    var res = _oService.Fetch(sFetch,callBack);


}

function callBack(results){

var fullName=results[0].attributes["fullname"].value;
}