Saturday, 2 February 2019

CRM Portal Codes

=======================================================================
function retrievedata(SQrequestType) {
    $.ajax({
        crossOrigin: true,
        method: "GET",
        url: "/WebPage/",
        datatype: "json"
    }).fail(function (jqXHR, textStatus, error) { ShowLocationErrorMsg(error, null); })
        .done(function (result) {
            if (result.data[0].HasError) {
             
            }
            else {
                var FetchDetails = result.data;
             
                if (FetchDetails != null) {
                    var dropdown = $("#new_buid");
                    dropdown.empty();
                    $.each(FetchDetails, function (m, location) {
                        if (SQrequestType == "MCA" || SQrequestType == "Usage") {
                            var option = $('<option>').text(location.name).val(location.businessunitid);
                            FetchDetails.push(option);
                            $("#new_buid").html(FetchDetails);
                        }
                     
                    });
                    dropdown[0].selectedIndex = -1;
                }
            }
        });
}


function ShowLocationErrorMsg(errorMsg, errorObj) {
    console.log("In ShowLocationErrorMsg ");
    alert("Error:" + errorMsg);
    console.log("Error: " + errorMsg);
}


=====================================================================

{% fetchxml portalQuery %}
<fetch>
  <entity name="businessunit">
    <attribute name="name"/>
    <attribute name="parentbusinessunitid"/>
    <attribute name="businessunitid"/>
    <attribute name="locationtype"/>
     <attribute name="isdisabled"/>
    <order ascending="true" attribute="name"/>
    <filter type="and">
      <condition attribute="locationtype" value="96224" operator="eq"/>
      <condition attribute="isdisabled" value="0" operator="eq"/>
    </filter>
  </entity>
</fetch>
{% endfetchxml %}
{% assign locations = portalQuery.results.entities %}
{
    "data" :
    [
    {% if locations and locations.size > 0 %}
    {% for item in portalQuery.results.entities %}
    {
        "name": "{{item.name}}",
        "businessunitid": "{{item.businessunitid}}"
    }
    {% unless forloop.last %},
{% endunless %}
{% endfor %}
{% else %}
{
  "name": "",
  "HasError": true, "Body": { "Message": "No results found" }
}
{% endif %}
]
}

====================================================================


{% assign details =request.params['refidata'] %}


{% fetchxml MsgData %}

   <fetch mapping="logical" version="1.0" distinct="false" output-format="xml-platform">
  <entity name="casemessage">
    <attribute name="casemessageid" />
    <attribute name="message" />
    <attribute name="createdon" />
    <attribute name="messagestatus" />
    <order descending="false" attribute="message" />
    <filter type="and">
      <condition value="{{ request.params['id'] | xml_escape }}"  attribute="casemessageid" uitype="casemessage" uiname="" operator="eq" />
    </filter>
  </entity>
</fetch>

{% endfetchxml %} [ {% for item in MsgData.results.entities %}

{ "source":"{{ item.messagetypes }}",
    "status":"{{item.messagestatus}}"

}

{% unless forloop.last %}, {% endunless %}
{% endfor %} ]


function GetMsgStatus(statusid) {
    var source;
    $.ajax({
        crossOrigin: true,
        method: "GET",
        url: "/msg/?id=" + statusid,
        dataType: "json",
        async: false

    }).fail(function (jqXHR, textStatus, error) { ShowErrorMsg(error, null); })
        .done(function (result) {
         
            var order = result;
            order.forEach(function (element) {
                status = element.status;
           
            });
        });

    return status;
}
====================================

Retrieving Fetchxml data using liquid Templates


=========================================================
{% assign L1 =request.params['refid'] %}

{% fetchxml lobData %}

<fetch mapping="logical" version="1.0" distinct="false" output-format="xml-platform">
<entity name="new_lineofbusiness">
  <attribute name="new_msname" />
  <attribute name="createdon" />
  <attribute name="new_line" />
  <attribute name="new_group" />
  <order descending="false" attribute="new_mslobname" />
  <filter type="and">
    <condition value="{{ request.params['refid'] | xml_escape }}"  attribute="new_lineo" operator="eq"  />
  </filter>
</entity>
</fetch>

{% endfetchxml %} [ {% for item in lobData.results.entities %}

{ "id":"{{ item.new_group.id }}",
    "name":"{{ item.new_group.name }}"

}

{% unless forloop.last %}, {% endunless %}
{% endfor %} ]

//application/json
====================================================================

if (window.jQuery) {
    (function ($) {

        $(document).ready(function () {
            debugger
            $.ajax({
                type: "GET",
                url: "/testodata/",
                dataType: 'json'
            }).fail(function (jqXHR, textStatus, error) { ShowErrorMsg(error, null); })
                        .done(function (result) {
                            var account = result;
                            account.forEach(function (element) {
                                var ttrr = element.businessunitid + " " + element.name;
                                $("#new_name").val(ttrr);



                            });
                        });

        }

           );

    }(window.jQuery));
}

=====================================================================
{% endfetchxml %} [ {% for item in chData.results.entities %}

"{{item.new_name}}"
{% unless forloop.last %}, {% endunless %}
{% endfor %} ]


{% endfetchxml %} [ {% for item in ContactData.results.entities %}

{ "id":"{{ item.contactid }}",
"emailid":"{{ item.emailaddress1 }}"

}

{% unless forloop.last %}, {% endunless %}
{% endfor %} ]

Odata queries in Portals

====================================================
Administrator(guid'3317e3b9-ab26-e911-9461-0003ff910db5')
Administrator?$filter=new_department/Value eq 100000000
Administrator?$filter=new_branch/Id eq (guid'475b158c-541c-e511-80d3-3863bb347ba8')
new_administrationsSet?$filter=new_name eq 'test'
new_administrationsSet?$filter=CreatedOn eq datetime'2019-02-12'

Friday, 1 February 2019

function Multioptions() {
    var PL_FeedbackCategory, PLV_PogramCategory;
    PLV_PogramCategory = Xrm.Page.getAttribute("new_departmentstext");
    PL_FeedbackCategory = Xrm.Page.getAttribute("new_department");
    GenericOnLoad(PL_FeedbackCategory, PLV_PogramCategory, "new_departmentstext", 150);
}

function GenericOnLoad(PL, PLV, fieldname, divSize) {
    if (PL.getValue() != null) {
        parent.document.getElementById(PL.getName()).style.display = "none";
    }
 
    var addDiv = document.createElement("div");
    addDiv.id = "div_" + fieldname;
    addDiv.setAttribute("style", "overflow-y:auto; height:" + divSize + "px; border:1px #6699cc solid; background-color:#ffffff;");

    var addTable = document.createElement('table');
    addTable.id = "table_" + fieldname;
    //  if (PL.getValue() != null)
    //   {
    parent.document.getElementById(PL.getName()).parentNode.appendChild(addDiv);
    //  }

    addDiv.appendChild(addTable);

    var PLlength = PL.getOptions().length;
    var PLsortedValues = PL.getOptions();
    function compare(a, b) {
        return a.text.localeCompare(b.text);
    }

    PLsortedValues.sort(compare);

    for (var i = 1; i < PLlength; i++) {

        var pOption = PLsortedValues[i];
        if (pOption != null) {
            if (!IsChecked(pOption.text)) {
                var addInput = document.createElement("input");
                addInput.setAttribute("type", "checkbox");
                addInput.setAttribute("style", "border:none; width:25px; align:left;");
            }
            else {
                var addInput = document.createElement("input");
                addInput.setAttribute("type", "checkbox");
                addInput.setAttribute("checked", "checked");
                addInput.setAttribute("style", "border:none; width:25px; align:left;");
            }

            var addLabel = document.createElement("label");
            addLabel.innerText = pOption.text;

            var row = document.createElement("tr");
            for (var j = 1; j < 3; j++) {
                var td = document.createElement('td');
                if (j == 1) {
                    td.appendChild(addInput);
                }
                else {
                    td.appendChild(addLabel);
                }
                row.appendChild(td);
            }
            addTable.appendChild(row);
        }
    }
    function IsChecked(pText) {

        if (PLV.getValue() != "" && PLV.getValue() != null) {
            var PLVT = PLV.getValue().split(";");
            for (var i = 0; i < PLVT.length; i++) {
                if (PLVT[i] == pText)
                    return true;
            }
        }
        return false;
    }
    function OnLoad() {
        var tableid = "table_" + fieldname;
        var table = parent.document.getElementById(tableid);
        if (table != null) {
            var rows = table.getElementsByTagName("tr");

            for (var i = 0; i < rows.length; i++) {
                var cell = rows[i].getElementsByTagName("Input");
                if (cell[0].type == "checkbox") {
                    if (cell[0].checked) {
                        table.insertBefore(rows[i], rows[0]);
                    }
                }
            }
        }
    }
}

function Form_OnSave() {


    var PL_FeedbackCategory = Xrm.Page.getAttribute("new_department");

    GenericOnSave(PL_FeedbackCategory, "new_departmentstext");

    function GenericOnSave(PL, fieldname) {

        var tableid = "table_" + fieldname;
        var table = parent.document.getElementById(tableid);
        var result = '';
        if (table != null) {
            var rows = table.getElementsByTagName("tr");

            for (var i = 0; i < rows.length; i++) {
                var cell = rows[i].getElementsByTagName("Input");
                if (cell[0].type == "checkbox") {
                    if (cell[0].checked) {
                        result += rows[i].cells[1].innerText + ";";
                        table.insertBefore(rows[i], rows[0]);
                    }
                }
            }
            control = Xrm.Page.getControl(fieldname);
            attribute = control.getAttribute();
            attribute.setValue(result);
        }
    }
}

/////////==========================================================================================================

////Mutlti Optionset for Portal Side:

// JavaScript source code
$(document).ready(function () {
    debugger;


    var PL_DIOPartnerSelectionOptions = [];

    $('#new_department option').each(function (i) {
        var textvalues = $(this).text()
        //   alert(textvalues);

        if (textvalues != undefined && textvalues != "") {
            PL_DIOPartnerSelectionOptions[i] = $(this).text();
        }
    });

    var PL_DIOPartnerSelection = $("#new_department");
    var PLV_DIOPartnerSelection = $("#new_departmentstext");
    GenericOnLoad(PL_DIOPartnerSelection, PL_DIOPartnerSelectionOptions, PLV_DIOPartnerSelection);

    function GenericOnLoad(PL, PLOptions, PLV) {
        var PL_Name = PL.attr("id");
        document.getElementById(PL_Name).style.display = "none";
        document.getElementById(PL_Name).style.display = "none";

        var divid = "div_" + PL_Name;
        var tableid = "table_" + PL_Name;
        var addDiv = $("<div style='overflow-y:auto; height:150px; border:1px #6699cc solid; background-color:#ffffff;' id='" + divid + "'></div>");
        var addTable = $("<table id='" + tableid + "'></table>");

        $("#" + PL_Name).parent().append(addDiv);
        $("#" + divid).append(addTable);

        for (var i = 0; i < PLOptions.length; i++) {
            if (PLOptions[i] != undefined) {


                var pOption = PLOptions[i];
                if (pOption == "") {
                    continue;
                }
                else if (!IsChecked(pOption)) {
                    var trHTML = "";
                    trHTML += "<tr><td><input type='checkbox' style='border:none; width:25px; align:left;' onclick='UpdateSelectedOptions()'></td><td>" + pOption + "</td></tr>";
                    addTable.append(trHTML);
                    OnLoad();
                }
                else {
                    var trHTML = "";
                    trHTML += "<tr><td><input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' onclick='UpdateSelectedOptions()'></td><td>" + pOption + "</td></tr>";
                    addTable.append(trHTML);
                    OnLoad();
                }
            }
        }
        function IsChecked(pText) {
            if (PLV.val() !== "" && PLV.val() !== null) {
                // var PLVT = PLV.value.split(";");
                var PLVT = PLV.val().split(";");
                for (var i = 0; i < PLVT.length; i++) {
                    if (PLVT[i] == pText)
                        return true;

                }
            }
            else { return false; }
        }

        function OnLoad() {
            var getInput = $('#table_' + PL.attr('id'));
            var rows = getInput.find('tr');
            var result = '';
            var checkedRows = [];
            var sortedRows = [];

            for (var i = 0; i < rows.length; i++) {
                var $tds = rows.eq(i).find('td');
                var checked = $tds.eq(0).find('input[type="checkbox"]');
                if (getInput !== null) {
                    if (checked.is(':checked')) {
                        checkedRows.push(rows.eq(i));
                        //getInput.prepend(rows.eq(i));
                    }
                }
            }

            sortedRows = sortCheckedRows(checkedRows);
            getInput.prepend(sortedRows);

         
        }
    }



});

function sortCheckedRows(rows) {
    var sRows = rows.sort(function (a, b) {
        return a.find('td').eq(1).text == b.find('td').eq(1).text ? 0 : a.find('td').eq(1).text < b.find('td').eq(1).text ? -1 : 1
    });
    return sRows;
}

function UpdateSelectedOptions() {


    var PL_DIOPartnerSelection = $("#new_department");
    var PLV_DIOPartnerSelection = $("#new_departmentstext");

    if (PL_DIOPartnerSelection !== null) {
        GenericOnSave(PL_DIOPartnerSelection, PLV_DIOPartnerSelection);
    }

    function GenericOnSave(PL, PLV) {
        var getInput = $('#table_' + PL.attr('id'));
        var rows = getInput.find('tr');
        var result = '';
        var checkedRows = [];
        var sortedRows = [];

        for (var i = 0; i < rows.length; i++) {
            var $tds = rows.eq(i).find('td');
            var checked = $tds.eq(0).find('input[type="checkbox"]');
            var option = $tds.eq(1).text();
            if (getInput !== null) {
                if (checked.is(':checked')) {
                    result += option + ";";
                    checkedRows.push(rows.eq(i));
                    //getInput.prepend(rows.eq(i));
                }
            }
        }

        sortedRows = sortCheckedRows(checkedRows);
        getInput.prepend(sortedRows);

        PLV.val(result);
    }
}

Wednesday, 26 December 2018

Changing Record Status in MSCRM Using Javascripts

Chnaging The Record Status using Javascripts In MSCRM
============================================================


function changeRecordStatus() {

  var  vEntityName = Xrm.Page.data.entity.getEntityName();
    var guid = Xrm.Page.data.entity.getId();
    guid = guid.replace('{', '').replace('}', '');
    var url = "";
    if (Xrm.Page.context.getClientUrl) {
        
        url = Xrm.Page.context.getClientUrl();
    }
    else {
       
        url = Xrm.Page.context.getServerUrl();
    }
    
    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\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    request += "<request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    request += "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>EntityMoniker</c:key>";
    request += "<c:value i:type=\"a:EntityReference\">";
    request += "<a:Id>" + guid + "</a:Id>";
    request += "<a:LogicalName>" + vEntityName + "</a:LogicalName>";
    request += "<a:Name i:nil=\"true\" />";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>State</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "<a:Value>" + 1 + "</a:Value>";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>Status</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "<a:Value>" + 2 + "</a:Value>";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "</a:Parameters>";
    request += "<a:RequestId i:nil=\"true\" />";
    request += "<a:RequestName>SetState</a:RequestName>";
    request += "</request>";
    request += "</Execute>";
    request += "</s:Body>";
    request += "</s:Envelope>";
    //send set state request
    $.ajax({
        type: "POST",
        contentType: "text/xml; charset=utf-8",
        datatype: "xml",
        url: url + "/XRMServices/2011/Organization.svc/web",
        data: request,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
            XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            Xrm.Page.data.refresh();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Plugin triggering on Actions in MSCRM

Plugin triggering on actions in mscrm
============================================================

 public class TestingActions:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
           

            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            tracingService.Trace("triggered");
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            string firstname = context.InputParameters.Contains("Firstname") == true ? context.InputParameters["Firstname"].ToString() : string.Empty;
            tracingService.Trace(firstname);
            Entity TestEnity = service.Retrieve("new_testcrm", new Guid(firstname), new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
            context.OutputParameters["SearchResults"] = TestEnity;

        }

    }

==========================

Action:



ActionsCallingfromWEPAPI Using Javascrips


ActionsCallingfromWEPAPI Using Javascrips
===================================================

function ActionscallingfromWEBAPi() {

    var Gudid = Xrm.Page.data.entity.getId();
    Gudid = Gudid.replace('{', '').replace('}', '');
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/new_testcrms(" + Gudid + ")/Microsoft.Dynamics.CRM.new_TestActions", true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                debugger;
                /// lookupfield returnType:
                var results = JSON.parse(this.response);
                alert(results.accountid);
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
}