Example #1
0
        public IEnumerable <Guid> CommitEnumerable()
        {
            var response           = new List <Guid>();
            var transactionRequest = new ExecuteTransactionRequest
            {
                Requests = new OrganizationRequestCollection()
            };

            foreach (var entity in Added.Keys)
            {
                Added[entity].PersistAdded(entity);
            }
            foreach (var entity in Modified.Keys)
            {
                Modified[entity].PersistUpdated(entity);
            }
            foreach (var entity in Removed.Keys)
            {
                Removed[entity].PersistRemoved(entity);
            }

            Added.Clear();
            Modified.Clear();
            Removed.Clear();

            try
            {
                for (int i = 0; i < Requests.Count; i += _batchSize)
                {
                    var requestBatch = Requests.Skip(i).Take(_batchSize);

                    transactionRequest.Requests.AddRange(requestBatch);
                    var multipleResponse = (ExecuteTransactionResponse)_service.Execute(transactionRequest);
                    response.AddRange(CrmHelper.GetGuidsAsEnumerable(multipleResponse));

                    transactionRequest = new ExecuteTransactionRequest
                    {
                        Requests = new OrganizationRequestCollection()
                    };
                }
            }
            catch (FaultException <OrganizationServiceFault> fault)
            {
                if (fault.Detail.ErrorDetails.Contains("MaxBatchSize"))
                {
                    int maxBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]);
                    if (maxBatchSize < transactionRequest.Requests.Count)
                    {
                        var errMsg =
                            string.Format(
                                "The input request collection contains {0} requests, which exceeds the maximum allowed {1}",
                                transactionRequest.Requests.Count, maxBatchSize);
                        throw new InvalidOperationException(errMsg, fault);
                    }
                }

                throw;
            }

            return(response);
        }