protected override void ProcessRecord()
        {
            base.ProcessRecord();

            Guid duplicateRuleId = DuplicateRuleId != Guid.Empty ? DuplicateRuleId : GetDuplicateRuleId(DuplicateRuleName);

            base.WriteVerbose(string.Format("Publishing a CRM duplicate rule with Id: {0}", duplicateRuleId));

            var publishAllXmlRequest = new PublishDuplicateRuleRequest
            {
                DuplicateRuleId = duplicateRuleId
            };

            OrganizationService.Execute(publishAllXmlRequest);

            base.WriteVerbose("Publish duplicate rule request sent out successfully");
        }
Esempio n. 2
0
        public void PublishDuplicateDetectionRule(Entity entityBeforeStatusCodeChange, Entity curEntity)
        {
            if (entityBeforeStatusCodeChange.LogicalName.Equals(Constant.DuplicateRule.EntityLogicalName, StringComparison.OrdinalIgnoreCase))
            {
                if (entityBeforeStatusCodeChange.Contains(Constant.Entity.StatusCode) &&
                    entityBeforeStatusCodeChange.GetAttributeValue <OptionSetValue>(Constant.Entity.StatusCode).Value == 2) //"Published"
                {
                    var publishReq = new PublishDuplicateRuleRequest {
                        DuplicateRuleId = entityBeforeStatusCodeChange.Id
                    };
                    OrganizationService.Execute(publishReq);

                    // update the curEntity to publish state in order to get it matched during VERIFICATION
                    curEntity[Constant.Entity.StateCode]  = entityBeforeStatusCodeChange.GetAttributeValue <OptionSetValue>(Constant.Entity.StateCode);  //active
                    curEntity[Constant.Entity.StatusCode] = entityBeforeStatusCodeChange.GetAttributeValue <OptionSetValue>(Constant.Entity.StatusCode); //published

                    // sleep to let the process finish before continuing ;)
                    Thread.Sleep(2000);
                }
            }
        }
        private void PublishRules(IOrganizationService service, ITracingService tracing)
        {
            try {
                var rules = GetDuplicateRules(service, tracing);

                tracing.Trace("Fetched " + rules.Count + " duplicate rules that meet all conditions.");

                if (rules.Count >= 1)
                {
                    ExecuteMultipleRequest request = new ExecuteMultipleRequest()
                    {
                        Settings = new ExecuteMultipleSettings()
                        {
                            ContinueOnError = false,
                            ReturnResponses = false
                        },
                        Requests = new OrganizationRequestCollection()
                    };

                    foreach (Entity rule in rules)
                    {
                        PublishDuplicateRuleRequest publishReq = new PublishDuplicateRuleRequest {
                            DuplicateRuleId = rule.Id
                        };
                        request.Requests.Add(publishReq);
                    }

                    service.Execute(request);
                }
                else
                {
                    tracing.Trace("Plugin execution cancelled, as there are no duplicate detection rules to publish.");
                }
            } catch (Exception ex) {
                tracing.Trace(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            String accountName = "Contoso, Ltd";
            String websiteUrl  = "http://www.contoso.com/";

            Console.WriteLine("  Creating duplicate records (Account name={0}, Website URL={1})", accountName,
                              websiteUrl);
            // Create some duplicate records
            for (int i = 0; i < 2; i++)
            {
                var account = new Account()
                {
                    Name       = accountName,
                    WebSiteURL = websiteUrl
                };
                account.Id           = service.Create(account);
                duplicateAccounts[i] = account;
            }

            accountName = "Contoso Pharmaceuticals";
            Console.WriteLine("  Creating a non-duplicate record (Account name={0}, Website URL={1})",
                              accountName, websiteUrl);

            // Create a record that is NOT a duplicate
            var distinctAccount = new Account()
            {
                Name       = accountName,
                WebSiteURL = websiteUrl
            };

            distinctAccount.Id = service.Create(distinctAccount);
            account            = distinctAccount;


            Console.WriteLine("  Creating a duplicate detection rule");
            // Create a duplicate detection rule
            rule = new DuplicateRule()
            {
                Name               = "Accounts with the same Account name and website url",
                BaseEntityName     = Account.EntityLogicalName,
                MatchingEntityName = Account.EntityLogicalName
            };
            rule.Id = service.Create(rule);

            // Create a duplicate detection rule condition
            var nameCondition = new DuplicateRuleCondition()
            {
                BaseAttributeName     = "name",
                MatchingAttributeName = "name",
                OperatorCode          = new OptionSetValue(0), // value 0 = 'exact match'
                // set the regarding id to point to the rule created earlier,
                // associating this condition with that rule
                RegardingObjectId = rule.ToEntityReference()
            };

            service.Create(nameCondition);

            var websiteCondition = new DuplicateRuleCondition()
            {
                BaseAttributeName     = "websiteurl",
                MatchingAttributeName = "websiteurl",
                OperatorCode          = new OptionSetValue(0),
                RegardingObjectId     = rule.ToEntityReference()
            };

            service.Create(websiteCondition);

            Console.WriteLine("  Publishing duplicate detection rule");
            // Publish the rule
            var publishRequest = new PublishDuplicateRuleRequest()
            {
                DuplicateRuleId = rule.Id
            };
            var publishResponse = (PublishDuplicateRuleResponse)service.Execute(publishRequest);

            // The PublishDuplicateRule request returns before the publish is completed,
            // so we keep retrieving the async job state until it is "Completed"
            Console.WriteLine("  Checking to see if duplicate detection rule has finished publishing");
            WaitForAsyncJobToFinish(service, publishResponse.JobId, 120);
        }
Esempio n. 5
0
        private void TsbTransferDupeRulesClick(object sender, EventArgs e)
        {
            if (lvDedupeRules.SelectedItems.Count > 0 && AdditionalConnectionDetails.Count > 0)
            {
                var selectedRules = lvDedupeRules.SelectedItems.Cast <ListViewItem>().Select(item => (IGrouping <Guid, Entity>)item.Tag).ToList();

                lbLogs.Items.Clear();
                tsbLoadDupeRules.Enabled     = false;
                tsbTransferDupeRules.Enabled = false;
                btnSelectTarget.Enabled      = false;
                Cursor = Cursors.WaitCursor;

                var worker = new BackgroundWorker();
                worker.DoWork += (s, evt) =>
                {
                    var selections    = (List <IGrouping <Guid, Entity> >)evt.Argument;
                    var total         = selections.Count;
                    var current       = 0;
                    var targetService = AdditionalConnectionDetails.First().GetCrmServiceClient();

                    foreach (var ruleGroup in selections)
                    {
                        current++;

                        string name = ruleGroup.First().GetAttributeValue <string>("name");

                        SendMessageToStatusBar(this,
                                               new StatusBarMessageEventArgs(current * 100 / total, "Processing rule '" + name + "'..."));

                        try
                        {
                            var ruleToTransfer = new Entity(ruleGroup.First().LogicalName);
                            foreach (var attribute in ruleGroup.First().Attributes)
                            {
                                // skip related condition records
                                if (!attribute.Key.StartsWith("condition."))
                                {
                                    ruleToTransfer[attribute.Key] = attribute.Value;
                                }
                            }

                            // Delete existing conditions (or delete entire rule)
                            Guid existingId = _drManager.DedupeRuleExists(targetService, name);
                            if (existingId != Guid.Empty)
                            {
                                ruleToTransfer["duplicateruleid"] = existingId;

                                targetService.Delete(ruleToTransfer.LogicalName, existingId);
                            }

                            existingId = targetService.Create(ruleToTransfer);
                            ruleToTransfer["duplicateruleid"] = existingId;

                            // iterate conditions and apply those
                            foreach (var condition in ruleGroup)
                            {
                                var dedupeCondition = new Entity("duplicaterulecondition")
                                {
                                    ["regardingobjectid"] =
                                        new EntityReference(ruleToTransfer.LogicalName, existingId)
                                };
                                foreach (var attribute in condition.Attributes)
                                {
                                    // only use related condition records
                                    if (attribute.Key.StartsWith("condition.") && !attribute.Key.EndsWith(".duplicateruleconditionid"))
                                    {
                                        dedupeCondition[attribute.Key.Replace("condition.", String.Empty)] = ((AliasedValue)attribute.Value).Value;
                                    }
                                }

                                targetService.Create(dedupeCondition);
                            }

                            // publish if source as also pubished
                            if (ruleGroup.First().GetAttributeValue <OptionSetValue>("statecode").Value == 1) // active
                            {
                                PublishDuplicateRuleRequest publishReq = new PublishDuplicateRuleRequest
                                {
                                    DuplicateRuleId = existingId
                                };
                                targetService.Execute(publishReq);
                            }

                            Log(name, true);
                        }
                        catch (Exception error)
                        {
                            Log(name, false, error.Message);
                        }
                    }
                };
                worker.ProgressChanged += (s, evt) =>
                {
                    SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(0, evt.UserState.ToString()));
                };
                worker.RunWorkerCompleted += (s, evt) =>
                {
                    if (evt.Error != null)
                    {
                        MessageBox.Show(ParentForm, @"An error has occured while transferring dedupe rules: " + evt.Error.Message, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    tsbLoadDupeRules.Enabled     = true;
                    tsbTransferDupeRules.Enabled = true;
                    btnSelectTarget.Enabled      = true;
                    Cursor = Cursors.Default;

                    SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(string.Empty));
                };
                worker.WorkerReportsProgress = true;
                worker.RunWorkerAsync(selectedRules);
            }
            else
            {
                MessageBox.Show(@"You have to select at least one source dedupe rule and a target organisation to continue.", @"Warning",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            #region Creating Accounts

            String accountName = "Contoso, Ltd";
            String websiteUrl = "http://www.contoso.com/";

            Console.WriteLine("  Creating duplicate records (Account name={0}, Website URL={1})", accountName, 
                websiteUrl);
            // Create some duplicate records
            for (int i = 0; i < 2; i++)
            {
                Account account = new Account()
                {
                    Name = accountName,
                    WebSiteURL = websiteUrl
                };
                account.Id = _serviceProxy.Create(account);
                _duplicateAccounts[i] = account;
            }

            accountName = "Contoso Pharmaceuticals";
            Console.WriteLine("  Creating a non-duplicate record (Account name={0}, Website URL={1})", 
                accountName, websiteUrl);
            // Create a record that is NOT a duplicate
            Account distinctAccount = new Account()
            {
                Name = accountName,
                WebSiteURL = websiteUrl
            };
            distinctAccount.Id = _serviceProxy.Create(distinctAccount);
            _account = distinctAccount;

            #endregion

            #region Create and Publish duplicate detection rule

            Console.WriteLine("  Creating a duplicate detection rule");
            // Create a duplicate detection rule
            _rule = new DuplicateRule()
            {
                Name = "Accounts with the same Account name and website url",
                BaseEntityName = Account.EntityLogicalName,
                MatchingEntityName = Account.EntityLogicalName
            };
            _rule.Id = _serviceProxy.Create(_rule);

            // Create a duplicate detection rule condition
            DuplicateRuleCondition nameCondition = new DuplicateRuleCondition()
            {
                BaseAttributeName = "name",
                MatchingAttributeName = "name",
                OperatorCode = new OptionSetValue(0), // value 0 = 'exact match'
                // set the regarding id to point to the rule created earlier,
                // associating this condition with that rule
                RegardingObjectId = _rule.ToEntityReference()
            };
            _serviceProxy.Create(nameCondition);

            DuplicateRuleCondition websiteCondition = new DuplicateRuleCondition()
            {
                BaseAttributeName = "websiteurl",
                MatchingAttributeName = "websiteurl",
                OperatorCode = new OptionSetValue(0),
                RegardingObjectId = _rule.ToEntityReference()
            };
            _serviceProxy.Create(websiteCondition);

            Console.WriteLine("  Publishing duplicate detection rule");
            // Publish the rule
            PublishDuplicateRuleRequest publishRequest = new PublishDuplicateRuleRequest()
            {
                DuplicateRuleId = _rule.Id
            };
            PublishDuplicateRuleResponse publishResponse = (PublishDuplicateRuleResponse)_serviceProxy.Execute(publishRequest);

            // The PublishDuplicateRule request returns before the publish is completed,
            // so we keep retrieving the async job state until it is "Completed"
            Console.WriteLine("  Checking to see if duplicate detection rule has finished publishing");
            WaitForAsyncJobToFinish(publishResponse.JobId, 60);

            #endregion
        }