public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string refreshToken    = request.DataStore.GetJson("MsCrmToken")["refresh_token"].ToString();
            string organizationUrl = request.DataStore.GetValue("OrganizationUrl");

            string[] entities = request.DataStore.GetValue("Entities").Split(new[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

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

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

            Dictionary <string, bool> entitiesToReprocess = new Dictionary <string, bool>();

            for (int i = 0; i < maxRetries; i++)
            {
                try
                {
                    Parallel.ForEach(entities, (entity) =>
                    {
                        try
                        {
                            entitiesToReprocess.Add(entity, this.CheckAndUpdateEntity(entity, proxy, request.Logger));
                        }
                        catch (Exception e)
                        {
                            e.Data.Add("entity", entity);
                            throw;
                        }
                    });
                }
                catch (Exception e)
                {
                    if (e.GetType() == typeof(AggregateException))
                    {
                        string output = string.Empty;
                        foreach (var ex in (e as AggregateException).InnerExceptions)
                        {
                            output += ex.Message + $"[{ex.Data["entity"]}]. ";
                        }

                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(e), e, "DefaultErrorCode", output));
                    }
                    else
                    {
                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(e), e, "DefaultErrorCode", e.Message));
                    }
                }

                if (!entitiesToReprocess.Values.Contains(false))
                {
                    break;
                }
            }

            return(new ActionResponse(ActionStatus.Success));
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.CheckCertificateRevocationList = true;

            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);

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

            Dictionary <string, bool> entitiesToReprocess = new Dictionary <string, bool>();

            bool retryNeeded = true;

            for (int i = 0; i < maxRetries && retryNeeded; i++)
            {
                try
                {
                    Parallel.ForEach(entities, (e) => { this.CheckAndUpdateEntity(e.Key, proxy, request.Logger); });

                    retryNeeded = false;
                }
                catch (AggregateException aex)
                {
                    string output = string.Empty;
                    foreach (var ex in aex.InnerExceptions)
                    {
                        output += ex.Message + $"[{ex.Data["entity"]}]. ";
                    }

                    return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(aex), aex, "DefaultErrorCode", output));
                }
                catch (Exception e)
                {
                    return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(e), e, "DefaultErrorCode", e.Message));
                }
            }

            return(new ActionResponse(ActionStatus.Success));
        }
Beispiel #3
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            RestClient    rc;
            List <string> result                      = new List <string>();
            string        refreshToken                = request.DataStore.GetJson("MsCrmToken")["refresh_token"].ToString();
            string        organizationUrl             = request.DataStore.GetValue("OrganizationUrl");
            Dictionary <string, string> entities_dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(request.DataStore.GetValue("Entities"));
            List <string> coreObjects                 = new List <string>();

            foreach (var entity in entities_dict)
            {
                coreObjects.Add(entity.Key);
            }

            var crmObjects = new List <string>();

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

            var token = request.DataStore.GetJson("MsCrmToken", "access_token");
            AuthenticationHeaderValue bearer = new AuthenticationHeaderValue("Bearer", token);
            var orgUrl = request.DataStore.GetValue("OrganizationUrl");

            rc = new RestClient(request.DataStore.GetValue("ConnectorUrl"), bearer);
            string response = await rc.Get(MsCrmEndpoints.URL_ENTITIES, "organizationurl=" + orgUrl);

            MsCrmEntity[] provisionedEntities = JsonConvert.DeserializeObject <MsCrmEntity[]>(response);

            foreach (var entity in provisionedEntities)
            {
                if (!coreObjects.Contains(entity.LogicalName))
                {
                    crmObjects.Add(entity.LogicalName);
                }
            }

            return(new ActionResponse(ActionStatus.Success, JsonUtility.Serialize(crmObjects)));
        }
        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>();

            var 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>";

                    var fetchRequest = new ExecuteFetchRequest()
                    {
                        FetchXml = xml
                    };

                    var result = (ExecuteFetchResponse)proxy.Execute(fetchRequest);

                    var 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));
        }