Saturday, 16 November 2019

CalculateRollupFieldRequest


EntityReference Note = Case.GetAttributeValue<EntityReference>("caseid");
CalculateRollupFieldRequest calculateRollup = new CalculateRollupFieldRequest();
calculateRollup.FieldName = _FieldSchemaName;
    calculateRollup.Target = new EntityReference(_EntitySchemaName, Note.Id);
CalculateRollupFieldResponse resp = (CalculateRollupFieldResponse)_service.Execute(calculateRollup);

filterSubGrid



https://nishantrana.me/2017/05/21/filter-subgrid-in-dynamics-365-with-new-form-rendering-or-turbo-form/

function filterSubGrid()
{
// get the current record's guid
var entityId = Xrm.Page.data.entity.getId();

// refer the subgrid
var testGrid = window.parent.document.getElementById("Test");

if (testGrid == null)
{
setTimeout(function () {filterSubGrid(); }, 2000);
return;
}

// fetch xml code using User operator
var fetchXml = "<fetch distinct='false' no-lock='false' mapping='logical'>" +
"<entity name='new_test' >" +
"<attribute name='new_name' />" +
" <attribute name='new_testname' />" +
"<order attribute='new_name' descending='true' />" +
"<filter type='and'>" +
"<condition attribute='new_testid' operator='under' value='"+entityId+"'"+"/>" +
"</filter>" +
"</entity>" +
"</fetch>";

if (testGrid.control != null)
{
testGrid.control.SetParameter("fetchXml", fetchXml);
testGrid.control.refresh();
}
else
{
setTimeout(filterSubGrid, 500);
}
}

Common Methods



 vaf["missionid"] = setLookupObject(missionId, "mission");
   

function setLookupObject(id, logicalName) {
    ///<summary>
    /// Function to set and return a lookup object
    ///</summary>
    var lookupObject = new Object();
    lookupObject.Id = id;
    lookupObject.LogicalName = logicalName;
    return lookupObject;
}

BPF




  static void Main(string[] args)
        {
            ClientCredentials clientCredentials = new ClientCredentials();
            clientCredentials.UserName.UserName = "";
            clientCredentials.UserName.Password = "";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri(""), null, clientCredentials, null);
            AdvanceBusinessProcessFlow(organizationService);

        }

        private static void AdvanceBusinessProcessFlow(IOrganizationService service)
        {
            // Retrieve all process instances
            RetrieveProcessInstancesRequest instanceRequest = new RetrieveProcessInstancesRequest
            {
                EntityId = new Guid("bceb89f8-4808-ea11-a811-000d3af02cd4"),
                EntityLogicalName = "new_student"
            };
            RetrieveProcessInstancesResponse instanceResponse = (RetrieveProcessInstancesResponse)service.Execute(instanceRequest);

            // First record is the active process instance
            Entity activeProcessInstance = instanceResponse.Processes.Entities[0];
            var activeProcessId = activeProcessInstance.Id;
            var activeStageId = new Guid(activeProcessInstance.Attributes["processstageid"].ToString());

            // Retrieve the process stages in the active path of the current process instance
            RetrieveActivePathRequest activePathRequest = new RetrieveActivePathRequest
            {
                ProcessInstanceId = activeProcessId
            };

            // System.ServiceModel.FaultException exception occurs here
            RetrieveActivePathResponse activePathResponse = (RetrieveActivePathResponse)service.Execute(activePathRequest);

            string activeStageName;
            int? activeStagePosition = null;
            int stageCount = activePathResponse.ProcessStages.Entities.Count;

            // Iterate through all process stages and identify active stage
            for (int i = 0; i < stageCount; i++)
            {
                if (activePathResponse.ProcessStages.Entities[i].Attributes["processstageid"].ToString() == activeStageId.ToString())
                {
                    activeStageName = activePathResponse.ProcessStages.Entities[i].Attributes["stagename"].ToString();
                    activeStagePosition = i;
                }
            }       

            // Auto-advance active stages of BPF to last stage so that BPF can be auto-finished
            while (activeStagePosition < stageCount - 1)
            {
                // Retrieve the stage ID of the next stage to be set as the active stage
                var newActiveStageId = (Guid)activePathResponse.ProcessStages.Entities[(int)++activeStagePosition].Attributes["processstageid"];

                // Retrieve the process instance record to update its active stage
                ColumnSet columnSet = new ColumnSet();
                columnSet.AddColumn("activestageid,traversedpath");
                Entity retrievedProcessInstance = service.Retrieve("new_testbpf", activeProcessId, columnSet);
                // Update active process stage
                retrievedProcessInstance["activestageid"] = new EntityReference("new_testbpf", newActiveStageId);
                service.Update(retrievedProcessInstance);
            }
        }

Email Templates

                  Email emailTemplate = new Email();
                ActivityParty fromAdd = new ActivityParty();
                fromAdd.PartyId = new EntityReference();
                fromAdd.PartyId.Id = this.Requestor.Get<EntityReference>(executionContext).Id;
                fromAdd.PartyId.LogicalName = Contact.EntityLogicalName.ToString();
                emailTemplate.From = new ActivityParty[] { fromAdd };
                ActivityParty toAdd = new ActivityParty();
                toAdd.PartyId = new EntityReference();
                toAdd.PartyId.Id = queueID;
                toAdd.PartyId.LogicalName = "queue";
                emailTemplate.To = new ActivityParty[] { toAdd };
                string emailsubject = this.Subject.Get<string>(executionContext).ToString();           
                emailTemplate.Subject = emailsubject;
                emailTemplate.Description = this.FullMessage.Get<string>(executionContext).ToString();

                EntityReference Regarding = new EntityReference();
                Regarding.Id = regardingCaseID;
                Regarding.LogicalName = "incident";
                emailTemplate.RegardingObjectId = Regarding;         
                emailTemplate.IsWorkflowCreated = true;
                if (queueID != null && queueID != Guid.Empty)
                {
                    QueryExpression queryQu = new QueryExpression
                    {
                        EntityName = Queue.EntityLogicalName,
                        ColumnSet = new ColumnSet("ownerid"),
                    };

                    queryQu.Criteria.AddCondition("queueid", ConditionOperator.Equal, queueID.ToString());

                    EntityCollection retrievedQu = _service.RetrieveMultiple(queryQu);
                    if (retrievedQu.Entities.Count > 0)
                    {
                        EntityReference queueOwner = (EntityReference)retrievedQu.Entities[0].Attributes["ownerid"];
                        emailTemplate.OwnerId = new EntityReference("team", queueOwner.Id);
                    }
                }

                Guid emailId = SendEmail(emailTemplate, _service, context, emailTemplate.Subject);
                Entity incidentEnity = new Entity();
                incidentEnity.Id = regardingCaseID;
                incidentEnity.LogicalName = "incident";

                incidentEnity.Attributes.Add("emailid", emailId.ToString());
                incidentEnity.Attributes.Add("email", new OptionSetValue(2));
                _service.Update(incidentEnity);

            }

            public static void AddAttachmentsToEmail(IOrganizationService _service, Guid activityId, Guid emailId, string emailSubject)
            {

                QueryExpression notesQuery = new QueryExpression
                {
                    EntityName = "annotation",
                    ColumnSet = new ColumnSet("filename", "documentbody", "mimetype", "objectid", "annotationid"),
                    Criteria = new FilterExpression()
                };
                notesQuery.Criteria.AddCondition("objectid", ConditionOperator.Equal, activityId);
                EntityCollection noteCol = _service.RetrieveMultiple(notesQuery);
                if (noteCol.Entities.Count > 0)
                {
                    for (int i = 0; i < noteCol.Entities.Count; i++)
                    {
                        string attachmentSubject = emailSubject;

                        // Create note in case                       
                        Entity setupAttachment = new Entity();
                        setupAttachment.LogicalName = "activitymimeattachment";
                        setupAttachment["subject"] = attachmentSubject;
                        setupAttachment["filename"] = (string)noteCol.Entities[i].Attributes["filename"];
                        setupAttachment["body"] = (string)noteCol.Entities[i].Attributes["documentbody"];
                        setupAttachment["mimetype"] = (string)noteCol.Entities[i].Attributes["mimetype"];
                        setupAttachment["objectid"] = new EntityReference("email", emailId);
                        setupAttachment["objecttypecode"] = "email";

                        _service.Create(setupAttachment);
                    }
                }

            }

            private Guid SendEmail(Email emailObj, IOrganizationService _service, IWorkflowContext context, string emailSubject)
            {
                Guid emailId = _service.Create(emailObj);

                //statecode is 1
                SetStateRequest req = new SetStateRequest();

                req.EntityMoniker = new EntityReference("email", emailId);

                req.State = new OptionSetValue(1);

                req.Status = new OptionSetValue(4);

                SetStateResponse resp = (SetStateResponse)_service.Execute(req);

                return emailId;

            }        

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