Beispiel #1
0
        private void ExecuteMultipleRequests(List <OrganizationRequest> requests)
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Creating entity records",
                Work    = (worker, args) =>
                {
                    var responses = new ExecuteMultipleResponseItemCollection();
                    var lists     = SplitList(requests);
                    var count     = 0;
                    foreach (var list in lists)
                    {
                        var collection = new OrganizationRequestCollection();
                        collection.AddRange(list);
                        var req = new ExecuteMultipleRequest
                        {
                            Requests = collection,
                            Settings = new ExecuteMultipleSettings {
                                ContinueOnError = true, ReturnResponses = false
                            }
                        };
                        count++;
                        var response = (ExecuteMultipleResponse)Service.Execute(req);
                        SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(count / requests.Count, $"{count}/{requests.Count} records created"));
                        responses.AddRange(response.Responses);
                    }

                    args.Result = responses;
                },
                PostWorkCallBack = (args) =>
                {
                    if (args.Error != null)
                    {
                        MessageBox.Show($"Something bad happened. Error message:\n{args.Error}", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    var result = (ExecuteMultipleResponseItemCollection)args.Result;
                    if (result.Count == 0)
                    {
                        MessageBox.Show($"{requests.Count} records successfully created");
                    }
                    else
                    {
                        var createdCount = requests.Count - result.Count;
                        MessageBox.Show($"{createdCount}/{requests.Count} records created. See error log for details.");

                        foreach (var response in result)
                        {
                            LogError(response.Fault.Message);
                        }
                    }
                },
                IsCancelable = true,
            });
        }
Beispiel #2
0
        private Mock <IExecuteMultipleResponseAdapter> GetExecuteMultipleResponseAdapter(IEnumerable <Guid> recordIds)
        {
            var executeMultipleResponseAdapter = new Mock <IExecuteMultipleResponseAdapter>();
            var responseCollection             = new ExecuteMultipleResponseItemCollection();

            responseCollection.AddRange(recordIds.Select(r => new ExecuteMultipleResponseItem()
            {
                Fault    = null,
                Response = new DeleteResponse()
                {
                    ResponseName = "delete",
                    Results      = new ParameterCollection {
                        { "id", r }
                    }
                }
            }));
            executeMultipleResponseAdapter
            .Setup(e => e.Responses)
            .Returns(responseCollection);
            return(executeMultipleResponseAdapter);
        }
        private DetectionResults GetUsageFetchAggregate(EntityMetadata emd, Settings settings, BackgroundWorker worker = null)
        {
            var result = new DetectionResults();

            List <AttributeMetadata> attributes = new List <AttributeMetadata>();

            var emRequest = new ExecuteMultipleRequest
            {
                Settings = new ExecuteMultipleSettings
                {
                    ContinueOnError = true,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };

            var fetchXmlAttrPart = $"<attribute name=\"{emd.PrimaryIdAttribute}\" aggregate=\"count\" alias=\"count\"/>";

            emRequest.Requests.Add(new RetrieveMultipleRequest
            {
                Query = new FetchExpression(string.Format(FetchXml, emd.LogicalName, fetchXmlAttrPart, "", settings.RecordsReturnedPerTrip))
            });

            var allResult = new ExecuteMultipleResponseItemCollection();

            foreach (var attribute in MetadataHelper.FilterAttributes(emd.Attributes).OrderBy(a => a.LogicalName))
            {
                if (settings.FilterAttributes &&
                    settings.Filters.ContainsKey(emd.LogicalName))
                {
                    EntityFilterSetting fs = settings.Filters[emd.LogicalName];
                    if (fs.Attributes.Count > 0 &&
                        !fs.Attributes.Contains(attribute.LogicalName))
                    {
                        continue;
                    }
                    if (fs.ShowOnlyCustom && !attribute.IsCustomAttribute.Value)
                    {
                        continue;
                    }
                    if (fs.ShowOnlyStandard && attribute.IsCustomAttribute.Value)
                    {
                        continue;
                    }
                }

                attributes.Add(attribute);

                var fetchXmlConditionNotNullPart = $"<condition attribute=\"{attribute.LogicalName}\" operator=\"not-null\"/>";
                emRequest.Requests.Add(new RetrieveMultipleRequest
                {
                    Query =
                        new FetchExpression(string.Format(FetchXml, emd.LogicalName, fetchXmlAttrPart,
                                                          fetchXmlConditionNotNullPart, settings.RecordsReturnedPerTrip))
                });

                if (emRequest.Requests.Count == settings.AttributesReturnedPerTrip)
                {
                    var tempResults = (ExecuteMultipleResponse)service.Execute(emRequest);
                    allResult.AddRange(tempResults.Responses);

                    emRequest = new ExecuteMultipleRequest
                    {
                        Settings = new ExecuteMultipleSettings
                        {
                            ContinueOnError = true,
                            ReturnResponses = true
                        },
                        Requests = new OrganizationRequestCollection()
                    };
                }
            }

            var results = (ExecuteMultipleResponse)service.Execute(emRequest);

            allResult.AddRange(results.Responses);

            var allResponse = (RetrieveMultipleResponse)allResult[0].Response;

            if (allResult[0].Fault != null)
            {
                result.IsAggregateQueryRecordLimitReached = allResult[0].Fault.ErrorCode == -2147164125;
                result.Fault = allResult[0].Fault;
                return(result);
            }

            var allCount = allResponse != null
                ? allResponse.EntityCollection.Entities.First().GetAttributeValue <AliasedValue>("count")
                : null;

            var allCountValue = allCount != null ? (int)allCount.Value : 0;

            result.Total  = allCountValue;
            result.Entity = emd.LogicalName;

            foreach (var attribute in attributes)
            {
                var index         = attributes.IndexOf(attribute);
                var resultNotNull = allResult[index + 1];

                if (resultNotNull.Fault != null)
                {
                    result.Fault = resultNotNull.Fault;
                    return(result);
                }

                var notNullValueAliased =
                    ((RetrieveMultipleResponse)resultNotNull.Response).EntityCollection.Entities.First()
                    .GetAttributeValue <AliasedValue>("count");

                var notNullValue = (int?)notNullValueAliased?.Value ?? 0;

                result.Results.Add(new DetectionResult
                {
                    Attribute  = attribute,
                    NotNull    = notNullValue,
                    Percentage = allCountValue != 0 ? (double)notNullValue * 100 / allCountValue : 0
                });
            }

            return(result);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var executeMultipleRequest = (ExecuteMultipleRequest)request;

            if (executeMultipleRequest.Settings == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "You need to pass a value for 'Settings' in execute multiple request");
            }

            if (executeMultipleRequest.Requests == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "You need to pass a value for 'Requests' in execute multiple request");
            }

            var service = ctx.GetFakedOrganizationService();

            var response = new ExecuteMultipleResponse();

            response.Results["Responses"] = new ExecuteMultipleResponseItemCollection();

            for (var i = 0; i < executeMultipleRequest.Requests.Count; i++)
            {
                var executeRequest = executeMultipleRequest.Requests[i];

                try
                {
                    service.Execute(executeRequest);

                    if (executeMultipleRequest.Settings.ReturnResponses)
                    {
                        response.Responses.Add(new ExecuteMultipleResponseItem
                        {
                            RequestIndex = i
                        });
                    }
                }
                catch (Exception ex)
                {
                    if (!response.IsFaulted)
                    {
                        response.Results["IsFaulted"] = true;
                    }

                    response.Responses.Add(new ExecuteMultipleResponseItem
                    {
                        Fault = new OrganizationServiceFault {
                            Message = ex.Message
                        },
                        RequestIndex = i
                    });

                    if (!executeMultipleRequest.Settings.ContinueOnError)
                    {
                        break;
                    }
                }
            }

            // Implement response behaviour as in https://msdn.microsoft.com/en-us/library/jj863631.aspx
            if (executeMultipleRequest.Settings.ReturnResponses)
            {
                response.Results["response.Responses"] = response.Responses;
            }
            else if (response.Responses.Any(resp => resp.Fault != null))
            {
                var failures = new ExecuteMultipleResponseItemCollection();

                failures.AddRange(response.Responses.Where(resp => resp.Fault != null));

                response.Results["response.Responses"] = failures;
            }

            return(response);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var executeMultipleRequest = (ExecuteMultipleRequest)request;

            if (executeMultipleRequest.Settings == null)
            {
                throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), "You need to pass a value for 'Settings' in execute multiple request");
            }

            if (executeMultipleRequest.Requests == null)
            {
                throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), "You need to pass a value for 'Requests' in execute multiple request");
            }

            var service = ctx.GetFakedOrganizationService();

            var response = new ExecuteMultipleResponse();
            response.Results["Responses"] = new ExecuteMultipleResponseItemCollection();

            for (var i = 0; i < executeMultipleRequest.Requests.Count; i++)
            {
                var executeRequest = executeMultipleRequest.Requests[i];

                try
                {
                    service.Execute(executeRequest);

                    if (executeMultipleRequest.Settings.ReturnResponses)
                    {
                        response.Responses.Add(new ExecuteMultipleResponseItem
                        {
                            RequestIndex = i
                        });
                    }
                }
                catch (Exception ex)
                {
                    if (!response.IsFaulted)
                    {
                        response.Results["IsFaulted"] = true;
                    }

                    response.Responses.Add(new ExecuteMultipleResponseItem
                    {
                        Fault = new OrganizationServiceFault { Message = ex.Message },
                        RequestIndex = i
                    });

                    if (!executeMultipleRequest.Settings.ContinueOnError)
                    {
                        break;
                    }
                }
            }

            // Implement response behaviour as in https://msdn.microsoft.com/en-us/library/jj863631.aspx
            if (executeMultipleRequest.Settings.ReturnResponses)
            {
                response.Results["response.Responses"] = response.Responses;
            }
            else if (response.Responses.Any(resp => resp.Fault != null))
            {
                var failures = new ExecuteMultipleResponseItemCollection();

                failures.AddRange(response.Responses.Where(resp => resp.Fault != null));

                response.Results["response.Responses"] = failures;
            }

            return response;
        }