Showing posts with label Retrieve All in CRM. Show all posts
Showing posts with label Retrieve All in CRM. Show all posts

Friday, July 27, 2018

ExecuteMultiple in Dynamics CRM/Retrieve All Records in Dynamics FetchXML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Collections;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Globalization;
using System.IO;

namespace Timer_for_Accounts
{
    class Program
    {
        public static void Main(string[] args)
        { 
            string strLogText = "Execution Started at :" + DateTime.Now;
            Console.WriteLine("Execution Started..");
            ClientCredentials Credentials = new ClientCredentials();
//Retrieve UserName and Password from App.config
            Credentials.UserName.UserName = ConfigurationManager.AppSettings["UserName"];
            Credentials.UserName.Password = ConfigurationManager.AppSettings["Password"];
            string uri = ConfigurationManager.AppSettings["uri"];
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(uri), null, Credentials, null);
            Console.WriteLine("Connected to Server Successfully.");
            //WE NEED TO USE {0} IN FETCHXML WHEN YOU WANT TO RETRIEVE ALL RECORDS
            var fetch = "<fetch {0} version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                "  <entity name='new_account'>" +
                                "    <attribute name='new_name' />" +
                                "    <attribute name='ownerid' />" +
                                "    <attribute name='createdon' />" +
                                "    <attribute name='createdby' />" +
                                "    <attribute name = 'modifiedon' />" +
                                "    <order attribute='createdon' descending='true' />" +
                                "      <filter type='and'>" +
                                "        <condition attribute='statecode' operator='eq' value='0' />" +
                                "      </filter>" +
                                "  </entity>" +
                                "</fetch>";
            EntityCollection recordstobeupdated = new EntityCollection();
            var accountRecords = RetrieveAllRecords(serviceProxy, fetch);
            for (int accountCount = 0; accountCount < accountRecords.Count; accountCount++)
            {
                recordstobeupdated.Entities.Add(accountRecords[accountCount]);
            }
            #region ExecuteMultiple to update records
            EntityCollection updateRecords = recordstobeupdated;
            ExecuteMultipleRequest requestForUpdates = new ExecuteMultipleRequest()
            {
                Requests = new OrganizationRequestCollection()
            };
            try
            {
                int remainingcount = updateRecords.Entities.Count % 100; ;
                int count = 0;
                int updatedcount = 0;
                requestForUpdates.Settings = new ExecuteMultipleSettings();
                requestForUpdates.Settings.ContinueOnError = true;
                requestForUpdates.Settings.ReturnResponses = true;
                Console.WriteLine("Started at :" + DateTime.Now.ToString());
                foreach (var entity in updateRecords.Entities)
                {
                    TimeSpan difference = DateTime.Now - (DateTime)entity.Attributes["createdon"];

                    int DifferenceDays = difference.Days + 1;
                    entity.Attributes["new_accountCountopendays"] = DifferenceDays;
                    UpdateRequest updateRequest = new UpdateRequest { Target = entity };
                    requestForUpdates.Requests.Add(updateRequest);
                    count = count + 1;
                    if (requestForUpdates.Requests.Count == 100)
                    {
                        //WE ARE EXECUTING 100 RECORDS AT A TIME YOU CAN INCREASE THE COUNT BASED ON YOUR REQUIREMENT
                        serviceProxy.Execute(requestForUpdates);
                        updatedcount = updatedcount + 100;
                        Console.WriteLine("Updated :" + updatedcount);
                        Console.WriteLine("Completed at :" + DateTime.Now.ToString());
                        requestForUpdates.Requests = new OrganizationRequestCollection();
                        count = 0;
                    }
                }
                if (count == remainingcount)
                {
                    serviceProxy.Execute(requestForUpdates);
                    int totalcounnt = updatedcount + count;
                    Console.WriteLine("Updated Remaining:" + totalcounnt);
                    requestForUpdates.Requests = new OrganizationRequestCollection();
                }
            }
            catch (System.ServiceModel.FaultException<OrganizationServiceFault> ex)
            {
                Console.WriteLine("Update request failed for the account{0} and the reason being: {1}",
                    ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message);
            }
            #endregion ExecuteMultiple for update records
        }

        public static List<Entity> RetrieveAllRecords(IOrganizationService service, string fetch)
        {
            var moreRecords = false;
            int page = 1;
            var cookie = string.Empty;
            List<Entity> Entities = new List<Entity>();
            do
            {
                var xml = string.Format(fetch, cookie);
                var collection = service.RetrieveMultiple(new FetchExpression(xml));
                if (collection.Entities.Count >= 0) Entities.AddRange(collection.Entities);
                moreRecords = collection.MoreRecords;
                if (moreRecords)
                {
                    page++;
                    cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(collection.PagingCookie), page);
                }
            } while (moreRecords);
            return Entities;
        }
    }
}