public void DeploymentImportXmlMultipleFilesForSameRecordTest()
        {
            var type = Entities.jmcg_testentity;

            PrepareTests();
            var workFolder = ClearFilesAndData(type);

            var recordName1 = CreateTestRecord(TestEntityType, new Dictionary <string, object>
            {
                { Fields.jmcg_testentity_.jmcg_name, "TestName1" }
            });
            var recordName2 = CreateTestRecord(TestEntityType, new Dictionary <string, object>
            {
                { Fields.jmcg_testentity_.jmcg_name, "TestName2" }
            });

            var exportService = new ExportXmlService(XrmRecordService);
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = new[] { new ExportRecordType()
                                              {
                                                  RecordType = new RecordType(TestEntityType, TestEntityType)
                                              } }
            };
            var exportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsTrue(exportResponse.Success);

            recordName1.SetField(Fields.jmcg_testentity_.jmcg_name, "TestName1 - Updated!");
            recordName1    = UpdateFieldsAndRetreive(recordName1, Fields.jmcg_testentity_.jmcg_name);
            exportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));
            Assert.IsTrue(exportResponse.Success);

            Assert.AreEqual(3, FileUtility.GetFiles(workFolder).Count());

            var app = CreateAndLoadTestApplication <ImportXmlModule>();

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            var dialog         = app.NavigateToDialog <ImportXmlModule, ImportXmlDialog>();
            var entryViewmodel = app.GetSubObjectEntryViewModel(dialog);

            //select the excel file with the errors and submit form
            app.EnterAndSaveObject(importRequest, entryViewmodel);

            //check validation results displayed
            var validationResults = dialog.Controller.UiItems.First() as ObjectDisplayViewModel;

            Assert.IsNotNull(validationResults);
            Assert.IsTrue(validationResults.GetObject() is ImportXmlValidationDialog.DuplicateImportXmlRecords);

            Assert.AreEqual(2, ((ImportXmlValidationDialog.DuplicateImportXmlRecords)validationResults.GetObject()).Duplicates.Count());
        }
        public void DeploymentImportXmlMaskEmailsTest()
        {
            PrepareTests();
            var workFolder = ClearFilesAndData();

            DeleteAll(Entities.account);

            var entity = CreateAccount();

            Assert.IsFalse(entity.GetStringField(Fields.account_.emailaddress1).Contains("_AT_"));

            var accountsExport = new ExportRecordType()
            {
                Type       = ExportType.AllRecords,
                RecordType = new RecordType(Entities.account, Entities.account)
            };

            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = new[] { accountsExport }
            };
            var exportService   = new ExportXmlService(XrmRecordService);
            var ecxportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(ecxportResponse.HasError);

            var importRequest = new ImportXmlRequest
            {
                Folder     = new Folder(workFolder),
                MaskEmails = true
            };
            var application     = CreateAndLoadTestApplication <ImportXmlModule>();
            var immportResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(immportResponse.HasError);

            entity = XrmService.GetFirst(Entities.account);
            Assert.IsTrue(entity.GetStringField(Fields.account_.emailaddress1).Contains("_AT_"));

            importRequest = new ImportXmlRequest
            {
                Folder     = new Folder(workFolder),
                MaskEmails = false
            };
            application     = CreateAndLoadTestApplication <ImportXmlModule>();
            immportResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(immportResponse.HasError);

            entity = XrmService.GetFirst(Entities.account);
            Assert.IsFalse(entity.GetStringField(Fields.account_.emailaddress1).Contains("_AT_"));
        }
        public void DeploymentImportXmlCreateMultipleWithSameNameTest()
        {
            var type = Entities.jmcg_testentity;

            PrepareTests();
            var workFolder = ClearFilesAndData(type);

            var recordName1a = CreateTestRecord(TestEntityType, new Dictionary <string, object>
            {
                { Fields.jmcg_testentity_.jmcg_name, "TestName1" }
            });
            var recordName1b = CreateTestRecord(TestEntityType, new Dictionary <string, object>
            {
                { Fields.jmcg_testentity_.jmcg_name, "TestName1" }
            });
            var recordName2 = CreateTestRecord(TestEntityType, new Dictionary <string, object>
            {
                { Fields.jmcg_testentity_.jmcg_name, "TestName2" }
            });

            var exportService = new ExportXmlService(XrmRecordService);
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = new[] { new ExportRecordType()
                                              {
                                                  RecordType = new RecordType(TestEntityType, TestEntityType)
                                              } }
            };
            var exportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsTrue(exportResponse.Success);

            DeleteAll(type);

            var application = CreateAndLoadTestApplication <ImportXmlModule>();

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            var response = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(response.HasError);

            var records = XrmRecordService.RetrieveAll(type, new string[0]);

            Assert.AreEqual(3, records.Count());
        }
        public void DeploymentImportXmlMultipleTest()
        {
            PrepareTests();
            var types      = new[] { Entities.jmcg_testentitytwo, Entities.jmcg_testentitythree, Entities.jmcg_testentity };
            var workFolder = ClearFilesAndData(types);

            var importService = new ImportXmlService(XrmRecordService);

            var createRecords = new List <Entity>();

            foreach (var type in types)
            {
                createRecords.Add(CreateTestRecord(type, importService));
            }

            var exportService = new ExportXmlService(XrmRecordService);
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = types.Select(t => new ExportRecordType()
                {
                    RecordType = new RecordType(t, t)
                })
            };
            var response = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(response.HasError);

            foreach (var type in types)
            {
                DeleteAll(type);
            }

            var application = CreateAndLoadTestApplication <ImportXmlModule>();

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            var importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(importResponse.HasError);
        }
        public void DeploymentImportXmlKnowledgeArticleTest()
        {
            PrepareTests();

            var type = "knowledgearticle";

            if (XrmRecordService.RecordTypeExists(type))
            {
                DeleteAll(type);

                var workFolder = ClearFilesAndData();

                //create or get a knowledge article
                var knowledgeArticle = XrmService.GetFirst(type, "articlepublicnumber", PopulateStringValue);
                if (knowledgeArticle == null)
                {
                    knowledgeArticle = CreateRecordAllFieldsPopulated("knowledgearticle");
                }

                //export to xml
                var export = new ExportRecordType()
                {
                    Type       = ExportType.AllRecords,
                    RecordType = new RecordType(type, type)
                };

                var exportRequest = new ExportXmlRequest
                {
                    Folder = new Folder(workFolder),
                    RecordTypesToExport = new[] { export }
                };
                var exportService   = new ExportXmlService(XrmRecordService);
                var ecxportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));
                Assert.IsFalse(ecxportResponse.HasError);

                //okay we will delete then create one with the same article number
                XrmService.Delete(knowledgeArticle);
                knowledgeArticle = CreateRecordAllFieldsPopulated("knowledgearticle");

                var kaCount = XrmService.RetrieveAllEntityType(type).Count();

                //import should match them
                var importRequest = new ImportXmlRequest
                {
                    Folder     = new Folder(workFolder),
                    MaskEmails = true
                };
                var application     = CreateAndLoadTestApplication <ImportXmlModule>();
                var immportResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
                Assert.IsFalse(immportResponse.HasError);
                Assert.AreEqual(kaCount, XrmService.RetrieveAllEntityType(type).Count());

                //now lets just verify for create (delete it prioor to import)
                XrmService.Delete(knowledgeArticle);
                importRequest = new ImportXmlRequest
                {
                    Folder     = new Folder(workFolder),
                    MaskEmails = true
                };
                application     = CreateAndLoadTestApplication <ImportXmlModule>();
                immportResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
                Assert.IsFalse(immportResponse.HasError);
                Assert.AreEqual(kaCount, XrmService.RetrieveAllEntityType(type).Count());
            }
        }
        public void DeploymentImportXmlTypesTest()
        {
            var query = new QueryExpression();

            PrepareTests();
            var types      = new[] { Entities.jmcg_testentitytwo, Entities.jmcg_testentitythree, Entities.jmcg_testentity };
            var workFolder = ClearFilesAndData(types);

            var importService = new ImportXmlService(XrmRecordService);

            var t1_1 = CreateTestRecord(Entities.jmcg_testentity, importService);
            var t1_2 = CreateTestRecord(Entities.jmcg_testentity, importService);
            var t1_3 = CreateTestRecord(Entities.jmcg_testentity, importService);

            var t2_1 = CreateTestRecord(Entities.jmcg_testentitytwo, importService);
            var t2_2 = CreateTestRecord(Entities.jmcg_testentitytwo, importService);
            var t2_3 = CreateTestRecord(Entities.jmcg_testentitytwo, importService);

            var t3_1 = CreateTestRecord(Entities.jmcg_testentitythree, importService);
            var t3_2 = CreateTestRecord(Entities.jmcg_testentitythree, importService);
            var t3_3 = CreateTestRecord(Entities.jmcg_testentitythree, importService);

            var t1RequestAll = new ExportRecordType()
            {
                Type       = ExportType.AllRecords,
                RecordType = new RecordType(Entities.jmcg_testentity, Entities.jmcg_testentity)
            };
            var t2RequestFetch = new ExportRecordType()
            {
                Type       = ExportType.FetchXml,
                RecordType = new RecordType(Entities.jmcg_testentitytwo, Entities.jmcg_testentitytwo),
                FetchXml   = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='2' >
                      <entity name='" + Entities.jmcg_testentitytwo + @"'>
                      </entity>
                    </fetch>"
            };
            var t3RequestSpecific = new ExportRecordType()
            {
                Type       = ExportType.SpecificRecords,
                RecordType = new RecordType(Entities.jmcg_testentitythree, Entities.jmcg_testentitythree),
                SpecificRecordsToExport = new[]
                {
                    new LookupSetting()
                    {
                        Record = new Lookup(Entities.jmcg_testentitythree, t3_1.Id.ToString(), "t3_1")
                    },
                    new LookupSetting()
                    {
                        Record = new Lookup(Entities.jmcg_testentitythree, t3_2.Id.ToString(), "t3_2")
                    },
                }
            };

            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = new[] { t1RequestAll, t2RequestFetch, t3RequestSpecific }
            };
            var exportService  = new ExportXmlService(XrmRecordService);
            var exportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(exportResponse.HasError);

            var entities = importService.LoadEntitiesFromXmlFiles(workFolder);

            Assert.AreEqual(7, entities.Count());

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };
            var importResponse = importService.Execute(importRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(importResponse.HasError);
        }
        public void DeploymentImportXmlSimpleTest()
        {
            var type = TestEntityType;

            PrepareTests();
            var workFolder = ClearFilesAndData(type);

            var importService = new ImportXmlService(XrmRecordService);

            var fields       = GetFields(type, importService);
            var updateFields = GetUpdateFields(type, importService);

            var record        = CreateTestRecord(type, importService);
            var createdEntity = XrmService.Retrieve(record.LogicalName, record.Id);

            var exportService = new ExportXmlService(XrmRecordService);
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = new[] { new ExportRecordType()
                                              {
                                                  RecordType = new RecordType(TestEntityType, TestEntityType)
                                              } }
            };
            var exportResponse = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsTrue(exportResponse.Success);

            XrmService.Delete(record);

            var application = CreateAndLoadTestApplication <ImportXmlModule>();

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            var response = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(response.HasError);

            var createdRecord = XrmService.Retrieve(type, createdEntity.Id);

            foreach (var updateField in updateFields)
            {
                Assert.IsTrue(XrmEntity.FieldsEqual(createdEntity.GetField(updateField),
                                                    createdRecord.GetField(updateField)));
            }

            foreach (var field in fields)
            {
                record.SetField(field, CreateNewEntityFieldValue(field, type, record));
            }

            XrmService.Update(record);
            record = XrmService.Retrieve(record.LogicalName, record.Id);

            importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            application = CreateAndLoadTestApplication <ImportXmlModule>();
            response    = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(response.HasError);

            var updatedRecord = XrmService.Retrieve(type, record.Id);

            foreach (var updateField in updateFields)
            {
                Assert.IsTrue(XrmEntity.FieldsEqual(createdEntity.GetField(updateField),
                                                    updatedRecord.GetField(updateField)));
            }
        }
        public void DeploymentImportXmlAssociationsAndNotesTest()
        {
            PrepareTests();
            var types      = new[] { Entities.jmcg_testentity };
            var workFolder = ClearFilesAndData(types);

            var importService = new ImportXmlService(XrmRecordService);

            var createRecords = new List <Entity>();

            foreach (var type in types)
            {
                for (var i = 0; i < 2; i++)
                {
                    createRecords.Add(CreateTestRecord(type, importService));
                }
            }
            //if throws error ensure the test entity allows notes
            XrmService.Associate(Relationships.jmcg_testentity_.jmcg_testentity_jmcg_testentity.Name, Entities.jmcg_testentity, createRecords[0].Id, true, Entities.jmcg_testentity, createRecords[1].Id);
            var aNote = CreateTestRecord(Entities.annotation, new Dictionary <string, object>
            {
                { Fields.annotation_.objectid, createRecords[0].ToEntityReference() },
                { Fields.annotation_.subject, "Test Scripting" },
                { Fields.annotation_.notetext, "Just For Importing Testing" },
            });


            var exportService = new ExportXmlService(XrmRecordService);
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                RecordTypesToExport = types.Select(t => new ExportRecordType()
                {
                    RecordType = new RecordType(t, t)
                }),
                IncludeNNRelationshipsBetweenEntities = true,
                IncludeNotes = true
            };
            var response = exportService.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(response.HasError);

            foreach (var type in types)
            {
                DeleteAll(type);
            }

            var application = CreateAndLoadTestApplication <ImportXmlModule>();

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            var importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(importResponse.HasError);

            var rMetadata = XrmService.GetRelationshipMetadata(Relationships.jmcg_testentity_.jmcg_testentity_jmcg_testentity.Name);

            foreach (var record in createRecords)
            {
                var loaded = Refresh(record);
                if (createRecords[0].Id == loaded.Id)
                {
                    var notes = XrmService.RetrieveAllAndClauses(Entities.annotation, new[]
                    {
                        new ConditionExpression(Fields.annotation_.objectid, ConditionOperator.Equal, loaded.Id)
                    });
                    Assert.AreEqual(1, notes.Count());
                    var associated = XrmService.GetAssociatedIds(rMetadata.SchemaName, rMetadata.Entity1IntersectAttribute, loaded.Id, rMetadata.Entity2IntersectAttribute);
                    Assert.AreEqual(1, associated.Count());
                    Assert.AreEqual(createRecords[1].Id, associated.First());
                }
            }
        }
        public void DeploymentImportXmlPortalTypeConfigTest()
        {
            PrepareTests();
            var types      = new[] { Entities.jmcg_testentitytwo, Entities.jmcg_testentitythree, Entities.jmcg_testentity };
            var workFolder = ClearFilesAndData(types);

            //okay this script is to verify importing microsoft portal types
            //which aren't so simple as to just match by name
            //as for example webpage have a root page, and language specific page(s)

            //create a web page with an access control rule
            RecreatePortalData();

            var parentWebPage = XrmService.RetrieveAllAndClauses(Entities.adx_webpage, new[]
            {
                new ConditionExpression(Fields.adx_webpage_.adx_rootwebpageid, ConditionOperator.Null)
            }).First();

            //export to xml
            var exportApp     = new ExportXmlService(XrmRecordService);// CreateAndLoadTestApplication<ExportXmlModule>();
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(workFolder),
                IncludeNNRelationshipsBetweenEntities = true,
                RecordTypesToExport = new[]
                {
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_webrole, Entities.adx_webrole)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_webpage, Entities.adx_webpage)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_websitelanguage, Entities.adx_websitelanguage)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_webpageaccesscontrolrule, Entities.adx_webpageaccesscontrolrule)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_webform, Entities.adx_webform)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_webformstep, Entities.adx_webformstep)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.adx_webformmetadata, Entities.adx_webformmetadata)
                    },
                }
            };

            var exportResponse = exportApp.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(exportResponse.HasError);

            //lets recreate all the web page data so the ids don't match when importing
            //this will verify it matches them based on the root/unique field configs in XrmTypesConfig
            RecreatePortalData();

            var application   = CreateAndLoadTestApplication <ImportXmlModule>();
            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(workFolder)
            };

            var importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(importResponse.HasError);

            VerifyWebPageRecords();

            //lets just do several other things which will verify some other matching logic

            //delete the root page in the import files - this will verify the language specific page
            //will correctly resolve its parent independently
            //despite it having a different id and not being part of the import
            var parentWebPageFile = FileUtility.GetFiles(workFolder).First(f => f.Contains(parentWebPage.Id.ToString().Replace("-", "_")));

            File.Delete(parentWebPageFile);

            importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(importResponse.HasError);

            VerifyWebPageRecords();

            //delete both web pages in the import files - this will verify the web page access contorl rule
            //will correctly resolve its parent independently
            //despite it having a different id and not being part of the import
            var webPageFile = FileUtility.GetFiles(workFolder).Where(f => f.Contains(Entities.adx_webpage + "_"));

            foreach (var file in webPageFile)
            {
                File.Delete(file);
            }

            importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(importResponse.HasError);

            VerifyWebPageRecords();

            //lets do the same but delete the web page access control rule
            //first to verify it also matches the parent when creating
            XrmService.Delete(XrmService.GetFirst(Entities.adx_webpageaccesscontrolrule));
            importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(importResponse.HasError);

            VerifyWebPageRecords();
        }
        public void DeploymentImportXmlProductsAndPricingTest()
        {
            PrepareTests();

            //created csv files for all the relevant data so lets just hook into that to generate test data
            GenerateProductData();

            //export to xml
            var exportApp     = new ExportXmlService(XrmRecordService);// CreateAndLoadTestApplication<ExportXmlModule>();
            var exportRequest = new ExportXmlRequest
            {
                Folder = new Folder(WorkFolder),
                IncludeNNRelationshipsBetweenEntities = true,
                RecordTypesToExport = new[]
                {
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.product, Entities.product)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.pricelevel, Entities.pricelevel)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.productpricelevel, Entities.productpricelevel)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.uom, Entities.uom)
                    },
                    new ExportRecordType()
                    {
                        RecordType = new RecordType(Entities.uomschedule, Entities.uomschedule)
                    },
                }
            };
            //verify no errors
            var exportResponse = exportApp.Execute(exportRequest, new ServiceRequestController(Controller));

            Assert.IsFalse(exportResponse.HasError);

            //delete all the data so when we import the xml it is creating new
            DeleteProductData();

            //import the xml
            var application   = CreateAndLoadTestApplication <ImportXmlModule>();
            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(WorkFolder)
            };
            //verify no errors
            var importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(importResponse.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);

            //rerun the import
            application   = CreateAndLoadTestApplication <ImportXmlModule>();
            importRequest = new ImportXmlRequest
            {
                Folder = new Folder(WorkFolder)
            };

            importResponse = application.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(importResponse.HasError);
            //verify the price list item we updated is changed
            latestPriceListItem = Refresh(latestPriceListItem);
            Assert.AreEqual(initialPrice, latestPriceListItem.GetMoneyValue(Fields.productpricelevel_.amount));
        }
        public void DeploymentExportXmlModuleTestExportWithSpecificValues()
        {
            DeleteAll(Entities.account);

            var account = CreateRecordAllFieldsPopulated(Entities.account);

            FileUtility.DeleteFiles(TestingFolder);

            var accountRecord = XrmRecordService.Get(account.LogicalName, account.Id.ToString());

            var application = CreateAndLoadTestApplication <ExportXmlModule>();

            application.AddModule <SavedRequestModule>();

            var instance = new ExportXmlRequest();

            instance.IncludeNotes = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.Folder = new Folder(TestingFolder);
            instance.RecordTypesToExport = new[]
            {
                new ExportRecordType()
                {
                    Type       = ExportType.AllRecords,
                    RecordType = new RecordType(Entities.account, Entities.account),
                    SpecificRecordsToExport = new LookupSetting[0]
                }
            };

            var entryForm = application.NavigateToDialogModuleEntryForm <ExportXmlModule, ExportXmlDialog>();

            application.EnterObject(instance, entryForm);
            var recordTypesGrid = entryForm.GetEnumerableFieldViewModel(nameof(ExportXmlRequest.RecordTypesToExport));

            var row = recordTypesGrid.GridRecords.First();

            row.EditRow();

            var exportTypeEntry = entryForm.ChildForms.First() as RecordEntryFormViewModel;

            Assert.IsNotNull(exportTypeEntry);
            exportTypeEntry.LoadFormSections();

            //okay so at this point we aere in the export type form
            //need to add a row to the explicit value grid which will open the form
            var specificValuesGrid = exportTypeEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.ExplicitValuesToSet));

            specificValuesGrid.AddRow();
            var specificValueEntry = exportTypeEntry.ChildForms.First() as RecordEntryFormViewModel;

            Assert.IsNotNull(specificValueEntry);
            specificValueEntry.LoadFormSections();

            var fieldSelectionViewModel = specificValueEntry.GetRecordFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.FieldToSet));
            var clearValueViewModel     = specificValueEntry.GetBooleanFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ClearValue));

            //select several field types and verify the field control changes to the correct type for that field
            fieldSelectionViewModel.Value = fieldSelectionViewModel.ItemsSource.First(f => f.Key == Fields.account_.customertypecode);
            Assert.IsTrue(specificValueEntry.GetFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)) is PicklistFieldViewModel);
            Assert.IsTrue(specificValueEntry.GetPicklistFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)).ItemsSource.Any());

            fieldSelectionViewModel.Value = fieldSelectionViewModel.ItemsSource.First(f => f.Key == Fields.account_.primarycontactid);
            Assert.IsTrue(specificValueEntry.GetFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)) is LookupFieldViewModel);
            specificValueEntry.GetLookupFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)).Search();
            Assert.IsTrue(specificValueEntry.GetLookupFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)).LookupGridViewModel.DynamicGridViewModel.GridRecords.Any());

            //verify the field value hidden if we select to clear the value
            clearValueViewModel.Value = true;
            Assert.IsFalse(specificValueEntry.GetFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)).IsVisible);
            clearValueViewModel.Value = false;

            //okay so this is the specific field and value we will set
            var fakeExplicitExportValue = "fakeExplicitExportValue";

            fieldSelectionViewModel.Value = fieldSelectionViewModel.ItemsSource.First(f => f.Key == Fields.account_.address1_line1);
            Assert.IsTrue(specificValueEntry.GetFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet)) is StringFieldViewModel);
            var descriptionViewModel = specificValueEntry.GetStringFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet));

            descriptionViewModel.Value = fakeExplicitExportValue;

            Assert.IsTrue(specificValueEntry.Validate());
            specificValueEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(exportTypeEntry.ChildForms.Any());

            //okay lets add an explicit lookup value as well
            specificValuesGrid = exportTypeEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.ExplicitValuesToSet));
            specificValuesGrid.AddRow();
            specificValueEntry = exportTypeEntry.ChildForms.First() as RecordEntryFormViewModel;
            Assert.IsNotNull(specificValueEntry);
            specificValueEntry.LoadFormSections();

            fieldSelectionViewModel       = specificValueEntry.GetRecordFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.FieldToSet));
            fieldSelectionViewModel.Value = fieldSelectionViewModel.ItemsSource.First(f => f.Key == Fields.account_.primarycontactid);
            var lookupFieldViewModel = specificValueEntry.GetLookupFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet));

            lookupFieldViewModel.Search();
            Assert.IsTrue(lookupFieldViewModel.LookupGridViewModel.DynamicGridViewModel.GridRecords.Any());
            lookupFieldViewModel.LookupGridViewModel.DynamicGridViewModel.SelectedRow = lookupFieldViewModel.LookupGridViewModel.DynamicGridViewModel.GridRecords.First();
            lookupFieldViewModel.OnRecordSelected(lookupFieldViewModel.LookupGridViewModel.DynamicGridViewModel.GridRecords.First().Record);

            Assert.IsTrue(specificValueEntry.Validate());
            specificValueEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(exportTypeEntry.ChildForms.Any());

            //okay lets add an explicit picklist value as well
            specificValuesGrid = exportTypeEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.ExplicitValuesToSet));
            specificValuesGrid.AddRow();
            specificValueEntry = exportTypeEntry.ChildForms.First() as RecordEntryFormViewModel;
            Assert.IsNotNull(specificValueEntry);
            specificValueEntry.LoadFormSections();

            fieldSelectionViewModel       = specificValueEntry.GetRecordFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.FieldToSet));
            fieldSelectionViewModel.Value = fieldSelectionViewModel.ItemsSource.First(f => f.Key == Fields.account_.customertypecode);
            var picklistFieldViewModel = specificValueEntry.GetPicklistFieldFieldViewModel(nameof(ExportRecordType.ExplicitFieldValues.ValueToSet));

            Assert.IsTrue(picklistFieldViewModel.ItemsSource.Any());
            picklistFieldViewModel.Value = picklistFieldViewModel.ItemsSource.First();

            Assert.IsTrue(specificValueEntry.Validate());
            specificValueEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(exportTypeEntry.ChildForms.Any());

            Assert.IsTrue(exportTypeEntry.Validate());
            exportTypeEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(entryForm.ChildForms.Any());

            //okay lets verify save and load object as well
            //initially the dynamic object property for setting san explicit type
            //did not seralise due to known types in the serialiser

            //lets remove any saved requests as this part relies on it being the only saved one
            var savedRequests = new SavedSettings()
            {
                SavedRequests = new object[0]
            };
            var settingsManager = application.Controller.ResolveType <ISettingsManager>();

            settingsManager.SaveSettingsObject(savedRequests, typeof(ExportXmlRequest));


            //trigger save request
            var saveRequestButton = entryForm.GetButton("SAVEREQUEST");

            saveRequestButton.Invoke();

            //enter and save details
            var saveRequestForm = application.GetSubObjectEntryViewModel(entryForm);
            var detailsEntered  = new SaveAndLoadFields()
            {
                Name = "TestName"
            };

            application.EnterAndSaveObject(detailsEntered, saveRequestForm);
            Assert.IsFalse(entryForm.ChildForms.Any());
            Assert.IsFalse(entryForm.LoadingViewModel.IsLoading);

            //trigger load request
            var loadRequestButton = entryForm.GetButton("LOADREQUEST");

            loadRequestButton.Invoke();
            var loadRequestForm = application.GetSubObjectEntryViewModel(entryForm);
            //select and load the saved request
            var subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests));

            Assert.IsTrue(subGrid.GridRecords.Count() == 1);
            subGrid.GridRecords.First().IsSelected = true;
            var loadButton = subGrid.DynamicGridViewModel.GetButton("LOADREQUEST");

            loadButton.Invoke();
            //verify loads
            Assert.IsFalse(entryForm.ChildForms.Any());
            Assert.IsFalse(entryForm.LoadingViewModel.IsLoading);

            //this one will invoke the export
            Assert.IsTrue(entryForm.Validate());
            entryForm.SaveButtonViewModel.Invoke();

            //verify the exported records had the explicit value we set in them
            var importServoice = new ImportXmlService(XrmRecordService);
            var loadEntities   = importServoice.LoadEntitiesFromXmlFiles(TestingFolder);

            foreach (var entity in loadEntities)
            {
                Assert.AreEqual(fakeExplicitExportValue, entity.GetStringField(Fields.account_.address1_line1));
            }
        }
        public void DeploymentExportXmlModuleTestExportWithBulkAddToGridField()
        {
            DeleteAll(Entities.account);

            var account = CreateRecordAllFieldsPopulated(Entities.account);

            FileUtility.DeleteFiles(TestingFolder);

            var accountRecord = XrmRecordService.Get(account.LogicalName, account.Id.ToString());

            var application = CreateAndLoadTestApplication <ExportXmlModule>();

            var instance = new ExportXmlRequest();

            instance.IncludeNotes = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.Folder = new Folder(TestingFolder);
            instance.RecordTypesToExport = new[]
            {
                new ExportRecordType()
                {
                    Type       = ExportType.AllRecords,
                    RecordType = new RecordType(Entities.account, Entities.account),
                    SpecificRecordsToExport = new LookupSetting[0]
                }
            };

            var entryForm = application.NavigateToDialogModuleEntryForm <ExportXmlModule, ExportXmlDialog>();

            application.EnterObject(instance, entryForm);
            var recordTypesGrid = entryForm.GetEnumerableFieldViewModel(nameof(ExportXmlRequest.RecordTypesToExport));

            //okay so we will be doing bulk adds on fields in this grid row
            var row = recordTypesGrid.GridRecords.First();

            row.GetPicklistFieldFieldViewModel(nameof(ExportRecordType.Type)).Value = PicklistOption.EnumToPicklistOption(ExportType.SpecificRecords);
            //first do it for an Enumerable lookup field (specific records for export)
            var specificRecordsGridField = row.GetEnumerableFieldViewModel(nameof(ExportRecordType.SpecificRecordsToExport));

            Assert.IsTrue(string.IsNullOrWhiteSpace(specificRecordsGridField.StringDisplay));
            Assert.IsNull(specificRecordsGridField.DynamicGridViewModel);
            Assert.IsNotNull(specificRecordsGridField.BulkAddButton);

            //trigger the add multiple option
            specificRecordsGridField.BulkAddButton.Invoke();
            var bulkAddForm = entryForm.ChildForms.First() as QueryViewModel;

            //verify a quickfind finds a record
            bulkAddForm.QuickFindText = account.GetStringField(Fields.account_.name);
            bulkAddForm.QuickFind();

            //select and add
            bulkAddForm.DynamicGridViewModel.GridRecords.First().IsSelected = true;
            //this triggered by the grid event
            bulkAddForm.DynamicGridViewModel.OnSelectionsChanged();
            //this is supposed to be the add selected button
            bulkAddForm.DynamicGridViewModel.CustomFunctions.Last().Invoke();
            //verify we now have a record selected and displayed for the field
            Assert.IsFalse(string.IsNullOrWhiteSpace(specificRecordsGridField.StringDisplay));

            //now do it for an Enumerable field (fields for inlcusion)
            //this sets it in context
            row.GetBooleanFieldFieldViewModel(nameof(ExportRecordType.IncludeAllFields)).Value = false;
            var excludeFieldsGrid = row.GetEnumerableFieldViewModel(nameof(ExportRecordType.IncludeOnlyTheseFields));

            Assert.IsTrue(string.IsNullOrWhiteSpace(excludeFieldsGrid.StringDisplay));

            //trigger the add multiple option
            excludeFieldsGrid.BulkAddButton.Invoke();
            bulkAddForm = entryForm.ChildForms.First() as QueryViewModel;
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            bulkAddForm.QuickFindText = Fields.account_.name;
            bulkAddForm.QuickFind();

            Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage);
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            bulkAddForm.DynamicGridViewModel.GridRecords.First().IsSelected = true;
            //this triggered by the grid event
            bulkAddForm.DynamicGridViewModel.OnSelectionsChanged();
            //this is supposed to be the add selected button
            bulkAddForm.DynamicGridViewModel.CustomFunctions.Last().Invoke();
            Assert.IsFalse(entryForm.ChildForms.Any());
            //verify we now have a record selected and displayed for the field
            Assert.IsFalse(string.IsNullOrWhiteSpace(excludeFieldsGrid.StringDisplay));
        }
        public void DeploymentExportXmlModuleTest()
        {
            //script 2 exports

            //first one with only one specific field

            var account = CreateAccount();

            FileUtility.DeleteFiles(TestingFolder);

            var application = CreateAndLoadTestApplication <ExportXmlModule>();

            var instance = new ExportXmlRequest();

            instance.IncludeNotes = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.Folder = new Folder(TestingFolder);
            instance.RecordTypesToExport = new[]
            {
                new ExportRecordType()
                {
                    Type                   = ExportType.AllRecords,
                    RecordType             = new RecordType(Entities.account, Entities.account),
                    IncludeAllFields       = false,
                    IncludeOnlyTheseFields = new [] { new FieldSetting()
                                                      {
                                                          RecordField = new RecordField(Fields.account_.createdby, Fields.account_.createdby)
                                                      } }
                }
            };

            var response = application.NavigateAndProcessDialog <ExportXmlModule, ExportXmlDialog, ExportXmlResponse>(instance);

            Assert.IsFalse(response.HasError);

            Assert.IsTrue(FileUtility.GetFiles(TestingFolder).Any());

            var importXmlService = new ImportXmlService(XrmRecordService);
            var loaded           = importXmlService.LoadEntitiesFromXmlFiles(TestingFolder);

            foreach (var item in loaded)
            {
                Assert.IsNull(item.GetField(Fields.account_.createdon));
                Assert.IsNotNull(item.GetField(Fields.account_.createdby));
                Assert.IsNotNull(item.GetField(Fields.account_.name));
            }

            FileUtility.DeleteFiles(TestingFolder);

            //first verify when all fields selected
            application = CreateAndLoadTestApplication <ExportXmlModule>();

            instance = new ExportXmlRequest();
            instance.IncludeNotes = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.Folder = new Folder(TestingFolder);
            instance.RecordTypesToExport = new[]
            {
                new ExportRecordType()
                {
                    Type             = ExportType.AllRecords,
                    RecordType       = new RecordType(Entities.account, Entities.account),
                    IncludeAllFields = true
                }
            };

            response = application.NavigateAndProcessDialog <ExportXmlModule, ExportXmlDialog, ExportXmlResponse>(instance);
            Assert.IsFalse(response.HasError);

            Assert.IsTrue(FileUtility.GetFiles(TestingFolder).Any());

            loaded = importXmlService.LoadEntitiesFromXmlFiles(TestingFolder);
            foreach (var item in loaded)
            {
                Assert.IsNotNull(item.GetField(Fields.account_.createdon));
                Assert.IsNotNull(item.GetField(Fields.account_.createdby));
                Assert.IsNotNull(item.GetField(Fields.account_.name));
            }
        }
        public void DeploymentExportXmlModuleTestExportWithBulkAddToGridAndQuery()
        {
            DeleteAll(Entities.account);

            var account = CreateRecordAllFieldsPopulated(Entities.account);

            FileUtility.DeleteFiles(TestingFolder);

            var accountRecord = XrmRecordService.Get(account.LogicalName, account.Id.ToString());

            //okay create/navigate to a new entry form entering an ExportXmlRequest
            var application = CreateAndLoadTestApplication <ExportXmlModule>();
            var instance    = new ExportXmlRequest();

            instance.IncludeNotes = true;
            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.Folder = new Folder(TestingFolder);
            instance.RecordTypesToExport = new[]
            {
                new ExportRecordType()
                {
                    Type       = ExportType.SpecificRecords,
                    RecordType = new RecordType(Entities.account, Entities.account),
                    SpecificRecordsToExport = new [] { new LookupSetting()
                                                       {
                                                           Record = accountRecord.ToLookup()
                                                       } }
                }
            };
            var entryForm = application.NavigateToDialogModuleEntryForm <ExportXmlModule, ExportXmlDialog>();

            application.EnterObject(instance, entryForm);

            //get the record types subgrid
            var recordTypesGrid = entryForm.GetEnumerableFieldViewModel(nameof(ExportXmlRequest.RecordTypesToExport));
            var row             = recordTypesGrid.GridRecords.First();

            //edit the accounts export record row
            row.EditRow();
            var specificRecordEntry = entryForm.ChildForms.First() as RecordEntryFormViewModel;

            specificRecordEntry.LoadFormSections();
            var specificRecordsGrid = specificRecordEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.SpecificRecordsToExport));

            //delete the row we added
            specificRecordsGrid.GridRecords.First().DeleteRow();
            Assert.IsFalse(specificRecordsGrid.GridRecords.Any());

            //now add using the add multiple option
            var customFunction = specificRecordsGrid.DynamicGridViewModel.AddMultipleRowButton;

            customFunction.Invoke();
            var bulkAddForm = specificRecordEntry.ChildForms.First() as QueryViewModel;

            //verify a quickfind finds a record
            bulkAddForm.QuickFindText = account.GetStringField(Fields.account_.name);
            bulkAddForm.QuickFind();
            Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage);
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            //now do an and query on every field in the entity and verify it works
            bulkAddForm.QueryTypeButton.Invoke();

            var lastCondition = bulkAddForm.FilterConditions.Conditions.Last();

            Assert.AreEqual(Entities.account, lastCondition.GetRecordTypeFieldViewModel(nameof(ConditionViewModel.QueryCondition.RecordType)).Value.Key);
            var fieldViewModel    = lastCondition.GetRecordFieldFieldViewModel(nameof(ConditionViewModel.QueryCondition.FieldName));
            var validSearchFields = fieldViewModel.ItemsSource.Select(i => i.Key).ToArray();

            foreach (var field in validSearchFields)
            {
                var fieldvalue = accountRecord.GetField(field);
                if (fieldvalue != null)
                {
                    lastCondition = bulkAddForm.FilterConditions.Conditions.Last();
                    Assert.AreEqual(Entities.account, lastCondition.GetRecordTypeFieldViewModel(nameof(ConditionViewModel.QueryCondition.RecordType)).Value.Key);
                    fieldViewModel       = lastCondition.GetRecordFieldFieldViewModel(nameof(ConditionViewModel.QueryCondition.FieldName));
                    fieldViewModel.Value = fieldViewModel.ItemsSource.ToArray().First(i => i.Key == field);
                    var conditionTypeViewModel = lastCondition.GetPicklistFieldFieldViewModel(nameof(ConditionViewModel.QueryCondition.ConditionType));
                    conditionTypeViewModel.Value = conditionTypeViewModel.ItemsSource.First(i => i.Value == ConditionType.Equal.ToString());
                    var valueViewModel = lastCondition.GetFieldViewModel(nameof(ConditionViewModel.QueryCondition.Value));
                    valueViewModel.ValueObject = fieldvalue;
                    //bulkAddForm.QuickFind();
                    //Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage);
                    //Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());
                }
            }
            bulkAddForm.QuickFind();
            Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage);
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());
            //select and add
            bulkAddForm.DynamicGridViewModel.GridRecords.First().IsSelected = true;
            //this triggered by the grid event
            bulkAddForm.DynamicGridViewModel.OnSelectionsChanged();
            //this is supposed to be the add selected button
            bulkAddForm.DynamicGridViewModel.CustomFunctions.Last().Invoke();

            //and verify the row was added to the records for export
            Assert.IsTrue(specificRecordsGrid.GridRecords.Any());

            //okay now lets do the equivalent for a grid of fields

            //set this false so the selection of fields is in context
            specificRecordEntry.GetBooleanFieldFieldViewModel(nameof(ExportRecordType.IncludeAllFields)).Value = false;

            //get the fields grid and trigger bulk add function
            var excludeFieldsGrid = specificRecordEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.IncludeOnlyTheseFields));

            //now add using the add multiple option
            excludeFieldsGrid.DynamicGridViewModel.AddMultipleRowButton.Invoke();
            bulkAddForm = specificRecordEntry.ChildForms.First() as QueryViewModel;
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            bulkAddForm.QuickFindText = Fields.account_.name;
            bulkAddForm.QuickFind();

            Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage);
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            bulkAddForm.DynamicGridViewModel.GridRecords.First().IsSelected = true;
            //this triggered by the grid event
            bulkAddForm.DynamicGridViewModel.OnSelectionsChanged();
            //this is supposed to be the add selected button
            bulkAddForm.DynamicGridViewModel.CustomFunctions.Last().Invoke();
            Assert.IsFalse(specificRecordEntry.ChildForms.Any());
            //and verify the row was added to the records for export
            Assert.IsTrue(excludeFieldsGrid.GridRecords.Any());

            specificRecordEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(entryForm.ChildForms.Any());

            //okay now lets to bulk add on the record types grid
            var subGrid = entryForm.GetEnumerableFieldViewModel(nameof(ExportXmlRequest.RecordTypesToExport));

            subGrid.DynamicGridViewModel.AddMultipleRowButton.Invoke();

            bulkAddForm = entryForm.ChildForms.First() as QueryViewModel;

            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            bulkAddForm.QuickFindText = Entities.contact;
            bulkAddForm.QuickFind();

            Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage);
            Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any());

            bulkAddForm.DynamicGridViewModel.GridRecords.First().IsSelected = true;
            //this triggered by the grid event
            bulkAddForm.DynamicGridViewModel.OnSelectionsChanged();
            //this is supposed to be the add selected button
            bulkAddForm.DynamicGridViewModel.CustomFunctions.Last().Invoke();

            Assert.IsFalse(entryForm.ChildForms.Any());
        }
Exemplo n.º 15
0
        public void DeploymentImportActivityPartiesTest()
        {
            PrepareTests();

            var contact1 = XrmService.GetFirst(Entities.contact, Fields.contact_.fullname, "TESTEMAIL IMPORT 1")
                           ?? CreateTestRecord(Entities.contact, new Dictionary <string, object>
            {
                { Fields.contact_.firstname, "TESTEMAIL" },
                { Fields.contact_.lastname, "IMPORT 1" },
                { Fields.contact_.emailaddress1, "*****@*****.**" }
            });
            var contact2 = XrmService.GetFirst(Entities.contact, Fields.contact_.fullname, "TESTEMAIL IMPORT 2")
                           ?? CreateTestRecord(Entities.contact, new Dictionary <string, object>
            {
                { Fields.contact_.firstname, "TESTEMAIL" },
                { Fields.contact_.lastname, "IMPORT 2" },
                { Fields.contact_.emailaddress1, "*****@*****.**" }
            });
            var account = XrmService.GetFirst(Entities.account, Fields.account_.name, "TESTEMAILIMPORT")
                          ?? CreateTestRecord(Entities.account, new Dictionary <string, object>
            {
                { Fields.account_.name, "TESTEMAILIMPORT" },
                { Fields.account_.emailaddress1, "*****@*****.**" }
            });
            var queue = XrmService.GetFirst(Entities.queue, Fields.queue_.name, "TESTQUEUE")
                        ?? CreateTestRecord(Entities.queue, new Dictionary <string, object>
            {
                { Fields.queue_.name, "TESTQUEUE" },
                { Fields.queue_.emailaddress, "*****@*****.**" }
            });

            var email = new Entity(Entities.email);

            email.SetField(Fields.email_.subject, "Testing Import Email " + DateTime.Now.ToFileTime().ToString());
            email.AddFromParty(queue.LogicalName, queue.Id);
            email.AddToParty(contact1.LogicalName, contact1.Id);
            email.AddToParty(contact2.LogicalName, contact2.Id);
            email.AddToParty(account.LogicalName, account.Id);
            email.AddActivityParty(Fields.email_.to, "*****@*****.**");
            email = CreateAndRetrieve(email);

            XrmService.SetState(email, OptionSets.Email.ActivityStatus.Completed, OptionSets.Email.StatusReason.Sent);

            //okay lets xml export
            var exportXmlApplication = CreateAndLoadTestApplication <ExportXmlModule>();

            var instance = new ExportXmlRequest();

            instance.IncludeNNRelationshipsBetweenEntities = true;
            instance.Folder = new Folder(TestingFolder);
            instance.RecordTypesToExport = new[]
            {
                new ExportRecordType()
                {
                    Type       = ExportType.SpecificRecords,
                    RecordType = new RecordType(Entities.email, Entities.email),
                    SpecificRecordsToExport = new LookupSetting[]
                    {
                        new LookupSetting()
                        {
                            Record = new Lookup(email.LogicalName, email.Id.ToString(), email.GetStringField(Fields.email_.subject))
                        }
                    }
                }
            };

            var exportXmlResponse = exportXmlApplication.NavigateAndProcessDialog <ExportXmlModule, ExportXmlDialog, ExportXmlResponse>(instance);

            Assert.IsFalse(exportXmlResponse.HasError);

            //okay lets delete the email then import it
            XrmService.Delete(email);

            //do an xml import
            var importXmlApplication = CreateAndLoadTestApplication <ImportXmlModule>();

            var importRequest = new ImportXmlRequest
            {
                Folder = new Folder(TestingFolder)
            };

            var importXmlResponse = importXmlApplication.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);

            Assert.IsFalse(importXmlResponse.HasError);

            Assert.AreEqual(1, importXmlResponse.ImportSummary.Count());
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Created == 1));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Updated == 0));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.NoChange == 0));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Errors == 0));

            var importedEmail = XrmService.Retrieve(email.LogicalName, email.Id);

            Assert.AreEqual(OptionSets.Email.StatusReason.Sent, importedEmail.GetOptionSetValue(Fields.email_.statuscode));
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.from).Count() == 1);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.from).Count(p => Entities.queue == p.GetLookupType(Fields.activityparty_.partyid)) == 1);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count() == 4);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count(p => Entities.contact == p.GetLookupType(Fields.activityparty_.partyid)) == 2);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count(p => Entities.account == p.GetLookupType(Fields.activityparty_.partyid)) == 1);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count(p => null == p.GetField(Fields.activityparty_.partyid) && p.GetStringField(Fields.activityparty_.addressused) == "*****@*****.**") == 1);

            importXmlResponse = importXmlApplication.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(importXmlResponse.HasError);

            Assert.AreEqual(1, importXmlResponse.ImportSummary.Count());
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Created == 0));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Updated == 0));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.NoChange == 1));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Errors == 0));

            importedEmail = XrmService.Retrieve(email.LogicalName, email.Id);
            XrmService.SetState(importedEmail, OptionSets.Email.ActivityStatus.Open);

            var toParties = importedEmail.GetActivityParties(Fields.email_.to);

            importedEmail.SetField(Fields.email_.to, toParties.Skip(1).ToArray());
            importedEmail = UpdateFieldsAndRetreive(importedEmail, Fields.email_.to);

            importXmlResponse = importXmlApplication.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
            Assert.IsFalse(importXmlResponse.HasError);

            Assert.AreEqual(1, importXmlResponse.ImportSummary.Count());
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Created == 0));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Updated == 1));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.NoChange == 0));
            Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Errors == 0));

            importedEmail = XrmService.Retrieve(email.LogicalName, email.Id);

            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.from).Count() == 1);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.from).Count(p => Entities.queue == p.GetLookupType(Fields.activityparty_.partyid)) == 1);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count() == 4);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count(p => Entities.contact == p.GetLookupType(Fields.activityparty_.partyid)) == 2);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count(p => Entities.account == p.GetLookupType(Fields.activityparty_.partyid)) == 1);
            Assert.IsTrue(importedEmail.GetActivityParties(Fields.email_.to).Count(p => null == p.GetField(Fields.activityparty_.partyid) && p.GetStringField(Fields.activityparty_.addressused) == "*****@*****.**") == 1);
        }
Exemplo n.º 16
0
        public void DeploymentImportMultipleCachingTest()
        {
            //this script added when refactored to use execute multiples
            //so that a script covered resolving matches both with and without
            //caching target records
            //generally the scripts use a small number of records
            //which doesnt exceed the standard cache threshold
            //this uses a caching and non changing threshold for
            //a spreadsheet which contain various lookup fields
            //including circular and multi type lookups

            //runs through for both excel and xml imports
            //including where ids do and dont match

            PrepareTests();
            var cacheLimits = new[] { 5, 50 };
            var setSize     = 10;

            foreach (var cacheLimit in cacheLimits)
            {
                FileUtility.DeleteFiles(TestingFolder);
                FileUtility.DeleteSubFolders(TestingFolder);

                var workFolder = TestingFolder + @"\TestImportMultiples";
                FileUtility.CheckCreateFolder(workFolder);
                var sourceExcelFile = Path.Combine(workFolder, @"TestImportMultiples.xlsx");
                File.Copy(@"TestImportMultiples.xlsx", sourceExcelFile);

                DeleteAll(Entities.account);
                DeleteAll(Entities.jmcg_testentity);
                DeleteAll(Entities.contact);

                var importExcelApp = CreateAndLoadTestApplication <ImportExcelModule>();
                importExcelApp.AddModule <SavedRequestModule>();
                ClearSavedRequests <ImportExcelModule, ImportExcelDialog>(importExcelApp);

                //navigate to the dialog
                var dialog         = importExcelApp.NavigateToDialog <ImportExcelModule, ImportExcelDialog>();
                var entryViewmodel = importExcelApp.GetSubObjectEntryViewModel(dialog);
                //select the excel file with the errors and submit form
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile);
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExecuteMultipleSetSize)).ValueObject = setSize;
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.TargetCacheLimit)).ValueObject       = cacheLimit;
                Assert.IsTrue(entryViewmodel.Validate());
                entryViewmodel.SaveButtonViewModel.Invoke();

                var importExcelResponse = dialog.CompletionItem as ImportExcelResponse;
                if (importExcelResponse.HasError)
                {
                    Assert.Fail(importExcelResponse.GetResponseItemsWithError().First().Exception.XrmDisplayString());
                }

                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Created > 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Updated == 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.NoChange == 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                //lets do another and verify no errors or changes
                dialog         = importExcelApp.NavigateToDialog <ImportExcelModule, ImportExcelDialog>();
                entryViewmodel = importExcelApp.GetSubObjectEntryViewModel(dialog);
                //select the excel file with the errors and submit form
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile);
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExecuteMultipleSetSize)).ValueObject = setSize;
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.TargetCacheLimit)).ValueObject       = cacheLimit;
                Assert.IsTrue(entryViewmodel.Validate());
                entryViewmodel.SaveButtonViewModel.Invoke();

                importExcelResponse = dialog.CompletionItem as ImportExcelResponse;
                if (importExcelResponse.HasError)
                {
                    Assert.Fail(importExcelResponse.GetResponseItemsWithError().First().Exception.XrmDisplayString());
                }

                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Created == 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Updated == 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.NoChange > 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                //okay lets do an xml export
                var exportXmlApplication = CreateAndLoadTestApplication <ExportXmlModule>();

                var instance = new ExportXmlRequest();
                instance.IncludeNNRelationshipsBetweenEntities = true;
                instance.Folder = new Folder(TestingFolder);
                instance.RecordTypesToExport = new[]
                {
                    new ExportRecordType()
                    {
                        Type       = ExportType.AllRecords,
                        RecordType = new RecordType(Entities.account, Entities.account),
                    },
                    new ExportRecordType()
                    {
                        Type       = ExportType.AllRecords,
                        RecordType = new RecordType(Entities.contact, Entities.contact),
                    },
                    new ExportRecordType()
                    {
                        Type       = ExportType.AllRecords,
                        RecordType = new RecordType(Entities.jmcg_testentity, Entities.jmcg_testentity),
                    },
                };

                var exportXmlResponse = exportXmlApplication.NavigateAndProcessDialog <ExportXmlModule, ExportXmlDialog, ExportXmlResponse>(instance);
                Assert.IsFalse(exportXmlResponse.HasError);

                //do an xml import
                var importXmlApplication = CreateAndLoadTestApplication <ImportXmlModule>();

                var importRequest = new ImportXmlRequest
                {
                    Folder = new Folder(TestingFolder)
                };

                var importXmlResponse = importXmlApplication.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
                Assert.IsFalse(importXmlResponse.HasError);

                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Created == 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Updated == 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.NoChange > 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                //do another xml import after deleting the data and recreating with different ids (from excel import)

                DeleteAll(Entities.account);
                DeleteAll(Entities.jmcg_testentity);
                DeleteAll(Entities.contact);

                importExcelApp = CreateAndLoadTestApplication <ImportExcelModule>();
                importExcelApp.AddModule <SavedRequestModule>();
                ClearSavedRequests <ImportExcelModule, ImportExcelDialog>(importExcelApp);

                dialog         = importExcelApp.NavigateToDialog <ImportExcelModule, ImportExcelDialog>();
                entryViewmodel = importExcelApp.GetSubObjectEntryViewModel(dialog);
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile);
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExecuteMultipleSetSize)).ValueObject = setSize;
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.TargetCacheLimit)).ValueObject       = cacheLimit;
                Assert.IsTrue(entryViewmodel.Validate());
                entryViewmodel.SaveButtonViewModel.Invoke();

                importExcelResponse = dialog.CompletionItem as ImportExcelResponse;
                if (importExcelResponse.HasError)
                {
                    Assert.Fail(importExcelResponse.GetResponseItemsWithError().First().Exception.XrmDisplayString());
                }

                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Created > 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Updated == 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.NoChange == 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                importXmlApplication = CreateAndLoadTestApplication <ImportXmlModule>();

                importRequest = new ImportXmlRequest
                {
                    Folder = new Folder(TestingFolder)
                };

                importXmlResponse = importXmlApplication.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
                Assert.IsFalse(importXmlResponse.HasError);

                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Created == 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Updated == 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.NoChange > 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                //okay finally lets delete half the records just for inclusion of a parital import

                //xml import half deleted

                DeleteHalfTheRecords();

                importXmlApplication = CreateAndLoadTestApplication <ImportXmlModule>();

                importRequest = new ImportXmlRequest
                {
                    Folder = new Folder(TestingFolder)
                };

                importXmlResponse = importXmlApplication.NavigateAndProcessDialog <ImportXmlModule, ImportXmlDialog, ImportXmlResponse>(importRequest);
                Assert.IsFalse(importXmlResponse.HasError);

                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Created > 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.Any(i => i.NoChange > 0));
                Assert.IsTrue(importXmlResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                //excel import half deleted

                importExcelApp = CreateAndLoadTestApplication <ImportExcelModule>();
                importExcelApp.AddModule <SavedRequestModule>();
                ClearSavedRequests <ImportExcelModule, ImportExcelDialog>(importExcelApp);

                DeleteHalfTheRecords();

                dialog         = importExcelApp.NavigateToDialog <ImportExcelModule, ImportExcelDialog>();
                entryViewmodel = importExcelApp.GetSubObjectEntryViewModel(dialog);
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile);
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExecuteMultipleSetSize)).ValueObject = setSize;
                entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.TargetCacheLimit)).ValueObject       = cacheLimit;
                Assert.IsTrue(entryViewmodel.Validate());
                entryViewmodel.SaveButtonViewModel.Invoke();

                importExcelResponse = dialog.CompletionItem as ImportExcelResponse;
                if (importExcelResponse.HasError)
                {
                    Assert.Fail(importExcelResponse.GetResponseItemsWithError().First().Exception.XrmDisplayString());
                }

                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Created > 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.Any(i => i.NoChange > 0));
                Assert.IsTrue(importExcelResponse.ImportSummary.All(i => i.Errors == 0));

                ValidateimportedData();

                DeleteAll(Entities.account);
                DeleteAll(Entities.jmcg_testentity);
                DeleteAll(Entities.contact);
            }
        }