public void WHEN_nested_properties_gets_property_with_incorrect_node_names_THEN_value_returned()
        {
            var leafNode = new ConfigurableProperty
            {
                Name  = "leafNode",
                Value = "leaf-value"
            };

            var parentNode = new ConfigurableProperty
            {
                Name            = "parentNode",
                ChildProperties = new List <ConfigurableProperty> {
                    leafNode
                }
            };

            var sut = new ConfigurableProperty
            {
                Name            = "rootNode",
                ChildProperties = new List <ConfigurableProperty> {
                    parentNode
                }
            };

            var tryResult = sut.TryGetProperty(new string[3] {
                "rootNode", "not-the-parentNode", "leafNode"
            },
                                               out var valueResult);

            tryResult.Should().BeFalse();
            valueResult.Should().BeNull();
        }
        public void WHEN_nested_properties_gets_value_with_matched_node_names_THEN_value_returned()
        {
            var leafNode = new ConfigurableProperty {
                Name  = "leafNode",
                Value = "leaf-value"
            };

            var parentNode = new ConfigurableProperty {
                Name            = "parentNode",
                ChildProperties = new List <ConfigurableProperty> {
                    leafNode
                }
            };

            var sut = new ConfigurableProperty
            {
                Name            = "rootNode",
                ChildProperties = new List <ConfigurableProperty> {
                    parentNode
                }
            };

            var tryResult = sut.TryGetValue(new string[3] {
                "rootNode", "parentNode", "leafNode"
            },
                                            out var valueResult);

            tryResult.Should().BeTrue();
            valueResult.Should().Be("leaf-value");
        }
        public void WHEN_property_contains_a_litteral_expression_THEN_type_is_returned_AND_value_can_be_read()
        {
            var sut = new ConfigurableProperty
            {
                Name = "propertyWithExpression"
            };

            sut.ChildProperties.Add(new ConfigurableProperty
            {
                Name            = "expr",
                ChildProperties = new List <ConfigurableProperty>
                {
                    new ConfigurableProperty
                    {
                        Name            = "Literal",
                        ChildProperties = new List <ConfigurableProperty>
                        {
                            new ConfigurableProperty
                            {
                                Name  = "Value",
                                Value = "The-Actual-Value"
                            }
                        }
                    }
                }
            });

            var propertyType = sut.GetPropertyType();

            propertyType.Should().Be(ConfigurablePropertyType.literalExpression);

            var propertyValue = sut.GetLiteralObjectValue();

            propertyValue.Should().Be("The-Actual-Value");
        }
        public void WHEN_property_contains_a_theme_colour_expression_THEN_type_is_returned()
        {
            var sut = new ConfigurableProperty
            {
                Name = "propertyWithExpression"
            };

            sut.ChildProperties.Add(new ConfigurableProperty
            {
                Name            = "expr",
                ChildProperties = new List <ConfigurableProperty>
                {
                    new ConfigurableProperty
                    {
                        Name            = "ThemeDataColor",
                        ChildProperties = new List <ConfigurableProperty>
                        {
                            new ConfigurableProperty
                            {
                                Name  = "ColorId",
                                Value = "1"
                            }
                        }
                    }
                }
            });

            var propertyType = sut.GetPropertyType();

            propertyType.Should().Be(ConfigurablePropertyType.themeDataColorExpression);
        }
        public void WHEN_property_contains__a_solid_colour_THEN_type_is_returned()
        {
            var sut = new ConfigurableProperty
            {
                Name = "propertyWithExpression"
            };

            sut.ChildProperties.Add(new ConfigurableProperty
            {
                Name            = "solid",
                ChildProperties = new List <ConfigurableProperty>
                {
                    new ConfigurableProperty
                    {
                        Name            = "color",
                        ChildProperties = new List <ConfigurableProperty>
                        {
                            new ConfigurableProperty
                            {
                                Name  = "black",
                                Value = "000"
                            }
                        }
                    }
                }
            });

            var propertyType = sut.GetPropertyType();

            propertyType.Should().Be(ConfigurablePropertyType.solidColor);
        }
Exemplo n.º 6
0
        private void ApplyIntConfigurationSetting(ConfigurableObject <T> cfgObject, ConfigurableProperty cfgProperty,
                                                  ConfigurationSetting cfgSetting)
        {
            Type propertyType = cfgProperty.PropertyMetadata.PropertyInfo.PropertyType;
            int? value        = cfgSetting.Value.TryParseInt();

            if (propertyType == (typeof(int)))
            {
                if (value == null)
                {
                    throw new ConfigurationErrorsException(String.Format(
                                                               "Unable to apply configuration setting [{0}: {1}] to property [{2}/{3}]. [{1}] can not be converted to a 32-bit integer value.",
                                                               cfgSetting.Name, cfgSetting.Value,
                                                               cfgObject.TypeMetadata.Type.Name,
                                                               cfgProperty.PropertyMetadata.PropertyInfo
                                                               .Name));
                }

                cfgProperty.PropertyMetadata.PropertyInfo.SetValue(cfgObject.Target, value.Value);
            }
            else if (propertyType == (typeof(int?)))
            {
                cfgProperty.PropertyMetadata.PropertyInfo.SetValue(cfgObject.Target, value);
            }
        }
Exemplo n.º 7
0
        public void CombinatorCombinesAdditionalProperties()
        {
            LineSeriesConfigurator a = new();
            LineSeriesConfigurator b = new();

            Expression <Func <LineSeries, string?> > propertyExpression = ls => ls.LabelFormatString;
            const string format = "ABC";

            a.SetAdditional(propertyExpression, format);

            // Property only set on a
            Combinator <LineSeriesConfigurator> combinator = new(a, b);

            LineSeriesConfigurator combined = combinator.Combine();

            ConfigurableProperty <string>?combinedProperty = combined.AdditionalProperties.Get(propertyExpression);

            Assert.NotNull(combinedProperty);
            Assert.True(combinedProperty !.IsSet);
            Assert.Equal(format, combinedProperty.Value);

            // Property set on a AND b, should take the value from a and ignore b
            b.SetAdditional(propertyExpression, "ANOTHER RANDOM VALUE");

            combinator = new Combinator <LineSeriesConfigurator>(a, b);

            combined = combinator.Combine();

            combinedProperty = combined.AdditionalProperties.Get(propertyExpression);
            Assert.NotNull(combinedProperty);
            Assert.True(combinedProperty !.IsSet);
            Assert.Equal(format, combinedProperty.Value);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Unsets a <see cref="ConfigurableProperty{T}"/> on a <typeparamref name="TConfigurator"/>.
        /// </summary>
        /// <param name="configurator">The configurator that owns the property.</param>
        /// <param name="propertyCallback">A callback to select the property on the <paramref name="configurator"/>.</param>
        /// <returns>The <paramref name="configurator"/>.</returns>
        public static TConfigurator Unset <TConfigurator, TProperty>(this TConfigurator configurator,
                                                                     Func <TConfigurator, ConfigurableProperty <TProperty> > propertyCallback)
            where TConfigurator : IConfigurator
        {
            ConfigurableProperty <TProperty> property = propertyCallback(configurator);

            property.Unset();

            return(configurator);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Sets a <see cref="ConfigurableProperty{T}"/> on a <typeparamref name="TConfigurator"/>.
        /// </summary>
        /// <param name="configurator">The configurator that owns the property.</param>
        /// <param name="propertyCallback">A callback to select the property on the <paramref name="configurator"/>.</param>
        /// <param name="value">The value to set the <typeparamref name="TProperty"/> to.</param>
        /// <returns>The <paramref name="configurator"/>.</returns>
        public static TConfigurator Set <TConfigurator, TProperty>(this TConfigurator configurator,
                                                                   Func <TConfigurator, ConfigurableProperty <TProperty> > propertyCallback, TProperty?value)
            where TConfigurator : IConfigurator
        {
            ConfigurableProperty <TProperty> property = propertyCallback(configurator);

            property.Set(value);

            return(configurator);
        }
Exemplo n.º 10
0
        public void WHEN_correct_config_settings_exist_THEN_get_formatting_returns_null()
        {
            var styleProperties = new List <ConfigurableProperty>
            {
                new ConfigurableProperty {
                    Name = "font-colour", Value = "000"
                },
                new ConfigurableProperty {
                    Name = "font-family", Value = "Arial"
                }
            };

            var objectsNode = new ConfigurableProperty
            {
                Name            = "objects",
                ChildProperties = styleProperties
            };

            var visualNode = new ConfigurableProperty
            {
                Name            = "singleVisual",
                ChildProperties = new List <ConfigurableProperty>
                {
                    objectsNode
                }
            };

            var anotherRootNode = new ConfigurableProperty
            {
                Name = "another-root"
            };

            var sut = new VisualElement
            {
                Name          = "Test-Element",
                VisualType    = "TestVisual",
                Configuration = new List <ConfigurableProperty>
                {
                    visualNode,
                    anotherRootNode
                }
            };

            var result = sut.TryGetVisualFormatting(out var resultValue);

            result.Should().BeTrue();
            resultValue.Should().BeEquivalentTo(styleProperties);
        }
        public void WHEN_single_property_gets_property_with_incorrect_name_THEN_null_returned()
        {
            var sut = new ConfigurableProperty
            {
                Name  = "propertyName",
                Value = 123
            };

            var tryResult = sut.TryGetProperty(new string[1] {
                "notPropertyName"
            },
                                               out var valueResult);

            tryResult.Should().BeFalse();
            valueResult.Should().BeNull();
        }
        public void WHEN_single_property_gets_value_with_matched_name_THEN_value_returned()
        {
            var sut = new ConfigurableProperty
            {
                Name  = "propertyName",
                Value = 123
            };

            var tryResult = sut.TryGetValue(new string[1] {
                "propertyName"
            },
                                            out var valueResult);

            tryResult.Should().BeTrue();
            valueResult.Should().Be(123);
        }
Exemplo n.º 13
0
        private void ApplyConfigurationSetting(ConfigurableObject <T> cfgObject, ConfigurableProperty cfgProperty,
                                               ConfigurationSetting cfgSetting)
        {
            Type propertyType = cfgProperty.PropertyMetadata.PropertyInfo.PropertyType;

            if ((propertyType == typeof(bool)) || (propertyType == typeof(bool?)))
            {
                ApplyBooleanConfigurationSetting(cfgObject, cfgProperty, cfgSetting);
            }
            else if ((propertyType == typeof(DateTime)) || (propertyType == typeof(DateTime?)))
            {
                ApplyDateTimeConfigurationSetting(cfgObject, cfgProperty, cfgSetting);
            }
            else if ((propertyType == typeof(double)) || (propertyType == typeof(double?)))
            {
                ApplyDoubleConfigurationSetting(cfgObject, cfgProperty, cfgSetting);
            }
            else if ((propertyType == typeof(Guid)) || (propertyType == typeof(Guid?)))
            {
                ApplyGuidConfigurationSetting(cfgObject, cfgProperty, cfgSetting);
            }
            else if ((propertyType == typeof(int)) || (propertyType == typeof(int?)))
            {
                ApplyIntConfigurationSetting(cfgObject, cfgProperty, cfgSetting);
            }
            else if ((propertyType == typeof(long)) || (propertyType == typeof(long?)))
            {
                ApplyLongConfigurationSettings(cfgObject, cfgProperty, cfgSetting);
            }
            else if ((propertyType == typeof(string)))
            {
                cfgProperty.PropertyMetadata.PropertyInfo.SetValue(cfgObject.Target, cfgSetting.Value);
            }
            else
            {
                throw new ConfigurationErrorsException(
                          String.Format(
                              "Unable to apply configuration setting [{0}: {1}] to property [{2}/{3}]. The target property must be of type 'bool', 'bool?', 'DateTime', 'DateTime?', 'double', 'double?', 'Guid', 'Guid?', 'int', 'int?', 'long', 'long?' or 'string'.",
                              cfgSetting.Name, cfgSetting.Value, cfgObject.TypeMetadata.Type.Name,
                              cfgProperty.PropertyMetadata.PropertyInfo.Name));
            }
        }
Exemplo n.º 14
0
        private IEnumerable <string> GetPrioritizedConventionalSettingNames(ConfigurableObject <T> cfgObject,
                                                                            ConfigurableProperty cfgProperty)
        {
            if (String.IsNullOrEmpty(cfgObject.Name) == false)
            {
                yield return(String.Format("{0}.{1}.{2}",
                                           cfgObject.Name,
                                           cfgObject.TypeMetadata.Type.Name,
                                           cfgProperty.PropertyMetadata.PropertyInfo.Name));

                yield return(String.Format("{0}.{1}",
                                           cfgObject.Name,
                                           cfgProperty.PropertyMetadata.PropertyInfo.Name));
            }

            yield return(String.Format("{0}.{1}",
                                       cfgObject.TypeMetadata.Type.Name,
                                       cfgProperty.PropertyMetadata.PropertyInfo.Name));

            yield return(cfgProperty.PropertyMetadata.PropertyInfo.Name);
        }
Exemplo n.º 15
0
        public void WHEN_correct_config_settings_exist_THEN_get_formatting_returns_null()
        {
            var styleProperties = new List <ConfigurableProperty>
            {
                new ConfigurableProperty {
                    Name = "font-colour", Value = "000"
                },
                new ConfigurableProperty {
                    Name = "font-family", Value = "Arial"
                }
            };

            var objectsNode = new ConfigurableProperty
            {
                Name            = "objects",
                ChildProperties = styleProperties
            };

            var anotherRootNode = new ConfigurableProperty
            {
                Name = "another-root"
            };

            var sut = new ReportPage
            {
                Name          = "Test-Page",
                DisplayName   = "Page Name",
                Configuration = new List <ConfigurableProperty>
                {
                    objectsNode,
                    anotherRootNode
                }
            };

            var result = sut.TryGetPageFormatting(out var resultValue);

            result.Should().BeTrue();
            resultValue.Should().BeEquivalentTo(styleProperties);
        }
Exemplo n.º 16
0
        private ConfigurableObject <T> ToConfigurableObject(T @object, string objectName = null)
        {
            var cfgObject = new ConfigurableObject <T>();

            cfgObject.Name         = objectName;
            cfgObject.Target       = @object;
            cfgObject.TypeMetadata = new TypeMetadata(typeof(T));

            foreach (PropertyMetadata propertyMetadata in cfgObject.TypeMetadata.Properties)
            {
                ConfigurableAttribute cfgAttribute =
                    propertyMetadata.Attributes.OfType <ConfigurableAttribute>().SingleOrDefault();

                if (cfgAttribute != null)
                {
                    var cfgProperty = new ConfigurableProperty();

                    cfgProperty.IsRequired       = cfgAttribute.IsRequired;
                    cfgProperty.PropertyMetadata = propertyMetadata;

                    if (String.IsNullOrEmpty(cfgAttribute.SettingName))
                    {
                        cfgProperty.PrioritizedSettingNames =
                            GetPrioritizedConventionalSettingNames(cfgObject, cfgProperty).ToArray();
                    }
                    else
                    {
                        cfgProperty.PrioritizedSettingNames = new[]
                        { cfgAttribute.SettingName.Merge(new { Name = objectName }) };
                    }

                    cfgObject.Properties.Add(cfgProperty);
                }
            }

            return(cfgObject);
        }
Exemplo n.º 17
0
        public void cmdShow(string args)
        {
            if (!CheckModule(false, EModuleType.None))
            {
                return;
            }
            args = args.Trim().ToLowerInvariant();

            Module curM = _Current.ModuleType == EModuleType.Module ? (Module)_Current : null;

            switch (args)
            {
            case "":
            case "info": { cmdInfo(args); break; }

            case "options":
            case "config":
            {
                // set target id
                Target[] ps = null;

                if (curM != null)
                {
                    ps = curM.Targets;
                    if (ps != null)
                    {
                        int ix = 0;
                        foreach (Target t in ps)
                        {
                            t.Id = ix; ix++;
                        }
                    }
                }

                CommandTable tb = new CommandTable();

                string title = "";
                for (int x = 0; x <= 2; x++)
                {
                    PropertyInfo[] pis = null;

                    object pv = _Current;
                    switch (x)
                    {
                    case 0:
                    {
                        if (_Current.ModuleType == EModuleType.Payload)
                        {
                            title = Lang.Get("Payload_Options", _Current.FullPath);
                        }
                        else
                        {
                            title = Lang.Get("Module_Options", _Current.FullPath);
                        }

                        pis = ReflectionHelper.GetProperties(_Current, true, true, true);
                        break;
                    }

                    case 1:
                    {
                        title = Lang.Get("Current_Target");
                        if (ps != null && ps.Length > 1)
                        {
                            pis = ReflectionHelper.GetProperties(_Current, "Target");
                        }
                        break;
                    }

                    case 2:
                    {
                        if (curM != null)
                        {
                            if (curM.Payload != null)
                            {
                                pv    = curM.Payload;
                                pis   = ReflectionHelper.GetProperties(curM.Payload, true, true, true);
                                title = Lang.Get("Payload_Options", curM.Payload.FullPath);
                            }
                            else
                            {
                                if (curM.PayloadRequirements != null && curM.PayloadRequirements.ItsRequired())
                                {
                                    pis   = ReflectionHelper.GetProperties(_Current, "Payload");
                                    title = Lang.Get("Selected_Payload");
                                }
                            }
                        }
                        break;
                    }
                    }

                    if (pis != null)
                    {
                        bool primera = true;        // (x != 1 || !hasX0);
                        foreach (PropertyInfo pi in pis)
                        {
                            ConfigurableProperty c = pi.GetCustomAttribute <ConfigurableProperty>();
                            if (c == null)
                            {
                                continue;
                            }

                            if (primera)
                            {
                                if (tb.Count > 0)
                                {
                                    tb.AddRow("", "", "");
                                }
                                CommandTableRow row = tb.AddRow(0, title, "", "");
                                tb.AddRow("", "", "");

                                row[0].Align = CommandTableCol.EAlign.None;
                                row[1].Align = CommandTableCol.EAlign.None;
                                row[2].Align = CommandTableCol.EAlign.None;
                                primera      = false;
                            }

                            object val = pi.GetValue(pv);
                            if (val == null)
                            {
                                val = "NULL";
                                CommandTableRow row = tb.AddRow(pi.Name, val.ToString(), c.Description);
                                if (!c.Optional)
                                {
                                    row[1].ForeColor = ConsoleColor.Red;
                                }
                                else
                                {
                                    //if (x == 0 || x == 3)
                                    row[1].ForeColor = ConsoleColor.DarkRed;
                                }
                            }
                            else
                            {
                                val = ConvertHelper.ToString(val);

                                CommandTableRow row = tb.AddRow(pi.Name, val.ToString(), c.Description);
                                if (x == 0 || x == 3)
                                {
                                    row[1].ForeColor = ConsoleColor.Cyan;
                                }
                            }
                        }
                    }
                }

                string separator = tb.Separator;
                foreach (CommandTableRow row in tb)
                {
                    foreach (CommandTableCol col in row)
                    {
                        if (col.ReplicatedChar == '\0')
                        {
                            switch (col.Index)
                            {
                            case 0: _IO.SetForeColor(ConsoleColor.DarkGray); break;

                            case 1: _IO.SetForeColor(col.ForeColor); break;

                            case 2: _IO.SetForeColor(ConsoleColor.Yellow); break;
                            }
                        }
                        else
                        {
                            _IO.SetForeColor(col.ForeColor);
                        }

                        if (col.Index != 0)
                        {
                            _IO.Write(separator);
                        }
                        _IO.Write(col.GetFormatedValue());
                    }
                    _IO.WriteLine("");
                }
                break;
            }

            case "payloads":
            {
                ModuleHeader <Payload>[] ps = curM == null ? null : PayloadCollection.Current.GetAvailables(curM.PayloadRequirements).ToArray();
                if (ps == null || ps.Length <= 0)
                {
                    _IO.WriteInfo(Lang.Get("Nothing_To_Show"));
                }
                else
                {
                    CommandTable tb = new CommandTable();

                    tb.AddRow(tb.AddRow(Lang.Get("Name"), Lang.Get("Description")).MakeSeparator());

                    foreach (ModuleHeader <Payload> p in ps)
                    {
                        tb.AddRow(p.FullPath, p.Description);
                    }

                    _IO.Write(tb.Output());
                }
                break;
            }

            case "targets":
            {
                Target[] ps = curM == null ? null : curM.Targets;
                if (ps == null || ps.Length <= 0)
                {
                    _IO.WriteInfo(Lang.Get("Nothing_To_Show"));
                }
                else
                {
                    CommandTable tb = new CommandTable();

                    tb.AddRow(tb.AddRow(Lang.Get("Name"), Lang.Get("Description")).MakeSeparator());

                    int ix = 0;
                    foreach (Target p in ps)
                    {
                        p.Id = ix; ix++;
                        tb.AddRow(p.Id.ToString(), p.Name);
                    }

                    _IO.Write(tb.Output());
                }
                break;
            }

            default:
            {
                // incorrect use
                _IO.WriteError(Lang.Get("Incorrect_Command_Usage"));
                _IO.AddInput("help show");
                break;
            }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Check Required Properties
        /// </summary>
        /// <param name="obj">Object to check</param>
        /// <param name="cmd">Command</param>
        /// <param name="error">Variable for capture the error fail</param>
        /// <returns>Return true if OK, false if not</returns>
        public static bool CheckRequiredProperties(object obj, CommandLayer cmd, out string error)
        {
            error = null;
            Type fileInfoType = typeof(FileInfo);
            Type dirInfoType  = typeof(DirectoryInfo);

            foreach (PropertyInfo pi in ReflectionHelper.GetProperties(obj, true, true, true))
            {
                ConfigurableProperty c = pi.GetCustomAttribute <ConfigurableProperty>();
                if (c == null)
                {
                    continue;
                }

                object val = pi.GetValue(obj, null);

                if (val == null)
                {
                    if (c.Optional)
                    {
                        continue;
                    }

                    error = Lang.Get("Require_Set_Property", pi.Name);
                    return(false);
                }
                else
                {
                    if (pi.PropertyType == fileInfoType)
                    {
                        RequireExistsAttribute c2 = pi.GetCustomAttribute <RequireExistsAttribute>();
                        if (c2 != null && !c2.IsValid(val))
                        {
                            error = Lang.Get("File_Defined_Not_Exists", pi.Name);
                            return(false);
                        }
                    }
                    else
                    {
                        if (pi.PropertyType == dirInfoType)
                        {
                            // Check directory
                            DirectoryInfo di = (DirectoryInfo)val;
                            di.Refresh();
                            if (!di.Exists)
                            {
                                if (cmd == null)
                                {
                                    // Por si acaso
                                    error = Lang.Get("Folder_Required", di.FullName);
                                    return(false);
                                }

                                cmd.WriteLine(Lang.Get("Folder_Required_Ask", di.FullName));
                                if (!(bool)ConvertHelper.ConvertTo(cmd.ReadLine(null, null), typeof(bool)))
                                {
                                    error = Lang.Get("Folder_Required", di.FullName);
                                    return(false);
                                }

                                try { di.Create(); }
                                catch (Exception e) { cmd.WriteError(e.ToString()); }
                            }
                        }
                    }
                }
            }

            return(error == null);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Check Required Properties
        /// </summary>
        /// <param name="error">Variable for capture the error fail</param>
        /// <returns>Return true if OK, false if not</returns>
        public bool CheckRequiredProperties(out string error)
        {
            error = null;

            Type fileInfoType = typeof(FileInfo);
            Type dirInfoType  = typeof(DirectoryInfo);

            foreach (PropertyInfo pi in ReflectionHelper.GetProperties(this, true, true, true))
            {
                ConfigurableProperty c = pi.GetCustomAttribute <ConfigurableProperty>();
                if (c == null)
                {
                    continue;
                }

                object val = pi.GetValue(this);

                if (val == null)
                {
                    if (!c.Required)
                    {
                        continue;
                    }

                    error = Lang.Get("Require_Set_Property", pi.Name);
                    return(false);
                }
                else
                {
                    if (pi.PropertyType == fileInfoType)
                    {
                        FileRequireExists c2 = pi.GetCustomAttribute <FileRequireExists>();
                        if (c2 != null && !c2.IsValid(val))
                        {
                            error = Lang.Get("File_Defined_Not_Exists", pi.Name);
                            return(false);
                        }
                    }
                }
            }

            if (this is Module)
            {
                // Module especify
                Module m = (Module)this;

                if (m.Target == null)
                {
                    error = Lang.Get("Require_Set_Property", "Target");
                    return(false);
                }

                if (m.Payload == null)
                {
                    if (m.PayloadRequirements != null && m.PayloadRequirements.ItsRequired())
                    {
                        error = Lang.Get("Require_Set_Property", "Payload");
                        return(false);
                    }
                }

                if (m.Payload != null)
                {
                    foreach (PropertyInfo pi in ReflectionHelper.GetProperties(m.Payload, true, true, true))
                    {
                        ConfigurableProperty c = pi.GetCustomAttribute <ConfigurableProperty>();
                        if (c == null)
                        {
                            continue;
                        }

                        object val = pi.GetValue(m.Payload);

                        if (val == null)
                        {
                            if (!c.Required)
                            {
                                continue;
                            }

                            error = Lang.Get("Require_Set_Property", pi.Name);
                            return(false);
                        }
                        else
                        {
                            if (pi.PropertyType == fileInfoType)
                            {
                                FileRequireExists c2 = pi.GetCustomAttribute <FileRequireExists>();
                                if (c2 != null && !c2.IsValid(val))
                                {
                                    error = Lang.Get("File_Defined_Not_Exists", pi.Name);
                                    return(false);
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Return Properties
        /// </summary>
        /// <param name="obj">Object</param>
        /// <param name="requiereRead">True for require read</param>
        /// <param name="requireWrite">True for require write</param>
        public static PropertyInfo[] GetProperties(object obj, bool requiereRead, bool requireWrite, bool excludeNonEditableProperties)
        {
            if (obj == null)
            {
                return new PropertyInfo[] { }
            }
            ;

            List <PropertyInfo> ls = new List <PropertyInfo>();

            foreach (PropertyInfo pi in obj.GetType().GetProperties())
            {
                if (requiereRead && !pi.CanRead)
                {
                    continue;
                }
                if (requireWrite && !pi.CanWrite)
                {
                    continue;
                }

                if (excludeNonEditableProperties)
                {
                    ConfigurableProperty cfg = pi.GetCustomAttribute <ConfigurableProperty>();
                    if (cfg == null)
                    {
                        continue;
                    }

                    if (pi.PropertyType.IsClass)
                    {
                        if (pi.PropertyType != ConvertHelper._StringType &&
                            pi.PropertyType != ConvertHelper._BoolType &&

                            pi.PropertyType != ConvertHelper._SByteType &&
                            pi.PropertyType != ConvertHelper._UInt16Type &&
                            pi.PropertyType != ConvertHelper._UInt32Type &&
                            pi.PropertyType != ConvertHelper._UInt64Type &&

                            pi.PropertyType != ConvertHelper._ByteType &&
                            pi.PropertyType != ConvertHelper._Int16Type &&
                            pi.PropertyType != ConvertHelper._Int32Type &&
                            pi.PropertyType != ConvertHelper._Int64Type &&

                            pi.PropertyType != ConvertHelper._DecimalType &&
                            pi.PropertyType != ConvertHelper._FloatType &&
                            pi.PropertyType != ConvertHelper._DoubleType &&

                            pi.PropertyType != ConvertHelper._UriType &&
                            pi.PropertyType != ConvertHelper._EncodingType &&
                            pi.PropertyType != ConvertHelper._IPAddressType &&
                            pi.PropertyType != ConvertHelper._IPEndPointType &&
                            pi.PropertyType != ConvertHelper._TimeSpanType &&
                            pi.PropertyType != ConvertHelper._DateTimeType &&
                            pi.PropertyType != ConvertHelper._DirectoryInfoType &&
                            pi.PropertyType != ConvertHelper._FileInfoType &&
                            pi.PropertyType != ConvertHelper._RegexType &&

                            pi.PropertyType != typeof(List <byte>) &&
                            pi.PropertyType != typeof(List <sbyte>) &&
                            pi.PropertyType != typeof(List <short>) &&
                            pi.PropertyType != typeof(List <ushort>) &&
                            pi.PropertyType != typeof(List <int>) &&
                            pi.PropertyType != typeof(List <uint>) &&
                            pi.PropertyType != typeof(List <long>) &&
                            pi.PropertyType != typeof(List <ulong>) &&

                            pi.PropertyType != typeof(byte[]) &&
                            pi.PropertyType != typeof(sbyte[]) &&
                            pi.PropertyType != typeof(short[]) &&
                            pi.PropertyType != typeof(ushort[]) &&
                            pi.PropertyType != typeof(int[]) &&
                            pi.PropertyType != typeof(uint[]) &&
                            pi.PropertyType != typeof(long[]) &&
                            pi.PropertyType != typeof(ulong[]) &&

                            // Class with string constructor
                            !(pi.PropertyType.IsClass && pi.PropertyType.GetConstructor(new Type[] { ConvertHelper._StringType }) != null) &&

                            // Array[Enum]
                            !(pi.PropertyType.IsArray && pi.PropertyType.GetElementType().IsEnum)
                            )
                        {
                            continue;
                        }
                    }
                }
                ls.Add(pi);
            }
            ls.Sort(Sort);
            return(ls.ToArray());
        }
Exemplo n.º 21
0
        private static List <ConfigurableProperty> AddChildProperties(
            List <ConfigurableProperty> properties,
            JsonElement?element)
        {
            if (!element.HasValue)
            {
                return(properties);
            }

            if (element.Value.ValueKind == JsonValueKind.Object)
            {
                var nextElement = element.Value.EnumerateObject();
                while (nextElement.MoveNext())
                {
                    var newProperty = new ConfigurableProperty
                    {
                        Name = nextElement.Current.Name,
                        Raw  = nextElement.Current.Value.GetRawText()
                    };

                    switch (nextElement.Current.Value.ValueKind)
                    {
                    case JsonValueKind.Object:
                        newProperty.ChildProperties = AddChildProperties(
                            new List <ConfigurableProperty>(),
                            nextElement.Current.Value);
                        break;

                    case JsonValueKind.String:
                        newProperty.Value = nextElement.Current.Value.GetString();
                        break;

                    case JsonValueKind.Number:
                        newProperty.Value = nextElement.Current.Value.GetDecimal();
                        break;

                    case JsonValueKind.True:
                        newProperty.Value = true;
                        break;

                    case JsonValueKind.False:
                        newProperty.Value = false;
                        break;

                    case JsonValueKind.Array:
                        var valueArray      = new object[nextElement.Current.Value.GetArrayLength()];
                        var childProperties = new List <ConfigurableProperty>();

                        var arrayItem = nextElement.Current.Value.EnumerateArray();

                        var i           = 0;
                        var isValueType = false;

                        while (arrayItem.MoveNext())
                        {
                            switch (arrayItem.Current.ValueKind)
                            {
                            case JsonValueKind.Object:
                                isValueType = false;
                                childProperties.AddRange(AddChildProperties(new List <ConfigurableProperty>(), arrayItem.Current));
                                break;

                            case JsonValueKind.String:
                                isValueType   = true;
                                valueArray[i] = arrayItem.Current.GetString() ?? "";
                                break;

                            case JsonValueKind.Number:
                                isValueType   = true;
                                valueArray[i] = arrayItem.Current.GetDecimal();
                                break;

                            default: break;
                            }

                            i++;
                        }

                        if (isValueType)
                        {
                            newProperty.Value = valueArray;
                        }
                        else
                        {
                            newProperty.ChildProperties = childProperties;
                        }

                        break;

                    default:
                        break;
                    }

                    properties.Add(newProperty);
                }
            }
            else if (element.Value.ValueKind == JsonValueKind.Array)
            {
                var nextPropery = element.Value.EnumerateArray();
                while (nextPropery.MoveNext())
                {
                    return(AddChildProperties(properties, nextPropery.Current));
                }
            }

            return(properties);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Check Required Properties
        /// </summary>
        /// <param name="propertyName">Variable for capture property fail</param>
        /// <returns>Return true if OK, false if not</returns>
        public bool CheckRequiredProperties(out string propertyName)
        {
            propertyName = null;

            foreach (PropertyInfo pi in ReflectionHelper.GetProperties(this, true, true, true))
            {
                ConfigurableProperty c = pi.GetCustomAttribute <ConfigurableProperty>();
                if (c == null)
                {
                    continue;
                }

                if (!c.Required)
                {
                    continue;
                }
                if (pi.GetValue(this) == null)
                {
                    propertyName = pi.Name;
                    return(false);
                }
            }

            if (this is Module)
            {
                // Module especify
                Module m = (Module)this;

                if (m.Target == null)
                {
                    propertyName = "Target";
                    return(false);
                }

                if (m.Payload == null)
                {
                    if (m.PayloadRequirements != null && m.PayloadRequirements.ItsRequired())
                    {
                        propertyName = "Payload";
                        return(false);
                    }
                }

                if (m.Payload != null)
                {
                    foreach (PropertyInfo pi in ReflectionHelper.GetProperties(m.Payload, true, true, true))
                    {
                        ConfigurableProperty c = pi.GetCustomAttribute <ConfigurableProperty>();
                        if (c == null)
                        {
                            continue;
                        }

                        if (!c.Required)
                        {
                            continue;
                        }
                        if (pi.GetValue(m.Payload) == null)
                        {
                            propertyName = pi.Name;
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Return Properties
        /// </summary>
        /// <param name="obj">Object</param>
        /// <param name="requiereRead">True for require read</param>
        /// <param name="requireWrite">True for require write</param>
        public static PropertyInfo[] GetProperties(object obj, bool requiereRead, bool requireWrite, bool excludeNonEditableProperties)
        {
            if (obj == null)
            {
                return new PropertyInfo[] { }
            }
            ;

            List <PropertyInfo> ls = new List <PropertyInfo>();

            foreach (PropertyInfo pi in obj.GetType().GetProperties())
            {
                if (requiereRead && !pi.CanRead)
                {
                    continue;
                }
                if (requireWrite && !pi.CanWrite)
                {
                    continue;
                }

                if (excludeNonEditableProperties)
                {
                    ConfigurableProperty cfg = pi.GetCustomAttribute <ConfigurableProperty>();
                    if (cfg == null)
                    {
                        continue;
                    }

                    if (pi.PropertyType.IsClass)
                    {
                        if (pi.PropertyType != typeof(string) &&
                            pi.PropertyType != typeof(Boolean) &&

                            pi.PropertyType != typeof(SByte) &&
                            pi.PropertyType != typeof(UInt16) &&
                            pi.PropertyType != typeof(UInt32) &&
                            pi.PropertyType != typeof(UInt64) &&

                            pi.PropertyType != typeof(Byte) &&
                            pi.PropertyType != typeof(Int16) &&
                            pi.PropertyType != typeof(Int32) &&
                            pi.PropertyType != typeof(Int64) &&

                            pi.PropertyType != typeof(Decimal) &&
                            pi.PropertyType != typeof(float) &&
                            pi.PropertyType != typeof(Double) &&

                            pi.PropertyType != typeof(IPAddress) &&
                            pi.PropertyType != typeof(IPEndPoint) &&
                            pi.PropertyType != typeof(TimeSpan) &&
                            pi.PropertyType != typeof(DateTime) &&
                            pi.PropertyType != typeof(DirectoryInfo) &&
                            pi.PropertyType != typeof(FileInfo) &&

                            pi.PropertyType != typeof(List <byte>) &&
                            pi.PropertyType != typeof(List <sbyte>) &&
                            pi.PropertyType != typeof(List <short>) &&
                            pi.PropertyType != typeof(List <ushort>) &&
                            pi.PropertyType != typeof(List <int>) &&
                            pi.PropertyType != typeof(List <uint>) &&
                            pi.PropertyType != typeof(List <long>) &&
                            pi.PropertyType != typeof(List <ulong>) &&

                            pi.PropertyType != typeof(byte[]) &&
                            pi.PropertyType != typeof(sbyte[]) &&
                            pi.PropertyType != typeof(short[]) &&
                            pi.PropertyType != typeof(ushort[]) &&
                            pi.PropertyType != typeof(int[]) &&
                            pi.PropertyType != typeof(uint[]) &&
                            pi.PropertyType != typeof(long[]) &&
                            pi.PropertyType != typeof(ulong[])
                            )
                        {
                            continue;
                        }
                    }
                }
                ls.Add(pi);
            }
            ls.Sort(Sort);
            return(ls.ToArray());
        }