예제 #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InventoryItemListViewModel"/> class
        /// </summary>
        public InventoryItemListViewModel(
            IInventoryManager inventoryManager,
            IDialogCoordinator coordinator,
            Dispatcher dispatcher)
        {
            this._inventoryManager  = inventoryManager;
            this._dialogCoordinator = coordinator;
            this._dispatcher        = dispatcher;

            CreateItemCommand = new DelegateCommand(this.ExecuteCreate);
            EditItemCommand   = new DelegateCommand(this.ExecuteEdit, () => SelectedItems.Any());
            DeleteItemCommand = new DelegateCommand(this.ExecuteDelete, () => Items != null && Items.Count > 0);
            SearchCommand     = new DelegateCommand(this.ExecuteSearch, () => SearchString != null && SearchString != string.Empty);

            GridHeaders = new List <string>()
            {
                "Code", "Description", "Vendor", "Quantity", "Cost",
                "Price", "Contractor Price", "Electrician Price"
            };

            DropDownOptions = GetDropDownOptions().OrderBy(item => item).ToList();
            SelectedField   = DropDownOptions.First();

            SelectedItems = new List <InventoryItem>();
            Items         = new ObservableCollection <InventoryItem>(_inventoryManager.Inventory.Items);

            ItemsToModify = new ObservableCollection <InventoryItem>();
            ItemsToModify.CollectionChanged += HandleSave;
            IsSaving = false;
        }
예제 #2
0
        public T SelectOptionFromMyEnviornmentDropDown <T>(DropDownOptions optionName) where T : class
        {
            MyEnvironmentDropDown.Click();
            switch (optionName)
            {
            case DropDownOptions.Structure:
                WebDriverFactory.BrowserWaitInstance.Until(ExpectedConditions.ElementToBeClickable(MyEnvironmentDropDown.FindElement(By.XPath(HomePageLocators.StructureButtonLocator)))).Click();
                Thread.Sleep(2000);
                return((T)Activator.CreateInstance(typeof(T)));

            case DropDownOptions.Users:
                MyEnvironmentDropDown.FindElement(By.LinkText(HomePageLocators.UsersButtonLocator)).Click();
                return((T)Activator.CreateInstance(typeof(T)));

            case DropDownOptions.Participants:
                MyEnvironmentDropDown.FindElement(By.LinkText(HomePageLocators.ParticipantsButtonLocator)).Click();
                return((T)Activator.CreateInstance(typeof(T)));

            case DropDownOptions.Orders:
                MyEnvironmentDropDown.FindElement(By.LinkText(HomePageLocators.OrdersButtonLocator)).Click();
                return((T)Activator.CreateInstance(typeof(T)));

            default:
                throw new ArgumentOutOfRangeException("Option in dropdown doesn't find.");
            }
        }
예제 #3
0
    public void DropdownOptionSelected(int indexSelected)
    {
        Debug.Log("Selected: " + myDropdown.options[indexSelected].text);
        //System.Type myType = typeof(DropDownOptions);

        DropDownOptions enumSelected = (DropDownOptions)System.Enum.Parse(typeof(DropDownOptions), myDropdown.options[indexSelected].text);
    }
예제 #4
0
        public async Task AddSelectItem(string id, string key, DropDownOptions dropDown)
        {
            var selectObject = await _context.SelectLists.Find(w => w.FormId == id && w.PropertyKey == key).SingleAsync();

            var filter = Builders <SelectList> .Filter.Eq(s => s.Id, selectObject.Id);

            var update = Builders <SelectList> .Update.AddToSet(s => s.Items, dropDown);

            await _context.SelectLists.UpdateOneAsync(filter, update);
        }
예제 #5
0
        protected override IEnumerable <string> MergeDependencies(IJsonCustomFieldDefinition json, bool overwrite)
        {
            var properties = DisplayInfo.Merge(json.Display).ToList();

            if (json.Options != null)
            {
                DropDownOptions.Update(json.Options.Select(a => a.GetFromCache <DropDownOption, IJsonCustomDropDownOption>(Auth, overwrite)));
                properties.Add(nameof(CustomFieldDefinition.Options));
            }

            return(properties);
        }
예제 #6
0
        public void Search()
        {
            PrefabInfo current = null;

            UIScrollPanelItem.ItemData selected = null;
            if (scrollPanel.selectedItem != null)
            {
                current = scrollPanel.selectedItem.asset.prefab;
            }

            string          text = "";
            DropDownOptions type = DropDownOptions.All;

            if (input != null)
            {
                text = input.text;
                type = (DropDownOptions)typeFilter.selectedIndex;

                if (!FindIt.isRicoEnabled && type >= DropDownOptions.Rico)
                {
                    type += 2;
                }
            }

            // set up prop categories for props generated by Elektrix's TVP mod. Need the TVP Patch mod
            if (FindIt.isTVPPatchEnabled && !AssetTagList.instance.isTVPPatchModProcessed)
            {
                AssetTagList.instance.SetTVPProps();
            }

            // extra size check for growable
            if (type == DropDownOptions.Growable)
            {
                // if switch back from rico with size > 4, default size = all
                if (UISearchBox.instance.buildingSizeFilterIndex.x > 4)
                {
                    UISearchBox.instance.sizeFilterX.selectedIndex = 0;
                }
                if (UISearchBox.instance.buildingSizeFilterIndex.y > 4)
                {
                    UISearchBox.instance.sizeFilterY.selectedIndex = 0;
                }
            }

            matches = AssetTagList.instance.Find(text, type);

            // sort by used/unused instance count
            if (Settings.showInstancesCounter && Settings.instanceCounterSort != 0)
            {
                if (Settings.instanceCounterSort == 1)
                {
                    if (Settings.includePOinstances)
                    {
                        matches = matches.OrderByDescending(s => (s.instanceCount + s.poInstanceCount)).ToList();
                    }
                    else
                    {
                        matches = matches.OrderByDescending(s => s.instanceCount).ToList();
                    }
                }
                else
                {
                    if (Settings.includePOinstances)
                    {
                        matches = matches.OrderBy(s => (s.instanceCount + s.poInstanceCount)).ToList();
                    }
                    else
                    {
                        matches = matches.OrderBy(s => s.instanceCount).ToList();
                    }
                }
            }

            // sort by most recently downloaded
            else if (!Settings.useRelevanceSort)
            {
                matches = matches.OrderByDescending(s => s.downloadTime).ToList();
            }
            // sort by relevance, same as original Find It
            else
            {
                // sort network by ui priority instead
                if (UISearchBox.instance?.typeFilter.selectedIndex == 1)
                {
                    matches = matches.OrderBy(s => s.uiPriority).ToList();
                }
                else
                {
                    text = text.ToLower().Trim();
                    // if search input box is not empty, sort by score
                    if (!text.IsNullOrWhiteSpace())
                    {
                        float maxScore = 0;
                        foreach (Asset assetItr in matches)
                        {
                            if (assetItr.score > 0)
                            {
                                maxScore = assetItr.score;
                                break;
                            }
                        }
                        if (maxScore > 0)
                        {
                            matches = matches.OrderByDescending(s => s.score).ToList();
                        }
                        else
                        {
                            matches = matches.OrderBy(s => s.title).ToList();
                        }
                    }
                    // if seach input box is empty, sort by asset title
                    else
                    {
                        matches = matches.OrderBy(s => s.title).ToList();
                    }
                }
            }

            scrollPanel.Clear();
            searchResultList.Clear();
            foreach (Asset asset in matches)
            {
                if (asset.prefab != null)
                {
                    UIScrollPanelItem.ItemData data = new UIScrollPanelItem.ItemData();
                    data.name       = asset.title;// + "_" + asset.steamID;
                    data.tooltip    = Asset.GetLocalizedTooltip(asset, asset.prefab, data.name);
                    data.tooltipBox = GeneratedPanel.GetTooltipBox(TooltipHelper.GetHashCode(data.tooltip));
                    data.asset      = asset;

                    scrollPanel.itemsData.Add(data);
                    searchResultList.Add(data.name);
                    if (asset.prefab == current)
                    {
                        selected = data;
                    }
                }
            }

            scrollPanel.DisplayAt(0);
            scrollPanel.selectedItem = selected;

            if (scrollPanel.selectedItem != null)
            {
                FindIt.SelectPrefab(scrollPanel.selectedItem.asset.prefab);
            }
            else
            {
                ToolsModifierControl.SetTool <DefaultTool>();
            }
        }
        public async Task <ActionResult <bool> > AddSelectItem(string formId, string key, [FromBody] DropDownOptions dropDown)
        {
            await _repo.AddSelectItem(formId, key, dropDown);

            return(NoContent());
        }
예제 #8
0
파일: Property.cs 프로젝트: hol430/ApsimX
        /// <summary>
        /// Instantiates a Property object by reading metadata about
        /// the given property.
        /// </summary>
        /// <param name="obj">The object reference used to fetch the current value of the property.</param>
        /// <param name="metadata">Property metadata.</param>
        public Property(object obj, PropertyInfo metadata)
        {
            IModel model = obj as IModel;

            ID   = Guid.NewGuid();
            Name = metadata.GetCustomAttribute <DescriptionAttribute>()?.ToString();
            if (string.IsNullOrEmpty(Name))
            {
                Name = metadata.Name;
            }

            Tooltip    = metadata.GetCustomAttribute <TooltipAttribute>()?.Tooltip;
            Separators = metadata.GetCustomAttributes <SeparatorAttribute>()?.Select(s => s.ToString())?.ToList();

            Value = metadata.GetValue(obj);
            if (metadata.PropertyType == typeof(DateTime) || (metadata.PropertyType == typeof(DateTime?) && Value != null))
            {
                // Note: ToShortDateString() uses the current culture, which is what we want in this case.
                Value = ((DateTime)Value).ToShortDateString();
            }
            // ?else if property type isn't a struct?
            else if (Value != null && typeof(IModel).IsAssignableFrom(Value.GetType()))
            {
                Value = ((IModel)Value).Name;
            }
            else if (metadata.PropertyType.IsEnum)
            {
                Value = VariableProperty.GetEnumDescription((Enum)Enum.Parse(metadata.PropertyType, Value?.ToString()));
            }
            else if (metadata.PropertyType != typeof(bool) && metadata.PropertyType != typeof(System.Drawing.Color))
            {
                Value = ReflectionUtilities.ObjectToString(Value, CultureInfo.CurrentCulture);
            }

            // fixme - need to fix this unmaintainable mess brought across from the old PropertyPresenter
            DisplayAttribute attrib      = metadata.GetCustomAttribute <DisplayAttribute>();
            DisplayType      displayType = attrib?.Type ?? DisplayType.None;

            // For compatibility with the old PropertyPresenter, assume a default of
            // DisplayType.DropDown if the Values property is specified.
            if (displayType == DisplayType.None && !string.IsNullOrEmpty(attrib?.Values))
            {
                displayType = DisplayType.DropDown;
            }

            if (attrib != null && !string.IsNullOrEmpty(attrib.EnabledCallback))
            {
                BindingFlags flags  = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
                MethodInfo   method = metadata.DeclaringType.GetMethod(attrib.EnabledCallback, flags);
                if (method == null)
                {
                    // Try a property with this name.
                    PropertyInfo enabledProperty = metadata.DeclaringType.GetProperty(attrib.EnabledCallback, flags);
                    if (enabledProperty == null)
                    {
                        throw new InvalidOperationException($"Unable to evaluate enabled callback {attrib.EnabledCallback} for property {metadata.Name} on type {metadata.DeclaringType.FullName} - method or property does not exist");
                    }

                    if (enabledProperty.PropertyType != typeof(bool))
                    {
                        throw new InvalidOperationException($"Property {enabledProperty.Name} is not a valid enabled callback, because it has a return type of {enabledProperty.PropertyType}. It should have a bool return type.");
                    }
                    if (!enabledProperty.CanRead)
                    {
                        throw new InvalidOperationException($"Property {enabledProperty.Name} is not a valid enabled callback, because it does not have a get accessor.");
                    }

                    Enabled = (bool)enabledProperty.GetValue(obj);
                }
                else
                {
                    if (method.ReturnType != typeof(bool))
                    {
                        throw new InvalidOperationException($"Method {metadata.Name} is not a valid enabled callback, because it has a return type of {method.ReturnType}. It should have a bool return type.");
                    }
                    ParameterInfo[]      parameters            = method.GetParameters();
                    List <ParameterInfo> nonOptionalParameters = parameters.Where(p => !p.IsOptional).ToList();
                    if (nonOptionalParameters.Count != 0)
                    {
                        throw new InvalidOperationException($"Method {metadata.Name} is not a valid enabled callback, because it takes {nonOptionalParameters.Count} non-optional arguments ({string.Join(", ", nonOptionalParameters.Select(p => p.Name))}). It should take 0 arguments");
                    }

                    Enabled = (bool)method.Invoke(obj, null);
                }
            }
            else
            {
                Enabled = true;
            }

            switch (displayType)
            {
            case DisplayType.None:
                if (metadata.PropertyType.IsEnum)
                {
                    // Enums use dropdown
                    DropDownOptions = Enum.GetValues(metadata.PropertyType).Cast <Enum>()
                                      .Select(e => VariableProperty.GetEnumDescription(e))
                                      .ToArray();
                    DisplayMethod = PropertyType.DropDown;
                }
                else if (typeof(IModel).IsAssignableFrom(metadata.PropertyType))
                {
                    // Model selector - use a dropdown containing names of all models in scope.
                    DisplayMethod   = PropertyType.DropDown;
                    DropDownOptions = model.FindAllInScope()
                                      .Where(m => metadata.PropertyType.IsAssignableFrom(m.GetType()))
                                      .Select(m => m.Name)
                                      .ToArray();
                }
                else if (metadata.PropertyType == typeof(bool))
                {
                    DisplayMethod = PropertyType.Checkbox;
                }
                else if (metadata.PropertyType == typeof(System.Drawing.Color))
                {
                    DisplayMethod = PropertyType.Colour;
                }
                else
                {
                    DisplayMethod = PropertyType.SingleLineText;
                }
                break;

            case DisplayType.FileName:
                DisplayMethod = PropertyType.File;
                break;

            case DisplayType.FileNames:
                DisplayMethod = PropertyType.Files;
                break;

            case DisplayType.DirectoryName:
                DisplayMethod = PropertyType.Directory;
                break;

            case DisplayType.DropDown:
                string methodName = metadata.GetCustomAttribute <DisplayAttribute>().Values;
                if (methodName == null)
                {
                    throw new ArgumentNullException($"When using DisplayType.DropDown, the Values property must be specified.");
                }
                BindingFlags flags  = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
                MethodInfo   method = model.GetType().GetMethod(methodName, flags);

                object[] args = metadata.GetCustomAttribute <DisplayAttribute>().ValuesArgs;

                // Attempt to resolve links - populating the dropdown may
                // require access to linked models.
                Simulations sims = model.FindAncestor <Simulations>();
                if (sims != null)
                {
                    sims.Links.Resolve(model, allLinks: true, throwOnFail: false);
                }

                DropDownOptions = ((IEnumerable <object>)method.Invoke(model, args))?.Select(v => v?.ToString())?.ToArray();
                DisplayMethod   = PropertyType.DropDown;
                break;

            case DisplayType.CultivarName:
                DisplayMethod = PropertyType.DropDown;
                IPlant       plant         = null;
                PropertyInfo plantProperty = model.GetType().GetProperties().FirstOrDefault(p => typeof(IPlant).IsAssignableFrom(p.PropertyType));
                if (plantProperty != null)
                {
                    plant = plantProperty.GetValue(model) as IPlant;
                }
                else
                {
                    plant = model.FindInScope <IPlant>();
                }
                if (plant != null)
                {
                    DropDownOptions = PropertyPresenterHelpers.GetCultivarNames(plant);
                }
                break;

            case DisplayType.TableName:
                DisplayMethod   = PropertyType.DropDown;
                DropDownOptions = model.FindInScope <IDataStore>()?.Reader?.TableNames?.ToArray();
                break;

            case DisplayType.FieldName:
                DisplayMethod = PropertyType.DropDown;
                IDataStore   storage           = model.FindInScope <IDataStore>();
                PropertyInfo tableNameProperty = model.GetType().GetProperties().FirstOrDefault(p => p.GetCustomAttribute <DisplayAttribute>()?.Type == DisplayType.TableName);
                string       tableName         = tableNameProperty?.GetValue(model) as string;
                if (storage != null && storage.Reader.TableNames.Contains(tableName))
                {
                    DropDownOptions = storage.Reader.ColumnNames(tableName).ToArray();
                }
                break;

            case DisplayType.LifeCycleName:
                DisplayMethod = PropertyType.DropDown;
                Zone zone = model.FindInScope <Zone>();
                if (zone != null)
                {
                    DropDownOptions = PropertyPresenterHelpers.GetLifeCycleNames(zone);
                }
                break;

            case DisplayType.LifePhaseName:
                DisplayMethod = PropertyType.DropDown;
                LifeCycle lifeCycle = null;
                if (attrib.LifeCycleName != null)
                {
                    lifeCycle = model.FindInScope <LifeCycle>(attrib.LifeCycleName);
                }
                else
                {
                    foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (property.PropertyType == typeof(string))
                        {
                            string    value = property.GetValue(model) as string;
                            LifeCycle match = model.FindInScope <LifeCycle>(value);
                            if (match != null)
                            {
                                lifeCycle = match;
                                break;
                            }
                        }
                    }
                }
                if (lifeCycle != null)
                {
                    DropDownOptions = PropertyPresenterHelpers.GetPhaseNames(lifeCycle).ToArray();
                }
                break;

            case DisplayType.Model:
                DisplayMethod   = PropertyType.DropDown;
                DropDownOptions = model.FindAllInScope().Where(m => metadata.PropertyType.IsAssignableFrom(m.GetType()))
                                  .Select(m => m.Name)
                                  .ToArray();
                break;

            case DisplayType.ResidueName:
                if (model is SurfaceOrganicMatter surfaceOM)
                {
                    DisplayMethod   = PropertyType.DropDown;
                    DropDownOptions = surfaceOM.ResidueTypeNames().ToArray();
                    break;
                }
                else
                {
                    throw new NotImplementedException($"Display type {displayType} is only supported on models of type {typeof(SurfaceOrganicMatter).Name}, but model is of type {model.GetType().Name}.");
                }

            case DisplayType.MultiLineText:
                DisplayMethod = PropertyType.MultiLineText;
                if (Value is IEnumerable enumerable && metadata.PropertyType != typeof(string))
                {
                    Value = string.Join(Environment.NewLine, ((IEnumerable)metadata.GetValue(obj)).ToGenericEnumerable());
                }
                break;

            // Should never happen - presenter should handle this(?)
            //case DisplayType.SubModel:
            default:
                throw new NotImplementedException($"Unknown display type {displayType}");
            }

            // If the list of dropdown options doesn't contain the actual value of the
            // property, add that value to the list of valid options.
            if (DisplayMethod == PropertyType.DropDown && Value != null)
            {
                if (DropDownOptions == null)
                {
                    DropDownOptions = new string[1] {
                        Value.ToString()
                    }
                }
                ;
                else if (!DropDownOptions.Contains(Value.ToString()))
                {
                    List <string> values = DropDownOptions.ToList();
                    values.Add(Value.ToString());
                    DropDownOptions = values.ToArray();
                }
            }
        }
예제 #9
0
        private static void SetDropDownOptions <TModel, TInterfaceConstraint>(TModel model, IComponentContext container, PropertyInfo propInfo, IEntity entity)
            where TModel : TInterfaceConstraint, new()
        {
            var attr = propInfo.GetCustomAttributes(true).OfType <ColumnDefinitionAttribute>().FirstOrDefault();

            if (propInfo.PropertyType == typeof(DropDownOptions) && !string.IsNullOrEmpty(attr.DisplayValue) && !string.IsNullOrEmpty(attr.DisplayText))
            {
                Type[]          types       = new Type[] { typeof(string), typeof(object[]), typeof(string), typeof(object[]), typeof(string[]), typeof(string[]) };
                var             ts          = typeof(IEntityService <>);
                var             serviceType = ts.MakeGenericType(new[] { Type.GetType(string.Format(System.Web.Configuration.WebConfigurationManager.AppSettings["DataAssemblyFormat"], attr.EntityName)) });
                var             service     = container.Resolve(serviceType);
                DropDownOptions options     = null;

                //if (model.GetType().IsAssignableTo<IMongoModel>())
                //{
                //    var collectionName = string.Concat(attr.EntityName, "options");
                //    if (string.IsNullOrEmpty(attr.TableOptions))
                //        collectionName = attr.TableOptions;

                //    var mongoDatabase = (IMongoDatabase)service.GetType().GetProperty("MongoDatabase");
                //    var col = mongoDatabase.GetCollection<KeyValue>(collectionName);
                //    var filter = Builders<KeyValue>.Filter;

                //    var list = await col.Find(filter.Empty).ToListAsync();
                //    options = new DropDownOptions { DisplayValue = attr.DisplayValue, DisplayText = attr.DisplayText, Items = list };
                //}
                //{
                string        whereClause = string.Empty;
                List <object> parameters  = null;
                if (!string.IsNullOrEmpty(attr.WhereClause))
                {
                    whereClause = attr.WhereClause;

                    // verify if exists dynamic parameters on where clause
                    // ex.: CustomerId=={CustomerId}
                    if (entity != null)
                    {
                        parameters = new List <object>();
                        int i = 0;

                        var match = Regex.Match(attr.WhereClause, @"\{(\w+)\}");
                        while (match.Success)
                        {
                            var key          = match.Groups[0].Value;
                            var propertyName = match.Groups[1].Value;
                            var value        = entity.GetType().GetProperty(propertyName).GetValue(entity, null);

                            whereClause = whereClause.Replace(key, string.Format("@{0}", i));
                            parameters.Add(value);

                            match = match.NextMatch();
                            i++;
                        }
                    }
                }

                List <string> orderBy = null;
                if (!string.IsNullOrEmpty(attr.OrderBy))
                {
                    orderBy = new List <string>();
                    orderBy.AddRange(attr.OrderBy.Split(new[] { "," }, StringSplitOptions.None));
                    orderBy.ForEach(o => o = o.Trim());
                }

                var parametersArray = (parameters != null) ? parameters.ToArray() : null;
                var orderByArray    = (orderBy != null) ? orderBy.ToArray() : null;

                var keyValues = ((List <KeyValue>)service.GetType().GetMethod("GetEntities", types).Invoke(service, new object[] { "new ( Id as Key, " + attr.DisplayText + " as Value )", null, whereClause, parametersArray, orderByArray, null })).ToArray();
                options = new DropDownOptions {
                    DisplayValue = attr.DisplayValue, DisplayText = attr.DisplayText, Items = keyValues
                };
                //}

                propInfo.SetValue(model, options, null);
            }
        }
        public override void FromXML(XmlNode vNode)
        {
            base.FromXML(vNode);

            foreach (XmlAttribute vNodeAttrib in vNode.Attributes)
            {
                try
                {
                    switch (vNodeAttrib.LocalName)
                    {
                    case "default":
                        DefaultValue = vNodeAttrib.Value;
                        break;
                    }
                } catch (FormatException) {
                    throw new InvalidXMLValueException("OverlayDropDown", vNodeAttrib.Value, InvalidXMLValueException.Reason.FormatIncorrect);
                } catch (OverflowException) {
                    throw new InvalidXMLValueException("OverlayDropDown", vNodeAttrib.Value, InvalidXMLValueException.Reason.Overflow);
                }
            }

            XmlNodeList oNodes = vNode.SelectNodes("Option");

            foreach (XmlNode oNode in oNodes)
            {
                string lbl = null;
                string val = null;

                foreach (XmlAttribute xAttrib in oNode.Attributes)
                {
                    switch (xAttrib.LocalName)
                    {
                    case "label":
                        lbl = xAttrib.Value;
                        break;

                    case "value":
                        val = xAttrib.Value;
                        break;
                    }
                }

                if (lbl != null && val == null)
                {
                    val = lbl;
                }

                if (lbl == null && val != null)
                {
                    lbl = val;
                }

                if (lbl != null && val != null)
                {
                    DropDownOptions.Add(new DropDownOption()
                    {
                        name = lbl, value = val
                    });
                }
            }
        }