Пример #1
0
        public QueryExpression Convert(IOrganizationService service)
        {
            try
            {
                string fetchXml = "";
                fetchXml += "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                fetchXml += "<entity name='pd_ordershelllineitem'>";
                fetchXml += "<attribute name='pd_ordershelllineitemid' />";
                fetchXml += "<attribute name='pd_name' />";
                fetchXml += "<attribute name='createdon' />";
                fetchXml += "<order attribute='pd_name' descending='false' />";
                fetchXml += "<filter type='and'>";
                fetchXml += "<condition attribute='pd_ordershellheaderid' operator='eq' uiname='test 1 Header' uitype='pd_ordershellheader' value='{9AAC56F7-02F9-E611-8102-FC15B428FAC0}' />";
                fetchXml += "<condition attribute='pd_nonvisiblelineitem' operator='eq' value='0' />";
                fetchXml += "</filter>";
                fetchXml += "<link-entity name='pep_locationproduct' from='pep_locationproductid' to='pd_locationproductid' visible='false' link-type='outer' alias='a_339f5c2437eae611810ac4346bad41fc'>";
                fetchXml += "<attribute name='pd_pdunavailable' />";
                fetchXml += "<attribute name='pep_locationitem' />";
                fetchXml += "</link-entity></entity></fetch>";

                FetchXmlToQueryExpressionRequest convertRequest = new FetchXmlToQueryExpressionRequest();
                convertRequest.FetchXml = fetchXml;

                FetchXmlToQueryExpressionResponse convertResponse = (FetchXmlToQueryExpressionResponse)service.Execute(convertRequest);

                return(convertResponse.Query);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ShowDataWindow(FetchXmlToQueryExpressionResponse response)
        {
            InitializeComponent();

            DataTable responseDataTable = new DataTable("Response Table");

            var columns = response.Query.ColumnSet.Columns.ToArray();

            foreach (var column in columns)
            {
                responseDataTable.Columns.Add(column);
            }

            var results = response.Results;

            foreach (var record in results)
            {
                var newRow = responseDataTable.NewRow();



                responseDataTable.Rows.Add(newRow);
            }

            ResponseDataGrid.DataContext = responseDataTable;
        }
        public void ExecuteRecordsCount()
        {
            string exportConfigFilePath = "TestData/ExportConfig.json";
            string schemaFilePath       = "TestData/ContactSchemaWithOwner.xml";
            var    mockService          = new Mock <IOrganizationService>();

            var response = new FetchXmlToQueryExpressionResponse();

            response.Results["Query"] = new QueryExpression();

            mockService.Setup(a => a.Execute(It.IsAny <FetchXmlToQueryExpressionRequest>()))
            .Returns(response);

            using (var worker = new BackgroundWorker())
            {
                worker.WorkerReportsProgress = true;

                using (DataGridView gridView = new DataGridView())
                {
                    FluentActions.Invoking(() => RecordCounterProcessor.ExecuteRecordsCount(exportConfigFilePath, schemaFilePath, mockService.Object, worker, gridView))
                    .Should()
                    .Throw <NullReferenceException>();
                }
            }

            mockService.Verify(a => a.Execute(It.IsAny <FetchXmlToQueryExpressionRequest>()), Times.Once);
        }
Пример #4
0
        private FetchXmlToQueryExpressionResponse HandleFetchXmlToQueryExpression(OrganizationRequest orgRequest, EntityReference userRef)
        {
            var request = MakeRequest <FetchXmlToQueryExpressionRequest>(orgRequest);
            var resp    = new FetchXmlToQueryExpressionResponse();

            resp.Results["Query"] = XmlHandling.FetchXmlToQueryExpression(request.FetchXml);
            return(resp);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req     = request as FetchXmlToQueryExpressionRequest;
            var service = ctx.GetOrganizationService();
            FetchXmlToQueryExpressionResponse response = new FetchXmlToQueryExpressionResponse();

            response["Query"] = XrmFakedContext.TranslateFetchXmlDocumentToQueryExpression(ctx, XrmFakedContext.ParseFetchXml(req.FetchXml));;
            return(response);
        }
Пример #6
0
        public QueryExpression ConvertFetchToQuery(string fetchXml)
        {
            FetchXmlToQueryExpressionRequest conversionRequest = new FetchXmlToQueryExpressionRequest
            {
                FetchXml = fetchXml
            };
            FetchXmlToQueryExpressionResponse conversionResponse = (FetchXmlToQueryExpressionResponse)ServiceProxy.Execute(conversionRequest);

            return(conversionResponse.Query);
        }
Пример #7
0
    public static QueryExpression ConvertFetchXmlToQuery(string fetchXml, IOrganizationService crmService)
    {
        FetchXmlToQueryExpressionRequest fetchXmlRequest = new FetchXmlToQueryExpressionRequest();

        fetchXmlRequest.FetchXml = fetchXml;
        FetchXmlToQueryExpressionResponse fetchXmlResponse
            = (FetchXmlToQueryExpressionResponse)crmService.Execute(fetchXmlRequest);

        return(fetchXmlResponse.Query);
    }
Пример #8
0
        public static IEnumerable <T> RetrieveMultiple <T>(this IOrganizationService service, FetchExpression fetchExpression) where T : Entity
        {
            FetchXmlToQueryExpressionRequest conversionRequest = new FetchXmlToQueryExpressionRequest
            {
                FetchXml = fetchExpression.Query
            };

            FetchXmlToQueryExpressionResponse conversionResponse = (FetchXmlToQueryExpressionResponse)service.Execute(conversionRequest);

            return(service.RetrieveMultiple <T>(conversionResponse.Query));
        }
Пример #9
0
        public static QueryExpression ConvertRollupQueryToQueryExpression(EntityReference rollupQueryEr, IOrganizationService service)
        {
            Entity rollupQuery = service.Retrieve(rollupQueryEr.LogicalName, rollupQueryEr.Id, new ColumnSet("fetchxml"));
            FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest()
            {
                FetchXml = rollupQuery["fetchxml"] as string,
            };

            FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)service.Execute(req);

            return(resp.Query);
        }
            protected override void Test(IOrganizationService service)
            {
                //Test framework does not support the FetchXmlToQueryExpression so we fake the expected API result for the specified fetchXml.
                var fakedFetchQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression()
                {
                    EntityName = "new_transactiondatarecord",
                    ColumnSet  = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "new_transactiondatarecordid" }),
                    Criteria   = new Microsoft.Xrm.Sdk.Query.FilterExpression
                    {
                        FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
                        Conditions     =
                        {
                            new Microsoft.Xrm.Sdk.Query.ConditionExpression("new_datafield1", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, "TestValue")
                        }
                    }
                };

                service = new OrganizationServiceBuilder()
                          .WithFakeExecute((s, r) => {
                    if (r.RequestName == "FetchXmlToQueryExpression")
                    {
                        FetchXmlToQueryExpressionResponse resp = new FetchXmlToQueryExpressionResponse();
                        resp.Results.Add("Query", fakedFetchQuery);
                        return(resp);
                    }
                    return(s.Execute(r));
                })
                          .Build();

                var executionContext   = GetExecutionContext(service);
                var serializer         = new DefaultSerializer();
                var transactionPointer = new RecordPointer <Guid>(Ids.ExistingTransaction.LogicalName, Ids.ExistingTransaction.EntityId);

                var transactionServiceFactory = Container.Resolve <ITransactionServiceFactory>();
                var transactionService        = transactionServiceFactory.CreateTransactionService(executionContext, false);

                var transaction = transactionService.LoadTransaction(executionContext, transactionPointer);

                var evaluatorType = new EvaluatorType.DataReccordQueryMatchEvaluator(
                    Ids.DataRecordQueryEvaluator.ToRecordPointer(), "TestEvaluator",
                    "S3.D365.Transactions",
                    "CCLLC.BTF.Process.CDS.EvaluatorType.DataReccordQueryMatchEvaluator");



                string parameterJson = "{\"FetchXml\":\"<fetch><entity name='new_transactiondatarecord'><filter type='and'><condition value='TestValue' attribute='new_datafield1' operator='eq'/></filter></entity></fetch>\"}";

                var parameters = serializer.CreateParamters(parameterJson);

                var result = evaluatorType.Evaluate(executionContext, parameters, transaction);

                Assert.AreEqual(true, result.Passed);
            }
Пример #11
0
        private QueryExpression ConvertFetchXMLtoQueryExpression(string fetchXmlQuery)
        {
            FetchXmlToQueryExpressionRequest conversionRequest = new FetchXmlToQueryExpressionRequest
            {
                FetchXml = fetchXmlQuery
            };

            FetchXmlToQueryExpressionResponse conversionResponse =
                (FetchXmlToQueryExpressionResponse)service.Execute(conversionRequest);

            QueryExpression queryExpression = conversionResponse.Query;

            return(queryExpression);
        }
        private FetchXmlToQueryExpressionResponse ExecuteInternal(FetchXmlToQueryExpressionRequest request)
        {
            var       s = new XmlSerializer(typeof(FetchType));
            FetchType fetch;

            using (var r = new StringReader(request.FetchXml))
            {
                fetch = (FetchType)s.Deserialize(r);
                r.Close();
            }
            var qe       = LocalCrmDatabase.ConvertFetchToQueryExpression(this, fetch);
            var response = new FetchXmlToQueryExpressionResponse();

            response["FetchXml"] = qe;
            return(response);
        }
Пример #13
0
        /// <summary>
        /// Retrieve member list from dynamic marketing list.
        /// Convert fetchxml to <see cref="QueryExpression"/>.
        /// </summary>
        /// <param name="fetxhxml"></param>
        /// <param name="membertype"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        ListMemberResult PopulateDynamicList(string fetxhxml, ListMemberTypeCode membertype, int count)
        {
            ExceptionThrow.IfNullOrEmpty(fetxhxml, "fetxhxml");

            ListMemberResult result = new ListMemberResult();

            FetchXmlToQueryExpressionRequest request = new FetchXmlToQueryExpressionRequest()
            {
                FetchXml = fetxhxml
            };

            FetchXmlToQueryExpressionResponse serviceResponse = (FetchXmlToQueryExpressionResponse)this.OrganizationService.Execute(request);

            string nameAttribute = membertype == ListMemberTypeCode.Account ? "name" : "fullname";

            result = FetchData(serviceResponse.Query, membertype, nameAttribute, count, false);

            return(result);
        }
Пример #14
0
        public EntityCollection GetData(ObjectExporter pExport)
        {
            EntityCollection _entityCollection;

            if (string.IsNullOrEmpty(pExport.Fetch))
            {
                QueryExpression _query = new QueryExpression(pExport.Entity);
                _entityCollection = pExport.ServiceClient.RetrieveMultiple(_query);
            }
            else
            {
                FetchXmlToQueryExpressionRequest _fetchXmlToQueryExpression = new FetchXmlToQueryExpressionRequest()
                {
                    FetchXml = pExport.Fetch
                };
                FetchXmlToQueryExpressionResponse _fetchXmlToQueryExpressionResponse =
                    (FetchXmlToQueryExpressionResponse)pExport.ServiceClient.Execute(_fetchXmlToQueryExpression);

                _entityCollection = pExport.ServiceClient.RetrieveMultiple(_fetchXmlToQueryExpressionResponse.Query);
            }

            return(_entityCollection);
        }
        public ShowDataWindow(FetchXmlToQueryExpressionResponse response)
        {
            InitializeComponent();

            DataTable responseDataTable = new DataTable("Response Table");

            var columns = response.Query.ColumnSet.Columns.ToArray();

            foreach (var column in columns)
            {
                responseDataTable.Columns.Add(column);
            }

            var results = response.Results;

            foreach (var record in results)
            {
                var newRow = responseDataTable.NewRow();

                responseDataTable.Rows.Add(newRow);
            }

            ResponseDataGrid.DataContext = responseDataTable;
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            #region Setup
            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service        = serviceFactory.CreateOrganizationService(null);
            #endregion
            try
            {
                if (context.MessageName != "RetrieveMultiple" || context.Stage != 40 || context.Mode != 0 || !context.InputParameters.Contains("Query") || !(context.InputParameters["Query"] is Microsoft.Xrm.Sdk.Query.FetchExpression))
                {
                    return;
                }
                if (context.InputParameters.Contains("Query"))
                {
                    string bidsheetId     = string.Empty;
                    var    query          = ((Microsoft.Xrm.Sdk.Query.FetchExpression)context.InputParameters["Query"]).Query;
                    int    IsContainsFlag = query.IndexOf("FilterProd");
                    if (IsContainsFlag != -1)
                    {
                        if (context.InputParameters["Query"] is FetchExpression)
                        {
                            FetchExpression fetchExpression = context.InputParameters["Query"] as FetchExpression;
                            FetchXmlToQueryExpressionRequest fetchXmlToQueryExpressionRequest = new FetchXmlToQueryExpressionRequest()
                            {
                                FetchXml = fetchExpression.Query
                            };
                            FetchXmlToQueryExpressionResponse fetchXmlToQueryExpressionResponse = (service.Execute(fetchXmlToQueryExpressionRequest) as FetchXmlToQueryExpressionResponse);

                            foreach (var filter in fetchXmlToQueryExpressionResponse.Query.LinkEntities)
                            {
                                foreach (var condition in filter.LinkCriteria.Conditions)
                                {
                                    if (condition.AttributeName == "ig1_bidsheetid")
                                    {
                                        bidsheetId = condition.Values[0].ToString();
                                    }
                                }
                            }
                        }
                        string conditions = GetConditions("b88439fd-1efc-49aa-9e0b-365742715e33");
                        FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest();
                        req.FetchXml = $@"<fetch>
                                            <entity name='product'>
                                            <attribute name='name' />
                                            <attribute name='ig1_bidsheetcategory' />
                                            <filter type='or'>
                                            {conditions}
                                            </filter>
                                            <order attribute='ig1_bidsheetcategory' />
                                            </entity>
                                        </fetch>";

                        FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)service.Execute(req);
                        context.InputParameters["Query"] = resp.Query;
                    }
                }
            }
            catch (Exception ex)
            {
                IOrganizationService serviceAdmin = serviceFactory.CreateOrganizationService(null);
                Entity errorLog = new Entity("ig1_pluginserrorlogs");
                errorLog["ig1_name"]             = "An error occurred in FilterProductBasedOnCategory Plug-in";
                errorLog["ig1_errormessage"]     = ex.Message;
                errorLog["ig1_errordescription"] = ex.ToString();
                serviceAdmin.Create(errorLog);
            }
        }
Пример #17
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            var tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("DCN Portal CGI plugin.");
            try
            {
                // Obtain the execution context from the service provider.
                IPluginExecutionContext context = (IPluginExecutionContext)
                                                  serviceProvider.GetService(typeof(IPluginExecutionContext));
                // Obtain the organization service reference.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                tracingService.Trace("Input Parameters {0}", context.InputParameters);
                foreach (var ip in context.InputParameters)
                {
                    tracingService.Trace("{0}/{1}", ip.Key, ip.Value);
                }
                if (!(context.InputParameters.Contains("Query")))
                {
                    throw new ApplicationException("No query expresssion.");
                }
                QueryExpression query;
                if (context.InputParameters["Query"] is QueryExpression q)
                {
                    query = q;
                }
                else if (context.InputParameters["Query"] is FetchExpression fetchQ)
                {
                    FetchXmlToQueryExpressionRequest conversionRequest = new FetchXmlToQueryExpressionRequest()
                    {
                        FetchXml = fetchQ.Query
                    };
                    FetchXmlToQueryExpressionResponse conversionResponse = (service.Execute(conversionRequest) as FetchXmlToQueryExpressionResponse);
                    query = conversionResponse.Query;
                }
                else
                {
                    throw new ApplicationException("Invalid query parameter.");
                }

                if (query.EntityName != "ace_dcnportalcgi")
                {
                    throw new ApplicationException("Portal CGI plugin is incorrectly registered.");
                }
                var condition = query.Criteria.Conditions.First(ce => ce.AttributeName == "ace_name");
#if DEBUG
                foreach (var value in condition.Values)
                {
                    tracingService.Trace("Condition.Value: {0}", value);
                }
#endif
                var cgiParameter = condition.Values[0].ToString();
                tracingService.Trace("cgiParameter: {0}", cgiParameter);
                Dictionary <string, string> parameters;
                try
                {
                    parameters = JsonConvert.DeserializeObject <Dictionary <string, string> >(cgiParameter);
                } catch (JsonReaderException ex)
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }


                var cgiServiceName = (string)parameters["Service"];
                tracingService.Trace("Service {0}", cgiServiceName);
                var    cgiService = GetCgiService(cgiServiceName);
                string jsonResult;
                try
                {
                    jsonResult = cgiService.Execute(parameters, service, tracingService);
                    tracingService.Trace("Json result: {0}", jsonResult);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Whoopsy daisy... {0}", ex);
                    jsonResult =
                        @"{
    ""Status"": ""Error"",
    ""Error"": """ + ex.Message + @"""
}";
                }

                if (!(context.OutputParameters.Contains("BusinessEntityCollection") &&
                      context.OutputParameters["BusinessEntityCollection"] is EntityCollection))
                {
                    throw new ApplicationException("No BusinessEntityCollection.");
                }
                var entityCollection = (EntityCollection)context.OutputParameters["BusinessEntityCollection"];
                entityCollection.Entities.Clear();

                var output = new Entity("ace_dcnportalcgi");
                output["ace_cgivalue"] = jsonResult;
                entityCollection.Entities.Add(output);

                tracingService.Trace("Done!");
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                tracingService.Trace("Fault: {0} {1}", ex.Message, ex.StackTrace);
                throw new InvalidPluginExecutionException("An error occurred in the PortalCGIHandler plug-in", ex);
            }
            catch (Exception ex)
            {
                tracingService.Trace("PortalCGIHandler: {0}", ex.ToString());
                throw new ApplicationException(string.Format("Unexpected exception: {0}", ex.Message));
            }
        }
Пример #18
0
        public void Execute(IServiceProvider serviceProvider)
        {
            #region Setup
            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service        = serviceFactory.CreateOrganizationService(context.UserId);
            #endregion
            try
            {
                if (context.MessageName != "RetrieveMultiple" || context.Stage != 20 || context.Mode != 0 || !context.InputParameters.Contains("Query") || !(context.InputParameters["Query"] is Microsoft.Xrm.Sdk.Query.FetchExpression))
                {
                    return;
                }
                if (context.InputParameters.Contains("Query"))
                {
                    string bidsheetId     = string.Empty;
                    var    query          = ((Microsoft.Xrm.Sdk.Query.FetchExpression)context.InputParameters["Query"]).Query;
                    int    IsContainsFlag = query.IndexOf("ZZZAAA");
                    if (IsContainsFlag != -1)
                    {
                        if (context.InputParameters["Query"] is FetchExpression)
                        {
                            FetchExpression fetchExpression = context.InputParameters["Query"] as FetchExpression;
                            FetchXmlToQueryExpressionRequest fetchXmlToQueryExpressionRequest = new FetchXmlToQueryExpressionRequest()
                            {
                                FetchXml = fetchExpression.Query
                            };
                            FetchXmlToQueryExpressionResponse fetchXmlToQueryExpressionResponse = (service.Execute(fetchXmlToQueryExpressionRequest) as FetchXmlToQueryExpressionResponse);

                            foreach (var filter in fetchXmlToQueryExpressionResponse.Query.LinkEntities)
                            {
                                foreach (var condition in filter.LinkCriteria.Conditions)
                                {
                                    if (condition.AttributeName == "ig1_bidsheetid")
                                    {
                                        bidsheetId = condition.Values[0].ToString();
                                    }
                                }
                            }
                        }
                        var categoryId = GetcategoryId(bidsheetId);
                        FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest();
                        req.FetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                       "  <entity name='ig1_bidsheetpricelistitem'>" +
                                       "    <attribute name='ig1_bidsheetpricelistitemid' />" +
                                       "    <attribute name='ig1_product' />" +
                                       "    <attribute name='ig1_materialcost' />" +
                                       "    <attribute name='ig1_category' />" +
                                       "    <order attribute='ig1_category' descending='false' />" +
                                       "    <filter type='and'>" +
                                       "      <condition attribute='ig1_category' operator='eq' value='" + categoryId + "' />" +
                                       "      <condition attribute='ig1_bidsheet' operator='eq' value='" + bidsheetId + "' />" +
                                       "    </filter>" +
                                       "  </entity>" +
                                       "</fetch>";
                        FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)service.Execute(req);
                        context.InputParameters["Query"] = resp.Query;
                    }
                }
            }
            catch (Exception ex)
            {
                IOrganizationService serviceAdmin = serviceFactory.CreateOrganizationService(null);
                Entity errorLog = new Entity("ig1_pluginserrorlogs");
                errorLog["ig1_name"]             = "An error occurred in FilterContingencyGrid Plug-in";
                errorLog["ig1_errormessage"]     = ex.Message;
                errorLog["ig1_errordescription"] = ex.ToString();
                serviceAdmin.Create(errorLog);
            }
        }
Пример #19
0
        private void CreateBulkDeleteJobs(ScheduledJob job)
        {
            IsBusyMessage.SetValue("Creating new schedule...");
            IsBusyProgress.SetValue(0);
            // Convert bulk delete fetch into QueryExpression
            string fetchxml = "<fetch distinct='false' no-lock='false' mapping='logical'><entity name='lead'><attribute name='fullname' /><attribute name='statuscode' /><attribute name='createdon' /><attribute name='subject' /><attribute name='leadid' /><filter type='and'><condition attribute='ownerid' operator='eq-userid' /><condition attribute='statecode' operator='eq' value='0' /><condition attribute='address1_county' operator='eq' value='deleteme' /></filter><order attribute='createdon' descending='true' /></entity></fetch>";
            FetchXmlToQueryExpressionRequest convertRequest = new FetchXmlToQueryExpressionRequest();

            convertRequest.FetchXml = fetchxml;
            OrganizationServiceProxy.BeginExecute(convertRequest, delegate(object state)
            {
                FetchXmlToQueryExpressionResponse response = (FetchXmlToQueryExpressionResponse)OrganizationServiceProxy.EndExecute(state);

                List <BulkDeleteRequest> bulkDeleteRequests = new List <BulkDeleteRequest>();

                // If the recurrance is minutely, hourly, weekly we need to schedule multiple jobs
                if (job.Recurrance.GetValue().Value != RecurranceFrequencyNames.DAILY)
                {
                    DateTime startDate = DateTimeEx.UTCToLocalTimeFromSettings(job.StartDate.GetValue(), OrganizationServiceProxy.GetUserSettings());

                    DateInterval interval = DateInterval.Days;
                    int incrementAmount   = 1;
                    int dayInterval       = 1;
                    int recurranceCount   = 0;
                    int totalCount        = 0;
                    string freq           = RecurranceFrequencyNames.DAILY;

                    switch (job.Recurrance.GetValue().Value)
                    {
                    case RecurranceFrequencyNames.MINUTELY:
                        interval        = DateInterval.Minutes;
                        incrementAmount = job.RecurEvery.GetValue();
                        dayInterval     = 1;
                        recurranceCount = (60 * 24) / incrementAmount;
                        break;

                    case RecurranceFrequencyNames.HOURLY:
                        interval        = DateInterval.Hours;
                        incrementAmount = job.RecurEvery.GetValue();
                        dayInterval     = 1;
                        recurranceCount = 24 / incrementAmount;
                        break;

                    case RecurranceFrequencyNames.WEEKLY:
                    case RecurranceFrequencyNames.YEARLY:
                        // To schedule weekly, me must create a job per week day for the whole year, and set recurrance to every 365 days
                        // but this doesn't deal with leap years, so we can't do it!
                        throw new Exception("The selected schedule interval is currently not supported due to the limitation of bulk delete");
                    }

                    if (incrementAmount < 0)
                    {
                        throw new Exception("Invalid schedule");
                    }

                    // Increment in the recurrency frequence
                    for (int i = 0; i < recurranceCount; i++)
                    {
                        BulkDeleteRequest request     = new BulkDeleteRequest();
                        request.QuerySet              = response.Query.Replace(@"<d:anyType ", @"<d:anyType xmlns:e=""http://www.w3.org/2001/XMLSchema"" ");
                        request.SendEmailNotification = false;
                        request.StartDateTime         = startDate;
                        request.RecurrencePattern     = "FREQ=DAILY;INTERVAL=" + dayInterval.ToString();
                        request.JobName = "Scheduled Job " + i.Format("0000") + " " + job.ScheduledJobId.GetValue().Value;
                        ArrayEx.Add(bulkDeleteRequests, request);
                        startDate = DateTimeEx.DateAdd(interval, incrementAmount, startDate);
                    }
                }
                else
                {
                    // Just a single request
                    BulkDeleteRequest request     = new BulkDeleteRequest();
                    request.QuerySet              = response.Query.Replace(@"<d:anyType ", @"<d:anyType xmlns:e=""http://www.w3.org/2001/XMLSchema"" ");
                    request.SendEmailNotification = false;
                    request.StartDateTime         = job.StartDate.GetValue();
                    request.RecurrencePattern     = RecurrancePatternMapper.Serialise(job);
                    request.JobName = "Scheduled Job " + job.ScheduledJobId.GetValue().Value;
                    ArrayEx.Add(bulkDeleteRequests, request);
                }

                BatchCreateBulkDeleteJobs(bulkDeleteRequests, delegate()
                {
                    IsBusy.SetValue(false);
                    JobsViewModel.Reset();
                    JobsViewModel.Refresh();
                });
            });
        }
Пример #20
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                ITracingService             tracingService    = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                IPluginExecutionContext     executionContext  = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory orgServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        orgService        = orgServiceFactory.CreateOrganizationService((Guid?)executionContext.UserId);
                tracingService.Trace($"strConfig: {strConfig}", new object[0]);
                tracingService.Trace($"_controlAttribute: {_controlAttribute}", new object[0]);
                tracingService.Trace($"nodeQueryFields: {nodeQueryFields.Count}", new object[0]);
                if (executionContext.InputParameters.Contains("Query"))
                {
                    tracingService.Trace("has a query", new object[0]);
                    QueryExpression queryExpression = new QueryExpression();
                    bool            flag            = false;
                    bool            flag2           = false;
                    string          fetchXml        = string.Empty;
                    if (executionContext.InputParameters["Query"] is FetchExpression)
                    {
                        flag2 = true;
                        tracingService.Trace("query is a fetchexpression", new object[0]);
                        fetchXml = ((FetchExpression)executionContext.InputParameters["Query"]).Query;
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.LoadXml(fetchXml);
                        XmlElement documentElement = xmlDocument.DocumentElement;
                        string     xpath           = $"//condition[@attribute='{_controlAttribute}' and @operator='eq' and @value='{_controlValue}']";
                        XmlNode    xmlNode         = documentElement.SelectSingleNode(xpath);
                        if (xmlNode != null)
                        {
                            FetchXmlToQueryExpressionRequest fetchExpression = new FetchXmlToQueryExpressionRequest();
                            fetchExpression.FetchXml = fetchXml;
                            FetchXmlToQueryExpressionResponse response = (FetchXmlToQueryExpressionResponse)orgService.Execute(fetchExpression);
                            queryExpression = response.Query;
                            XmlNode parentNode = xmlNode.ParentNode;
                            parentNode.RemoveChild(xmlNode);
                            fetchXml = GetFirstParent(parentNode).OuterXml;
                            flag     = true;
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    else if (executionContext.InputParameters["Query"] is QueryExpression)
                    {
                        tracingService.Trace("query is a queryexpression", new object[0]);
                        queryExpression = (QueryExpression)executionContext.InputParameters["Query"];
                        flag            = true;
                    }
                    if (flag && queryExpression.Criteria != null)
                    {
                        tracingService.Trace("non-null criteria", new object[0]);
                        string text2 = "";
                        tracingService.Trace("filter count: " + ((Collection <FilterExpression>)queryExpression.Criteria.Filters).Count.ToString(), new object[0]);
                        if (((Collection <FilterExpression>)queryExpression.Criteria.Filters).Count > 0)
                        {
                            foreach (FilterExpression item in (Collection <FilterExpression>)queryExpression.Criteria.Filters)
                            {
                                AddFilterConditionsToDictionary(item);
                            }
                        }
                        if (((Collection <ConditionExpression>)queryExpression.Criteria.Conditions).Count > 0)
                        {
                            int num = -1;
                            for (int i = 0; i < ((Collection <ConditionExpression>)queryExpression.Criteria.Conditions).Count; i++)
                            {
                                ConditionExpression val9 = ((Collection <ConditionExpression>)queryExpression.Criteria.Conditions)[i];
                                AddConditionToDictionary(val9);
                                if (val9.AttributeName.ToUpper() == _controlAttribute.ToUpper())
                                {
                                    num = i;
                                }
                            }
                            if (num != -1)
                            {
                                ((Collection <ConditionExpression>)queryExpression.Criteria.Conditions).RemoveAt(num);
                            }
                        }
                        foreach (string key in _conditionDictionary.Keys)
                        {
                            text2 += $"key: {key}, value: {_conditionDictionary[key].ToString()}\n";
                        }
                        tracingService.Trace("conditions: " + text2, new object[0]);
                        if (_conditionDictionary.ContainsKey(_controlAttribute.ToUpper()) && (string)_conditionDictionary[_controlAttribute.ToUpper()] == _controlValue)
                        {
                            strErrorText = strErrorText + "found " + _controlValue + "\r\n";
                            tracingService.Trace("should execute create/update", new object[0]);
                            createOrUpdate = true;
                            strErrorText   = strErrorText + bah_edipi_text + "\r\n";
                            object obj = strErrorText;
                            strErrorText = obj + "aryFields.Count:" + aryFields.Count + "\r\n";
                            for (int j = 0; j < aryFields.Count; j++)
                            {
                                strErrorText = strErrorText + "looping:" + j.ToString() + "\r\n";
                                QueryFields queryFields = (QueryFields)aryFields[j];
                                if (_conditionDictionary.ContainsKey(queryFields.ODataName.ToUpper()))
                                {
                                    queryFields.Value = _conditionDictionary[queryFields.SchemaName.ToUpper()].ToString();
                                    hshEntityAttribs.Add(queryFields.SchemaName, queryFields);
                                    tracingService.Trace($"Hsh: {queryFields.SchemaName}-{queryFields.Value}", new object[0]);
                                }
                            }
                        }
                    }
                    if (createOrUpdate)
                    {
                        bool             flag3             = false;
                        EntityCollection contactCollection = new EntityCollection();
                        foreach (XmlNode childNode in searchNodes[0].ChildNodes)
                        {
                            string text3 = generateSearchFetch(childNode, hshEntityAttribs, tracingService);
                            tracingService.Trace("Fetch: " + text3);
                            if (text3 != "SEARCHFIELDNOTINQUERY")
                            {
                                tracingService.Trace(string.Format("Search: {0}, FetchXML: {1}", childNode.Attributes["name"].Value, text3), new object[0]);
                                FetchExpression val11 = new FetchExpression(text3);
                                contactCollection = orgService.RetrieveMultiple(val11);
                                XmlNode xmlNode3 = childNode.Attributes["returnnone"];
                                if (xmlNode3 != null && !string.IsNullOrEmpty(xmlNode3.Value))
                                {
                                    if (xmlNode3.Value.ToUpper() == "true".ToUpper() && ((Collection <Entity>)contactCollection.Entities).Count > 0)
                                    {
                                        flag3 = true;
                                        break;
                                    }
                                }
                                else
                                {
                                    if (((Collection <Entity>)contactCollection.Entities).Count > 1)
                                    {
                                        flag3 = false;
                                        XmlNode xmlNode4 = childNode.Attributes["ignoremultiples"];
                                        if (xmlNode4 != null && !string.IsNullOrEmpty(xmlNode4.Value) && xmlNode4.Value.ToUpper() == "true".ToUpper())
                                        {
                                            flag3 = true;
                                        }
                                        break;
                                    }
                                    if (((Collection <Entity>)contactCollection.Entities).Count == 1)
                                    {
                                        flag3 = false;
                                        break;
                                    }
                                }
                            }
                        }
                        if (!flag3)
                        {
                            if (((Collection <Entity>)contactCollection.Entities).Count > 1)
                            {
                                ((Collection <Entity>)contactCollection.Entities).Clear();
                            }

                            if (((Collection <Entity>)contactCollection.Entities).Count == 0)
                            {
                                Entity newContact = new Entity("contact");
                                tracingService.Trace("Create: parsing hashtable", new object[0]);
                                ICollection keys = hshEntityAttribs.Keys;
                                foreach (string item2 in keys)
                                {
                                    QueryFields queryFields2 = (QueryFields)hshEntityAttribs[item2];
                                    if (queryFields2.Value != null)
                                    {
                                        tracingService.Trace($"strprop:{item2} -- {queryFields2.Value} : {queryFields2.TypeName}", new object[0]);
                                        if (queryFields2.TypeName.ToUpper() == "STRING")
                                        {
                                            newContact[item2] = (object)queryFields2.Value;
                                        }
                                        else if (queryFields2.TypeName.ToUpper() == "DATE")
                                        {
                                            newContact[item2] = (object)DateTime.Parse(queryFields2.Value);
                                        }
                                        else if (queryFields2.TypeName.ToUpper() == "NUMERIC")
                                        {
                                            newContact[item2] = (object)Convert.ToDecimal(queryFields2.Value);
                                        }
                                        else if (queryFields2.TypeName.ToUpper() == "OPTIONSET")
                                        {
                                            OptionSetValue opt = new OptionSetValue();
                                            opt.Value         = (Convert.ToInt32(queryFields2.Value));
                                            newContact[item2] = (object)opt;
                                        }
                                        else if (queryFields2.TypeName.ToUpper().StartsWith("LOOKUP"))
                                        {
                                            string text6 = queryFields2.TypeName.Split("-".ToCharArray())[1];
                                            newContact[item2] = (object)new EntityReference(text6, new Guid(queryFields2.Value));
                                        }
                                    }
                                    else
                                    {
                                        tracingService.Trace($"strprop:{item2} has no value.", new object[0]);
                                    }
                                }
                                orgService.Create(newContact);
                            }
                            else
                            {
                                if (((Collection <Entity>)contactCollection.Entities).Count != 1)
                                {
                                    throw new InvalidPluginExecutionException("Multiple records found using the provided EDIPI value.");
                                }
                                Entity val12 = ((Collection <Entity>)contactCollection.Entities)[0];
                                tracingService.Trace("Update: parsing hashtable", new object[0]);
                                ICollection keys = hshEntityAttribs.Keys;
                                foreach (string item3 in keys)
                                {
                                    QueryFields queryFields2 = (QueryFields)hshEntityAttribs[item3];
                                    if (queryFields2.Value != null && queryFields2.Value != string.Empty)
                                    {
                                        tracingService.Trace($"strprop:{item3} -- {queryFields2.Value} : {queryFields2.TypeName}", new object[0]);
                                        if (queryFields2.TypeName.ToUpper() == "STRING")
                                        {
                                            val12[item3] = (object)queryFields2.Value;
                                        }
                                        else if (queryFields2.TypeName.ToUpper() == "DATE")
                                        {
                                            val12[item3] = (object)DateTime.Parse(queryFields2.Value);
                                        }
                                        else if (queryFields2.TypeName.ToUpper() == "NUMERIC")
                                        {
                                            val12[item3] = (object)Convert.ToDecimal(queryFields2.Value);
                                        }
                                        else if (queryFields2.TypeName.ToUpper() == "OPTIONSET")
                                        {
                                            OptionSetValue val14 = new OptionSetValue();
                                            val14.Value  = (Convert.ToInt32(queryFields2.Value));
                                            val12[item3] = (object)val14;
                                        }
                                        else if (queryFields2.TypeName.ToUpper().StartsWith("LOOKUP"))
                                        {
                                            string text6 = queryFields2.TypeName.Split("-".ToCharArray())[1];
                                            val12[item3] = (object)new EntityReference(text6, new Guid(queryFields2.Value));
                                        }
                                    }
                                    else
                                    {
                                        tracingService.Trace($"strprop:{item3} has no value.", new object[0]);
                                    }
                                }
                                orgService.Update(val12);
                            }
                        }
                    }
                    if (flag2)
                    {
                        executionContext.InputParameters["Query"] = (object)new FetchExpression(fetchXml);
                    }
                }
                else
                {
                    tracingService.Trace("value of returnNoContact is true", new object[0]);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
 private FetchXmlToQueryExpressionResponse ExecuteInternal(FetchXmlToQueryExpressionRequest request)
 {
     var s = new XmlSerializer(typeof (FetchType));
     FetchType fetch;
     using (var r = new StringReader(request.FetchXml))
     {
         fetch = (FetchType) s.Deserialize(r);
         r.Close();
     }
     var qe = LocalCrmDatabase.ConvertFetchToQueryExpression(this, fetch);
     var response = new FetchXmlToQueryExpressionResponse();
     response["FetchXml"] = qe;
     return response;
 }