Monday, November 21, 2016

webclient timeout exception c#

HI All,

Please find the below code to Overcome Timeout Issue from WebClient

         /// <summary>
        /// MyWebClient to increase Timeout
        /// </summary>
        public class MyWebClient : WebClient
        {
            //time in milliseconds
            private int timeout;
            public int Timeout
            {
                get
                {
                    return timeout;
                }
                set
                {
                    timeout = value;
                }
            }

            public MyWebClient()
            {
                this.timeout = 300000;
            }

            public MyWebClient(int timeout)
            {
                this.timeout = timeout;
            }

            protected override WebRequest GetWebRequest(Uri address)
            {
                var result = base.GetWebRequest(address);
                result.Timeout = this.timeout;
                return result;
            }
        }

Call the Above Code using below

using (var client = new MyWebClient())
 {
client.Headers.Add(username and Password); // Replace "username and Password" with your username and Password
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var result = client.UploadString(URL, "POST", JSONData); // Replace "URL" with your Service URL and "JSONData" with your JSON Output Data
}


Tuesday, October 25, 2016

Add Multiple Party list Users MSCRM Email in PreCreate by splitting String

Hi all,

Pleaes find the Below code for Creating Lead and Adding that user into activity party List

createLead("test;test",service,from);


        public static void createLead(string splitString, IOrganizationService service, string fieldName, Entity target)
        {
            string[] arrayfromtextEmail = splitString.Split(';');
            EntityCollection collectionEmailAddress = new EntityCollection();
            foreach (string loopWord in arrayfromtextEmail)
            {
                Guid getLeadID = checkEmailIDExisits(service, loopWord);
                if (getLeadID == Guid.Empty)
                {
                    Lead createLead = new Lead();
                    createLead.FirstName = loopWord.Substring(0, loopWord.IndexOf("@"));
                    createLead.EMailAddress1 = loopWord;
                    getLeadID = service.Create(createLead);
                }
                Entity Emailparty = new Entity(ActivityParty.EntityLogicalName);
                Emailparty["addressused"] = loopWord;
                Emailparty["partyid"] = new EntityReference(Lead.EntityLogicalName, getLeadID);
                collectionEmailAddress.Entities.Add(Emailparty);
            }
            target[fieldName] = collectionEmailAddress;
        }

Check Valid Email from String c#

Hi All,

Please find the Code for Checking Valid Email from String

bool getValidationChecked = checkValidEmail(test@test.com);

public static bool checkValidEmail(string emailID)
        {
            bool validEmailAddress = false;
            string[] arrayAdditionalTo = emailID.Split(';');
            foreach (string word in arrayAdditionalTo)
            {
                string pattern = null;
                pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

                if (Regex.IsMatch(word, pattern))
                {
                    validEmailAddress = true;
                }
                else
                {
                    return false;
                }
            }
            if (validEmailAddress)
            {
                return true;
            }
            return false;
}

Monday, October 24, 2016

Load Javascript in the Ribbon Function MSCRM

Hi All,

Please find the below code to load the Javascript

Call the Below Function as

LoadWebResource("email.js");


function LoadWebResource(resource) {
    var httpRequest = null;
    try {
        if (window.XMLHttpRequest) {  // code for IE7+, Firefox, Chrome, Opera, Safari
            httpRequest = new XMLHttpRequest();
        }
        else {  // code for IE6, IE5
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var serverUrl = Xrm.Page.context.getClientUrl();
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        httpRequest.open("GET", serverUrl + "/webresources/" + resource, false);
        httpRequest.send(null);
        eval(httpRequest.responseText);
    }
    catch (e) {
        alert("LoadWebResource >> Error loading " + resource + ":\n" + e.description);
    }
}

Friday, October 21, 2016

Trigger a plugin when Case is Closed

Hi All,

Please find the below steps to trigger plugin for Case Close.





Pass Parameter as IncidentResolution


IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("IncidentResolution"))
{
     Entity incidentResolution = (Entity)context.InputParameters["IncidentResolution"];
     Guid relatedIncidentGuid = ((EntityReference)incidentResolution.Attributes["incidentid"]).Id;
}

IncidentResolution is a special entity that holds the information about the incident record that is being closed.

Thursday, October 20, 2016

Convert String to Json Object and Get Particular Values from C# MSCRM

Hi All,

Please find the code below to read string from Configuration Entity and Convert it into Json Object

Eg for Json Data

string json = @"{""12112083"":{""Topic_ID"":""12112083"",""Moved_ID"":""51"",""subject"":""Due to a computer virus, many of my files are \u005CCrypted\u005C,espe"",""Start_date"":""10/6/2012 6:54:37 PM"",""InitialResponseDueDate"":""10/6/2012 7:01:37 PM"",""Locked"":""0"",""QValue"":""$10"",""Status"":""1"",""Author_ID"":""71318191"" }";

QueryExpression getConfigData = new QueryExpression("new_configuration");
getConfigData.ColumnSet = new ColumnSet("new_value");
getConfigData.Criteria.AddCondition(new ConditionExpression("new_key", ConditionOperator.Equal, "getStringValue"));

EntityCollection resultConfigdata = service.RetrieveMultiple(getConfigData);

JToken token = JObject.Parse(resultConfigdata[0].Attributes["new_value"].ToString());
string topicid = (string)token.SelectToken("Topic_ID"); 
string movedid = (string)token.SelectToken("Moved_ID");

string startdate = (string)token.SelectToken("Start_date");

Wednesday, October 19, 2016

eventsourcecreatedeventargs Error in Unit test

Hi all,

If you find below error, Open Fakes Folder edit mscorlib.fakes and add the following code


<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="mscorlib" Version="4.0.0.0"/>
  <StubGeneration>
    <Remove FullName="System.Diagnostics.Tracing"/>
  </StubGeneration>
</Fakes>


Note :

Replace the Error (System.Diagnostics.Tracing) with the error you are getting

Friday, October 14, 2016

Load JQGrid Using API Calls HTML


<html>
<head>

    <script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="/WebResources/Jquery.min.js" type="text/javascript"></script>
    <script src="/WebResources/bootstrap.min.js" type="text/javascript"></script>
    <script src="/WebResources/grid.locale_en.js" type="text/javascript"></script>
    <script src="/WebResources/jquery.jqgrid.min.js" type="text/javascript"></script>

    <link href="/WebResources/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="/WebResources/ui.jqgrid.css" rel="stylesheet" type="text/css">
    <link href="/WebResources/jquery_ui.css" rel="stylesheet" type="text/css">

    <style>
        .ui-jqgrid tr.jqgrow td {
            white-space: normal !important;
            height: auto;
            vertical-align: text-top;
            padding-top: 2px;
        }
    </style>


    <script type="text/javascript">

//You can user above code for get Parameter from Query String

        var getQueryString = function (field) {
            var href = decodeURIComponent(window.location.href);
            var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
            var string = reg.exec(href);
            return string ? string[1] : null;
        };

        var SerialNumber = getQueryString('serialnumber');
        var ProductNumber = getQueryString('productnumber');


        $(function () {
            var snrUrl = "URL"; //Pass Your URL Here
            //debugger;
            $.ajax({
                type: "GET",
                url: snrUrl,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successCallBack,
                error: errorCallBack

            });
        });
        function successCallBack(result) {
//Hidden the Image Once the Service Gets Success Result
            document.getElementById("Loading").style.visibility = 'hidden';

            $("#JQGridLoad").jqGrid({ //set your grid id
                data: result, //insert data from the data object we created above
                datatype: 'local',
//Pass Coloumn Name Below
                colNames: ['Number',
                    'Description’
], //define column names
                colModel: [
                { name: ' Number', index: 'Number', key: true, width: 200 },
                { name: 'Description', index: 'Description', key: true, width: 500 }
                ], //define column models
                celledit: false,
                loadtext: "Loading...",
                sortname: 'Number', //the column according to which data is to be sorted; optional
                viewrecords: true,
                sortorder: "asc",
                caption: "Data" // Set the Caption
            });
        }
        function errorCallBack(result) {
            alert(result.data);
        }
    </script>
    <meta>
    <meta>
</head>
<body style="overflow-wrap: break-word;">
    <table id=" JQGridLoad"></table>

//Pass the Image Which you Required so that it will Load and Hide till the Data Gets Load From Service
    <img style="padding-left:48%" id="Loading" src="/webresources/ _/scripts/progressindicator"><table id="loader"></table>


</body>

</html>


Dynamically Create HTML Table with JQGrid FetchXML MSCRM

Hi All,

Dynamically Create HTML Table with JQGrid FetchXML MSCRM

<html>
<head>

    <title>Log Details</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        table {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

            table th {
                background-color: #F7F7F7;
                color: #333;
                font-weight: bold;
            }

            table th, table td {
                padding: 5px;
                border-color: #ccc;
            }
    </style>
    <script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="../WebResources/Jquery.min.js" type="text/javascript"></script>
    <script src="../WebResources/bootstrap.min.js" type="text/javascript"></script>
    <script src="../WebResources/grid.locale_en.js" type="text/javascript"></script>
    <script src="../WebResources/jquery.jqgrid.min.js" type="text/javascript"></script>
    <script src="../WebResources/scripts/XrmServiceToolkit" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        function getAccountServices() {
            var getQueryString = function (field) {
                var href = decodeURIComponent(window.location.href);
                var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
                var string = reg.exec(href);
                return string ? string[1] : null;
            };

            var ContactID = getQueryString('contact');
            var CaseID = getQueryString('case');

            var SecurityLogFetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name= 'new_names'>" +
    "<attribute name='new_namesid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_dates' />" +
    "<attribute name='new_loopstring' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<filter type='and'>" +
        "<condition attribute='new_case' operator='eq' value='" + CaseID + "' />" +
        "<condition attribute='new_contact' operator='eq' value='" + ContactID + "' />" +
      "</filter>" +
    "</filter>" +
  "</entity>" +
"</fetch>";
            var contactsLog = new Array();
            contactsLog.push(["Name", "Date", "LoopString"]);
            var contactRecords = XrmServiceToolkit.Soap.Fetch(SecurityLogFetchXML);
            if (contactRecords.length > 0) {
                for (var contact = 0 ; contact < contactRecords.length; contact++) {
                    contactsLog.push([
                        contactRecords[contact].attributes.new_name? contactRecords[contact].attributes.new_name.value : "",
                        contactRecords[contact].attributes.new_dates ? contactRecords[contact].attributes.new_dates.value : "",
                        contactRecords[contact].attributes.new_loopstring ? contactRecords[contact].attributes.new_loopstring.value : "",
                    ]);
                }
                //Build an array containing Customer records.

                //Create a HTML Table element.
                var table = document.createElement("TABLE");
                table.border = "1";
                //Get the count of columns.
                var columnCount = contactsLog[0].length;
                //Add the header row.
                var row = table.insertRow(-1);
                for (var i = 0; i < columnCount; i++) {
                    var headerCell = document.createElement("TH");
                    headerCell.innerHTML = contactsLog[0][i];
                    row.appendChild(headerCell);
                }
                //Add the data rows.

                for (var i = 1; i < contactsLog.length; i++) {
                    row = table.insertRow(-1);
                    for (var j = 0; j < columnCount; j++) {
                        var cell = row.insertCell(-1);
                        cell.innerHTML = contactsLog[i][j];
                    }
                }
                var dvTable = document.getElementById("dvTable");
                dvTable.innerHTML = "";
                dvTable.appendChild(table);
            }
        }

    </script>
</head>
<body onload="getAccountServices();" style="overflow-wrap: break-word;">
    <div id="dvTable">

    </div>

</body>

Day 11 - Customizing Option Sets Dropdown Fields with JavaScript

  In this Blog, we will see how to Customizing Option Sets Dropdown Fields with JavaScript label1 = formContext.getAttribute( "bosch_op...