Showing posts with label Client Side. Show all posts
Showing posts with label Client Side. Show all posts

Tuesday, November 24, 2015

Update Grid Fetch in client side


Here is my example to update grid request in Client Site.

create new function and check if grid is already loaded

function UpdateGridOptions() {

    var myGrid = document.getElementById("myGridExample");

   
    if (myGrid == null || myGrid .readyState != "complete") {
     
        setTimeout('UpdateGridOptions()', 1000);
        return;
    }
    if (Xrm.Page.getAttribute('accountid').getValue() != null) {
        var accountId = Xrm.Page.getAttribute('accountid').getValue()[0].id;
        var fetchXml = GetFetchForGrid(accountId, Xrm.Page.data.entity.getId());
        //update grid with new fetchXml
        myGrid .control.SetParameter("fetchXml", fetchXml);
        //Refresh grid
        myGrid .control.refresh();

    }
}
Enjoy,
Rami Heleg

Thursday, May 21, 2015

Converting HTML to description field in Email Activity show html tags..

To remove all HTML tags when insert the html to description fields replace the content with the next command:


Xrm.Page.getAttribute("description").setValue(Xrm.Page.getAttribute("description").getValue().replace(/<[^>]*>?/g, ""));


Enjoy,
Rami Heleg

Implement nolock in Fetch

By default SQL server defined to lock records when execute query and rows selected until finish to execute.. problem when we have many records.

to prevent lock records in CRM, DBA allow to define all database to work with no-lock and we have another option to request fetch with no lock.

Example:









Enjoy,
Rami Heleg

Wednesday, May 20, 2015

Set field Mandatory, Recommended


//Mandatory
 Xrm.Page.getAttribute("new_field").setRequiredLevel('required');
//Usual,
Xrm.Page.getAttribute("new_field").setRequiredLevel('none');
//Recommended
Xrm.Page.getAttribute("new_field").setRequiredLevel('recommended');

Enjoy,
Rami Heleg

Submit Fields even if fields disabled


If Fields in disabled mode CRM doesn't send the value to server.. because of that we have the property Submit


example:
Xrm.Page.getAttribute("new_field").setSubmitMode("always");

Full example - Assign Request – Client side

//Assign to user
    AssignRequest(Xrm.Page.data.entity.getId(), 'incident', result.fl_userid.Value, 'systemuser');
//Assign to Team
    AssignRequest(Xrm.Page.data.entity.getId(), 'incident', result.fl_teamid.Value, 'team');

function AssignRequest(targetID, targetLogicalName, assigneeID, assigneeLogicalName) {
    var requestMain = ""
    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:AssignRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Target</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + targetID + "</a:Id>";
    requestMain += "              <a:LogicalName>" + targetLogicalName + "</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Assignee</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + assigneeID + "</a:Id>";
    requestMain += "              <a:LogicalName>" + assigneeLogicalName + "</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>Assign</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";
    try {
        var req = new XMLHttpRequest();
    }
    catch (e) {
        var req = new ActiveXObject("Msxml2.XMLHTTP");
    }
    req.open("POST", getServerUrlWithOrgServicePath(), isAsync)

    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    try { req.responseType = 'msxml-document'; } catch (e) { }
    req.send(requestMain);

    if (req.readyState == 4) {
        if (req.status == 200) {
            return true;
        }
        else {
            return req.responseXML;
        }
    }
}

function getServerUrlWithOrgServicePath() {
    var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
    var serverUrl = Xrm.Page.context.getClientUrl();
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);

    }
    return serverUrl + OrgServicePath;
}

Enjoy,
Rami Heleg

Remove new record in lookup

var lookup = FLHTM.GetElement('new_lookupid');
lookup.AddParam("ShowNewButton", "1");

Set lookup Values

//get values base fetch or ODATA

http://mscrm201x.blogspot.co.il/2015/05/full-example-get-contact-details-base_20.html

var lookupData = new Array();
var lookupItem = new Object();
lookupItem.id = result[0].accountid.Value; // SET ID
lookupItem.name = result[0].name.Value; //SET NAME
lookupItem.typename = "account"; //ENTITY NAME
lookupData[0] = lookupItem;
Xrm.Page.getAttribute('customerid').setValue(lookupData);

Attach Event on field - Client side


// select the field and define the event on change
 Xrm.Page.getAttribute('new_fieldName').addOnChange(FieldChanged);


function FieldChanged(){
alert('function FieldChanged');
}

Full example - get Contact Details base ODATA – Client side

function FormOnLoad() {
    try {
        if (Xrm.Page.data.entity.getId() == null) { return true; }
        var contactId = Xrm.Page.data.entity.getId();
        var queryUrl = "ContactSet(guid'" + contactId + "')"
        var result = RequestODATA(queryUrl);
        alert(result[0].FullName);
    }
    catch (ex) {
        alert(ex.message);
    }
}

function RequestODATA(query) {
    try {
        var xmlhttp = new XMLHttpRequest();
    }
    catch (e) {
        var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    xmlhttp.open("GET", prependOrgName("/xrmservices/2011/organizationdata.svc/") + query, false);
    xmlhttp.send();
    return GetReturnObject(xmlhttp.responseText, null, "");
}

function GetReturnObject   (xmlText, linksArr, fatherNode) {
    var returnObjectNSResolver = { m: "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata", d: "http://schemas.microsoft.com/ado/2007/08/dataservices" };
    var Entities = new Array();
    Entities.flError = {};
    try {
        var xml = XUI.Xml.LoadXml(xmlText.replace('xmlns="http://www.w3.org/2005/Atom"', ""));
        var entrys = XUI.Xml.SelectNodes(xml, fatherNode + '/entry', null);

        var entityName = GetEntityName(xml);
        Entities.EntityName = entityName;
        for (var i = 0; !IsNull(entrys), i < entrys.length; i++) {
            var linksXML = entrys[i].getElementsByTagName('link');


            var obj = new Object();

            if (!IsNull(linksArr)) {
                obj.LinksExpanded = GetLinks2Expand(entrys[i], linksArr);
            }
            var props = XUI.Xml.SelectSingleNode(entrys[i], "content/m:properties", returnObjectNSResolver);
            for (var j = 0; j < props.childNodes.length; j++) {
                if (props.childNodes[j].nodeType != 1)
                    continue;
                var type = props.childNodes[j].getAttribute("m:type");
                var propName = props.childNodes[j].tagName.replace("d:", "");
                switch (IsNull(type) ? "" : type) {
                    case FieldTypes.int:
                    case FieldTypes.double:
                    case FieldTypes.long:
                    case FieldTypes.string:
                    case FieldTypes.datetime:
                    case FieldTypes.guid:
                    case FieldTypes.decimal:
                        var propValue = IsNull(XUI.Xml.GetText(props.childNodes[j])) ? "" : XUI.Xml.GetText(props.childNodes[j]);
                        eval("obj." + propName + " = null; var tempEval = null;");
                        tempEval = propValue;
                        var evalExpression = ("obj." + propName + " = tempEval");
                        break;
                    case FieldTypes.bool:
                        var propValue = IsNull(XUI.Xml.GetText(props.childNodes[j])) ? "false" : XUI.Xml.GetText(props.childNodes[j]);
                        if (propValue == "")
                            propValue = "false";
                        var evalExpression = "obj." + propName + " = " + FixedString(propValue) + ";";
                        break;
                    case FieldTypes.money:
                    case FieldTypes.optionSetValue:
                        var value = XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:Value', returnObjectNSResolver);
                        var propValue = IsNull(value) ? "" : XUI.Xml.GetText(value);
                        break;
                    case FieldTypes.entityReference:
                        var id = IsNull(XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:Id', returnObjectNSResolver)) ? "" : "'" + XUI.Xml.GetText(XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:Id', returnObjectNSResolver)) + "'";
                        var logic = IsNull(XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:LogicalName', returnObjectNSResolver)) ? "" : "'" + XUI.Xml.GetText(XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:LogicalName', returnObjectNSResolver)) + "'";
                        var display = IsNull(XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:Name', returnObjectNSResolver)) ? "" : "'" + FixedString(XUI.Xml.GetText(XUI.Xml.SelectSingleNode(props.childNodes[j], 'd:Name', returnObjectNSResolver))) + "'";
                        break;
                }
                eval(evalExpression);
            }
            Entities.push(obj);
        }

        if (Entities.length == 0) {
            var error = xml.getElementsByTagName('error');

            if (!IsNull(error[0])) {
                Entities.flError.Message = XUI.Xml.GetText(XUI.Xml.SelectSingleNode(error[0], 'message', null));
                Entities.flError.Code = 1;
            }
            else {
                Entities.flError.Message = "Query with returned no results";
                Entities.flError.Code = 2;
            }
        }
        else {
            Entities.flError.Message = "";
            Entities.flError.Code = 0;
        }
    } catch (e) {
        Entities.flError.Message = e.message;
        Entities.flError.Code = 3;
    }

    return Entities;
}

function GetEntityName (xml) {
    var retVal = "";
    var node = XUI.Xml.SelectSingleNode(xml, "//link[@rel='edit']", null);
    if (!IsNull(node)) {
        retVal = node.getAttribute("title");
    }
    return retVal;
}


function GetLinks2Expand   (xmlTemp, linksArr) {
    var xml = new ActiveXObject("Microsoft.XMLDOM");
    xml.loadXML(xmlTemp.xml);
    var xpathOne = "m:inline";
    var xpathMany = "m:inline/feed";
    var xmlDeclaration = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>";
    var retArray = new Array();
    for (var i = 0; i < linksArr.length; i++) {
        var node = XUI.Xml.SelectSingleNode(xml, "//link[@title = '" + linksArr[i] + "']", null);
        if (!IsNull(node)) {
            var title = node.getAttribute('title');
            var tmpArr;
            if (!IsNull(XUI.Xml.SelectSingleNode(node, xpathMany, null))) {
                tmpArr = this.GetReturnObject(xmlDeclaration + XUI.Xml.SelectSingleNode(node, xpathMany, null).xml, null, "feed");
            }
            else if (!IsNull(XUI.Xml.SelectSingleNode(node, xpathOne, null))) {
                tmpArr = this.GetReturnObject(xmlDeclaration + XUI.Xml.SelectSingleNode(node, xpathOne, null).xml, null, xpathOne);
            }
            if (!IsNull(title) && !IsNull(linksArr)) {
                var LinkObject = new Link(title, tmpArr);
                retArray.push(LinkObject);
            }
        }
    }
    return retArray;
}

FieldTypes = {
    int: "Edm.Int32",
    long: "Edm.Int64",
    bool: "Edm.Boolean",
    guid: "Edm.Guid",
    datetime: "Edm.DateTime",
    decimal: "Edm.Decimal",
    optionSetValue: "Microsoft.Crm.Sdk.Data.Services.OptionSetValue",
    money: "Microsoft.Crm.Sdk.Data.Services.Money",
    entityReference: "Microsoft.Crm.Sdk.Data.Services.EntityReference",
    double: "Edm.Double",
    string: ""
}

function  FixedString(str) {
    str = str.replace("\\", "\\\\");
    str = str.replace(/\'/g, "\\'");
    var newStr = str;
    return newStr;
}

Enjoy,
Rami Heleg

Hide\Show Section - Client side

function VisibleSection(tabName,sectionName, true);


//Get Three parameters tabname, section, visible true\false
function VisibleSection(tabName,sectionName, value) {
    var tabs = Xrm.Page.ui.tabs.get();
    for (var i in tabs) {
        var tab = tabs[i];
        if (tab.getName() ==tabName) {
            var section = tab.sections.get(sectionName);
            if (section != null)
                section.setVisible(value);
        }
    }
}

Enjoy,

Rami Heleg

Full example - get Contact Details base Fetch\Soap – Client side

function FormOnLoad() {
    try {
        if (Xrm.Page.data.entity.getId() == null) { return true; }
        var contactId = Xrm.Page.data.entity.getId();
        var fetch = BuilFetchForContact(contactId);
        var result = ExecuteFetchRequest(fetch);
        alert(result[0].fullname.Value);
    }
    catch (ex) {
        alert(ex.message);
    }
}
function BuilFetchForContact(contactId) {
    var fetch = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">';
    fetch +=        '<entity name="contact">';
    fetch +=            '<attribute name="fullname" />';
    fetch +=            '<attribute name="telephone1" />';
    fetch +=            '<attribute name="contactid" />';
    fetch +=            '<filter type="and">';
    fetch +=                '<condition attribute="contactid" operator="eq"  value="' + contactId + '" />';
    fetch +=            '</filter>';
    fetch +=        '</entity>';
    fetch +=    '</fetch>';
    return fetch;
}

function ExecuteFetchRequest (fetch) {
    var fetchFormatedString = CrmEncodeDecode.CrmXmlEncode(fetch);
    var requestMain = "";
    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:ExecuteFetchRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>FetchXml</c:key>";
    requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + fetchFormatedString + "</c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>ExecuteFetch</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";

    try {
        var req = new XMLHttpRequest();
    }
    catch (e) {
        var req = new ActiveXObject("Msxml2.XMLHTTP");
    }

    var isAsync = false;

    req.open("POST", getServerUrlWithOrgServicePath(), isAsync)
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    try { req.responseType = 'msxml-document'; } catch (e) { }
    req.send(requestMain);
    return CreateResultsArray(req);
}

function getServerUrlWithOrgServicePath () {
    var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
    var serverUrl = Xrm.Page.context.getClientUrl();
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);

    }
    return serverUrl + OrgServicePath;
}

function CreateResultsArray (request) {
    var createResultsArrayNSResolver = { a: "http://schemas.microsoft.com/xrm/2011/Contracts", c: "http://schemas.datacontract.org/2004/07/System.Collections.Generic" };

    var xmlDocument = XUI.Xml.LoadXml(request.responseText.replace('xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"', ''));

    var fetchResultsText = XUI.Xml.GetText(XUI.Xml.SelectSingleNode(xmlDocument, "//a:Results/a:KeyValuePairOfstringanyType/c:value", createResultsArrayNSResolver));
    var fetchResultsNode = XUI.Xml.LoadXml(fetchResultsText);

    var arr = XUI.Xml.SelectNodes(fetchResultsNode, "//result", null);
    var retArr = new Array();
    for (var i = 0; i < arr.length; i++) {
        var resultObj = {};
        for (var j = 0; j < arr[i].childNodes.length; j++) {
            if (arr[i].childNodes[j].nodeType != 1)
                continue;
            var fixedNodeName = arr[i].childNodes[j].tagName.replace(".", "_");
            resultObj[fixedNodeName] = {};
            resultObj[fixedNodeName].Value = XUI.Xml.GetText(arr[i].childNodes[j]);
            resultObj[fixedNodeName].Attributes = {};
            for (var k = 0; k < arr[i].childNodes[j].attributes.length; k++) {
                resultObj[fixedNodeName].Attributes[arr[i].childNodes[j].attributes[k].name] = XUI.Xml.GetText(arr[i].childNodes[j].attributes[k]);
            }
        }
        retArr.push(resultObj);
    }
    return retArr;
}