public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var executeFetchRequest = (ExecuteFetchRequest)request;

            if (executeFetchRequest.FetchXml == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "You need to provide FetchXml value");
            }

            var service = ctx.GetFakedOrganizationService();

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(executeFetchRequest.FetchXml)
            };
            var queryResult = (service.Execute(retrieveMultiple) as RetrieveMultipleResponse).EntityCollection;

            XDocument doc = new XDocument(new XElement("resultset",
                                                       new XAttribute("morerecords", Convert.ToInt16(queryResult.MoreRecords))));

            if (queryResult.PagingCookie != null)
            {
                doc.Root.Add(new XAttribute("paging-cookie", queryResult.PagingCookie));
            }

            var allowedAliases = new string[0];

            var fetchXmlDocument = XDocument.Parse(executeFetchRequest.FetchXml).Root;

            if (fetchXmlDocument != null)
            {
                var linkedEntityName = fetchXmlDocument.Descendants("link-entity").Attributes("name").Select(a => a.Value).Distinct();
                allowedAliases = linkedEntityName.Concat(fetchXmlDocument.Descendants("link-entity").Attributes("alias").Select(a => a.Value).Distinct()).ToArray();
            }

            foreach (var row in queryResult.Entities)
            {
                doc.Root.Add(CreateXmlResult(row, ctx, allowedAliases));
            }

            var response = new ExecuteFetchResponse
            {
                Results = new ParameterCollection
                {
                    { "FetchXmlResult", doc.ToString() }
                }
            };

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


            if (executeFetchRequest.FetchXml == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "You need to provide FetchXml value");
            }

            var service = ctx.GetFakedOrganizationService();

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(executeFetchRequest.FetchXml)
            };
            var queryResult = (service.Execute(retrieveMultiple) as RetrieveMultipleResponse).EntityCollection;



            XDocument doc = new XDocument(new XElement("resultset",
                                                       new XAttribute("morerecords", Convert.ToInt16(queryResult.MoreRecords))));

            if (queryResult.PagingCookie != null)
            {
                doc.Root.Add(new XAttribute("paging-cookie", queryResult.PagingCookie));
            }

            foreach (var row in queryResult.Entities)
            {
                doc.Root.Add(CreateXmlResult(row, ctx));
            }

            var response = new ExecuteFetchResponse
            {
                Results = new ParameterCollection
                {
                    { "FetchXmlResult", doc.ToString() }
                }
            };

            return(response);
        }
Esempio n. 3
0
        protected List <Entity> RetrieveAnnotationEntity(CodeActivityContext context, ColumnSet noteColumns, int maxRecords = 1)
        {
            double                      miunutesOld     = 0;
            List <Entity>               returnValue     = new List <Entity>();
            IWorkflowContext            workflowContext = context.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory  = context.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service         = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);

            int?objectTypeCode = this.RetrieveEntityObjectTypeCode(workflowContext, service);

            if (objectTypeCode == null)
            {
                throw new ArgumentException($"Objecttypecode not found in metadata for entity {workflowContext.PrimaryEntityName}");
            }

            ExecuteFetchResponse fetchResponse = null;
            ExecuteFetchRequest  request       = new ExecuteFetchRequest();

            try
            {
                if (String.IsNullOrWhiteSpace(this.FileName.Get(context)))
                {
                    request.FetchXml =
                        $@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
                              <entity name=""annotation"">
                                <attribute name=""annotationid"" />
                                <attribute name=""createdon"" />
                                <filter type=""and"">
                                  <condition attribute=""isdocument"" operator=""eq"" value=""1"" />
                                  <condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEntityId}"" />
                                  <condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
                                </filter>
                                <order attribute=""createdon"" descending=""true"" />
                              </entity>
                            </fetch>";
                }
                else
                {
                    request.FetchXml =
                        $@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
                              <entity name=""annotation"">
                                <attribute name=""annotationid"" />
                                <attribute name=""createdon"" />
                                <filter type=""and"">
                                  <condition attribute=""filename"" operator=""like"" value=""%{this.FileName.Get(context)}%"" />
                                  <condition attribute=""isdocument"" operator=""eq"" value=""1"" />
                                  <condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEntityId}"" />
                                  <condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
                                </filter>
                                <order attribute=""createdon"" descending=""true"" />
                              </entity>
                            </fetch>";
                }

                fetchResponse = service.Execute(request) as ExecuteFetchResponse;

                XmlDocument queryResults = new XmlDocument();
                queryResults.LoadXml(fetchResponse.FetchXmlResult);
                int days    = 0;
                int minutes = 0;
                for (int i = 0; i < queryResults["resultset"].ChildNodes.Count; i++)
                {
                    if (queryResults["resultset"].ChildNodes[i]["createdon"] != null && !String.IsNullOrWhiteSpace(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText))
                    {
                        DateTime createdon = DateTime.Parse(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText);
                        if (createdon.Kind == DateTimeKind.Local)
                        {
                            createdon = createdon.ToUniversalTime();
                        }
                        TimeSpan difference = DateTime.Now.ToUniversalTime() - createdon;
                        miunutesOld = difference.TotalMinutes;
                        switch (this.TimeSpanOption.Get(context).Value)
                        {
                        case 222540000:
                            minutes = this.TimeSpanValue.Get(context);
                            break;

                        case 222540001:
                            minutes = this.TimeSpanValue.Get(context) * 60;
                            break;

                        case 222540002:
                            days = this.TimeSpanValue.Get(context);
                            break;

                        case 222540003:
                            days = this.TimeSpanValue.Get(context) * 7;
                            break;

                        case 222540004:
                            days = this.TimeSpanValue.Get(context) * 365;
                            break;
                        }
                        TimeSpan allowedDifference = new TimeSpan(days, 0, minutes, 0);
                        if (difference <= allowedDifference)
                        {
                            returnValue.Add(service.Retrieve("annotation", Guid.Parse(queryResults["resultset"].ChildNodes[i]["annotationid"].InnerText), noteColumns));
                        }
                    }

                    if (returnValue.Count >= maxRecords)
                    {
                        break;
                    }
                }
            }
            catch (System.ServiceModel.FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                throw new ArgumentException("There was an error executing the FetchXML. Message: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(returnValue);
        }
        public async override Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var dataMovement = request.DataStore.GetValue("DataMovement");

            if (dataMovement == "Scribe")
            {
                return(new ActionResponse(ActionStatus.Success));
            }

            string refreshToken    = request.DataStore.GetJson("MsCrmToken")["refresh_token"].ToString();
            string organizationUrl = request.DataStore.GetValue("OrganizationUrl");
            Dictionary <string, string> entities = JsonConvert.DeserializeObject <Dictionary <string, string> >(request.DataStore.GetValue("Entities"));

            var crmToken = CrmTokenUtility.RetrieveCrmOnlineToken(refreshToken, request.Info.WebsiteRootUrl, request.DataStore, organizationUrl);

            Dictionary <string, int> initialCounts = new Dictionary <string, int>();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.CheckCertificateRevocationList = true;
            OrganizationWebProxyClient proxy = new OrganizationWebProxyClient(new Uri($"{organizationUrl}XRMServices/2011/Organization.svc/web"), true)
            {
                HeaderToken = crmToken["access_token"].ToString()
            };

            string count = string.Empty;
            int    max   = 0;

            foreach (var entry in entities)
            {
                try
                {
                    var xml = $@"
                        <fetch distinct='false' mapping='logical' aggregate='true'> 
                            <entity name='{entry.Key}'> 
                                 <attribute name = '{entry.Value}' alias = '{entry.Key}_count' aggregate = 'count'/>
                            </entity> 
                        </fetch>";

                    ExecuteFetchRequest fetchRequest = new ExecuteFetchRequest()
                    {
                        FetchXml = xml
                    };
                    ExecuteFetchResponse result = (ExecuteFetchResponse)proxy.Execute(fetchRequest);
                    XDocument            xdoc   = XDocument.Parse(result.FetchXmlResult);

                    count = xdoc.Descendants().First(e => e.Name == $"{entry.Key}_count").Value;
                }
                catch (Exception e)
                {
                    if (e.Message == $"The entity with a name = '{entry.Key}' was not found in the MetadataCache.")
                    {
                        return(new ActionResponse(ActionStatus.Failure, null, e, "NotPSAInstance"));
                    }

                    if (e.Message == "AggregateQueryRecordLimit exceeded. Cannot perform this operation.")
                    {
                        count = "-1";
                    }
                    else
                    {
                        throw;
                    }
                }

                if (Convert.ToInt32(count) > max)
                {
                    max = Convert.ToInt32(count);
                }

                initialCounts.Add(entry.Key.ToLowerInvariant(), Convert.ToInt32(count));
            }
            var missingCounts = new List <string>();

            foreach (var pair in initialCounts)
            {
                if (pair.Value == -1)
                {
                    missingCounts.Add(pair.Key);
                }
            }

            foreach (var entry in missingCounts)
            {
                initialCounts[entry] = max;
            }

            request.DataStore.AddToDataStore("InitialCounts", JsonUtility.GetJObjectFromObject(initialCounts));
            return(new ActionResponse(ActionStatus.Success));
        }