Example #1
0
        public void InicializarPFE(Oracle ora)
        {
            Oracle = ora;
            Emr    = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = true,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };

            var url = XrmServiceUriFactory.CreateOrganizationServiceUri(Comun.ConnStringCrm.Split(';')[0].Split('=')[1]);
            var usr = Comun.ConnStringCrm.Split(';')[1].Split('=')[1];
            var pwd = Comun.ConnStringCrm.Split(';')[2].Split('=')[1];

            OSManager = new OrganizationServiceManager(url, usr, pwd);
            OSOptions = new OrganizationServiceProxyOptions
            {
                Timeout = new TimeSpan(0, Comun.TimeOutEnMinutos, 0)
            };
            PFERequests = new Dictionary <string, ExecuteMultipleRequest>();
            RequestKey  = 0;
        }
Example #2
0
        /// <summary>
        /// Initialize Organization client for D365 integration
        /// </summary>
        private void InitializeOrganizationServiceManager()
        {
            var serverUri = XrmServiceUriFactory.CreateOnlineOrganizationServiceUri(JobSettings.CrmOrganizationName, CrmOnlineRegion.EMEA);

            OrganizationServiceManager = new OrganizationServiceManager(serverUri, JobSettings.CrmUserName, JobSettings.CrmUserPassword);
            OrganizationServiceManager.ParallelProxy.MaxDegreeOfParallelism = JobSettings.ThreadNumber;
            Log($"Organization service initialized to {serverUri.ToString()} with user {JobSettings.CrmUserName}!");
        }
Example #3
0
        /// <summary>
        /// Executes multiple creates concurrently within one or more Batches, with each Batch limited to 1000 records.
        /// </summary>
        /// <param name="serviceManager"></param>
        /// <param name="entityTuple"></param>
        /// <param name="totalRequestBatches"></param>
        /// <param name="totalRequestsPerBatch"></param>
        /// <returns></returns>
        public static List <Guid> CreateParallelExecuteMultiple(OrganizationServiceManager serviceManager, Tuple <EntityMetadata, Entity> entityTuple, int totalRequestBatches, int totalRequestsPerBatch)
        {
            Console.WriteLine();
            log.Info("Create Mode: Parallel Execute Multiple");

            List <Guid> ids = new List <Guid>();
            IDictionary <string, ExecuteMultipleRequest> requests = new Dictionary <string, ExecuteMultipleRequest>();

            for (int i = 0; i < totalRequestBatches; i++)
            {
                ExecuteMultipleRequest executeMultipleRequest = new ExecuteMultipleRequest()
                {
                    Requests = new OrganizationRequestCollection(),
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    RequestId = Guid.NewGuid()
                };

                for (int j = 0; j < totalRequestsPerBatch; j++)
                {
                    Guid?preAssignedId;
                    preAssignedId = Guid.NewGuid();

                    ids.Add(preAssignedId.Value);
                    Entity entity = CreateEntity(entityTuple, preAssignedId);

                    CreateRequest mRequest = new CreateRequest()
                    {
                        Target    = entity,
                        RequestId = Guid.NewGuid()
                    };
                    mRequest.Parameters.Add("SuppressDuplicateDetection", true); // Disable duplicate detection
                    executeMultipleRequest.Requests.Add(mRequest);
                }
                requests.Add(new KeyValuePair <string, ExecuteMultipleRequest>(i.ToString(), executeMultipleRequest));
                log.InfoFormat("Request Id for request batch number {0}: {1}", i, executeMultipleRequest.RequestId);
            }
            log.InfoFormat("Creating {0} record(s)...", totalRequestBatches * totalRequestsPerBatch);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Parallel execution of all ExecuteMultipleRequest in the requests Dictionary
            IDictionary <string, ExecuteMultipleResponse> responseForCreateRecords = serviceManager.ParallelProxy.Execute <ExecuteMultipleRequest, ExecuteMultipleResponse>(requests);
            int threadsCount = Process.GetCurrentProcess().Threads.Count;

            sw.Stop();

            log.InfoFormat("Number of threads used: {0}", threadsCount);
            log.InfoFormat("Seconds to create {0} record(s): {1}s", totalRequestBatches * totalRequestsPerBatch, sw.Elapsed.TotalSeconds);

            return(ids);
        }
        /// <summary>
        /// Demonstrates a claims-based, cross-realm connection to Organization.svc using a username, password, and alternate realm
        /// </summary>
        /// <remarks>
        /// Authentication will be handled by federated realm's identity provider. Issued token will be converted to current realm token that CRM will accept.
        /// OrganizationServiceManager stores endpoint metadata and security token. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicCrossRealmConnectionToCrm()
        {
            var serverUri = XrmServiceUriFactory.CreateOrganizationServiceUri("https://mycrmserver:5555/myorganization");
            var manager   = new OrganizationServiceManager(serverUri, "username", "password", homeRealm: new Uri("https://myhomerealm.com"));

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
        /// <summary>
        /// Demonstrates an online-federated connection to Organization.svc using a userprincipalname and password
        /// </summary>
        /// <remarks>
        /// OrganizationServiceManager stores endpoint metadata and security token. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicConnectionToCrmOnline()
        {
            var serverUri = XrmServiceUriFactory.CreateOnlineOrganizationServiceUri("myorganization", CrmOnlineRegion.NA);
            var manager   = new OrganizationServiceManager(serverUri, "*****@*****.**", "password");

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
        /// <summary>
        /// Demonstrates a basic Active Directory connection to Organization.svc using a username, password, and domain
        /// </summary>
        /// <remarks>
        /// OrganizationServiceManager stores endpoint metadata. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicADConnectionToCrm()
        {
            var serverUri = XrmServiceUriFactory.CreateOrganizationServiceUri("http://mycrmserver:5555/myorganization");
            var manager   = new OrganizationServiceManager(serverUri, "username", "password", "mydomain");

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
        /// <summary>
        /// Demonstrates a claims-based connection to Organization.svc using a pre-authenticated instance of AuthenticationCredentials
        /// </summary>
        /// <remarks>
        /// OrganizationServiceManager stores endpoint metadata and security token. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicPreAuthConnectionToCrm(AuthenticationCredentials preAuthCredentials)
        {
            var serverUri = XrmServiceUriFactory.CreateOrganizationServiceUri("https://mycrmserver:5555/myorganization");
            var manager   = new OrganizationServiceManager(serverUri, preAuthCredentials);

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
Example #8
0
        public OrganizationServiceManager GetCdsConnection()
        {
            var environmentUrl = PromptFor("environment url");
            var uri            = XrmServiceUriFactory.CreateOrganizationServiceUri(environmentUrl);
            var username       = PromptFor("username");
            var password       = PromptForPassword();

            var serviceManager = new OrganizationServiceManager(uri, username, password);

            return(serviceManager);
        }
Example #9
0
        public static int?GetEntityTypeCode(OrganizationServiceManager osm, string entity)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest();

            request.LogicalName   = entity;
            request.EntityFilters = EntityFilters.Entity;

            RetrieveEntityResponse response = (RetrieveEntityResponse)osm.GetProxy().Execute(request);
            EntityMetadata         metadata = response.EntityMetadata;

            return(metadata.ObjectTypeCode);
        }
Example #10
0
        private static void Upload(OrganizationServiceManager osmSource, OrganizationServiceManager osmDestination)
        {
            var templates = GetTemplates(osmSource);

            Console.WriteLine($"\r\nFound {templates.Count} docx templates to upload");

            Parallel.ForEach(templates,
                             new ParallelOptions {
                MaxDegreeOfParallelism = 5
            },
                             (template =>
            {
                string name = template.GetAttributeValue <string>("name");
                Console.WriteLine($"Uploading {name}");

                try
                {
                    string etc = template.GetAttributeValue <string>("associatedentitytypecode");

                    int?oldEtc = GetEntityTypeCode(osmSource, etc);
                    int?newEtc = GetEntityTypeCode(osmDestination, etc);

                    string fileName = ReRouteEtcViaOpenXML(template, name, etc, oldEtc, newEtc);

                    template["associatedentitytypecode"] = newEtc;
                    template["content"] = Convert.ToBase64String(File.ReadAllBytes(fileName));

                    Guid existingId = TemplateExists(osmDestination, name);
                    if (existingId != null && existingId != Guid.Empty)
                    {
                        template["documenttemplateid"] = existingId;

                        osmDestination.GetProxy().Update(template);
                        Console.WriteLine($"Updated {name}");
                    }
                    else
                    {
                        Guid id = osmDestination.GetProxy().Create(template);
                        Console.WriteLine($"Created {name}");
                    }

                    File.Delete(fileName);     // delete the updated file but keep the original
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    Console.WriteLine($"Failed to upload {name}!");
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.Detail != null ? ex.Detail.TraceText : "");
                    Console.WriteLine(ex.InnerException != null ? ex.InnerException.Message : "");
                }
            }));
        }
Example #11
0
 private static OrganizationServiceManager GetOrganizationServiceProxy()
 {
     try
     {
         var orgName        = "notsmooth";                          // CRM Organization Name
         var userName       = "******"; // User Name
         var password       = "******";                         // Password
         var uri            = XrmServiceUriFactory.CreateOnlineOrganizationServiceUri(orgName);
         var serviceManager = new OrganizationServiceManager(uri, userName, password);
         return(serviceManager);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        static void Main()
        {
            // The connection to the Organization web service.
            CrmServiceClient serviceClient = null;
            OrganizationServiceManager serviceManager;
            
            int timeoutInMinutes = int.Parse(ConfigurationManager.AppSettings["TimeoutInMinutes"]);
            int defaultConnectionLimit = int.Parse(ConfigurationManager.AppSettings["DefaultConnectionLimit"]);

            // Allows .NET to run multiple threads https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit(v=vs.110).aspx
            System.Net.ServicePointManager.DefaultConnectionLimit = defaultConnectionLimit;

            try
            {
                // Establish an authenticated connection to Crm.
                string connectionString = ConfigurationManager.ConnectionStrings["CrmConnect"].ConnectionString;
                
                CrmServiceClient.MaxConnectionTimeout = new TimeSpan(0, timeoutInMinutes, 0);
                serviceClient = new CrmServiceClient(connectionString);          
                serviceManager = new OrganizationServiceManager(serviceClient);

                LogAppSettings(); // Display App Settings
                DetermineOperationType(serviceClient, serviceManager);
               
                Console.WriteLine();
                Console.WriteLine("Completed!");
            }
            catch (FaultException<OrganizationServiceFault> e) { HandleException(e); }
            catch (TimeoutException e) { HandleException(e); }
            catch (SecurityTokenValidationException e) { HandleException(e); }
            catch (ExpiredSecurityTokenException e) { HandleException(e); }
            catch (MessageSecurityException e) { HandleException(e); }
            catch (SecurityNegotiationException e) { HandleException(e); }
            catch (SecurityAccessDeniedException e) { HandleException(e); }
            catch (FormatException e) { HandleException(e); }
            catch (InvalidOperationException e) { HandleException(e); }
            catch (Exception e) { HandleException(e); }

            finally
            {
                // Always dispose the service object to close the service connection and free resources.
                if (serviceClient != null) serviceClient.Dispose();

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Example #13
0
        private static Task <EntityCollection> TestRetrieveMultiple(OrganizationServiceManager osm, int i)
        {
            QueryExpression qe = new QueryExpression("account")
            {
                ColumnSet = new ColumnSet("accountid", "name")
            };

            qe.PageInfo = new PagingInfo()
            {
                Count = i * 100, PageNumber = 1
            };

            // this is the important part - using the OrganizationServiceManager, we'll call GetProxy, this creates a clone of the original connection. this is what allows us to execute stuff in parallel...
            Task <EntityCollection> m = osm.GetProxy().RetrieveMultipleAsync(qe); // the *Async methods are defined inside the OptimizedConnectionExtensions.cs

            return(m);
        }
Example #14
0
        private static Guid TemplateExists(OrganizationServiceManager osm, string name)
        {
            Guid result = Guid.Empty;

            QueryExpression qe = new QueryExpression("documenttemplate");

            qe.Criteria.AddCondition("status", ConditionOperator.Equal, false); // only get active templates
            qe.Criteria.AddCondition("name", ConditionOperator.Equal, name);

            var results = osm.GetProxy().RetrieveMultiple(qe);

            if (results != null && results.Entities != null && results.Entities.Count > 0)
            {
                result = results[0].Id;
            }

            return(result);
        }
        private static void Pfe()
        {
            try
            {
                Console.WriteLine("Testing plain pfe");
                var manager = new OrganizationServiceManager(serviceUri);

                Parallel.ForEach(Enumerable.Range(0, 100000), (index) =>
                {
                    var proxy = manager.GetProxy();
                    proxy.EnableProxyTypes();
                    proxy.Execute(new WhoAmIRequest());
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #16
0
        private static List <Entity> GetTemplates(OrganizationServiceManager osm)
        {
            QueryExpression qe = new QueryExpression("documenttemplate")
            {
                ColumnSet = new ColumnSet("content", "name", "associatedentitytypecode", "documenttype", "clientdata")
            };

            qe.Criteria.AddCondition("status", ConditionOperator.Equal, false);   // only get active templates
            qe.Criteria.AddCondition("documenttype", ConditionOperator.Equal, 2); // only word docs
            qe.Criteria.AddCondition("createdbyname", ConditionOperator.NotEqual, "SYSTEM");

            var results = osm.GetProxy().RetrieveMultiple(qe);

            if (results != null && results.Entities != null && results.Entities.Count > 0)
            {
                return(results.Entities.ToList());
            }

            return(new List <Entity>());
        }
Example #17
0
        private static void FetchParallel()
        {
            count = 0;
            CdsAuthHelper cdsAuthHelper = new CdsAuthHelper();

            using (var proxy = new OrganizationWebProxyClient(cdsAuthHelper.serviceUrl, false))
            {
                // Set Header with the token
                proxy.HeaderToken = cdsAuthHelper.token;

                string fetch = "<fetch mapping='logical' no-lock='true'>";
                fetch += "<entity name='account'>";
                fetch += "<attribute name='name'/>";
                fetch += "<attribute name='accountid'/>";
                fetch += "</entity>";
                fetch += "</fetch>";

                IDictionary <string, QueryBase> queries = new Dictionary <string, QueryBase>();
                queries.Add("result", new FetchExpression(fetch));

                Microsoft.Xrm.Tooling.Connector.CrmServiceClient context = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(proxy);

                var manager = new OrganizationServiceManager(context);

                IDictionary <string, EntityCollection> results = null;

                try
                {
                    results = manager.ParallelProxy.RetrieveMultiple(queries, true);

                    foreach (var result in results)
                    {
                        count += result.Value.Entities.Count;
                    }
                }
                catch (AggregateException ae)
                {
                    // Handle exceptions
                }
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting, please wait...");

            var osmSource      = new OrganizationServiceManager(ConfigurationManager.AppSettings["source.org.url"]);
            var osmDestination = new OrganizationServiceManager(ConfigurationManager.AppSettings["destination.org.url"]);

            var response = osmSource.GetProxy().Execute(new WhoAmIRequest()) as WhoAmIResponse;

            Console.WriteLine($"Logged into source crm as: {response.UserId}");

            response = osmDestination.GetProxy().Execute(new WhoAmIRequest()) as WhoAmIResponse;
            Console.WriteLine($"Logged into destination crm as: {response.UserId}");

            Console.WriteLine("\r\nAre you sure you want to upload all templates to the destination? Y/N");
            string input = (Console.ReadLine() ?? "").ToLower();

            if (input == "y" || input == "yes")
            {
                Upload(osmSource, osmDestination);
            }
        }
        /// <summary>
        /// Determines the operation type to be performed: Create, Update or Delete.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <param name="serviceManager"></param>
        private static void DetermineOperationType(CrmServiceClient serviceClient, OrganizationServiceManager serviceManager)
        {
            Console.WriteLine("\nThe following operation types are available: ");

            Console.WriteLine("(0) Create");
            Console.WriteLine("(1) Retrieve");
            Console.WriteLine("(2) Update");
            Console.WriteLine("(3) Delete");

            Console.Write("Specify the desired operation type: ");

            string response = Console.ReadLine();
            int createOperationType = int.Parse(response);
          
            switch (createOperationType)
            {
                case 0: // Create
                    log.Info("Selected operation: Create");
                    bool isOob = DetermineEntityType(); 
                    Tuple<EntityMetadata, Entity> entityTuple = RetrieveHelperMethods.RetrieveEntityList(serviceClient, isOob);
                    DetermineCreateOperationType(serviceClient, serviceManager, entityTuple);
                    break;
                case 1: // Retrieve
                    log.Info("Selected operation: Retrieve");
                    DetermineRetrieveOperationType(serviceClient);
                    break;
                case 2: // Update
                    log.Info("Selected operation: Update");
                    DetermineUpdateOperationType(serviceClient, serviceManager);
                    break;
                case 3: // Delete
                    log.Info("Selected operation: Delete");
                    DetermineDeleteOperationType(serviceClient, serviceManager);
                    break;
                default:
                    throw new InvalidOperationException("The specified operation type is not valid: " + response);
            }
            return;
        }
Example #20
0
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting to crm...");

            // this example shows how to use existing user auth (no need to explicitly state user/pass). Take a look at the overloaded methods for explicit user/pass auth
            var osm = new OrganizationServiceManager(ConfigurationManager.AppSettings["crm.sdkurl.org"]);

            // test the connection first
            var response = osm.GetProxy().Execute(new WhoAmIRequest()) as WhoAmIResponse;

            Console.WriteLine(response.UserId);

            // lets look at doing 100 retrieves in parallel properly :)
            Console.WriteLine("starting to execute 100 retrives...");

            Stopwatch sw = new Stopwatch();

            sw.Start();

            Task.Run(() =>
            {
                List <Task> tasks = new List <Task>();

                // loop through and create a bunch of things we want to execute asynchornously
                for (int i = 0; i < 100; i++)
                {
                    Task <EntityCollection> m = TestRetrieveMultiple(osm, i);

                    tasks.Add(m); // add the task to our list
                }

                Task.WaitAll(tasks.ToArray());
            }).Wait();

            sw.Stop();
            Console.WriteLine($"done!, took {sw.ElapsedMilliseconds}ms ({sw.ElapsedMilliseconds / 100m:N2}ms per retrieve)");
        }
Example #21
0
        private void InitializeOrganizationServiceManager()
        {
            // If you're using an old version of .NET this will enable TLS 1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var serverUri = XrmServiceUriFactory.CreateOnlineOrganizationServiceUri(JobSettings.CrmOrganizationName, CrmOnlineRegion.EMEA);

            OrganizationServiceManager = new OrganizationServiceManager(serverUri, JobSettings.CrmUserName, JobSettings.CrmUserPassword);

            // Change max connections from .NET to a remote service default: 2
            // Webapp targeted is Basic (Large)
            // Socket available is 256 for 1 app
            // We have 3 interfaces : (256 / 3) => 85 sockets per interface
            //
            // Resource : https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#per-sandbox-per-appper-site-numerical-limits
            ServicePointManager.DefaultConnectionLimit = 85;

            // Bump up the min threads reserved for this app to ramp connections faster - minWorkerThreads defaults to 4, minIOCP defaults to 4
            ThreadPool.SetMinThreads(10, 10);

            // Turn off the Expect 100 to continue message - 'true' will cause the caller to wait until it round-trip confirms a connection to the server
            ServicePointManager.Expect100Continue = false;

            // More info on Nagle at WikiPedia - can help perf (helps w/ conn reliability)
            ServicePointManager.UseNagleAlgorithm = false;

            //a new twist to existing connections
            var knownServicePointConnection = ServicePointManager.FindServicePoint(OrganizationServiceManager.ServiceUri);

            if (knownServicePointConnection != null)
            {
                knownServicePointConnection.ConnectionLimit   = ServicePointManager.DefaultConnectionLimit;
                knownServicePointConnection.Expect100Continue = ServicePointManager.Expect100Continue;
                knownServicePointConnection.UseNagleAlgorithm = ServicePointManager.UseNagleAlgorithm;
            }
        }
        /// <summary>
        /// Determines which delete operation should be performed: Execute Multiple | FetchXML.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <param name="serviceManager"></param>
        private static void DetermineDeleteOperationType(CrmServiceClient serviceClient, OrganizationServiceManager serviceManager)
        {
            int totalRequestsPerBatch = int.Parse(ConfigurationManager.AppSettings["TotalRequestsPerBatch"]);

            Console.WriteLine("\nThe following delete operation types are available: ");
            Console.WriteLine("(0) Parallel Execute Multiple | FetchXML");

            Console.Write("Specify the desired delete operation type: ");
            string response = Console.ReadLine();
            int deleteOperationType = int.Parse(response);

            switch (deleteOperationType)
            {
                case 0: // Parallel Execute Multiple | FetchXML
                    DeleteHelperMethods.DeleteFetchXml(serviceClient, serviceManager, totalRequestsPerBatch);
                    break;
                default:
                    throw new InvalidOperationException("The specified create operation type is not valid: " + response);
            }
            return;
        }
        /// <summary>
        /// Determines which create operation should be performed: Single, Execute Multiple or Parallel Execute Multiple.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <param name="serviceManager"></param>
        /// <param name="entityTuple"></param>
        private static void DetermineCreateOperationType(CrmServiceClient serviceClient, OrganizationServiceManager serviceManager, Tuple<EntityMetadata, Entity> entityTuple)
        {
            int totalRequestBatches = int.Parse(ConfigurationManager.AppSettings["TotalRequestBatches"]);
            int totalRequestsPerBatch = int.Parse(ConfigurationManager.AppSettings["TotalRequestsPerBatch"]);

            Console.WriteLine("\nThe following create operation types are available: ");

            Console.WriteLine("(0) Single");
            Console.WriteLine("(1) Execute Multiple");
            Console.WriteLine("(2) Parallel Execute Multiple");

            Console.Write("Specify the desired create operation type: ");
            string response = Console.ReadLine();
            int createOperationType = int.Parse(response);

            switch (createOperationType)
            {
                case 0: // Execute Single
                    CreateHelperMethods.CreateExecuteSingle(serviceClient, entityTuple, totalRequestBatches, totalRequestsPerBatch);
                    break;
                case 1: // Execute Multiple
                    CreateHelperMethods.CreateExecuteMultiple(serviceClient, entityTuple, totalRequestBatches, totalRequestsPerBatch);
                    break;
                case 2: // Parallel Execute Multiple
                    CreateHelperMethods.CreateParallelExecuteMultiple(serviceManager, entityTuple, totalRequestBatches, totalRequestsPerBatch);
                    break;
                default:
                    throw new InvalidOperationException("The specified create operation type is not valid: " + response);
            }
            return;
        }
        /// <summary>
        /// Executes multiple deletes concurrently within one or more Batches, with each batch limited to 1000 records, based on the provided FetchXML.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <param name="serviceManager"></param>
        /// <param name="totalRequestsPerBatch"></param>
        /// <returns></returns>
        public static List <Guid> DeleteFetchXml(CrmServiceClient serviceClient, OrganizationServiceManager serviceManager, int totalRequestsPerBatch)
        {
            EntityCollection recordsToBeDeleted = RetrieveHelperMethods.RetrieveMultipleFetchXml(serviceClient);

            return(DeleteParallelExecuteMultiple(serviceManager, recordsToBeDeleted, totalRequestsPerBatch));
        }
        /// <summary>
        /// Executes multiple deletes concurrently within one or more Batches, with each batch limited to 1000 records.
        /// </summary>
        /// <param name="serviceManager"></param>
        /// <param name="recordsToBeDeleted"></param>
        /// <param name="totalRequestsPerBatch"></param>
        /// <returns></returns>
        public static List <Guid> DeleteParallelExecuteMultiple(OrganizationServiceManager serviceManager, EntityCollection recordsToBeDeleted, int totalRequestsPerBatch)
        {
            int batchSize = 0;
            int recordsToBeDeletedCount = recordsToBeDeleted.Entities.Count;
            int batchNumber             = (int)Math.Ceiling((recordsToBeDeleted.Entities.Count * 1.0d) / (totalRequestsPerBatch * 1.0d));

            Console.WriteLine();
            log.Info("Delete Mode: Parallel Execute Multiple");

            List <Guid> ids = new List <Guid>();
            IDictionary <string, ExecuteMultipleRequest> requests = new Dictionary <string, ExecuteMultipleRequest>();

            for (int i = 0; i < batchNumber; i++)
            {
                ExecuteMultipleRequest executeMultipleRequest = new ExecuteMultipleRequest()
                {
                    Requests = new OrganizationRequestCollection(),
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    RequestId = Guid.NewGuid()
                };

                for (int j = recordsToBeDeleted.Entities.Count - 1; j >= 0; j--)
                {
                    Entity entityToBeDeleted = recordsToBeDeleted.Entities[j];
                    ids.Add(entityToBeDeleted.Id);

                    DeleteRequest deleteRequest = new DeleteRequest()
                    {
                        Target    = new EntityReference(entityToBeDeleted.LogicalName, entityToBeDeleted.Id),
                        RequestId = Guid.NewGuid()
                    };
                    executeMultipleRequest.Requests.Add(deleteRequest);
                    recordsToBeDeleted.Entities.RemoveAt(j);

                    if (batchSize == totalRequestsPerBatch - 1) // If we reach the batch limit, break from the loop
                    {
                        break;
                    }
                    batchSize++;
                }

                batchSize = 0;
                requests.Add(new KeyValuePair <string, ExecuteMultipleRequest>(i.ToString(), executeMultipleRequest));
                log.InfoFormat("Request Id for request batch number {0}: {1}", i, executeMultipleRequest.RequestId);
            }
            log.InfoFormat("Deleting {0} record(s)...", recordsToBeDeletedCount);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Parallel execution of all ExecuteMultipleRequest in the requests Dictionary
            IDictionary <string, ExecuteMultipleResponse> responseForDeleteRecords = serviceManager.ParallelProxy.Execute <ExecuteMultipleRequest, ExecuteMultipleResponse>(requests);
            int threadsCount = Process.GetCurrentProcess().Threads.Count;

            sw.Stop();

            log.InfoFormat("Number of threads used: {0}", threadsCount);
            log.InfoFormat("Seconds to delete {0} record(s): {1}s", recordsToBeDeletedCount, sw.Elapsed.TotalSeconds);

            return(ids);
        }
 public RandomContactsGenerator(OrganizationServiceManager serviceManager)
 {
     ServiceManager = serviceManager;
     Random         = new Random();
 }
Example #27
0
 public ApplicationDbContext(OrganizationServiceManager serviceManager)
     : base(serviceManager)
 {
 }
 public AllContactsFullNameApplicator(IFullNameCalculator fullNameCalculator, OrganizationServiceManager serviceManager)
 {
     FullNameCalculator = fullNameCalculator;
     ServiceManager     = serviceManager;
 }