private static void SaveWithAutoload(Application.Desktop.Test.TestApplication app, Application.ViewModel.RecordEntry.Form.RecordEntryFormViewModel entryViewmodel)
        {
            var saveRequestButton = entryViewmodel.GetButton("SAVEREQUEST");

            saveRequestButton.Invoke();
            //enter and save details
            var saveRequestForm = app.GetSubObjectEntryViewModel(entryViewmodel);
            var detailsEntered  = new SaveAndLoadFields()
            {
                Name     = "ScriptSaveAutoload",
                Autoload = true
            };

            app.EnterAndSaveObject(detailsEntered, saveRequestForm);
            Assert.IsFalse(entryViewmodel.ChildForms.Any());
            Assert.IsFalse(entryViewmodel.LoadingViewModel.IsLoading);
        }
Ejemplo n.º 2
0
        public void ConsoleApplicationModuleWithXrmConnectionGenerateBatAndExecuteTest()
        {
            //this is done in the load.edit saved request form
            //a button is added the the saved request grid whiuch generates the .bat

            //so we need to save a request
            //then navigate to the save requests and trigger the generate bat button

            var testApplication = CreateThisApp();

            //set to no previously saved ones
            var savedRequests   = new SavedSettings();
            var settingsManager = testApplication.Controller.ResolveType <ISettingsManager>();

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

            //navigate to the request and populate the string field
            var entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestWithXrmConnectionModule, TestSavedRequestWithXrmConnectionDialog>();
            var request   = new TestSavedRequestWithXrmConnectionDialogRequest()
            {
                SomeArbitraryString = nameof(TestSavedRequestWithXrmConnectionDialogRequest.SomeArbitraryString)
            };

            testApplication.EnterObject(request, entryForm);

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

            saveRequestButton.Invoke();

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

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

            //reopen app/dialog
            testApplication = CreateThisApp();
            entryForm       = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestWithXrmConnectionModule, TestSavedRequestWithXrmConnectionDialog>();

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

            loadRequestButton.Invoke();
            var loadRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm);

            //verify there is a saved request and trigger the generate bat button
            var subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests));

            Assert.IsTrue(subGrid.GridRecords.Count() == 1);
            subGrid.GridRecords.First().IsSelected = true;

            var generateBatButton = subGrid.DynamicGridViewModel.GetButton("GENERATEBAT");

            generateBatButton.Invoke();

            var testFiles = FileUtility.GetFiles(TestingFolder);

            Assert.AreEqual(1, testFiles.Count());
            Assert.IsTrue(testFiles.First().EndsWith(".bat"));

            var batContent = File.ReadAllText(testFiles.First());

            var args = ConsoleTestUtility.CommandLineToArgs(batContent)
                       .Skip(1)
                       .ToArray();

            var arguments       = ConsoleApplication.ParseCommandLineArguments(args);
            var applicationName = arguments.ContainsKey("SettingsFolderName") ? arguments["SettingsFolderName"] : "Unknown Console Context";

            //okay need to create app
            var dependencyResolver = new DependencyContainer();
            var controller         = new ConsoleApplicationController(applicationName, dependencyResolver);

            settingsManager = new DesktopSettingsManager(controller);
            var applicationOptions = new ApplicationOptionsViewModel(controller);
            var app = new ConsoleApplication(controller, applicationOptions, settingsManager);

            //load modules in folder path
            app.LoadModulesInExecutionFolder();

            //for this we will register saved connections in the console
            //in reality they would have been created on disk by the app and loaded by the module\

            //this was just debugging an invalid connection
            //var c1 = GetXrmRecordConfiguration();
            //var c2 = GetSavedXrmRecordConfiguration();
            //c1.Password = new Password("Nope", false, true);
            //c2.Password = new Password("Nope", false, true);
            //XrmConnectionModule.RefreshXrmServices(c1, app.Controller);
            //app.Controller.RegisterInstance<ISavedXrmConnections>(new SavedXrmConnections
            //{
            //    Connections = new[] { c2 }
            //});

            XrmConnectionModule.RefreshXrmServices(GetXrmRecordConfiguration(), app.Controller);
            app.Controller.RegisterInstance <ISavedXrmConnections>(new SavedXrmConnections
            {
                Connections = new[] { GetSavedXrmRecordConfiguration() }
            });

            //run app
            app.Run(args);
        }
Ejemplo n.º 3
0
        public void DeploymentImportSqlTest()
        {
            //this script create some data in a database
            //then runs a synch twice into dynamics with a reference change in between

            //it also fakes the process running in a console app

            //also verifies email sent with summary

            var queues = XrmRecordService.RetrieveAllAndClauses(Entities.queue, new[]
            {
                new Condition(Fields.queue_.emailaddress, ConditionType.NotNull)
            });

            Assert.IsTrue(queues.Count() > 1);
            var queueSendFrom = queues.ElementAt(0);
            var queueSendTo   = queues.ElementAt(1);

            //script of basic database import
            PrepareTests();
            DeleteAll(Entities.email);

            var sqlServer    = @"localhost\SQLEXPRESS";
            var databaseName = "TestScriptDatabaseImport";

            //request with mappings from sql to dynamics
            var request = new ImportSqlRequest()
            {
                ConnectionString             = $"Provider=sqloledb;Data Source={sqlServer};Initial Catalog={databaseName};Integrated Security=SSPI;",
                SendNotificationAtCompletion = true,
                SendNotificationFromQueue    = XrmRecordService.ToLookup(queueSendFrom),
                SendNotificationToQueue      = XrmRecordService.ToLookup(queueSendTo),
                Mappings = new[]
                {
                    new ImportSqlRequest.SqlImportTableMapping
                    {
                        SourceTable = new RecordType("Accounts", "Accounts"),
                        TargetType  = new RecordType(Entities.account, Entities.account),
                        Mappings    = new []
                        {
                            new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping()
                            {
                                SourceColumn = new RecordField("Name", "Name"),
                                TargetField  = new RecordField(Fields.account_.name, Fields.account_.name)
                            }
                        }
                    },
                    new ImportSqlRequest.SqlImportTableMapping
                    {
                        SourceTable = new RecordType("TestRecords", "TestRecords"),
                        TargetType  = new RecordType(Entities.jmcg_testentity, Entities.jmcg_testentity),
                        Mappings    = new []
                        {
                            new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping()
                            {
                                SourceColumn = new RecordField("Name", "Name"),
                                TargetField  = new RecordField(Fields.jmcg_testentity_.jmcg_name, Fields.jmcg_testentity_.jmcg_name)
                            },
                            new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping()
                            {
                                SourceColumn = new RecordField("Account", "Account"),
                                TargetField  = new RecordField(Fields.jmcg_testentity_.jmcg_account, Fields.jmcg_testentity_.jmcg_account)
                            },
                            new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping()
                            {
                                SourceColumn = new RecordField("Integer", "Integer"),
                                TargetField  = new RecordField(Fields.jmcg_testentity_.jmcg_integer, Fields.jmcg_testentity_.jmcg_integer)
                            }
                        }
                    }
                }
            };

            //create record and field metadata for the source mappings
            //which will be used to create the source database
            var recordMetadatas = new List <RecordMetadata>();

            foreach (var item in request.Mappings)
            {
                var recordMetadata = new RecordMetadata()
                {
                    SchemaName  = item.SourceTable.Key,
                    DisplayName = item.SourceTable.Key
                };
                var fields = new List <FieldMetadata>();
                foreach (var column in item.Mappings)
                {
                    fields.Add(new StringFieldMetadata(column.SourceColumn.Key, column.SourceColumn.Key));
                }
                recordMetadata.Fields = fields;
                recordMetadatas.Add(recordMetadata);
            }

            //if the database doesnt exist create it
            if (!SqlProvider.DatabaseExists(sqlServer, databaseName))
            {
                SqlProvider.CreateDatabase(sqlServer, databaseName);
            }
            //ensure the source database contains tables/columns for our source mappings metadata
            var recordMetadataService = new SqlRecordMetadataService(new SqlServerAndDbSettings(sqlServer, databaseName), recordMetadatas);

            recordMetadataService.RefreshSource();

            //configure synch data
            var recordsToCreate = 3;

            foreach (var tableMapping in request.Mappings)
            {
                //delete all in both
                var truncate = $"truncate table {tableMapping.SourceTable.Key}";
                recordMetadataService.ExecuteSql(truncate);
                DeleteAll(tableMapping.TargetType.Key);

                //create data in the db
                for (var i = 1; i <= recordsToCreate; i++)
                {
                    var newRecord = recordMetadataService.NewRecord(tableMapping.SourceTable.Key);
                    foreach (var fieldMapping in tableMapping.Mappings)
                    {
                        newRecord.SetField(fieldMapping.SourceColumn.Key, i.ToString(), recordMetadataService);
                    }
                    recordMetadataService.Create(newRecord);
                }
            }

            //run the synch
            var app = CreateAndLoadTestApplication <ImportSqlModule>();

            app.AddModule <ConsoleApplicationModule>();

            //navigate to the dialog
            var dialog         = app.NavigateToDialog <ImportSqlModule, ImportSqlDialog>();
            var entryViewmodel = app.GetSubObjectEntryViewModel(dialog);

            app.EnterObject(request, entryViewmodel);
            entryViewmodel.SaveButtonViewModel.Invoke();

            var completionScreen = app.GetCompletionViewModel(dialog);
            var importResponse   = completionScreen.GetObject() as ImportSqlResponse;

            Assert.IsNotNull(importResponse);
            Assert.IsFalse(importResponse.ResponseItems.Any());

            foreach (var tableMapping in request.Mappings)
            {
                var records = XrmRecordService.RetrieveAll(tableMapping.TargetType.Key, null);
                Assert.AreEqual(recordsToCreate, records.Count());
            }

            //point the account field in the db to 3
            var linkAllToAccount3 = $"update TestRecords set Account = 3";

            recordMetadataService.ExecuteSql(linkAllToAccount3);

            dialog         = app.NavigateToDialog <ImportSqlModule, ImportSqlDialog>();
            entryViewmodel = app.GetSubObjectEntryViewModel(dialog);
            app.EnterObject(request, entryViewmodel);

            //okay here we generate a saved request and get the command line for it
            //to also run a console app after this second synch
            ClearSavedRequests(app, entryViewmodel);
            //trigger save request
            var saveRequestButton = entryViewmodel.GetButton("SAVEREQUEST");

            saveRequestButton.Invoke();

            //enter and save details including autoload
            var saveRequestForm = app.GetSubObjectEntryViewModel(entryViewmodel);
            var detailsEntered  = new SaveAndLoadFields()
            {
                Name = "TestName"
            };

            app.EnterAndSaveObject(detailsEntered, saveRequestForm);
            Assert.IsFalse(entryViewmodel.ChildForms.Any());
            Assert.IsFalse(entryViewmodel.LoadingViewModel.IsLoading);

            //invoke load request dialog
            var loadRequestButton = entryViewmodel.GetButton("LOADREQUEST");

            loadRequestButton.Invoke();
            var loadRequestForm = app.GetSubObjectEntryViewModel(entryViewmodel);

            //verify there is a saved request and trigger the generate bat button
            var subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests));

            Assert.IsTrue(subGrid.GridRecords.Count() == 1);
            subGrid.GridRecords.First().IsSelected = true;

            var generateBatButton = subGrid.DynamicGridViewModel.GetButton("GENERATEBAT");

            generateBatButton.Invoke();

            var testFiles = FileUtility.GetFiles(TestingFolder);

            Assert.AreEqual(1, testFiles.Count());
            Assert.IsTrue(testFiles.First().EndsWith(".bat"));
            var batContent = File.ReadAllText(testFiles.First());

            loadRequestForm.CancelButtonViewModel.Invoke();
            Assert.IsFalse(entryViewmodel.ChildForms.Any());
            Assert.IsFalse(entryViewmodel.LoadingViewModel.IsLoading);

            //okay we now have the bat args for later so lets run the update synch in the app
            entryViewmodel.SaveButtonViewModel.Invoke();
            completionScreen = app.GetCompletionViewModel(dialog);
            importResponse   = completionScreen.GetObject() as ImportSqlResponse;
            Assert.IsNotNull(importResponse);
            Assert.IsFalse(importResponse.ResponseItems.Any());

            //verify all point to account 3
            var updatedRecords = XrmRecordService.RetrieveAll(Entities.jmcg_testentity, null);

            Assert.AreEqual(3, updatedRecords.Count());
            Assert.IsTrue(updatedRecords.All(r => r.GetLookupName(Fields.jmcg_testentity_.jmcg_account) == "3"));

            //okay lets fake run it for the console app args generated
            var args = ConsoleTestUtility.CommandLineToArgs(batContent)
                       .Skip(1)
                       .ToArray();

            var arguments       = ConsoleApplication.ParseCommandLineArguments(args);
            var applicationName = arguments.ContainsKey("SettingsFolderName") ? arguments["SettingsFolderName"] : "Unknown Console Context";

            //okay need to create app
            var dependencyResolver = new DependencyContainer();
            var controller         = new ConsoleApplicationController(applicationName, dependencyResolver);
            var settingsManager    = new DesktopSettingsManager(controller);
            var applicationOptions = new ApplicationOptionsViewModel(controller);
            var consoleApp         = new ConsoleApplication(controller, applicationOptions, settingsManager);

            //load modules in folder path
            consoleApp.LoadModulesInExecutionFolder();

            var connection = GetSavedXrmRecordConfiguration();

            XrmConnectionModule.RefreshXrmServices(GetXrmRecordConfiguration(), app.Controller);
            app.Controller.RegisterInstance <ISavedXrmConnections>(new SavedXrmConnections
            {
                Connections = new[] { connection }
            });

            //run app
            consoleApp.Run(args);

            //email created for each synch
            var emails = XrmRecordService.RetrieveAll(Entities.email, null);

            Assert.AreEqual(3, emails.Count());
            Assert.IsTrue(emails.All(e => e.GetOptionKey(Fields.email_.statecode) == OptionSets.Email.ActivityStatus.Completed.ToString()));
        }
        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));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Load a form for saving the details
        /// </summary>
        public void SaveObject(RecordEntryFormViewModel viewModel)
        {
            try
            {
                //subgrids don't map directly to object so need to unload them to object
                //before saving the record
                if (viewModel is ObjectEntryViewModel)
                {
                    var oevm = viewModel as ObjectEntryViewModel;
                    oevm.LoadSubgridsToObject();
                    var theObject     = oevm.GetObject();
                    var theObjectType = theObject.GetType();
                    if (!theObjectType.IsTypeOf(typeof(IAllowSaveAndLoad)))
                    {
                        throw new Exception(string.Format("type {0} is not of type {1}", theObjectType.Name, typeof(IAllowSaveAndLoad).Name));
                    }

                    ApplicationController.LogEvent("Save Request Loaded", new Dictionary <string, string> {
                        { "Type", theObjectType.Name }
                    });
                    //this is an object specifically for entering the name and autoload properties
                    //they are mapped into the IAllowSaveAndLoad object after entry then it is saved
                    var saveObject = new SaveAndLoadFields();

                    Action saveSettings = () =>
                    {
                        //map the entered properties into the new object we are saving
                        var mapper = new ClassSelfMapper();
                        mapper.Map(saveObject, theObject);

                        var settingsManager = viewModel.ApplicationController.ResolveType(typeof(ISettingsManager)) as ISettingsManager;
                        var settings        = settingsManager.Resolve <SavedSettings>(theObjectType);

                        //if we selected autoload then set it false for the others
                        if (saveObject.Autoload)
                        {
                            foreach (var item in settings.SavedRequests.Cast <IAllowSaveAndLoad>())
                            {
                                item.Autoload = false;
                            }
                        }
                        //add the one and save
                        settings.SavedRequests = settings.SavedRequests.Union(new[] { theObject }).ToArray();
                        settingsManager.SaveSettingsObject(settings, theObjectType);
                        ApplicationController.LogEvent("Save Request Completed", new Dictionary <string, string> {
                            { "Type", theObjectType.Name }, { "Is Completed Event", true.ToString() }, { "Autoload", saveObject.Autoload.ToString() }
                        });
                        //reload the form and notify
                        viewModel.ClearChildForms();
                        viewModel.LoadCustomFunctions();
                        viewModel.ApplicationController.UserMessage($"You Input Has Been Saved. To Load A Saved Input Or Generate A Bat Executable Click The '{LoadButtonLabel}' Button");
                    };

                    //load the entry form
                    var os  = new ObjectRecordService(saveObject, viewModel.ApplicationController, null);
                    var ofs = new ObjectFormService(saveObject, os, null);
                    var fc  = new FormController(os, ofs, viewModel.ApplicationController);

                    var vm = new ObjectEntryViewModel(saveSettings, () => viewModel.ClearChildForms(), saveObject, fc);
                    viewModel.LoadChildForm(vm);
                }
            }
            catch (Exception ex)
            {
                ApplicationController.ThrowException(ex);
            }
        }
Ejemplo n.º 6
0
        public void SavedRequestModuleTest()
        {
            var testApplication = CreateAndLoadTestApplication <SavedRequestModule>();

            testApplication.AddModule <TestSavedRequestModule>();

            //set to no previously saved ones
            var savedRequests   = new SavedSettings();
            var settingsManager = testApplication.Controller.ResolveType <ISettingsManager>();

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

            //navigate to the request and populate the string field
            var entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestModule, TestSavedRequestDialog>();
            var request   = new TestSavedRequestDialogRequest()
            {
                SomeArbitraryString = nameof(TestSavedRequestDialogRequest.SomeArbitraryString)
            };

            testApplication.EnterObject(request, entryForm);

            var loadDropDownButtons = entryForm.CustomFunctions.Where(f => f.Id == "LOADREQUESTDROPDOWN");

            Assert.AreEqual(0, loadDropDownButtons.Count());

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

            saveRequestButton.Invoke();

            //enter and save details including autoload
            var saveRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm);
            var detailsEntered  = new SaveAndLoadFields()
            {
                Name     = "TestName",
                Autoload = true
            };

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

            //okay lets verify that the dropdown of saved requests loaded
            loadDropDownButtons = entryForm.CustomFunctions.Where(f => f.Id == "LOADREQUESTDROPDOWN");
            Assert.AreEqual(1, loadDropDownButtons.Count());
            Assert.AreEqual(1, loadDropDownButtons.First().ChildButtons.Count());
            Assert.AreEqual("TestName", loadDropDownButtons.First().ChildButtons.First().Label);

            //reopen app/dialog and verify autoloads
            testApplication = CreateAndLoadTestApplication <SavedRequestModule>();
            testApplication.AddModule <TestSavedRequestModule>();
            entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestModule, TestSavedRequestDialog>();

            Assert.AreEqual(nameof(TestSavedRequestDialogRequest.SomeArbitraryString), entryForm.GetStringFieldFieldViewModel(nameof(TestSavedRequestDialogRequest.SomeArbitraryString)).Value);

            //clear the loaded string value
            entryForm.GetStringFieldFieldViewModel(nameof(TestSavedRequestDialogRequest.SomeArbitraryString)).Value = "Something Else";

            //invoke load request dialog in the dropdown
            loadDropDownButtons = entryForm.CustomFunctions.Where(f => f.Id == "LOADREQUESTDROPDOWN");
            Assert.AreEqual(1, loadDropDownButtons.Count());
            Assert.AreEqual(1, loadDropDownButtons.First().ChildButtons.Count());
            Assert.AreEqual("TestName", loadDropDownButtons.First().ChildButtons.First().Label);
            loadDropDownButtons.First().ChildButtons.First().Invoke();

            //verify loads
            Assert.IsFalse(entryForm.ChildForms.Any());
            Assert.IsFalse(entryForm.LoadingViewModel.IsLoading);
            Assert.AreEqual(nameof(TestSavedRequestDialogRequest.SomeArbitraryString), entryForm.GetStringFieldFieldViewModel(nameof(TestSavedRequestDialogRequest.SomeArbitraryString)).Value);

            //clear the loaded string value
            entryForm.GetStringFieldFieldViewModel(nameof(TestSavedRequestDialogRequest.SomeArbitraryString)).Value = "Something Else";

            //invoke load request dialog in the edit form
            var loadRequestButton = entryForm.GetButton("LOADREQUEST");

            loadRequestButton.Invoke();
            var loadRequestForm = testApplication.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);
            Assert.AreEqual(nameof(TestSavedRequestDialogRequest.SomeArbitraryString), entryForm.GetStringFieldFieldViewModel(nameof(TestSavedRequestDialogRequest.SomeArbitraryString)).Value);

            //verify if delete on the load form

            //invoke load form
            loadRequestButton = entryForm.GetButton("LOADREQUEST");
            loadRequestButton.Invoke();
            loadRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm);
            //delete the saved request in the grid
            subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests));
            subGrid.DynamicGridViewModel.DeleteRow(subGrid.GridRecords.First());
            loadRequestForm.SaveButtonViewModel.Invoke();
            Assert.IsFalse(entryForm.ChildForms.Any());
            Assert.IsFalse(entryForm.LoadingViewModel.IsLoading);

            //no saved dropdown
            loadDropDownButtons = entryForm.CustomFunctions.Where(f => f.Id == "LOADREQUESTDROPDOWN");
            Assert.AreEqual(0, loadDropDownButtons.Count());

            //verify no longer a saved request resolved by the settings manager
            settingsManager = testApplication.Controller.ResolveType <ISettingsManager>();
            savedRequests   = settingsManager.Resolve <SavedSettings>(typeof(TestSavedRequestDialogRequest));
            Assert.IsFalse(savedRequests.SavedRequests.Any());

            //verify does not throw fatal error if lookup referenced is deleted in the saved requests

            //create a saved request for a deleted solution
            var solution = ReCreateTestSolution();

            request = new TestSavedRequestDialogRequest()
            {
                Name                = "Foo",
                Autoload            = true,
                SomeArbitraryString = nameof(TestSavedRequestDialogRequest.SomeArbitraryString),
                XrmLookupField      = solution.ToLookup()
            };
            savedRequests = new SavedSettings()
            {
                SavedRequests = new[] { request }
            };
            settingsManager.SaveSettingsObject(savedRequests, typeof(TestSavedRequestDialogRequest));
            XrmRecordService.Delete(solution);

            //verify a user message is thrown when the autoload fires
            testApplication = CreateAndLoadTestApplication <SavedRequestModule>();
            testApplication.AddModule <TestSavedRequestModule>();

            try
            {
                entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestModule, TestSavedRequestDialog>();
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is FakeUserMessageException);
            }

            //verify saved requests load when a saved request has a deleted solution

            //create a saved request with a solution
            solution = ReCreateTestSolution();
            request  = new TestSavedRequestDialogRequest()
            {
                Name = "Foo",
                SomeArbitraryString = nameof(TestSavedRequestDialogRequest.SomeArbitraryString),
                XrmLookupField      = solution.ToLookup()
            };
            savedRequests = new SavedSettings()
            {
                SavedRequests = new[] { request }
            };
            settingsManager.SaveSettingsObject(savedRequests, typeof(TestSavedRequestDialogRequest));

            //load the dialog
            testApplication = CreateAndLoadTestApplication <SavedRequestModule>();
            testApplication.AddModule <TestSavedRequestModule>();
            entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestModule, TestSavedRequestDialog>();

            //delete the solution
            XrmRecordService.Delete(solution);

            //invoke the load request form
            loadRequestButton = entryForm.GetButton("LOADREQUEST");
            loadRequestButton.Invoke();

            //veirfy a user message is thrown if try to load the one with the deleted solution
            loadRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm);
            subGrid         = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests));
            Assert.IsTrue(subGrid.GridRecords.Count() == 1);
            subGrid.GridRecords.First().IsSelected = true;
            loadButton = subGrid.DynamicGridViewModel.GetButton("LOADREQUEST");

            try
            {
                loadButton.Invoke();
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is FakeUserMessageException);
            }
        }