public ColumnEditDialogViewModel(string recordType, IEnumerable <GridFieldMetadata> currentColumns, IRecordService recordService, Action <IEnumerable <GridFieldMetadata> > applySelections, Action onCancel, IApplicationController applicationController, bool allowLinkedFields = false)
            : base(applicationController)
        {
            RecordService     = recordService;
            RecordType        = recordType;
            ApplySelections   = applySelections;
            AllowLinkedFields = allowLinkedFields;
            var currentColumnsSelectables = new List <SelectableColumn>();

            foreach (GridFieldMetadata column in currentColumns)
            {
                string fieldNameIncludingPrefix = column.AliasedFieldName ?? column.FieldName;
                if (fieldNameIncludingPrefix.Contains("."))
                {
                    //aliased columns are stored within this vm in form
                    //lookup|recordtype.fieldname
                    //but externally in form
                    //lookup_recordtype.fieldname
                    //due to | not being a valid alias value
                    fieldNameIncludingPrefix = fieldNameIncludingPrefix.Replace("_" + column.AltRecordType + ".", "|" + column.AltRecordType + ".");
                }
                currentColumnsSelectables.Add(new SelectableColumn(fieldNameIncludingPrefix, column.OverrideLabel ?? RecordService.GetFieldLabel(column.FieldName, RecordType), column.WidthPart, RemoveCurrentField, AddCurrentField, ApplicationController));
            }
            CurrentColumns = new ObservableCollection <SelectableColumn>(currentColumnsSelectables);

            LinkOptions   = GetLinkOptionsList(RecordType);
            _selectedLink = LinkOptions.First();

            SelectableColumns = new ObservableCollection <SelectableColumn>(GetSelectableColumnsFor(RecordType));

            ApplyButtonViewModel  = new XrmButtonViewModel("Apply Changes", ApplyChanges, ApplicationController, "Apply The Selection Changes");
            CancelButtonViewModel = new XrmButtonViewModel("Cancel Changes", onCancel, ApplicationController, "Cancel The Selection Changes And Return");

            RefreshIsFirstColumn();
        }
Beispiel #2
0
        private static PicklistOption GetAsPicklistOption(object item)
        {
            object keyValue = GetKeyValue(item);
            var    option   = new PicklistOption(keyValue.ToString(), item.ToString());

            return(option);
        }
Beispiel #3
0
        private IEnumerable <PicklistOption> GetLinkOptionsList(string thisType)
        {
            //allow selection of lookup fields to allow inclusion of fields in related entities
            //or the primary entity being queried
            var thisTypeSelection = new PicklistOption(thisType, RecordService.GetDisplayName(thisType));
            var linkOptions       = new List <PicklistOption>();

            if (AllowLinkedFields)
            {
                var lookupFields = RecordService
                                   .GetFields(thisType)
                                   .Where(f => new[] { RecordFieldType.Lookup, RecordFieldType.Customer }.Contains(RecordService.GetFieldType(f, thisType)));
                foreach (var field in lookupFields)
                {
                    var targetTypes = RecordService.GetLookupTargetType(field, thisType);
                    if (targetTypes != null)
                    {
                        var fieldLabel       = RecordService.GetFieldLabel(field, thisType);
                        var split            = targetTypes.Split(',');
                        var areMultipleTypes = split.Count() > 1;
                        foreach (var type in split)
                        {
                            var key   = field + "|" + type;
                            var label = fieldLabel + (areMultipleTypes ? $" ({RecordService.GetDisplayName(type)})" : "");
                            linkOptions.Add(new PicklistOption(key, label));
                        }
                    }
                }
                linkOptions.Sort();
            }
            linkOptions.Insert(0, thisTypeSelection);
            return(linkOptions);
        }
Beispiel #4
0
        public void SavedXrmConnectionsModuleTestEnterSavedConnections()
        {
            var recordConnection = new XrmConfigurationMapper().Map(XrmConfiguration as XrmConfiguration);

            //clear all saved settings for test script app
            var testApplication = TestApplication.CreateTestApplication();
            var settingsFolder  = testApplication.Controller.SettingsPath;

            FileUtility.DeleteFiles(settingsFolder);

            //create app with saved connections module
            testApplication = TestApplication.CreateTestApplication();
            testApplication.AddModule <SavedXrmConnectionsModule>();

            //navgiate to adding saved conneciton
            var dialog = testApplication.NavigateToDialog <SavedXrmConnectionsModule, SavedXrmConnectionsDialog>();
            var savedConnectionsEntryForm = testApplication.GetSubObjectEntryViewModel(dialog);

            //click to add a connection to the grid
            var connectionsGrid = savedConnectionsEntryForm.GetEnumerableFieldViewModel(nameof(SavedXrmConnections.SavedXrmConnections.Connections));

            connectionsGrid.DynamicGridViewModel.AddRowButton.Invoke();
            var connectionEntry = testApplication.GetSubObjectEntryViewModel(savedConnectionsEntryForm);

            //verify autocompletes only display for those not reliant on existing values
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel);
            Assert.IsNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Domain)).AutocompleteViewModel);
            Assert.IsNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Username)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel);

            //enter the connection
            connectionEntry.GetBooleanFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Active)).Value = true;
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Name)).Value    = "Script Entry 1";
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).SearchButton.Invoke();
            Assert.IsTrue(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.Any());
            connectionEntry.GetPicklistFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.AuthenticationProviderType)).Value = connectionEntry.GetPicklistFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.AuthenticationProviderType)).ItemsSource.First(p => p == PicklistOption.EnumToPicklistOption(recordConnection.AuthenticationProviderType));
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).Value      = recordConnection.DiscoveryServiceAddress;
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Domain)).Value   = recordConnection.Domain;
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Username)).Value = recordConnection.Username;
            connectionEntry.GetFieldViewModel(nameof(SavedXrmRecordConfiguration.Password)).ValueObject      = recordConnection.Password;

            //including using autocomplete for the organisation unique name
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).SearchButton.Invoke();
            Assert.IsTrue(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.Any());
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.SelectedRow = connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.First(r => r.GetStringFieldFieldViewModel(nameof(Xrm.Organisation.UniqueName)).Value == recordConnection.OrganizationUniqueName);
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.SetToSelectedRow();
            Assert.AreEqual(recordConnection.OrganizationUniqueName, connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).Value);

            //save the connection and verify added to grid
            Assert.IsTrue(connectionEntry.Validate());
            connectionEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(savedConnectionsEntryForm.ChildForms.Any());
            connectionsGrid = savedConnectionsEntryForm.GetEnumerableFieldViewModel(nameof(SavedXrmConnections.SavedXrmConnections.Connections));
            Assert.AreEqual(1, connectionsGrid.GridRecords.Count);

            //save the connections and verify reloads same form with the connection
            Assert.IsTrue(savedConnectionsEntryForm.Validate());
            savedConnectionsEntryForm.SaveButtonViewModel.Invoke();

            savedConnectionsEntryForm = savedConnectionsEntryForm = testApplication.GetSubObjectEntryViewModel(dialog, index: 1);
            connectionsGrid           = savedConnectionsEntryForm.GetEnumerableFieldViewModel(nameof(SavedXrmConnections.SavedXrmConnections.Connections));
            Assert.AreEqual(1, connectionsGrid.GridRecords.Count);

            //go to add another connection and verify username now has autocomplete due to existing value
            connectionsGrid.DynamicGridViewModel.AddRowButton.Invoke();
            connectionEntry = testApplication.GetSubObjectEntryViewModel(savedConnectionsEntryForm);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Username)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel);
        }
        private void PopulateRecordEntry(RecordEntryViewModelBase entryViewModel, bool populateSubgrids = true)
        {
            var mainForminContent = entryViewModel.ParentForm ?? entryViewModel;

            entryViewModel.GetFieldViewModel <BigIntFieldViewModel>(nameof(TestAllFieldTypes.BigIntField)).Value   = 100;
            entryViewModel.GetBooleanFieldFieldViewModel(nameof(TestAllFieldTypes.BooleanField)).Value             = true;
            entryViewModel.GetFieldViewModel <DateFieldViewModel>(nameof(TestAllFieldTypes.DateField)).Value       = new DateTime(1990, 11, 15);
            entryViewModel.GetFieldViewModel <DecimalFieldViewModel>(nameof(TestAllFieldTypes.DecimalField)).Value = 200;
            entryViewModel.GetFieldViewModel <DoubleFieldViewModel>(nameof(TestAllFieldTypes.DoubleField)).Value   = 300;
            entryViewModel.GetFieldViewModel <FileRefFieldViewModel>(nameof(TestAllFieldTypes.FileField)).Value    = new FileReference(TestConstants.TestFolder);
            entryViewModel.GetFieldViewModel <FolderFieldViewModel>(nameof(TestAllFieldTypes.FolderField)).Value   = new Folder(TestConstants.TestFolder);
            entryViewModel.GetIntegerFieldFieldViewModel(nameof(TestAllFieldTypes.Integerield)).Value                = 400;
            entryViewModel.GetFieldViewModel <MoneyFieldViewModel>(nameof(TestAllFieldTypes.MoneyField)).Value       = 500;
            entryViewModel.GetFieldViewModel <PasswordFieldViewModel>(nameof(TestAllFieldTypes.PasswordField)).Value = new Password("Password");
            entryViewModel.GetPicklistFieldFieldViewModel(nameof(TestAllFieldTypes.PicklistField)).Value             = PicklistOption.EnumToPicklistOption(TestEnum.Option2);
            entryViewModel.GetStringFieldFieldViewModel(nameof(TestAllFieldTypes.StringField)).Value       = "Something";
            entryViewModel.GetFieldViewModel <UrlFieldViewModel>(nameof(TestAllFieldTypes.UrlField)).Value = new Url("http://google.com", "Google");

            entryViewModel.GetRecordTypeFieldViewModel(nameof(TestAllFieldTypes.RecordTypeField)).Value   = entryViewModel.GetRecordTypeFieldViewModel(nameof(TestAllFieldTypes.RecordTypeField)).ItemsSource.First();
            entryViewModel.GetRecordFieldFieldViewModel(nameof(TestAllFieldTypes.RecordFieldField)).Value = entryViewModel.GetRecordFieldFieldViewModel(nameof(TestAllFieldTypes.RecordFieldField)).ItemsSource.First();

            var recordFieldMultiSelectField = entryViewModel.GetFieldViewModel <RecordFieldMultiSelectFieldViewModel>(nameof(TestAllFieldTypes.RecordFieldMultiSelectField));

            recordFieldMultiSelectField.EditAction();
            //multiselection is done in a child dialog so select several and invoke save
            Assert.IsTrue(mainForminContent.ChildForms.Any());
            var multiSelectFieldEntry = mainForminContent.ChildForms.First() as MultiSelectDialogViewModel <RecordField>;

            multiSelectFieldEntry.ItemsSource.ElementAt(1).Select = true;
            multiSelectFieldEntry.ItemsSource.ElementAt(2).Select = true;
            multiSelectFieldEntry.ApplyButtonViewModel.Invoke();

            Assert.IsFalse(mainForminContent.ChildForms.Any());
            //verify values selected have been applied to the multiselect field
            Assert.IsNotNull(recordFieldMultiSelectField.DisplayLabel);
            Assert.AreEqual(2, recordFieldMultiSelectField.Value.Count());
            Assert.IsTrue(recordFieldMultiSelectField.Value.Any(p => p.Value == multiSelectFieldEntry.ItemsSource.ElementAt(1).Item));
            Assert.IsTrue(recordFieldMultiSelectField.Value.Any(p => p.Value == multiSelectFieldEntry.ItemsSource.ElementAt(1).Item));

            var lookupField = entryViewModel.GetLookupFieldFieldViewModel(nameof(TestAllFieldTypes.LookupField));

            lookupField.Search();
            lookupField.OnRecordSelected(lookupField.LookupGridViewModel.DynamicGridViewModel.GridRecords.First().Record);
            Assert.IsNotNull(lookupField.Value);
            Assert.AreEqual(lookupField.Value.Name, lookupField.EnteredText);

            var multiSelectField = entryViewModel.GetFieldViewModel <PicklistMultiSelectFieldViewModel>(nameof(TestAllFieldTypes.PicklistMultiSelectField));

            multiSelectField.EditAction();
            //multiselection is done in a child form so select several and invoke save
            Assert.IsTrue(mainForminContent.ChildForms.Any());
            var multiSelectOptionEntry = mainForminContent.ChildForms.First() as MultiSelectDialogViewModel <PicklistOption>;

            multiSelectOptionEntry.ItemsSource.ElementAt(1).Select = true;
            multiSelectOptionEntry.ItemsSource.ElementAt(2).Select = true;
            multiSelectOptionEntry.ApplyButtonViewModel.Invoke();
            Assert.IsFalse(mainForminContent.ChildForms.Any());
            //verify values selected have been applied to the multiselect field
            Assert.IsNotNull(multiSelectField.DisplayLabel);
            Assert.AreEqual(2, multiSelectField.Value.Count());
            Assert.IsTrue(multiSelectField.Value.Any(p => p == PicklistOption.EnumToPicklistOption(TestEnum.Option2)));
            Assert.IsTrue(multiSelectField.Value.Any(p => p == PicklistOption.EnumToPicklistOption(TestEnum.Option3)));

            if (entryViewModel is RecordEntryFormViewModel && populateSubgrids)
            {
                var gridField = ((RecordEntryFormViewModel)entryViewModel).GetEnumerableFieldViewModel(nameof(TestAllFieldTypes.EnumerableField));
                gridField.AddRow();
                var row = gridField.GridRecords.First();
                PopulateRecordEntry(row, populateSubgrids: false);
                gridField.AddRow();
                row = gridField.GridRecords.First();
                PopulateRecordEntry(row, populateSubgrids: false);
            }

            var objectFieldViewModel = entryViewModel.GetObjectFieldFieldViewModel(nameof(TestAllFieldTypes.ObjectField));

            objectFieldViewModel.SelectedItem = objectFieldViewModel.ItemsSource.First(r => r.Record != null);
            Assert.IsNotNull(objectFieldViewModel.Value);
        }
 protected bool IsValidForCode(PicklistOption option)
 {
     return
         (!string.IsNullOrWhiteSpace(CreateCodeLabel(option.Value)));
 }
        private IEnumerable <PicklistOption> GetSelections()
        {
            if (RecordType == null)
            {
                return(new PicklistOption[0]);
            }

            //need to generate a list of all join optionds
            //n:N, 1:N or N:1

            var options      = new List <PicklistOption>();
            var lookupFields = RecordService.GetFieldMetadata(RecordType)
                               .Where(f => f.FieldType == Record.Metadata.RecordFieldType.Lookup || f.FieldType == Record.Metadata.RecordFieldType.Customer)
                               .ToArray();

            //okay these need appending for each target type
            foreach (var lookupField in lookupFields)
            {
                var targetTypes = RecordService.GetLookupTargetType(lookupField.SchemaName, RecordType);
                if (!string.IsNullOrWhiteSpace(targetTypes))
                {
                    var relationshipLabel = lookupField.DisplayName;
                    var split             = targetTypes.Split(',');
                    var isMultiple        = split.Count() > 1;
                    foreach (var target in split)
                    {
                        var key    = $"n1:{lookupField.SchemaName}:{target}";
                        var label  = relationshipLabel + (isMultiple ? ($" ({RecordService.GetDisplayName(target)})") : null);
                        var option = new PicklistOption(key, label);
                        options.Add(option);
                    }
                }
            }

            var manyToManyRelationships = RecordService.GetManyToManyRelationships(RecordType).ToArray();

            foreach (var manyToMany in manyToManyRelationships)
            {
                if (manyToMany.RecordType1 == RecordType)
                {
                    var key    = $"nn:{manyToMany.IntersectEntityName}:{manyToMany.Entity1IntersectAttribute}:{manyToMany.Entity2IntersectAttribute}:{manyToMany.RecordType2}";
                    var label  = manyToMany.RecordType2UseCustomLabel ? manyToMany.RecordType2CustomLabel : RecordService.GetDisplayName(manyToMany.RecordType2);
                    var option = new PicklistOption(key, label);
                    options.Add(option);
                }
                if (manyToMany.RecordType2 == RecordType)
                {
                    var key    = $"nn:{manyToMany.IntersectEntityName}:{manyToMany.Entity2IntersectAttribute}:{manyToMany.Entity1IntersectAttribute}:{manyToMany.RecordType1}";
                    var label  = manyToMany.RecordType1UseCustomLabel ? manyToMany.RecordType1CustomLabel : RecordService.GetDisplayName(manyToMany.RecordType1);
                    var option = new PicklistOption(key, label);
                    options.Add(option);
                }
            }

            var oneToManyRelationships = RecordService.GetOneToManyRelationships(RecordType).ToArray();

            foreach (var oneToMany in oneToManyRelationships)
            {
                if (RecordService.FieldExists(oneToMany.ReferencingAttribute, oneToMany.ReferencingEntity))
                {
                    var key    = $"1n:{oneToMany.ReferencingEntity}:{oneToMany.ReferencingAttribute}";
                    var label  = $"{RecordService.GetDisplayName(oneToMany.ReferencingEntity)} ({RecordService.GetFieldLabel(oneToMany.ReferencingAttribute, oneToMany.ReferencingEntity)})";
                    var option = new PicklistOption(key, label);
                    options.Add(option);
                }
            }

            options.Sort((p1, p2) => p1.CompareTo(p2));
            options = options.Distinct().ToList();
            return(options);
        }
        public void VsixPackageSettingsModuleTestEnterPackageSettings()
        {
            var recordConnection = new XrmConfigurationMapper().Map(XrmConfiguration as XrmConfiguration);

            InitialiseModuleXrmConnection = false;
            var testApplication = CreateAndLoadTestApplication <XrmPackageSettingsModule>(loadXrmConnection: false);

            //navigate to package settings will initally load connection entry as we dont yet have one
            var dialog          = testApplication.NavigateToDialog <XrmPackageSettingsModule, XrmPackageSettingsDialog>();
            var connectionEntry = dialog.Controller.UiItems.First() as ObjectEntryViewModel;

            //verify autocompletes only display for those not reliant on existing values
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel);
            Assert.IsNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Domain)).AutocompleteViewModel);
            Assert.IsNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Username)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel);

            //enter the connection
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Name)).Value = "Script Entry 1";
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).SearchButton.Invoke();
            Assert.IsTrue(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.Any());
            connectionEntry.GetPicklistFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.AuthenticationProviderType)).Value = connectionEntry.GetPicklistFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.AuthenticationProviderType)).ItemsSource.First(p => p == PicklistOption.EnumToPicklistOption(recordConnection.AuthenticationProviderType));
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).Value      = recordConnection.DiscoveryServiceAddress;
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Domain)).Value   = recordConnection.Domain;
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Username)).Value = recordConnection.Username;
            connectionEntry.GetFieldViewModel(nameof(SavedXrmRecordConfiguration.Password)).ValueObject      = recordConnection.Password;

            //including using autocomplete for the organisation unique name
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).SearchButton.Invoke();
            Assert.IsTrue(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.Any());
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.SelectedRow = connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.First(r => r.GetStringFieldFieldViewModel(nameof(Xrm.Organisation.UniqueName)).Value == recordConnection.OrganizationUniqueName);
            connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.SetToSelectedRow();
            Assert.AreEqual(recordConnection.OrganizationUniqueName, connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).Value);

            //save the connection and verify added to grid
            Assert.IsTrue(connectionEntry.Validate());
            connectionEntry.SaveButtonViewModel.Invoke();

            var packageSettingsEntryForm = testApplication.GetSubObjectEntryViewModel(dialog, index: 1) as ObjectEntryViewModel;
            var connectionsGrid          = packageSettingsEntryForm.GetEnumerableFieldViewModel(nameof(XrmPackageSettings.Connections));

            Assert.AreEqual(1, connectionsGrid.GridRecords.Count);

            //go to add another connection and verify username now has autocomplete due to existing value
            connectionsGrid.DynamicGridViewModel.AddRowButton.Invoke();
            connectionEntry = testApplication.GetSubObjectEntryViewModel(packageSettingsEntryForm);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.Username)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="recordType"></param>
        /// <param name="dependantValue">Various uses...</param>
        /// <param name="record">The record containing the field we are getting the options for</param>
        /// <returns></returns>
        public override IEnumerable <PicklistOption> GetPicklistKeyValues(string fieldName, string recordType, string dependantValue, IRecord record)
        {
            //if the property is type RecordType
            //then get the record types from the lookup service
            var fieldType = this.GetFieldType(fieldName, recordType);

            switch (fieldType)
            {
            case RecordFieldType.RecordType:
            {
                var lookupService = GetLookupService(fieldName, recordType, dependantValue, record);

                if (OptionSetLimitedValues != null &&
                    OptionSetLimitedValues.ContainsKey(fieldName) &&
                    OptionSetLimitedValues[fieldName].Any())
                {
                    return(OptionSetLimitedValues[fieldName]
                           .Select(at => new RecordType(at, LookupService.GetRecordTypeMetadata(at).DisplayName))
                           .OrderBy(rt => rt.Value)
                           .ToArray());
                }
                else
                {
                    return(lookupService == null
                                ? new RecordType[0]
                                : lookupService.GetAllRecordTypes()
                           .Select(r => new RecordType(r, lookupService.GetRecordTypeMetadata(r).DisplayName))
                           .ToArray());
                }
            }

            case RecordFieldType.RecordField:
            {
                if (dependantValue == null)
                {
                    return(new RecordField[0]);
                }

                var    options         = new List <PicklistOption>();
                var    type            = dependantValue;
                string parentReference = null;
                if (dependantValue != null && dependantValue.Contains(':'))
                {
                    type            = ((string)dependantValue).Split(':').ElementAt(0);
                    parentReference = ((string)dependantValue).Split(':').ElementAt(1);
                }
                var lookupService = GetLookupService(fieldName, recordType, parentReference, record);

                var allFieldsMetadata = type.IsNullOrWhiteSpace() || lookupService == null
                            ? new IFieldMetadata[0]
                            : lookupService
                                        .GetFieldMetadata(type);
                var propertyInfo     = GetPropertyInfo(fieldName, recordType);
                var lookupConditions = propertyInfo.GetCustomAttributes <LookupCondition>();
                foreach (var condition in lookupConditions.Select(lc => lc.ToCondition()))
                {
                    allFieldsMetadata =
                        allFieldsMetadata.Where(f => MeetsCondition(f, condition)).ToArray();
                }
                var onlyInclude = OptionSetLimitedValues == null || !OptionSetLimitedValues.ContainsKey(fieldName)
                            ? null
                            : OptionSetLimitedValues[fieldName];

                return(allFieldsMetadata
                       .Select(f => new RecordField(f.SchemaName, f.DisplayName))
                       .Where(f => !f.Value.IsNullOrWhiteSpace())
                       .Where(f => onlyInclude == null || onlyInclude.Contains(f.Key))
                       .OrderBy(f => f.Value)
                       .ToArray());
            }

            case RecordFieldType.Picklist:
            {
                var type    = GetPropertyType(fieldName, recordType);
                var options = new List <PicklistOption>();
                if (type.Name == "IEnumerable`1")
                {
                    type = type.GenericTypeArguments[0];
                }
                foreach (Enum item in type.GetEnumValues())
                {
                    var enumMember             = item.GetType().GetMember(item.ToString()).First();
                    var validForFieldAttribute = enumMember.GetCustomAttribute <ValidForFieldTypes>();
                    if (validForFieldAttribute == null || dependantValue == null)
                    {
                        options.Add(PicklistOption.EnumToPicklistOption(item));
                    }
                    else
                    {
                        if (validForFieldAttribute.FieldTypes.Contains(dependantValue.ParseEnum <RecordFieldType>()))
                        {
                            options.Add(PicklistOption.EnumToPicklistOption(item));
                        }
                    }
                }
                var propertyInfo   = GetPropertyInfo(fieldName, recordType);
                var limitAttribute = propertyInfo.GetCustomAttribute <LimitPicklist>();
                if (limitAttribute != null)
                {
                    options =
                        options.Where(
                            o =>
                            limitAttribute.ToInclude.Select(kv => Convert.ToInt32(kv).ToString())
                            .Contains(o.Key))
                        .ToList();
                }
                return(options);
            }
            }
            throw new ArgumentOutOfRangeException(
                      string.Format("GetPicklistOptions Not Implemented For Fiel Of Type {0} Field: {1} Type {2}", fieldType,
                                    fieldName, recordType));
        }
        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));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="recordType"></param>
        /// <param name="dependantValue">Various uses...</param>
        /// <param name="record">The record containing the field we are getting the options for</param>
        /// <returns></returns>
        public override IEnumerable <PicklistOption> GetPicklistKeyValues(string fieldName, string recordType, string dependantValue, IRecord record)
        {
            //if the property is type RecordType
            //then get the record types from the lookup service
            var fieldType = this.GetFieldType(fieldName, recordType);

            switch (fieldType)
            {
            case RecordFieldType.RecordType:
            {
                var lookupService = GetLookupService(fieldName, recordType, dependantValue, record);

                if (OptionSetLimitedValues != null &&
                    OptionSetLimitedValues.ContainsKey(fieldName) &&
                    OptionSetLimitedValues[fieldName].Any())
                {
                    return(OptionSetLimitedValues[fieldName]
                           .Select(at => new RecordType(at, LookupService.GetRecordTypeMetadata(at).DisplayName))
                           .OrderBy(rt => rt.Value)
                           .ToArray());
                }
                else
                {
                    if (lookupService == null)
                    {
                        return(new RecordType[0]);
                    }
                    var recordTypes     = lookupService.GetAllRecordTypes();
                    var includeExplicit = new[] { "subject", "uom", "productpricelevel", "activitymimeattachment" };
                    var options         = recordTypes
                                          .Select(rt => lookupService.GetRecordTypeMetadata(rt))
                                          .Where(mt => mt.Searchable || includeExplicit.Contains(mt.SchemaName))
                                          .Select(mt => new RecordType(mt.SchemaName, mt.DisplayName))
                                          .ToList();
                    var classType = GetClassType(recordType);
                    var prop      = classType.GetProperty(fieldName);
                    if (prop.GetCustomAttribute <IncludeManyToManyIntersects>() != null)
                    {
                        var manyToManys = lookupService.GetManyToManyRelationships();
                        foreach (var manyToMany in manyToManys)
                        {
                            if (!options.Any(p => p.Key == manyToMany.IntersectEntityName))
                            {
                                options.Add(new RecordType(manyToMany.IntersectEntityName, manyToMany.PicklistDisplay));
                            }
                        }
                    }
                    var exclusionAttribute = prop.GetCustomAttribute <RecordTypeExclusions>();
                    if (exclusionAttribute != null)
                    {
                        options.RemoveAll(o => exclusionAttribute.RecordTypes.Contains(o.Key));
                    }
                    options.RemoveAll(o => string.IsNullOrWhiteSpace(o.Value));
                    return(options);
                }
            }

            case RecordFieldType.RecordField:
            {
                if (dependantValue == null)
                {
                    return(new RecordField[0]);
                }

                var    options         = new List <PicklistOption>();
                var    type            = dependantValue;
                string parentReference = null;
                if (dependantValue != null && dependantValue.Contains(':'))
                {
                    type            = ((string)dependantValue).Split(':').ElementAt(0);
                    parentReference = ((string)dependantValue).Split(':').ElementAt(1);
                }
                var lookupService = GetLookupService(fieldName, recordType, parentReference, record);

                var allFieldsMetadata = type.IsNullOrWhiteSpace() || lookupService == null
                            ? new IFieldMetadata[0]
                            : lookupService
                                        .GetFieldMetadata(type);
                var propertyInfo     = GetPropertyInfo(fieldName, recordType);
                var lookupConditions = propertyInfo.GetCustomAttributes <LookupCondition>();
                foreach (var condition in lookupConditions.Select(lc => lc.ToCondition()))
                {
                    allFieldsMetadata =
                        allFieldsMetadata.Where(f => MeetsCondition(f, condition)).ToArray();
                }
                var onlyInclude = OptionSetLimitedValues == null || !OptionSetLimitedValues.ContainsKey(fieldName)
                            ? null
                            : OptionSetLimitedValues[fieldName];

                return(allFieldsMetadata
                       .Select(f => new RecordField(f.SchemaName, f.IsPrimaryKey ? f.DisplayName + " Id" : f.DisplayName))
                       .Where(f => !f.Value.IsNullOrWhiteSpace())
                       .Where(f => onlyInclude == null || onlyInclude.Contains(f.Key))
                       .OrderBy(f => f.Value)
                       .ToArray());
            }

            case RecordFieldType.Picklist:
            {
                var type    = GetPropertyType(fieldName, recordType);
                var options = new List <PicklistOption>();
                if (type.Name == "IEnumerable`1")
                {
                    type = type.GenericTypeArguments[0];
                }
                foreach (Enum item in type.GetEnumValues())
                {
                    var enumMember             = item.GetType().GetMember(item.ToString()).First();
                    var validForFieldAttribute = enumMember.GetCustomAttribute <ValidForFieldTypes>();
                    if (validForFieldAttribute == null || dependantValue == null)
                    {
                        options.Add(PicklistOption.EnumToPicklistOption(item));
                    }
                    else
                    {
                        var dependencySplit = dependantValue.Split('|');
                        var fieldTypeEnum   = dependencySplit[0].ParseEnum <RecordFieldType>();
                        var supplementaryDependencyArguments = dependencySplit.Length == 1 || dependencySplit[1] == ""
                                    ? null
                                    : dependencySplit[1].Split(',');

                        if (validForFieldAttribute.FieldTypes.Contains(fieldTypeEnum))
                        {
                            if (validForFieldAttribute.IntegerType.HasValue)
                            {
                                if (supplementaryDependencyArguments != null &&
                                    supplementaryDependencyArguments.Contains(validForFieldAttribute.IntegerType.Value.ToString()))
                                {
                                    options.Add(PicklistOption.EnumToPicklistOption(item));
                                }
                            }
                            else if (validForFieldAttribute.TargetType != null)
                            {
                                if (supplementaryDependencyArguments != null &&
                                    supplementaryDependencyArguments.Contains(validForFieldAttribute.TargetType))
                                {
                                    options.Add(PicklistOption.EnumToPicklistOption(item));
                                }
                            }
                            else if (validForFieldAttribute.TargetType == null || supplementaryDependencyArguments == null)
                            {
                                options.Add(PicklistOption.EnumToPicklistOption(item));
                            }
                        }
                    }
                }
                var propertyInfo   = GetPropertyInfo(fieldName, recordType);
                var limitAttribute = propertyInfo.GetCustomAttribute <LimitPicklist>();
                if (limitAttribute != null)
                {
                    options =
                        options.Where(
                            o =>
                            limitAttribute.ToInclude.Select(kv => Convert.ToInt32(kv).ToString())
                            .Contains(o.Key))
                        .ToList();
                }
                return(options);
            }
            }
            return(null);
        }
        private void AutoOpenSelections()
        {
            var customFunction = new OnChangeFunction((RecordEntryViewModelBase revm, string changedField) =>
            {
                try
                {
                    if (revm is GridRowViewModel)
                    {
                        switch (changedField)
                        {
                        case nameof(ExportRecordType.IncludeAllFields):
                            {
                                if (!revm.GetBooleanFieldFieldViewModel(nameof(ExportRecordType.IncludeAllFields)).Value ?? false)
                                {
                                    var fieldsIncludedViewModel = revm.GetEnumerableFieldViewModel(nameof(ExportRecordType.IncludeOnlyTheseFields));
                                    if (fieldsIncludedViewModel.Value == null || !fieldsIncludedViewModel.Value.GetEnumerator().MoveNext())
                                    {
                                        fieldsIncludedViewModel.BulkAddButton?.Invoke();
                                    }
                                }
                                break;
                            }

                        case nameof(ExportRecordType.Type):
                            {
                                if (revm.GetPicklistFieldFieldViewModel(nameof(ExportRecordType.Type)).Value == PicklistOption.EnumToPicklistOption(ExportType.SpecificRecords))
                                {
                                    var recordsIncludedViewModel = revm.GetEnumerableFieldViewModel(nameof(ExportRecordType.SpecificRecordsToExport));
                                    if (recordsIncludedViewModel.Value == null || !recordsIncludedViewModel.Value.GetEnumerator().MoveNext())
                                    {
                                        recordsIncludedViewModel.BulkAddButton?.Invoke();
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    revm.ApplicationController.ThrowException(ex);
                }
            });

            this.AddOnChangeFunction(customFunction, typeof(ExportRecordType));
        }
        public void XrmConnectionModuleTestEnterConnection()
        {
            var recordConnection = new XrmConfigurationMapper().Map(XrmConfiguration as XrmConfiguration);

            //clear all saved settings for test script app
            var testApplication = TestApplication.CreateTestApplication();
            var settingsFolder  = testApplication.Controller.SettingsPath;

            FileUtility.DeleteFiles(settingsFolder);

            //create app with saved connections module
            testApplication = TestApplication.CreateTestApplication();
            testApplication.AddModule <SavedXrmConnectionsModule>();

            //navgiate to adding saved conneciton
            var module = testApplication.GetModule <XrmConnectionModule>();

            module.DialogCommand();
            var dialog          = testApplication.GetNavigatedDialog <XrmConnectionDialog>();
            var connectionEntry = testApplication.GetSubObjectEntryViewModel(dialog);

            //verify autocompletes only display for those not reliant on existing values
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel);
            Assert.IsNull(connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.Domain)).AutocompleteViewModel);
            Assert.IsNull(connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.Username)).AutocompleteViewModel);
            Assert.IsNotNull(connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel);

            //enter the connection
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.Name)).Value = "Script Entry 1";
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.DiscoveryServiceAddress)).SearchButton.Invoke();
            Assert.IsTrue(connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.DiscoveryServiceAddress)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.Any());
            connectionEntry.GetPicklistFieldFieldViewModel(nameof(XrmRecordConfiguration.AuthenticationProviderType)).Value = connectionEntry.GetPicklistFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.AuthenticationProviderType)).ItemsSource.First(p => p == PicklistOption.EnumToPicklistOption(recordConnection.AuthenticationProviderType));
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.DiscoveryServiceAddress)).Value      = recordConnection.DiscoveryServiceAddress;
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.Domain)).Value   = recordConnection.Domain;
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.Username)).Value = recordConnection.Username;
            connectionEntry.GetFieldViewModel(nameof(XrmRecordConfiguration.Password)).ValueObject      = recordConnection.Password;

            //including using autocomplete for the organisation unique name
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.OrganizationUniqueName)).SearchButton.Invoke();
            Assert.IsTrue(connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.Any());
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.SelectedRow = connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.DynamicGridViewModel.GridRecords.First(r => r.GetStringFieldFieldViewModel(nameof(Xrm.Organisation.UniqueName)).Value == recordConnection.OrganizationUniqueName);
            connectionEntry.GetStringFieldFieldViewModel(nameof(XrmRecordConfiguration.OrganizationUniqueName)).AutocompleteViewModel.SetToSelectedRow();
            Assert.AreEqual(recordConnection.OrganizationUniqueName, connectionEntry.GetStringFieldFieldViewModel(nameof(SavedXrmRecordConfiguration.OrganizationUniqueName)).Value);

            //save the connection and verify added to grid
            Assert.IsTrue(connectionEntry.Validate());
            connectionEntry.SaveButtonViewModel.Invoke();
        }
Beispiel #14
0
 public PicklistOptionSet()
 {
     PicklistOptions = new PicklistOption[] {};
 }
        public void VsixGeneralAssemblyCreateUpdateAndRunPluginAssemblyTest()
        {
            //alright so this is a slightly broader example for deploying assembly
            //covering more operations updating an assembly

            var testAssemblyName = "TestAssemblyDeploy.Plugins";

            DeleteTestPluginAssembly(useAssemblyName: testAssemblyName);
            Assert.IsFalse(GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName).Any());

            var          assemblyV1        = Path.Combine(GetSolutionRootFolder().FullName, "SolutionItems", "TestAssemblyDeploy", "Version1", testAssemblyName + ".dll");
            var          assemblyV2        = Path.Combine(GetSolutionRootFolder().FullName, "SolutionItems", "TestAssemblyDeploy", "Version2", testAssemblyName + ".dll");
            var          assemblyV3        = Path.Combine(GetSolutionRootFolder().FullName, "SolutionItems", "TestAssemblyDeploy", "Version3", testAssemblyName + ".dll");
            const string testWorkflowGroup = "ScriptWorkflowGroup";
            const string inputArgumentV1   = "InputArgument1";
            const string inputArgumentV2   = "InputArgument2";

            //okay initial assembly has
            //1 * plugin
            //1 * workflow activity with 1 input argument
            var testApplication = CreateAndLoadTestApplication <DeployAssemblyModule>(loadXrmConnection: false);

            //deploy first assembly version
            VisualStudioService.SetSelectedProjectAssembly(assemblyV1);
            var deployDialog    = testApplication.NavigateToDialog <DeployAssemblyModule, DeployAssemblyDialog>();
            var deployEntryForm = testApplication.GetSubObjectEntryViewModel(deployDialog);
            var pluginGrid      = deployEntryForm.GetEnumerableFieldViewModel(nameof(DeployAssemblyRequest.PluginTypes));

            //verify correct plugin types
            Assert.AreEqual(2, pluginGrid.GridRecords.Count);
            Assert.AreEqual(1, pluginGrid.GridRecords.Count(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));
            Assert.AreEqual(1, pluginGrid.GridRecords.Count(p => !p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));
            foreach (var item in pluginGrid.GridRecords.Where(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))))
            {
                //set workflow group
                item.GetStringFieldFieldViewModel(nameof(PluginType.GroupName)).Value = testWorkflowGroup;
            }
            Assert.IsTrue(deployEntryForm.Validate());
            deployEntryForm.SaveButtonViewModel.Invoke();
            //verify no errors
            var deployResponse = deployDialog.CompletionItem as DeployAssemblyResponse;

            Assert.IsFalse(deployResponse.HasError);

            //verify assembly created with correct plugin types
            var assemblyRecords = GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName);

            Assert.AreEqual(1, assemblyRecords.Count());
            foreach (var assembly in assemblyRecords)
            {
                var pluginTypes = GetPluginTypes(assembly);
                Assert.AreEqual(2, pluginTypes.Count());

                //first assembly version only has one of 2 workflow input arguments
                var argumentWorkflow = pluginTypes.First(p => p.GetStringField(Fields.plugintype_.name) == "TestAssemblyDeployWorkflowActivity1");
                Assert.AreEqual(testWorkflowGroup, argumentWorkflow.GetStringField(Fields.plugintype_.workflowactivitygroupname));
                var inputXmlField = argumentWorkflow.GetStringField(Fields.plugintype_.customworkflowactivityinfo);
                Assert.IsTrue(inputXmlField.Contains(inputArgumentV1));
                Assert.IsFalse(inputXmlField.Contains(inputArgumentV2));
            }

            //second assembly has
            //2 * plugin
            //2 * workflow activity
            //input argument added to the workflow activity in initial deployment

            //deploy second assembly version
            VisualStudioService.SetSelectedProjectAssembly(assemblyV2);
            deployDialog    = testApplication.NavigateToDialog <DeployAssemblyModule, DeployAssemblyDialog>();
            deployEntryForm = testApplication.GetSubObjectEntryViewModel(deployDialog);
            pluginGrid      = deployEntryForm.GetEnumerableFieldViewModel(nameof(DeployAssemblyRequest.PluginTypes));
            //verify correct plugin types
            Assert.AreEqual(4, pluginGrid.GridRecords.Count);
            Assert.AreEqual(2, pluginGrid.GridRecords.Count(p => p.GetBooleanFieldFieldViewModel(nameof(PluginType.IsDeployed)).Value ?? false));
            Assert.AreEqual(2, pluginGrid.GridRecords.Count(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));
            Assert.AreEqual(2, pluginGrid.GridRecords.Count(p => !p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));

            //set this to also refresh workflow arguments
            deployEntryForm.GetBooleanFieldFieldViewModel(nameof(DeployAssemblyRequest.TriggerWorkflowActivityRefreshes)).Value = true;
            foreach (var item in pluginGrid.GridRecords.Where(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))))
            {
                //set workflow group
                item.GetStringFieldFieldViewModel(nameof(PluginType.GroupName)).Value = testWorkflowGroup;
            }
            Assert.IsTrue(deployEntryForm.Validate());
            deployEntryForm.SaveButtonViewModel.Invoke();
            //verify no errors
            deployResponse = deployDialog.CompletionItem as DeployAssemblyResponse;
            Assert.IsFalse(deployResponse.HasError);

            //verify assembly created with correct plugin types
            assemblyRecords = GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName);
            Assert.AreEqual(1, assemblyRecords.Count());
            foreach (var assembly in assemblyRecords)
            {
                var pluginTypes = GetPluginTypes(assembly);
                Assert.AreEqual(4, pluginTypes.Count());

                //second assembly version only has one of 2 workflow input arguments
                var argumentWorkflow = pluginTypes.First(p => p.GetStringField(Fields.plugintype_.name) == "TestAssemblyDeployWorkflowActivity1");
                Assert.AreEqual(testWorkflowGroup, argumentWorkflow.GetStringField(Fields.plugintype_.workflowactivitygroupname));
                var inputXmlField = argumentWorkflow.GetStringField(Fields.plugintype_.customworkflowactivityinfo);
                Assert.IsTrue(inputXmlField.Contains(inputArgumentV1));
                Assert.IsTrue(inputXmlField.Contains(inputArgumentV2));
            }

            //next assembly has added an error thrown for account plugin
            //so we need to create a plugin trigger for it on create account
            //update the assembly
            //then verify the error is thrown wher creating an account

            //add plugin trigger for peoperation create account
            testApplication.AddModule <ManagePluginTriggersModule>();
            var triggersDialog    = testApplication.NavigateToDialog <ManagePluginTriggersModule, ManagePluginTriggersDialog>();
            var triggersEntryForm = testApplication.GetSubObjectEntryViewModel(triggersDialog);
            var triggersGrid      = triggersEntryForm.GetEnumerableFieldViewModel(nameof(ManagePluginTriggersRequest.Triggers));

            //add trigger to the grid
            triggersGrid.DynamicGridViewModel.AddRowButton.Invoke();
            Assert.IsTrue(triggersEntryForm.ChildForms.Any());
            var triggerEntry = testApplication.GetSubObjectEntryViewModel(triggersEntryForm);

            triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Plugin)).SelectedItem  = triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Plugin)).ItemsSource.First(p => p.Name == "TestAssemblyDeployPluginRegistration");
            triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Message)).SelectedItem = triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Message)).ItemsSource.First(p => p.Name == "Create");
            triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Stage)).Value        = triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Stage)).ItemsSource.First(p => p.Key == PicklistOption.EnumToPicklistOption(PluginTrigger.PluginStage.PreOperationEvent).Key);
            triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Mode)).Value         = triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Mode)).ItemsSource.First(p => p.Key == PicklistOption.EnumToPicklistOption(PluginTrigger.PluginMode.Synch).Key);
            triggerEntry.GetRecordTypeFieldViewModel(nameof(PluginTrigger.RecordType)).Value      = triggerEntry.GetRecordTypeFieldViewModel(nameof(PluginTrigger.RecordType)).ItemsSource.First(p => p.Key == Entities.account);
            Assert.IsTrue(triggerEntry.Validate());
            triggerEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(triggersEntryForm.ChildForms.Any());

            //save
            Assert.IsTrue(triggersEntryForm.Validate());
            triggersEntryForm.SaveButtonViewModel.Invoke();
            //verify no errors
            var triggersResponse = triggersDialog.CompletionItem as ManagePluginTriggersResponse;

            Assert.IsFalse(triggersResponse.HasError);

            //verify create account as we havewnt deployed the assembly throwing an error yet
            var account = CreateAccount();

            //update the assembly to the one throwing error for account create
            var updateAssemblyModule = testApplication.AddModule <UpdateAssemblyModule>();

            VisualStudioService.SetSelectedProjectAssembly(assemblyV3);
            updateAssemblyModule.DialogCommand();
            var updateAssemblyDialog = testApplication.GetNavigatedDialog <UpdateAssemblyDialog>();

            Assert.IsNull(updateAssemblyDialog.FatalException);
            var updateResponse = updateAssemblyDialog.CompletionItem as UpdateAssemblyResponse;

            Assert.IsNotNull(updateResponse.CompletionMessage);

            //verify error thrown now when creating account
            WaitTillTrue(() =>
            {
                var errorThrown = false;
                try
                {
                    account = CreateAccount();
                }
                catch (Exception)
                {
                    errorThrown = true;
                }
                return(errorThrown);
            });

            //update the assembly to the one doesnt throw an error
            VisualStudioService.SetSelectedProjectAssembly(assemblyV2);
            updateAssemblyModule.DialogCommand();
            updateAssemblyDialog = testApplication.GetNavigatedDialog <UpdateAssemblyDialog>();
            Assert.IsNull(updateAssemblyDialog.FatalException);
            updateResponse = updateAssemblyDialog.CompletionItem as UpdateAssemblyResponse;
            Assert.IsNotNull(updateResponse.CompletionMessage);

            //verify error not thrown now when creating account
            WaitTillTrue(() =>
            {
                var errorThrown = false;
                try
                {
                    account = CreateAccount();
                }
                catch (Exception)
                {
                    errorThrown = true;
                }
                return(!errorThrown);
            });

            //delete the assembly
            //if we dont delete it next time the script is run there are sometimes caching issues
            //due to deleting the creating the assembly in quick succession
            DeleteTestPluginAssembly(useAssemblyName: testAssemblyName);
            Assert.IsFalse(GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName).Any());
        }
Beispiel #16
0
        private void PopulateRecordEntry(RecordEntryViewModelBase entryViewModel, bool populateSubgrids = true)
        {
            entryViewModel.GetFieldViewModel <BigIntFieldViewModel>(nameof(TestAllFieldTypes.BigIntField)).Value   = 100;
            entryViewModel.GetBooleanFieldFieldViewModel(nameof(TestAllFieldTypes.BooleanField)).Value             = true;
            entryViewModel.GetFieldViewModel <DateFieldViewModel>(nameof(TestAllFieldTypes.DateField)).Value       = new DateTime(1990, 11, 15);
            entryViewModel.GetFieldViewModel <DecimalFieldViewModel>(nameof(TestAllFieldTypes.DecimalField)).Value = 200;
            entryViewModel.GetFieldViewModel <DoubleFieldViewModel>(nameof(TestAllFieldTypes.DoubleField)).Value   = 300;
            entryViewModel.GetFieldViewModel <FileRefFieldViewModel>(nameof(TestAllFieldTypes.FileField)).Value    = new FileReference(TestConstants.TestFolder);
            entryViewModel.GetFieldViewModel <FolderFieldViewModel>(nameof(TestAllFieldTypes.FolderField)).Value   = new Folder(TestConstants.TestFolder);
            entryViewModel.GetIntegerFieldFieldViewModel(nameof(TestAllFieldTypes.Integerield)).Value                = 400;
            entryViewModel.GetFieldViewModel <MoneyFieldViewModel>(nameof(TestAllFieldTypes.MoneyField)).Value       = 500;
            entryViewModel.GetFieldViewModel <PasswordFieldViewModel>(nameof(TestAllFieldTypes.PasswordField)).Value = new Password("Password");
            entryViewModel.GetPicklistFieldFieldViewModel(nameof(TestAllFieldTypes.PicklistField)).Value             = PicklistOption.EnumToPicklistOption(TestEnum.Option2);
            entryViewModel.GetStringFieldFieldViewModel(nameof(TestAllFieldTypes.StringField)).Value       = "Something";
            entryViewModel.GetFieldViewModel <UrlFieldViewModel>(nameof(TestAllFieldTypes.UrlField)).Value = new Url("http://google.com", "Google");

            entryViewModel.GetRecordTypeFieldViewModel(nameof(TestAllFieldTypes.RecordTypeField)).Value   = entryViewModel.GetRecordTypeFieldViewModel(nameof(TestAllFieldTypes.RecordTypeField)).ItemsSource.First();
            entryViewModel.GetRecordFieldFieldViewModel(nameof(TestAllFieldTypes.RecordFieldField)).Value = entryViewModel.GetRecordFieldFieldViewModel(nameof(TestAllFieldTypes.RecordFieldField)).ItemsSource.First();

            var recordFieldMultiSelectField = entryViewModel.GetFieldViewModel <RecordFieldMultiSelectFieldViewModel>(nameof(TestAllFieldTypes.RecordFieldMultiSelectField));

            recordFieldMultiSelectField.MultiSelectsVisible = true;
            recordFieldMultiSelectField.DynamicGridViewModel.GridRecords.ElementAt(1).GetBooleanFieldFieldViewModel(nameof(RecordFieldMultiSelectFieldViewModel.SelectablePicklistOption.Select)).Value = true;
            recordFieldMultiSelectField.DynamicGridViewModel.GridRecords.ElementAt(2).GetBooleanFieldFieldViewModel(nameof(RecordFieldMultiSelectFieldViewModel.SelectablePicklistOption.Select)).Value = true;
            Assert.IsNotNull(recordFieldMultiSelectField.DisplayLabel);
            Assert.AreEqual(2, recordFieldMultiSelectField.Value.Count());
            Assert.IsTrue(recordFieldMultiSelectField.Value.Any(p => p.Value == recordFieldMultiSelectField.DynamicGridViewModel.GridRecords.ElementAt(1).GetStringFieldFieldViewModel(nameof(RecordFieldMultiSelectFieldViewModel.SelectablePicklistOption.Item)).Value));
            Assert.IsTrue(recordFieldMultiSelectField.Value.Any(p => p.Value == recordFieldMultiSelectField.DynamicGridViewModel.GridRecords.ElementAt(2).GetStringFieldFieldViewModel(nameof(RecordFieldMultiSelectFieldViewModel.SelectablePicklistOption.Item)).Value));

            var lookupField = entryViewModel.GetLookupFieldFieldViewModel(nameof(TestAllFieldTypes.LookupField));

            lookupField.Search();
            lookupField.OnRecordSelected(lookupField.LookupGridViewModel.DynamicGridViewModel.GridRecords.First().Record);
            Assert.IsNotNull(lookupField.Value);
            Assert.AreEqual(lookupField.Value.Name, lookupField.EnteredText);

            var multiSelectField = entryViewModel.GetFieldViewModel <PicklistMultiSelectFieldViewModel>(nameof(TestAllFieldTypes.PicklistMultiSelectField));

            multiSelectField.MultiSelectsVisible = true;
            multiSelectField.DynamicGridViewModel.GridRecords.ElementAt(1).GetBooleanFieldFieldViewModel(nameof(PicklistMultiSelectFieldViewModel.SelectablePicklistOption.Select)).Value = true;
            multiSelectField.DynamicGridViewModel.GridRecords.ElementAt(2).GetBooleanFieldFieldViewModel(nameof(PicklistMultiSelectFieldViewModel.SelectablePicklistOption.Select)).Value = true;
            Assert.IsNotNull(multiSelectField.DisplayLabel);
            Assert.AreEqual(2, multiSelectField.Value.Count());
            Assert.IsTrue(multiSelectField.Value.Any(p => p == PicklistOption.EnumToPicklistOption(TestEnum.Option2)));
            Assert.IsTrue(multiSelectField.Value.Any(p => p == PicklistOption.EnumToPicklistOption(TestEnum.Option3)));

            if (entryViewModel is RecordEntryFormViewModel && populateSubgrids)
            {
                var gridField = ((RecordEntryFormViewModel)entryViewModel).GetEnumerableFieldViewModel(nameof(TestAllFieldTypes.EnumerableField));
                gridField.AddRow();
                var row = gridField.GridRecords.First();
                PopulateRecordEntry(row, populateSubgrids: false);
                gridField.AddRow();
                row = gridField.GridRecords.First();
                PopulateRecordEntry(row, populateSubgrids: false);
            }

            var objectFieldViewModel = entryViewModel.GetObjectFieldFieldViewModel(nameof(TestAllFieldTypes.ObjectField));

            objectFieldViewModel.SelectedItem = objectFieldViewModel.ItemsSource.First();
            Assert.IsNotNull(objectFieldViewModel.Value);
        }