Tuesday, January 9, 2018

HTML Page + Xrm.Internal.openDialog with Call back Function MSCRM 2016

Hi All,

We got a requirement that on click of Deactivate Button in contact, we need to call custom HTML Page to get Data and we need to update the same in Contact Entity and need to deactivate the Record.
RIBBON BUTTON CHANGES:
Open Ribbon Work Bench à Select your Solution à Click Deactivate Button à Right Click and Customize Commandà Change the Library to new one which you created à change the Function to OpenHTMLPage

Add a new CRMParameter and make a Priority as First to pass OBJECT TYPE CODE.



JAVASCRIPT FUNCTION:

function OpenHTMLPage(predefinedparameters) {
    debugger;
    var currentRecId = Xrm.Page.data.entity.getId();
    var someText = "info";
    var addParams = "recordid=" + currentRecId + "&entityname=" + Xrm.Page.data.entity.getEntityName() + "&entitytypecode=" + predefinedparameters;
    //Build the URI
    var src = "/WebResources/pa_HTMLPage.html?Data=" + encodeURIComponent(addParams);
    //Build dialog options
    var DialogOptions = new Xrm.DialogOptions();
    DialogOptions.width = 400;
    DialogOptions.height = 260;

    Xrm.Internal.openDialog(src, DialogOptions, null, null, CallbackFunction);
}
//Execute some action on closing of dialog
function CallbackFunction(returnValue) {
    Xrm.Page.data.refresh();
}


HTML PAGE:

<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="../WebResources/pa_jquery.1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        Mscrm.Utilities.setReturnValue("close");
        var entityEnum = {
            2: "contacts",
        };
        function ParseQueryString(query) {
            var result = {};
            if (typeof query == "undefined" || query == null) {
                return result;
            }
            var queryparts = query.split("&");
            for (var i = 0; i < queryparts.length; i++) {
                var params = queryparts[i].split("=");
                result[params[0]] = params.length > 1 ? params[1] : null;
            }
            return result;
        }

        function updateRequest(destinationUpdateRequest, destinationUpdateEntity) {
            var req = new XMLHttpRequest();
            req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/" + destinationUpdateEntity + "", 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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
            req.onreadystatechange = function () {
                if (this.readyState === 4) {
                    req.onreadystatechange = null;
                    if (this.status === 204) {
                        var GetEntityName = entityEnum[entityTypeCode];
                        var updateEntityRequest = GetEntityName + "(" + currentRecId.replace("{", "").replace("}", "") + ")";
                        deactivateRecord(updateEntityRequest);
                    } else {
                        document.getElementById('alertLabel').innerHTML = 'Error: Please contact System Administrator';
                    }
                }
            };
            req.send(JSON.stringify(destinationUpdateRequest));
        }
        var passedparams = "";
        var currentRecId = "";
        var entityName = "";
        var entityTypeCode = "";
        function processSubmitButton() {
            debugger;
            document.getElementById('alertLabel').innerHTML = 'Please Wait...';
            passedparams = ParseQueryString(GetGlobalContext().getQueryStringParameters()["Data"]);
            currentRecId = passedparams.recordid;
            entityName = passedparams.entityname;
            entityTypeCode = passedparams.entitytypecode;
            var entity = {};
            entity.contact_description = document.getElementById("descriptionValues").value;
            var GetEntityName = entityEnum[entityTypeCode];
            var updateEntityRequest = GetEntityName + "(" + currentRecId.replace("{", "").replace("}", "") + ")";
            updateRequest(entity, updateEntityRequest);
        }

        function deactivateRecord(destinationUpdateEntity) {
            var entity = {};
            entity.statuscode = 2;
            entity.statecode = 1;

            var req = new XMLHttpRequest();
            req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/" + destinationUpdateEntity + "", 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 === 204) {
                        Mscrm.Utilities.setReturnValue(true);
                        closeWindow();
                    }
                    else {
                        Xrm.Utility.alertDialog(this.statusText);
                    }
                }
            };
            req.send(JSON.stringify(entity));

        }
    </script>
    <style>
        h5 {
            font-family: Segoe UI,Tahoma,Arial;
            font-weight: bold;
            font-variant: normal;
            color: #000080;
            text-decoration: underline;
        }

        h6 {
            font-family: Segoe UI,Tahoma,Arial;
            font-weight: bold;
            font-variant: normal;
        }

        p {
            font-family: Segoe UI,Tahoma,Arial;
            font-size: 13px;
        }
    </style>

    <meta>
    <meta>
    <meta>
    <meta>
</head>

<body style="word-wrap: break-word;">
    <h5> Please Enter your Comments </h5>
    <textarea rows="4" cols="75" name="comment" id="descriptionValues">    </textarea>&nbsp;<div style="font-family: undefined;"><br></div><div style="font-family: undefined;">
        <button type="button" id="OnSubmitButtonClick" onclick="processSubmitButton()">Submit</button>
        <h6><label id="alertLabel"></label></h6>
    </div>

</body>
</html>

Thursday, November 23, 2017

Find "\" Special Character in String with Occurances - JavaScript

Hi All,

Please find the code below to identify Special Character in a String.

var valuewithSpecialCharacter ="yourname\name"
var findSpecialCharacterinDomainName = 0;

    for (i = 0; i <= valuewithSpecialCharacter.length; i++) {
        if (/^[a-zA-Z]+$/.test(valuewithSpecialCharacter[i])) {
            findSpecialCharacterinDomainName += 1;
        } else {
            break;
        }
    }

Note:

You will get Output Count findSpecialCharacterinDomainName.


Monday, October 30, 2017

Connection to CRM is not established. Aborting process.

Hi All, 


Please find the below Code for CRM SVC util Sevices For Early Binding if it throws Label Error


Inside Server:

CrmSvcUtil.exe /url:http://localhost:555/ORGANIZATIONNAME/XRMServices/2011/Organization.svc /out:GeneratedCode.cs interactivelogin:true

Outside Server:

CrmSvcUtil.exe /url:https://URL/ORGNAME/XRMServices/2011/Organization.svc /out:GeneratedCode.cs interactivelogin:true

Note:

If we didn't Use interactivelogin:true then in INSIDE/OUTSIDE Server the system automatically tries to HIT Internet URL 

Error will be like below:

Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (North America) URI is = https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Europe, Middle East and Africa) URI is = https://disco.crm4.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Asia Pacific Area) URI is = https://disco.crm5.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (South America) URI is = https://disco.crm2.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Oceania) URI is = https://disco.crm6.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Japan) URI is = https://disco.crm7.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (North America 2) URI is = https://disco.crm9.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Canada) URI is = https://disco.crm3.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (India) URI is = https://disco.crm8.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Germany) URI is = https://disco.crm.microsoftdynamics.de/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (United Kingdom) URI is = https://disco.crm11.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : No Orgs Found, Searched Online. Region Setting = 
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Exception: Connection to CRM is not established. Aborting process.
   at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.LoadMetadata(IServiceProvider service)
   at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
   at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : CrmSvcUtil
Method : LoadMetadata
Date : 13:49:39
Time : 30.10.2017
Error : Connection to CRM is not established. Aborting process.
Stack Trace : at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.LoadMetadata(IServiceProvider service)
   at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
   at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
======================================================================================================================


Monday, October 23, 2017

Export JQGrid Data to CSV - JavaScript


//Create Grid Table
$("#JQGridName").jqGrid({
    datatype: "local",
    colNames: ['colname'], // Pass Col Name
    colModel: [{ name: 'colval'}], // Pass Col Values
    search: true,
    pager: '#JQGridPager', // Pass Grid Pager Name
    data: ExhbReportArrayData, // Pass Value for Grid
    rowNum: 20,
    rowList: [10, 20],
    viewrecords: true,
    shrinkToFit: false,
    height: 'auto',
    fixed: false,
    multiselect: true,
    forceFit: true
});

//Add Button to Grid Pager
$("#JQGridName").jqGrid('navGrid', '#JQGridPager', { view: true, del: false, add: false, edit: false, excel: true })
.navButtonAdd('#JQGridPager', {
    caption: "Export to Excel",
    buttonicon: "ui-icon-save",
    onClickButton: function (e) {
        exportData(e, '#JQGridName');
    },
    position: "last"
});

// Export Function - exportData

function exportData(e, id) {
    var gridid = jQuery(id).getDataIDs(); // Get all the ids in array
    var label = jQuery(id).getRowData(gridid[0]); // Get First row to get the labels
    var mydata = $(id).jqGrid('getGridParam', 'data');
    var obj = new Object();
    obj.count = mydata.length;
    obj.items = new Array();
    for (var i = 0; i < mydata.length; i++) {
        obj.items.push(mydata[i]);
    }
    var json = JSON.stringify(obj);
    JSONToCSVConvertor(json, "csv", 1);
}

// JSON to CSV Converter Function

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";
        //This loop will extract the label from 1st index of on array
        for (var index in arrData.items[0]) {
            //Now convert each value to string and comma-seprated
            row += index + ',';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        CSV += row + '\r\n';
    }
    //1st loop is to extract each row
    for (var i = 0; i < arrData.items.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData.items[i]) {
            row += '"' + arrData.items[i][index].replace(/(<([^>]+)>)/ig, '') + '",';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        CSV += row + '\r\n';
    }
    if (CSV == '') {
        alert("Invalid data");
        return;
    }
    //this trick will generate a temp "a" tag
    var link = document.createElement("a");
    link.id = "lnkDwnldLnk";
    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);
    var csv = CSV;
    blob = new Blob([csv], { type: 'text/csv' });
    var isIE = false || !!document.documentMode;
    var isEdge = !isIE && !!window.StyleMedia;
    if (isIE) {
        window.navigator.msSaveOrOpenBlob(blob, 'DataName.csv'); // Downloaded File Name Value
    }
    else {
        var myURL = window.URL || window.webkitURL;
        var csvUrl = myURL.createObjectURL(blob);
        var filename = 'DataName.csv'; // Downloaded File Name Value
        jQuery("#lnkDwnldLnk")
                        .attr({
                            'download': filename,
                            'href': csvUrl
                        });
        jQuery('#lnkDwnldLnk')[0].click();
        document.body.removeChild(link);
    }
}

Thursday, June 1, 2017

Check Special Character Exists in String or Not JQUERY

HI all,

Please find the JQuery to check weather Given Special Character Exists in String or not

$(document).ready(function () {
    var charReg = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
    $('#firstNametxtId').keyup(function () {
        var isValid = false;
        var inputVal = $(this).val();
        if (inputVal != "") {
            if (charReg.test(inputVal)) {
                isValid = true;
            }
        } else {
           
        }
    });
});

Friday, May 5, 2017

Get More than 5000 record from Fetch XML MSCRM

Code for Fetching 5000 + records in single time


        public static EntityCollection GetAllRecords(string fetchxml, IOrganizationService service)
        {
            EntityCollection recordsList = new EntityCollection();
            // Define the fetch attributes.
            // Set the number of records per page to retrieve.
            int fetchCount = 5000;
            // Initialize the page number.
            int pageNumber = 1;

            // Specify the current paging cookie. For retrieving the first page,
            // pagingCookie should be null.
            string pagingCookie = null;
            int i = 0;
            while (true)
            {
                // Build fetchXml string with the placeholders.
                string xml = CreateXml(fetchxml, pagingCookie, pageNumber, fetchCount);

                // Excute the fetch query and get the xml result.
                RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

                EntityCollection returnCollection = ((RetrieveMultipleResponse)service.Execute(fetchRequest1)).EntityCollection;

                foreach (var c in returnCollection.Entities)
                {
                    recordsList.Entities.Add(c);
                }



                // Check for morerecords, if it returns 1.
                if (returnCollection.MoreRecords)
                {
                    i = i + 1;
                    // Increment the page number to retrieve the next page.
                    pageNumber++;

                    // Set the paging cookie to the paging cookie returned from current results.                          
                    pagingCookie = returnCollection.PagingCookie;
                }
                else
                {
                    // If no more records in the result nodes, exit the loop.
                    break;
                }
            }
            i = i + 0;
            return recordsList;
        }


        public static string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }

        public static string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }

//// Code  to Call process


string fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                  "<entity name='new_name'>" +
                                  "</entity>" +
                                "</fetch>";
                EntityCollection fetchErrorLogsforSafari = GetAllRecords(fetchXML, service);



How to Run Microsoft Flow for Every one Month

Introduction: In this Blog we will see how to Run Microsoft Flow for Every one Month. Implementation Steps:   1. Navigate to  https://make.p...