public IsValidResponse Validate()
 {
     var service = new XrmService(this);
     var response = service.VerifyConnection();
     var actualResponse = new IsValidResponse();
     foreach (var item in response.InvalidReasons)
         actualResponse.AddInvalidReason(item);
     return actualResponse;
 }
 private void ValidateQueuesHaveEmailPopulated()
 {
     if (IsMessage(PluginMessage.Create, PluginMessage.Update) && IsStage(PluginStage.PreOperationEvent))
     {
         var queueFields = QueueFields;
         foreach (var queueField in queueFields)
         {
             if (FieldChanging(queueField))
             {
                 var queueId = GetLookupGuid(queueField);
                 if (queueId.HasValue)
                 {
                     var mailbox = XrmService.Retrieve(Entities.queue, queueId.Value, new[] { Fields.queue_.emailaddress });
                     if (string.IsNullOrWhiteSpace(mailbox.GetStringField(Fields.queue_.emailaddress)))
                     {
                         throw new NullReferenceException(string.Format("{0} Does Not Have It's Email Address Populated", GetFieldLabel(queueField)));
                     }
                 }
             }
         }
     }
 }
示例#3
0
        public void RetrieveAllOrClauseTest()
        {
            Assert.Inconclusive("Costly test so escaping");

            PrepareTests();
            var orFilters = new List <FilterExpression>();

            for (var i = 0; i < 1000; i++)
            {
                var entity = new Entity(Entities.jmcg_testentity);
                entity.SetField("new_testentitycode", i + "Blah" + i);
                entity.SetField(Fields.jmcg_testentity_.jmcg_string, i + "Blah Blah" + i);
                XrmService.Create(entity);
                var filter = new FilterExpression();
                filter.AddCondition("new_testentitycode", ConditionOperator.Equal, i + "Blah" + i);
                filter.AddCondition(Fields.jmcg_testentity_.jmcg_string, ConditionOperator.Equal, i + "Blah Blah" + i);
                orFilters.Add(filter);
            }
            var entities = XrmService.RetrieveAll(Entities.jmcg_testentity, orFilters);

            Assert.IsTrue(entities.Count() == 1000);
        }
示例#4
0
        private void CreateRecords(string type, int numberToCreate)
        {
            var setSize       = 100;
            var numberCreated = 0;

            while (numberCreated < numberToCreate)
            {
                var creates = new System.Collections.Generic.List <Entity>();
                for (var i = 0; i < setSize; i++)
                {
                    var entity = new Entity(type);
                    entity.SetField(XrmService.GetPrimaryNameField(type), "Test Record " + i);
                    creates.Add(entity);
                    numberCreated++;
                    if (numberCreated >= numberToCreate)
                    {
                        break;
                    }
                }
                XrmService.CreateMultiple(creates);
            }
        }
        private IEnumerable <Entity> GetfailedJobs()
        {
            var lastFailure = Target.GetDateTimeField(Fields.jmcg_workflowtask_.jmcg_minimumtargetfailuredatetime)
                              ?? new DateTime(1910, 01, 01);
            var targetWorkflow = Target.GetLookupGuid(Fields.jmcg_workflowtask_.jmcg_targetworkflow)
                                 ?? Guid.Empty;

            var lastFailedJobQuery = XrmService.BuildQuery(Entities.asyncoperation,
                                                           GetFieldsToDisplayInNotificationEmail(),
                                                           new[]
            {
                new ConditionExpression(Fields.asyncoperation_.statuscode, ConditionOperator.Equal,
                                        OptionSets.SystemJob.StatusReason.Failed),
                new ConditionExpression(Fields.asyncoperation_.modifiedon, ConditionOperator.GreaterThan,
                                        lastFailure)
            }, null);
            var workflowLink = lastFailedJobQuery.AddLink(Entities.workflow, Fields.asyncoperation_.workflowactivationid,
                                                          Fields.workflow_.workflowid);

            workflowLink.LinkCriteria.AddCondition(new ConditionExpression(Fields.workflow_.parentworkflowid, ConditionOperator.Equal, targetWorkflow));
            return(XrmService.RetrieveFirstX(lastFailedJobQuery, HtmlEmailGenerator.MaximumNumberOfEntitiesToList + 1)); //add 1 to determine if exceeded the limit
        }
示例#6
0
        public Entity CreateAndRetrieve(Entity entity, XrmService useService = null)
        {
            useService = useService ?? XrmService;
            var primaryField = useService.GetPrimaryNameField(entity.LogicalName);

            if (!entity.Contains(primaryField))
            {
                entity.SetField(primaryField, "Test Record " + DateTime.Now.ToFileTimeUtc());
            }
            switch (entity.LogicalName)
            {
            case "sla":
            {
                if (!entity.Contains("applicablefrom"))
                {
                    entity.SetField("applicablefrom", "?");
                }
                break;
            }
            }
            return(useService.CreateAndRetreive(entity));
        }
        protected Entity CreateAccount()
        {
            var entity        = new Entity(Entities.account);
            var maxNameLength = XrmService.GetMaxLength(Fields.account_.name, Entities.account);

            entity.SetField(Fields.account_.name, "Test Account - " + DateTime.Now.ToLocalTime());
            entity.SetField(Fields.account_.fax, "0999999999fax");
            entity.SetField(Fields.account_.telephone1, "0999999999");
            entity.SetField(Fields.account_.emailaddress1, "*****@*****.**");
            entity.SetField(Fields.account_.address1_line1, "100 Collins St");
            entity.SetField(Fields.account_.address1_city, "Melbourne");
            entity.SetField(Fields.account_.address1_stateorprovince, "VIC");
            entity.SetField(Fields.account_.address1_postalcode, "3000");
            Entity contact = CreateContact(null);

            entity.SetLookupField(Fields.account_.primarycontactid, contact);

            var account = CreateAndRetrieve(entity);

            contact.SetLookupField(Fields.contact_.parentcustomerid, account);
            XrmService.Update(contact, new[] { Fields.contact_.parentcustomerid });
            return(account);
        }
示例#8
0
        public void LogEntityError(Entity entity, Exception ex)
        {
            if (_fieldsToRetry.ContainsKey(entity))
            {
                _fieldsToRetry.Remove(entity);
                Response.RemoveFieldForRetry(entity);
            }
            var field = AltMatchKeyDictionary.ContainsKey(entity.LogicalName)
                ? string.Join("|", AltMatchKeyDictionary[entity.LogicalName])
                : null;
            var value = AltMatchKeyDictionary.ContainsKey(entity.LogicalName)
                ? string.Join("|", AltMatchKeyDictionary[entity.LogicalName].Select(k => XrmService.GetFieldAsDisplayString(entity.LogicalName, k, entity.GetField(k))))
                : null;
            var rowNumber = entity.Contains("Sheet.RowNumber")
                ? entity.GetInt("Sheet.RowNumber")
                : (int?)null;
            var primaryField = XrmService.GetPrimaryNameField(entity.LogicalName);

            Response.AddImportError(entity,
                                    new DataImportResponseItem(entity.LogicalName, field, entity.GetStringField(primaryField), value,
                                                               ex.Message + (entity.Id != Guid.Empty ? " Id=" + entity.Id : ""),
                                                               ex, rowNumber: rowNumber));
        }
示例#9
0
 private void PicklistTest()
 {
     /*
      * Picklist field
      * */
     //Valid values
     Assert.IsTrue(
         XrmEntity.GetOptionSetValue(XrmService.ParseField(Fields.jmcg_testentity_.jmcg_picklist, Entities.jmcg_testentity, "Option 1")) ==
         OptionSets.TestEntity.Picklist.Option1);
     Assert.IsTrue(
         XrmEntity.GetOptionSetValue(XrmService.ParseField(Fields.jmcg_testentity_.jmcg_picklist, Entities.jmcg_testentity,
                                                           OptionSets.TestEntity.Picklist.Option1)) ==
         OptionSets.TestEntity.Picklist.Option1);
     try
     {
         var blah = XrmService.ParseField(Fields.jmcg_testentity_.jmcg_picklist, Entities.jmcg_testentity, "NOTANOPTION");
         Assert.Fail();
     }
     catch (Exception ex)
     {
         CheckException(ex);
     }
 }
示例#10
0
        public void PrepareTests(bool testComponentsRequired = false)
        {
            var verifyConnection = XrmService.VerifyConnection();

            if (!verifyConnection.IsValid)
            {
                Assert.Inconclusive("Could Not Connect To Crm Instance To Execute Tests {0}",
                                    verifyConnection.GetErrorString());
            }

            if (testComponentsRequired)
            {
                var testComponentSolutionName = "TestComponents";
                var solution = XrmService.GetFirst("solution", "uniquename", testComponentSolutionName);
                if (solution == null)
                {
                    throw new NullReferenceException(
                              string.Format(
                                  "Required solution {0} located in Solution Items is not installed in the CRM instance. You will need to install it and rerun the test",
                                  testComponentSolutionName));
                }
            }
        }
示例#11
0
        private IEnumerable <XrmAutonumber> GetAutonumbers(IEnumerable <ConditionExpression> conditions)
        {
            var query = new QueryExpression(Entities.jmcg_autonumber);

            query.ColumnSet = new ColumnSet(true);
            if (conditions != null)
            {
                foreach (var item in conditions)
                {
                    query.Criteria.AddCondition(item);
                }
            }

            var link = query.AddLink(Entities.jmcg_autonumber, Fields.jmcg_autonumber_.jmcg_parentautonumber,
                                     Fields.jmcg_autonumber_.jmcg_autonumberid);

            link.JoinOperator = JoinOperator.LeftOuter;
            link.EntityAlias  = ParentAlias;
            link.Columns      = new ColumnSet(true);
            return(XrmService.RetrieveAll(query)
                   .Select(e => new XrmAutonumber(e))
                   .ToArray());
        }
示例#12
0
        private void PublishImpl(XrmService context, VersioningService gitvc, DeployConfigurationModel deployConfiguration, TelemetryWrapper telemetry, RawChanges[] changes, string project)
        {
            try
            {
                ChangeManagerService container = new ChangeManagerService(changes, deployConfiguration.Prefix, context);
                telemetry.TrackCustomEventWithCustomMetrics("Deploy Started", new MetricData("Project Name", project));

                if (container.WebResources.Count > 0)
                {
                    ReportProgress?.Invoke(this, $"[DYNAMICS] => Found {container.WebResources.Count} Web Resource.");
                    ReportProgress?.Invoke(this, $"[DYNAMICS] => '{deployConfiguration.Prefix}' used as base path.");
                    ReportProgress?.Invoke(this, $"[DYNAMICS] => Fetching '{deployConfiguration.Solution}' solution from CRM.");
                    container.EnsureContinue(deployConfiguration.Solution, deployConfiguration.Prefix);

                    ReportProgress?.Invoke(this, $"[DYNAMICS] => Publishing changes to the CRM.");
                    var faultedFlushResult = context.Flush(container.BuildRequestList(deployConfiguration.Solution));

                    if (!faultedFlushResult && deployConfiguration.CheckInEnabled)
                    {
                        ReportProgress?.Invoke(this, $"[AZOPS] => Commit & Push in progress.");
                        gitvc.CommitAndPush(deployConfiguration.Password);
                    }

                    ReportProgress?.Invoke(this, $"[AZOPS] => Publish completed.");
                }

                telemetry.TrackCustomEventWithCustomMetrics("Deploy Finished", new MetricData("Project Name", project));
            }
            catch (Exception exception)
            {
                ReportProgress?.Invoke(this, $"[ERROR] => {exception.Message}\n");
                if (!(exception is ToolkitException))
                {
                    telemetry.TrackExceptionWithCustomMetrics(exception);
                }
            }
        }
        protected override void Execute()
        {
            var failedJobs    = GetfailedJobs();
            var hasNewFailure = failedJobs.Any();

            ActivityThisType.HasNewFailures.Set(ExecutionContext, hasNewFailure);
            if (hasNewFailure && Target.GetBoolean(Fields.jmcg_workflowtask_.jmcg_sendnotificationfortargetfailures))
            {
                var recipientQueue = Target.GetLookupGuid(Fields.jmcg_workflowtask_.jmcg_sendfailurenotificationsto);
                if (!recipientQueue.HasValue)
                {
                    throw new NullReferenceException(string.Format("Error required field {0} is empty on the target {1}", XrmService.GetFieldLabel(Fields.jmcg_workflowtask_.jmcg_sendfailurenotificationsto, TargetType), XrmService.GetEntityLabel(TargetType)));
                }

                var crmUrl = GetCrmURL();
                var email  = new HtmlEmailGenerator(XrmService, crmUrl, null);
                email.AppendParagraph(string.Format("This is an automated notification that workflows triggered by the {0} named '{1}' have failed. You will need to review the failures to fix any issues"
                                                    , XrmService.GetEntityLabel(TargetType)
                                                    , Target.GetStringField(Fields.jmcg_workflowtask_.jmcg_name)));
                var notes = Target.GetStringField(Fields.jmcg_workflowtask_.jmcg_notesfortargetfailureemail);
                if (!string.IsNullOrWhiteSpace(notes))
                {
                    email.AppendParagraph(notes.Replace("\n", "<br />"));
                }
                if (!string.IsNullOrWhiteSpace(crmUrl))
                {
                    email.AppendParagraph(email.CreateHyperlink(email.CreateUrl(Target), "Open " + XrmService.GetEntityLabel(TargetType)));
                }
                email.AppendTable(failedJobs, LocalisationService, GetFieldsToDisplayInNotificationEmail());

                var subject = XrmService.GetEntityLabel(TargetType) + " Target Failures: " + Target.GetStringField(Fields.jmcg_workflowtask_.jmcg_name);
                SendNotificationEmail(Entities.queue, recipientQueue.Value, subject, email.GetContent());

                Target.SetField(Fields.jmcg_workflowtask_.jmcg_minimumtargetfailuredatetime, DateTime.UtcNow);
                XrmService.Update(Target, new[] { Fields.jmcg_workflowtask_.jmcg_minimumtargetfailuredatetime });
            }
        }
示例#14
0
        /// <summary>
        /// Returns list of key values giving the types and field name parsed for the given string of field joins
        /// key = type, value = field
        /// </summary>
        /// <param name="xrmService"></param>
        /// <param name="fieldPath"></param>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        public static IEnumerable <KeyValuePair <string, string> > GetTypeFieldPath(this XrmService xrmService, string fieldPath, string sourceType)
        {
            var list             = new List <KeyValuePair <string, string> >();
            var splitOutFunction = fieldPath.Split(':');

            if (splitOutFunction.Count() > 1)
            {
                fieldPath = splitOutFunction.ElementAt(1);
            }
            var split       = fieldPath.Split('.');
            var currentType = sourceType;

            list.Add(new KeyValuePair <string, string>(currentType, split.ElementAt(0).Split('|').First()));
            var i = 1;

            if (split.Length > 1)
            {
                foreach (var item in split.Skip(1).Take(split.Length - 1))
                {
                    var fieldName = item.Split('|').First();
                    if (split.ElementAt(i - 1).Contains("|"))
                    {
                        var targetType = split.ElementAt(i - 1).Split('|').Last();
                        list.Add(new KeyValuePair <string, string>(targetType, fieldName));
                        currentType = targetType;
                    }
                    else
                    {
                        var targetType = xrmService.GetLookupTargetEntity(list.ElementAt(i - 1).Value, currentType);
                        list.Add(new KeyValuePair <string, string>(targetType, fieldName));
                        currentType = targetType;
                    }
                    i++;
                }
            }
            return(list);
        }
示例#15
0
        private void DoubleTest()
        {
            /*
             * Double field
             * */
            var maxDoubleValue = (double)XrmService.GetMaxDoubleValue(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity);
            var minDoubleValue = (double)XrmService.GetMinDoubleValue(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity);

            //Valid values
            Assert.IsTrue((double)XrmService.ParseField(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity, maxDoubleValue) ==
                          maxDoubleValue);
            Assert.IsTrue((double)XrmService.ParseField(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity, minDoubleValue) ==
                          minDoubleValue);
            Assert.IsTrue((double)XrmService.ParseField(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity, (double)5) == 5);
            Assert.IsTrue((double)XrmService.ParseField(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity, "20") == 20);
            //Outside range values
            try
            {
                var blah = XrmService.ParseField(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity, maxDoubleValue + 1);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                CheckException(ex);
            }

            try
            {
                var blah = XrmService.ParseField(Fields.jmcg_testentity_.jmcg_float, Entities.jmcg_testentity, minDoubleValue - 1);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                CheckException(ex);
            }
        }
示例#16
0
        private void StringTest()
        {
            /*
             * String field
             * */
            //
            var maxTextLength = XrmService.GetMaxLength(Fields.jmcg_testentity_.jmcg_string, Entities.jmcg_testentity);
            //Valid values
            var validString = ReplicateString("X", maxTextLength);

            Assert.IsTrue((string)XrmService.ParseField(Fields.jmcg_testentity_.jmcg_string, Entities.jmcg_testentity, validString) == validString);
            //invalid value
            var exceedLength = ReplicateString("X", maxTextLength + 1);

            try
            {
                var blah = XrmService.ParseField(Fields.jmcg_testentity_.jmcg_string, Entities.jmcg_testentity, exceedLength);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                CheckException(ex);
            }
        }
        private void AddReferenceConfigJoins(LinkEntity linkToReferenced, Entity thisEntity, string field)
        {
            var referencedType       = XrmEntity.GetLookupType(thisEntity.GetFieldValue(field));
            var referencedTypeConfig = XrmRecordService.GetTypeConfigs().GetFor(referencedType);

            if (referencedTypeConfig != null && referencedTypeConfig.UniqueChildFields != null)
            {
                foreach (var uniqueField in referencedTypeConfig.UniqueChildFields)
                {
                    var theValue = thisEntity.GetFieldValue($"{field}.{uniqueField}");
                    if (theValue == null)
                    {
                        linkToReferenced.LinkCriteria.AddCondition(new ConditionExpression(uniqueField, ConditionOperator.Null));
                    }
                    else if (theValue is EntityReference)
                    {
                        var name = XrmEntity.GetLookupName(theValue);
                        var type = XrmEntity.GetLookupType(theValue);
                        var nextLinkToReferenced = linkToReferenced.AddLink(type, uniqueField, XrmService.GetPrimaryKeyField(type));
                        if (name == null)
                        {
                            nextLinkToReferenced.LinkCriteria.AddCondition(XrmService.GetPrimaryNameField(type), ConditionOperator.Null);
                        }
                        else
                        {
                            nextLinkToReferenced.LinkCriteria.AddCondition(XrmService.GetPrimaryNameField(type), ConditionOperator.Equal, name);
                            AddReferenceConfigJoins(nextLinkToReferenced, thisEntity, $"{field}.{uniqueField}");
                        }
                    }
                    else
                    {
                        linkToReferenced.LinkCriteria.AddCondition(new ConditionExpression(uniqueField, ConditionOperator.Equal, XrmService.ConvertToQueryValue(uniqueField, referencedType, theValue)));
                    }
                }
            }
        }
示例#18
0
 static void Main(string[] args)
 {
     try
     {
         var settings = new ConsoleSettings(new[]
         {
             new ConsoleSettings.SettingFile(typeof(XrmSetting)),
         });
         if (!settings.ConsoleArgs(args))
         {
             var xrmSetting = settings.Resolve <XrmSetting>();
             var controller = new LogController();
             controller.AddUi(new ConsoleUserInterface(false));
             var xrmService = new XrmService(xrmSetting, controller);
             var me         = xrmService.WhoAmI();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.XrmDisplayString());
     }
     Console.WriteLine("Press Any Key To Close");
     Console.ReadKey();
 }
        public virtual Entity CreateAndRetrieve(Entity entity, XrmService xrmService = null)
        {
            if (xrmService == null)
            {
                xrmService = XrmService;
            }
            var primaryField = xrmService.GetPrimaryField(entity.LogicalName);

            if (!entity.Contains(primaryField))
            {
                entity.SetField(primaryField, ("Test Scripted Record" + DateTime.UtcNow.ToFileTime()).Left(xrmService.GetMaxLength(primaryField, entity.LogicalName)));
            }
            if (entity.LogicalName == Entities.contact && !entity.Contains(Fields.contact_.firstname))
            {
                entity.SetField(Fields.contact_.firstname, "Test");
            }
            if (entity.LogicalName == Entities.lead && !entity.Contains(Fields.lead_.firstname))
            {
                entity.SetField(Fields.lead_.firstname, "Test");
            }
            var id = xrmService.Create(entity);

            return(xrmService.Retrieve(entity.LogicalName, id));
        }
        public ImportSolutionsResponse ImportSolutions(Dictionary <string, byte[]> solutionFiles, LogController controller)
        {
            var response = new ImportSolutionsResponse();

            var  xrmService = XrmRecordService.XrmService;
            bool asynch     = xrmService.SupportsExecuteAsynch;

            controller.LogLiteral($"Loading Active {xrmService.GetEntityCollectionName(Entities.duplicaterule)}");
            var duplicateRules = xrmService.RetrieveAllAndClauses(Entities.duplicaterule, new[] { new ConditionExpression(Fields.duplicaterule_.statecode, ConditionOperator.Equal, OptionSets.DuplicateDetectionRule.Status.Active) }, new string[0]);

            foreach (var solutionFile in solutionFiles)
            {
                if (!response.Success)
                {
                    break;
                }
                try
                {
                    controller.LogLiteral(
                        $"Importing Solution {solutionFile.Key} Into {XrmRecordService.XrmRecordConfiguration?.ToString()}");
                    var importId = Guid.NewGuid();
                    var req      = new ImportSolutionRequest();
                    req.ImportJobId       = importId;
                    req.CustomizationFile = solutionFile.Value;
                    req.PublishWorkflows  = true;
                    req.OverwriteUnmanagedCustomizations = true;

                    var finished = new Processor();

                    if (!asynch)
                    {
                        try
                        {
                            var extraService           = new XrmService(xrmService.XrmConfiguration, new LogController(), xrmService.ServiceFactory);
                            var monitoreProgressThread = new Thread(() => DoProgress(importId, controller.GetLevel2Controller(), finished, extraService, asynch, solutionFile.Key, response));
                            monitoreProgressThread.IsBackground = true;
                            monitoreProgressThread.Start();
                            xrmService.Execute(req);
                            ProcessCompletedSolutionImportJob(response, xrmService, importId);
                        }
                        finally
                        {
                            lock (_lockObject)
                                finished.Completed = true;
                        }
                    }
                    else
                    {
                        var asynchRequest = new ExecuteAsyncRequest
                        {
                            Request = req
                        };
                        xrmService.Execute(asynchRequest);
                        DoProgress(importId, controller.GetLevel2Controller(), finished, xrmService, asynch, solutionFile.Key, response);
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    if (ex.Detail != null && ex.Detail.InnerFault != null && ex.Detail.InnerFault.InnerFault != null)
                    {
                        throw new Exception(string.Format("Error Importing Solution {0}\n{1}\n{2}", solutionFile, ex.Message, ex.Detail.InnerFault.InnerFault.Message), ex);
                    }
                    else
                    {
                        throw new Exception(
                                  string.Format("Error Importing Solution {0}\n{1}", solutionFile, ex.Message), ex);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error Importing Solution {0}", solutionFile), ex);
                }
            }
            controller.TurnOffLevel2();

            if (response.Success)
            {
                controller.LogLiteral("Publishing Customisations");
                xrmService.Publish();
            }

            controller.LogLiteral($"Checking Deactivated {xrmService.GetEntityCollectionName(Entities.duplicaterule)}");
            duplicateRules = xrmService.Retrieve(Entities.duplicaterule, duplicateRules.Select(e => e.Id), new[] { Fields.duplicaterule_.statecode, Fields.duplicaterule_.name });
            foreach (var rule in duplicateRules)
            {
                if (rule.GetOptionSetValue(Fields.duplicaterule_.statecode) == OptionSets.DuplicateDetectionRule.Status.Inactive)
                {
                    controller.LogLiteral($"Republishing {xrmService.GetEntityLabel(Entities.duplicaterule)} '{rule.GetStringField(Fields.duplicaterule_.name)}'");
                    xrmService.Execute(new PublishDuplicateRuleRequest()
                    {
                        DuplicateRuleId = rule.Id
                    });
                }
            }
            return(response);
        }
        public void DeploymentMigrateRecordsMatchByNameTest()
        {
            var migrateName = "MIGRATESCRIPTNAME";

            DeleteAll(Entities.account);
            var account1 = CreateTestRecord(Entities.account);

            account1.SetField(Fields.account_.name, migrateName);
            account1 = UpdateFieldsAndRetreive(account1, Fields.account_.name);
            var account2 = CreateTestRecord(Entities.account);

            account2.SetField(Fields.account_.name, migrateName);
            account2 = UpdateFieldsAndRetreive(account2, Fields.account_.name);

            var altConnection = GetAltSavedXrmRecordConfiguration();
            var altService    = new XrmRecordService(altConnection, ServiceFactory);
            var accountsAlt   = altService.RetrieveAllAndClauses(Entities.account, null);

            foreach (var account in accountsAlt)
            {
                altService.Delete(account);
            }

            var application = CreateAndLoadTestApplication <MigrateRecordsModule>();

            var instance = new MigrateRecordsRequest();

            instance.SourceConnection = GetSavedXrmRecordConfiguration();
            instance.TargetConnection = GetAltSavedXrmRecordConfiguration();
            instance.IncludeNotes     = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.MatchByName          = false;
            instance.RecordTypesToMigrate = new[]
            {
                new ExportRecordType()
                {
                    Type             = ExportType.AllRecords,
                    RecordType       = new RecordType(Entities.account, Entities.account),
                    IncludeAllFields = true,
                }
            };

            var response = application.NavigateAndProcessDialog <MigrateRecordsModule, MigrateRecordsDialog, MigrateRecordsResponse>(instance);

            if (response.HasError)
            {
                Assert.Fail(response.GetResponseItemsWithError().First().Exception.XrmDisplayString());
            }
            var summary = response.ImportSummary;

            Assert.AreEqual(1, summary.Count());

            Assert.AreEqual(2, summary.First().Created);

            accountsAlt = altService.RetrieveAllAndClauses(Entities.account, null);
            Assert.AreEqual(2, accountsAlt.Count());

            XrmService.Delete(account1);
            altService.Delete(accountsAlt.First(a => a.Id != account1.Id.ToString()));

            instance = new MigrateRecordsRequest();
            instance.SourceConnection = GetSavedXrmRecordConfiguration();
            instance.TargetConnection = GetAltSavedXrmRecordConfiguration();
            instance.IncludeNotes     = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.MatchByName          = true;
            instance.RecordTypesToMigrate = new[]
            {
                new ExportRecordType()
                {
                    Type             = ExportType.AllRecords,
                    RecordType       = new RecordType(Entities.account, Entities.account),
                    IncludeAllFields = true,
                }
            };

            response = application.NavigateAndProcessDialog <MigrateRecordsModule, MigrateRecordsDialog, MigrateRecordsResponse>(instance);
            if (response.HasError)
            {
                Assert.Fail(response.GetResponseItemsWithError().First().Exception.XrmDisplayString());
            }

            summary = response.ImportSummary;
            Assert.AreEqual(1, summary.Count());
            Assert.AreEqual(1, summary.First().NoChange);

            accountsAlt = altService.RetrieveAllAndClauses(Entities.account, null);
            Assert.AreEqual(1, accountsAlt.Count());

            DeleteMyToday();
        }
        private void ProcessCompletedSolutionImportJob(ImportSolutionsResponse response, XrmService xrmService, Guid importId)
        {
            var job = xrmService.GetFirst(Entities.importjob, Fields.importjob_.importjobid, importId);

            if (job != null)
            {
                var ignoreTheseErrorCodes = new[]
                {
                    "0x80045042", //reactivated workflows
                    "0x8004F039", //reactivated plugins
                    "0x80045043"  //deactivated duplicate detection rules - these get activated in next set of code
                };
                var dataString  = job.GetStringField(Fields.importjob_.data);
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(dataString);
                var resultNodes = xmlDocument.GetElementsByTagName("result");
                foreach (XmlNode node in resultNodes)
                {
                    var importResult = new SolutionImportResult(node, XrmRecordService);
                    if (!importResult.IsSuccess && (importResult.ErrorCode == null || !ignoreTheseErrorCodes.Contains(importResult.ErrorCode)))
                    {
                        response.AddResult(importResult);
                    }
                }
            }
        }
        public void DoProgress(Guid importId, LogController controller, Processor finished, XrmService xrmService, bool asynch, string solutionFile, ImportSolutionsResponse response)
        {
            lock (_lockObject)
            {
                if (!finished.Completed)
                {
                    controller.UpdateProgress(0, 100, "Import Progress");
                }
            }
            while (true)
            {
                Thread.Sleep(5000);
                // connect to crm again, don't reuse the connection that's used to import
                lock (_lockObject)
                {
                    if (finished.Completed)
                    {
                        return;
                    }
                }
                try
                {
                    var job = xrmService.GetFirst(Entities.importjob, Fields.importjob_.importjobid, importId);
                    if (job != null)
                    {
                        if (job.GetDateTimeField(Fields.importjob_.completedon).HasValue)
                        {
                            break;
                        }
                        var progress = job.GetDoubleValue(Fields.importjob_.progress);
                        lock (_lockObject)
                        {
                            if (finished.Completed)
                            {
                                break;
                            }
                            controller.UpdateProgress(Convert.ToInt32(progress / 1), 100, "Import Progress");
                        }
                    }
                }

                catch (Exception ex)
                {
                    controller.LogLiteral("Unexpected Error " + ex.Message);
                }
            }

            if (asynch)
            {
                var completedJob = xrmService.GetFirst(Entities.importjob, Fields.importjob_.importjobid, importId);
                var xml          = completedJob.GetStringField(Fields.importjob_.data);
                if (xml != null)
                {
                    var xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(xml);
                    var percentCompleted = Double.Parse(xmlDocument.GetElementsByTagName("importexportxml")[0].Attributes["progress"].Value);
                    if (percentCompleted < 100)
                    {
                        var settings = new XmlWriterSettings {
                            Indent = true
                        };
                        var xmlStringBuilder = new StringBuilder();
                        using (var xmlTextWriter = XmlWriter.Create(xmlStringBuilder, settings))
                        {
                            xmlDocument.WriteTo(xmlTextWriter);
                            xmlTextWriter.Flush();
                        }
                        response.FailedSolution    = solutionFile;
                        response.FailedSolutionXml = xmlStringBuilder.ToString();
                    }
                    else
                    {
                        ProcessCompletedSolutionImportJob(response, xrmService, importId);
                    }
                }
            }
        }
示例#24
0
        public void DeploymentImportCsvsMatchKeysTest()
        {
            //okay this script imports a sheet using
            //account number as the match key

            //the initial import creates new records
            //though one of the five rows throws error due to missing account number (key)

            //the subsequent one only allows updates
            //and I delete one of the records imported to verify
            //it throws an extra error due to a missing key for update in the target

            PrepareTests();
            DeleteAll(Entities.account);

            var workFolder = TestingFolder + @"\CsvsImportScript";

            FileUtility.CheckCreateFolder(workFolder);
            var sourceCsvsFile = Path.Combine(workFolder, @"account.csv");

            File.Copy(@"AccountsWithKeys.csv", sourceCsvsFile);

            var app            = CreateAndLoadTestApplication <ImportCsvsModule>();
            var dialog         = app.NavigateToDialog <ImportCsvsModule, ImportCsvsDialog>();
            var entryViewmodel = app.GetSubObjectEntryViewModel(dialog);

            entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportCsvsRequest.MaskEmails)).Value = true;

            //add csv row and set it to the source csv
            var tabMappingsGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportCsvsRequest.CsvsToImport));

            tabMappingsGrid.DynamicGridViewModel.AddRow();
            var accountMap    = tabMappingsGrid.DynamicGridViewModel.GridRecords.First();
            var fileReference = accountMap.GetFieldViewModel <FileRefFieldViewModel>(nameof(ImportCsvsRequest.CsvToImport.SourceCsv));

            fileReference.Value = new FileReference(sourceCsvsFile);
            //okay on change trigger should have fired and populated mappings on contact
            //now add match key
            var keyMapsField = accountMap.GetEnumerableFieldViewModel(nameof(ImportCsvsRequest.CsvToImport.AltMatchKeys));

            keyMapsField.EditButton.Command.Execute();
            var altMatchKeyEntryForm = entryViewmodel.ChildForms.First() as ObjectEntryViewModel;

            Assert.IsNotNull(altMatchKeyEntryForm);
            altMatchKeyEntryForm.LoadFormSections();
            var mapsField = altMatchKeyEntryForm.GetEnumerableFieldViewModel(nameof(ImportCsvsRequest.CsvToImport.AltMatchKeys));

            mapsField.AddRow();
            var matchKeyField = mapsField.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportCsvsRequest.CsvToImport.CsvImportMatchKey.TargetField));

            Assert.IsTrue(matchKeyField.ItemsSource.Any());
            matchKeyField.Value = matchKeyField.ItemsSource.First(f => f.Key == Fields.account_.accountnumber);
            altMatchKeyEntryForm.SaveButtonViewModel.Invoke();
            Assert.IsFalse(entryViewmodel.ChildForms.Any());

            //run the import and verify response and account count
            entryViewmodel.SaveButtonViewModel.Invoke();
            var response = app.GetCompletionViewModel(dialog).GetObject() as ImportCsvsResponse;

            Assert.IsNotNull(response);

            Assert.AreEqual(1, response.GetResponseItemsWithError().Count());
            var accounts = XrmService.RetrieveAllEntityType(Entities.account);

            Assert.AreEqual(4, accounts.Count());

            //delete one of the imported accounts
            XrmService.Delete(accounts.First());
            //second import - this one only allows updates
            dialog         = app.NavigateToDialog <ImportCsvsModule, ImportCsvsDialog>();
            entryViewmodel = app.GetSubObjectEntryViewModel(dialog);
            entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportCsvsRequest.MaskEmails)).Value = true;
            entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportCsvsRequest.UpdateOnly)).Value = true;

            //add csv row and set it to the source csv
            tabMappingsGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportCsvsRequest.CsvsToImport));
            tabMappingsGrid.DynamicGridViewModel.AddRow();
            accountMap          = tabMappingsGrid.DynamicGridViewModel.GridRecords.First();
            fileReference       = accountMap.GetFieldViewModel <FileRefFieldViewModel>(nameof(ImportCsvsRequest.CsvToImport.SourceCsv));
            fileReference.Value = new FileReference(sourceCsvsFile);
            //okay on change trigger should have fired and populated mappings on contact
            //now add match key
            keyMapsField = accountMap.GetEnumerableFieldViewModel(nameof(ImportCsvsRequest.CsvToImport.AltMatchKeys));
            keyMapsField.EditButton.Command.Execute();
            altMatchKeyEntryForm = entryViewmodel.ChildForms.First() as ObjectEntryViewModel;
            Assert.IsNotNull(altMatchKeyEntryForm);
            altMatchKeyEntryForm.LoadFormSections();
            mapsField = altMatchKeyEntryForm.GetEnumerableFieldViewModel(nameof(ImportCsvsRequest.CsvToImport.AltMatchKeys));
            mapsField.AddRow();
            matchKeyField = mapsField.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportCsvsRequest.CsvToImport.CsvImportMatchKey.TargetField));
            Assert.IsTrue(matchKeyField.ItemsSource.Any());
            matchKeyField.Value = matchKeyField.ItemsSource.First(f => f.Key == Fields.account_.accountnumber);
            altMatchKeyEntryForm.SaveButtonViewModel.Invoke();
            Assert.IsFalse(entryViewmodel.ChildForms.Any());

            //run the import and verify response and account count
            entryViewmodel.SaveButtonViewModel.Invoke();

            response = app.GetCompletionViewModel(dialog).GetObject() as ImportCsvsResponse;
            Assert.IsNotNull(response);

            Assert.AreEqual(2, response.GetResponseItemsWithError().Count());
            accounts = XrmService.RetrieveAllEntityType(Entities.account);
            Assert.AreEqual(3, accounts.Count());
        }
        public void Debug()
        {
            var me = XrmService.WhoAmI();

            //var holidays = CalculatedService.GetPublicHolidays(new DateTime(2020, 4, 17, 0, 0, 0, DateTimeKind.Utc), new DateTime(2020, 4, 18, 0, 0, 0, DateTimeKind.Utc), ServiceCalendarId);
        }
 public void RefreshAggregate(Guid id, XrmService service, LogController controller)
 {
     var newValue = GetAggregate(id, service);
     controller.LogLiteral(string.Format("Refreshing Field {0} In {1} To Value {2}", AggregateField, RecordTypeWithAggregate, newValue));
     service.SetFieldIfChanging(RecordTypeWithAggregate, id, AggregateField, newValue);
 }
示例#27
0
        public void DeploymentImportCsvsTestProductsAndPricings()
        {
            //imports product configurations in csv files
            PrepareTests();
            var workFolder = ClearFilesAndData();

            File.Copy(@"Price List Items.csv", Path.Combine(workFolder, @"Price List Items.csv"));
            File.Copy(@"Price Lists.csv", Path.Combine(workFolder, @"Price Lists.csv"));
            File.Copy(@"Products.csv", Path.Combine(workFolder, @"Products.csv"));
            File.Copy(@"uom.csv", Path.Combine(workFolder, @"uom.csv"));
            File.Copy(@"uomschedule.csv", Path.Combine(workFolder, @"uomschedule.csv"));

            //lets delete all these items
            var products = CsvUtility
                           .SelectAllRows(Path.Combine(workFolder, @"Products.csv"))
                           .Select(r => r.GetFieldAsString("Name"))
                           .ToArray();

            DeleteAllMatchingName(Entities.product, products);
            var unitGroups = CsvUtility
                             .SelectAllRows(Path.Combine(workFolder, @"uomschedule.csv"))
                             .Select(r => r.GetFieldAsString("Name"))
                             .ToArray();

            DeleteAllMatchingName(Entities.uomschedule, unitGroups);
            var priceLists = CsvUtility
                             .SelectAllRows(Path.Combine(workFolder, @"Price Lists.csv"))
                             .Select(r => r.GetFieldAsString("Name"))
                             .ToArray();

            DeleteAllMatchingName(Entities.pricelevel, priceLists);

            //run the import and verify no errors
            var application = CreateAndLoadTestApplication <ImportCsvsModule>();
            var request     = new ImportCsvsRequest
            {
                CsvsToImport = new[]
                {
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Price List Items.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Price Lists.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Products.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"uom.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"uomschedule.csv"))
                    },
                },
                DateFormat = DateFormat.American
            };
            var response = application.NavigateAndProcessDialog <ImportCsvsModule, ImportCsvsDialog, ImportCsvsResponse>(request);

            Assert.IsFalse(response.HasError);

            //okay lets get the last created price list item
            var query = XrmService.BuildQuery(Entities.productpricelevel, null, null, null);

            query.Orders.Add(new OrderExpression(Fields.productpricelevel_.createdon, OrderType.Descending));
            var latestPriceListItem = XrmService.RetrieveFirst(query);
            //verify it has a price
            var initialPrice = latestPriceListItem.GetMoneyValue(Fields.productpricelevel_.amount);

            Assert.IsTrue(initialPrice > 0);
            //now lets set it something else so we can verify it gets updated after the second run
            latestPriceListItem.SetMoneyField(Fields.productpricelevel_.amount, initialPrice.Value + 1);
            latestPriceListItem = UpdateFieldsAndRetreive(latestPriceListItem, Fields.productpricelevel_.amount);

            //run again and verify no errors
            request = new ImportCsvsRequest
            {
                CsvsToImport = new[]
                {
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Price List Items.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Price Lists.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Products.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"uom.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"uomschedule.csv"))
                    },
                },
                DateFormat = DateFormat.American
            };
            response = application.NavigateAndProcessDialog <ImportCsvsModule, ImportCsvsDialog, ImportCsvsResponse>(request);
            Assert.IsFalse(response.HasError);
            //verify the price list item we updated is changed
            latestPriceListItem = Refresh(latestPriceListItem);
            Assert.AreEqual(initialPrice, latestPriceListItem.GetMoneyValue(Fields.productpricelevel_.amount));
        }
        public void RefreshRollup(Guid id, LookupRollup rollup)
        {
            var newValue = GetRollup(rollup, id);

            XrmService.SetFieldIfChanging(rollup.RecordTypeWithRollup, id, rollup.RollupField, newValue);
        }
 public RollupService(XrmService xrmService)
 {
     XrmService = xrmService;
 }
        public object GetAggregate(Guid id, XrmService service)
        {
            object newValue = null;

            switch (AggregateType)
            {
                case AggregateType.Exists:
                    {
                        //if the aggregate returns a result > 0 then one exists
                        var result = service.RetrieveAllFetch(GetLookupFetch(id));
                        newValue = result.Any() &&
                                   XrmEntity.GetInt(result.ElementAt(0).GetFieldValue(FetchAlias)) > 0;
                        break;
                    }
                case AggregateType.Count:
                    {
                        var result = service.RetrieveAllFetch(GetLookupFetch(id));
                        if (result.Any())
                            newValue = result.ElementAt(0).GetFieldValue(FetchAlias);
                        break;
                    }
                case AggregateType.Sum:
                    {
                        var result = service.RetrieveAllFetch(GetLookupFetch(id));
                        if (result.Any())
                            newValue = result.ElementAt(0).GetFieldValue(FetchAlias);
                        break;
                    }
                case AggregateType.Min:
                    {
                        var query = GetAggregatedRecordQueryForLookup(id);
                        query.AddOrder(AggregatedField, OrderType.Ascending);
                        var minRecord = service.RetrieveFirst(query);
                        newValue = minRecord.GetField(AggregatedField);
                        break;
                    }
                case AggregateType.CSV:
                case AggregateType.PSV:
                    {
                        var query = GetAggregatedRecordQueryForLookup(id);

                        query.AddOrder(AggregatedField, OrderType.Ascending);
                        var records = service.RetrieveAll(query);
                        var labels =
                            records.Select(
                                delegate(Entity item) { return item.GetField(AggregatedField); }).
                                ToArray();
                        if (AggregateType == AggregateType.CSV)
                            newValue = string.Join(", ", labels);
                        else
                            newValue = string.Join("|", labels);
                        newValue = ((string)newValue).Left(1000);
                        break;
                    }
            }
            if (newValue == null && NullAmount != null)
                newValue = NullAmount;
            return newValue;
        }
 public WorkflowSchedulerService(XrmService xrmService)
 {
     XrmService = xrmService;
 }
 public AutonumberService(XrmService xrmService)
 {
     XrmService = xrmService;
 }
        public object GetRollup(LookupRollup rollup, Guid id)
        {
            object newValue = null;

            switch (rollup.RollupType)
            {
            case RollupType.Exists:
            {
                //if the Rollup returns a result > 0 then one exists
                var fetch  = GetLookupFetch(rollup, id);
                var result = XrmService.Fetch(fetch);
                newValue = result.Any() &&
                           XrmEntity.GetInt(result.First().GetField(FetchAlias)) > 0;
                break;
            }

            case RollupType.Count:
            {
                var result = XrmService.Fetch(GetLookupFetch(rollup, id));
                if (result.Any())
                {
                    newValue = result.ElementAt(0).GetField(FetchAlias);
                }
                break;
            }

            case RollupType.Sum:
            {
                var result = XrmService.Fetch(GetLookupFetch(rollup, id));
                if (result.Any())
                {
                    newValue = result.ElementAt(0).GetField(FetchAlias);
                }
                break;
            }

            case RollupType.Min:
            {
                var query = GetRollupQueryForLookup(rollup, id);
                query.AddOrder(rollup.FieldRolledup, OrderType.Ascending);
                var minRecord = XrmService.RetrieveFirst(query);
                newValue = minRecord.GetField(rollup.FieldRolledup);
                break;
            }

            case RollupType.Max:
            {
                var query = GetRollupQueryForLookup(rollup, id);
                query.AddOrder(rollup.FieldRolledup, OrderType.Descending);
                var maxRecord = XrmService.RetrieveFirst(query);
                newValue = maxRecord.GetField(rollup.FieldRolledup);
                break;
            }

            case RollupType.Mean:
            {
                var result = XrmService.Fetch(GetLookupFetch(rollup, id));
                if (result.Any())
                {
                    newValue = result.ElementAt(0).GetField(FetchAlias);
                }
                break;
            }

            case RollupType.SeparatedStrings:
            {
                var query = GetRollupQueryForLookup(rollup, id);

                query.AddOrder(rollup.FieldRolledup, OrderType.Ascending);
                var records = XrmService.RetrieveAll(query);
                var labels  =
                    records.Select(e => e.GetField(rollup.FieldRolledup)).
                    ToArray();
                newValue = string.Join(rollup.SeparatorString, labels);
                break;
            }

            case RollupType.First:
            {
                var query = GetRollupQueryForLookup(rollup, id);
                query.AddOrder(rollup.OrderByField, rollup.OrderType);
                if (rollup.OrderByField != "createdon")
                {
                    query.AddOrder("createdon", OrderType.Descending);
                }
                var record = XrmService.RetrieveFirst(query);
                newValue = record.GetField(rollup.FieldRolledup);
                if (newValue is Guid g && rollup.ObjectType == typeof(EntityReference))
                {
                    newValue = new EntityReference(rollup.RecordTypeRolledup, g);
                }
                break;
            }
            }
            if (newValue == null && rollup.NullAmount != null)
            {
                newValue = rollup.NullAmount;
            }
            if (newValue != null && rollup.ObjectType != null)
            {
                if (rollup.ObjectType == typeof(decimal))
                {
                    newValue = Convert.ToDecimal(newValue.ToString());
                }
            }
            return(newValue);
        }
示例#34
0
        public void BulkSmsSendStaticTests()
        {
            var bulkSms = CreateTestRecord(Entities.jmcg_bulksms);

            //validate sms content populated when send
            try
            {
                bulkSms.SetField(Fields.jmcg_bulksms_.jmcg_sendmessages, true);
                bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_sendmessages);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex is AssertFailedException);
            }
            bulkSms.SetField(Fields.jmcg_bulksms_.jmcg_smscontent, "Test Script Bulk SMS Content");
            bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_smscontent);
            //validate marketing list populated when send
            try
            {
                bulkSms.SetField(Fields.jmcg_bulksms_.jmcg_sendmessages, true);
                bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_sendmessages);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex is AssertFailedException);
            }
            bulkSms.SetLookupField(Fields.jmcg_bulksms_.jmcg_marketinglist, TestAccountMarketingList);
            bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_marketinglist);
            //validate marketing list for contacts when send
            try
            {
                bulkSms.SetField(Fields.jmcg_bulksms_.jmcg_sendmessages, true);
                bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_sendmessages);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex is AssertFailedException);
            }
            //okay now set to a contact marketing list
            //should be valid for send
            //lets add a contact with a mobile number
            //and one without a mobile number
            bulkSms.SetLookupField(Fields.jmcg_bulksms_.jmcg_marketinglist, TestContactMarketingList);
            bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_marketinglist);
            //clear the contact list
            var marketingListMembers = XrmService.GetMarketingListMemberIds(TestContactMarketingList.Id);

            foreach (var memberId in marketingListMembers)
            {
                RemoveListMember(memberId, TestContactMarketingList.Id);
            }
            //add test contact with mobile number
            if (string.IsNullOrWhiteSpace(TestContact.GetStringField(Fields.contact_.mobilephone)))
            {
                TestContact.SetField(Fields.contact_.mobilephone, "0438570301");
                TestContact = UpdateFieldsAndRetreive(TestContact, Fields.contact_.mobilephone);
            }
            AddListMember(TestContact.Id, TestContactMarketingList.Id);
            //add test contact2 without mobile number
            if (!string.IsNullOrWhiteSpace(TestContact2.GetStringField(Fields.contact_.mobilephone)))
            {
                TestContact2.SetField(Fields.contact_.mobilephone, null);
                TestContact2 = UpdateFieldsAndRetreive(TestContact2, Fields.contact_.mobilephone);
            }
            AddListMember(TestContact2.Id, TestContactMarketingList.Id);
            //send sms including error
            bulkSms.SetField(Fields.jmcg_bulksms_.jmcg_sendmessages, true);
            bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_sendmessages);
            Assert.IsTrue(bulkSms.GetBoolean(Fields.jmcg_bulksms_.jmcg_sendingmessages));
            Assert.IsFalse(bulkSms.GetBoolean(Fields.jmcg_bulksms_.jmcg_sendmessages));
            WaitTillTrue(() => !Refresh(bulkSms).GetBoolean(Fields.jmcg_bulksms_.jmcg_sendingmessages), 60);

            var smsMessages = GetSmsMessagesSent(bulkSms);
            var smsErrors   = GetSmsErrorsActive(bulkSms);

            Assert.AreEqual(1, smsMessages.Count());
            Assert.AreEqual(TestContact.Id, smsMessages.First().GetActivityPartyReferences(Fields.jmcg_sms_.to).First().Id);
            Assert.AreEqual(1, smsErrors.Count());
            Assert.AreEqual(TestContact2.Id, smsErrors.First().GetLookupGuid(Fields.jmcg_bulksmserror_.jmcg_contact));

            //fix error and reprocess

            //populate mobile number
            TestContact2.SetField(Fields.contact_.mobilephone, "0438570301");
            TestContact2 = UpdateFieldsAndRetreive(TestContact2, Fields.contact_.mobilephone);
            //resend
            bulkSms.SetField(Fields.jmcg_bulksms_.jmcg_sendmessages, true);
            bulkSms = UpdateFieldsAndRetreive(bulkSms, Fields.jmcg_bulksms_.jmcg_sendmessages);
            Assert.IsTrue(bulkSms.GetBoolean(Fields.jmcg_bulksms_.jmcg_sendingmessages));
            Assert.IsFalse(bulkSms.GetBoolean(Fields.jmcg_bulksms_.jmcg_sendmessages));
            WaitTillTrue(() => !Refresh(bulkSms).GetBoolean(Fields.jmcg_bulksms_.jmcg_sendingmessages), 60);

            //verify now 2 sms messages
            //and no active errors
            smsMessages = GetSmsMessagesSent(bulkSms);
            smsErrors   = GetSmsErrorsActive(bulkSms);
            Assert.AreEqual(2, smsMessages.Count());
            Assert.AreEqual(1, smsMessages.Count(e => e.GetActivityPartyReferences(Fields.jmcg_sms_.to).First().Id == TestContact.Id));
            Assert.AreEqual(1, smsMessages.Count(e => e.GetActivityPartyReferences(Fields.jmcg_sms_.to).First().Id == TestContact2.Id));
            Assert.AreEqual(0, smsErrors.Count());

            DeleteMyToday();
        }
 public OrganisationSettings(XrmService xrmService)
 {
     XrmService = xrmService;
 }
示例#36
0
        public void DeploymentImportCsvMultipleTest()
        {
            PrepareTests();
            var typesExTeam    = new[] { Entities.jmcg_testentitytwo, Entities.jmcg_testentitythree, Entities.jmcg_testentity, Entities.account };
            var workFolder     = ClearFilesAndData(typesExTeam);
            var testimportTeam = XrmService.GetFirst("team", "name", "TestImportTeam");

            if (testimportTeam != null)
            {
                XrmService.Delete(testimportTeam);
            }
            DeleteAll(Entities.account);
            File.Copy(@"Account.csv", Path.Combine(workFolder, @"Account.csv"));
            File.Copy(@"jmcg_testentity_account.csv", Path.Combine(workFolder, @"jmcg_testentity_account.csv"));
            File.Copy(@"Test Entity.csv", Path.Combine(workFolder, @"Test Entity.csv"));
            File.Copy(@"Test Entity Two.csv", Path.Combine(workFolder, @"Test Entity Two.csv"));
            File.Copy(@"Test Entity Three.csv", Path.Combine(workFolder, @"Test Entity Three.csv"));
            File.Copy(@"Team.csv", Path.Combine(workFolder, @"Team.csv"));

            var application = CreateAndLoadTestApplication <ImportCsvsModule>();

            var request = new ImportCsvsRequest
            {
                DateFormat   = DateFormat.American,
                CsvsToImport = new[] {
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Account.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"jmcg_testentity_account.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Test Entity.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Test Entity Two.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Test Entity Three.csv"))
                    },
                    new ImportCsvsRequest.CsvToImport {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Team.csv"))
                    },
                }
            };

            var response = application.NavigateAndProcessDialog <ImportCsvsModule, ImportCsvsDialog, ImportCsvsResponse>(request);

            Assert.IsFalse(response.HasError);

            application = CreateAndLoadTestApplication <ImportCsvsModule>();

            request = new ImportCsvsRequest
            {
                DateFormat   = DateFormat.American,
                CsvsToImport = new[] {
                    new ImportCsvsRequest.CsvToImport()
                    {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"Account.csv"))
                    }
                }
            };
            response = application.NavigateAndProcessDialog <ImportCsvsModule, ImportCsvsDialog, ImportCsvsResponse>(request);
            Assert.IsFalse(response.HasError);

            File.Copy(@"jmcg_testentity.csv", Path.Combine(workFolder, @"jmcg_testentity.csv"));

            //this one sets a record inactive state
            var accounta = CreateTestRecord(Entities.account, new Dictionary <string, object>()
            {
                { Fields.account_.name, "accounta" }
            });
            var accountb = CreateTestRecord(Entities.account, new Dictionary <string, object>()
            {
                { Fields.account_.name, "accountb" }
            });

            application = CreateAndLoadTestApplication <ImportCsvsModule>();

            request = new ImportCsvsRequest
            {
                DateFormat   = DateFormat.English,
                CsvsToImport = new[] {
                    new ImportCsvsRequest.CsvToImport()
                    {
                        SourceCsv = new FileReference(Path.Combine(workFolder, @"jmcg_testentity.csv"))
                    }
                }
            };

            response = application.NavigateAndProcessDialog <ImportCsvsModule, ImportCsvsDialog, ImportCsvsResponse>(request);
            Assert.IsFalse(response.HasError);

            var entity = XrmService.GetFirst(Entities.jmcg_testentity, Fields.jmcg_testentity_.jmcg_name, "BLAH 2");

            Assert.AreEqual(XrmPicklists.State.Inactive, entity.GetOptionSetValue(Fields.jmcg_testentity_.statecode));
        }