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



Monday, April 3, 2017

Call Fetch XML using Web API

Hi All,

Please find the code below to call Web Api with FetchXML.

var fetch = encodeURI("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'></fetch>"); // Pass Fetch XML
     var entityname = "new_test";  // Pass Entity Name
     var serverURL = Xrm.Page.context.getClientUrl();
     var Query = entityname + "?fetchXml=" + fetch;
    var req = new XMLHttpRequest();
    req.open("GET", serverURL + "/api/data/v8.0/" + Query, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function ()
     {
         if (this.readyState == 4 ) // Completed
        {
            req.onreadystatechange = null;
            if (this.status == 200)
            {
                var data = JSON.parse(this.response);
                if (data != null)
                 {
                    // Call Success Call back Function
                }

            }
             else
             {
// Call Error Call Back Function
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };
    req.send();

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.

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...