예제 #1
0
        /// <summary>
        /// Helper method for creating a value
        /// </summary>
        /// <param name="valueType">Type of the value to create</param>
        /// <param name="propertyValue">Value as string</param>
        /// <returns>object instance of the value</returns>
        private static object CreateValue(Type valueType, IniSection section, string sectionName, string propertyName, string defaultValue, string arraySeparator)
        {
            Dictionary <string, string> properties = sections[sectionName];
            bool   defaultUsed            = false;
            string propertyValue          = null;
            object defaultValueFromConfig = null;

            if (properties.ContainsKey(propertyName) && properties[propertyName] != null)
            {
                propertyValue = section.PreCheckValue(propertyName, properties[propertyName]);
            }
            else if (defaultValue != null && defaultValue.Trim().Length != 0)
            {
                propertyValue = defaultValue;
                defaultUsed   = true;
            }
            else
            {
                LOG.DebugFormat("Property {0} has no value or default value, this might be corrected later!", propertyName);
                // Check if the developer implemented a default for the property
                defaultValueFromConfig = section.GetDefault(propertyName);
                if (defaultValueFromConfig != null)
                {
                    LOG.DebugFormat("Default for Property {0} implemented!", propertyName);
                }
            }

            // Now set the value
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(List <>))
            {
                object list = Activator.CreateInstance(valueType);
                // Logic for List<>
                if (propertyValue == null)
                {
                    if (defaultValueFromConfig != null)
                    {
                        return(defaultValueFromConfig);
                    }
                    return(list);
                }
                string[] arrayValues = propertyValue.Split(new string[] { arraySeparator }, StringSplitOptions.None);
                if (arrayValues == null || arrayValues.Length == 0)
                {
                    return(list);
                }
                bool       addedElements = false;
                bool       parseProblems = false;
                MethodInfo addMethodInfo = valueType.GetMethod("Add");

                foreach (string arrayValue in arrayValues)
                {
                    if (arrayValue != null && arrayValue.Length > 0)
                    {
                        object newValue = null;
                        try {
                            newValue = ConvertValueToValueType(valueType.GetGenericArguments()[0], arrayValue);
                        } catch (Exception) {
                            //LOG.Error("Problem converting " + arrayValue + " to type " + fieldType.FullName, e);
                            parseProblems = true;
                        }
                        if (newValue != null)
                        {
                            addMethodInfo.Invoke(list, new object[] { newValue });
                            addedElements = true;
                        }
                    }
                }
                // Try to fallback on a default
                if (!addedElements && parseProblems)
                {
                    try {
                        object fallbackValue = ConvertValueToValueType(valueType.GetGenericArguments()[0], defaultValue);
                        addMethodInfo.Invoke(list, new object[] { fallbackValue });
                        return(list);
                    } catch (Exception) {
                        //LOG.Error("Problem converting " + defaultValue + " to type " + fieldType.FullName, e);
                    }
                }

                return(list);
            }
            else if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Dictionary <,>))
            {
                // Logic for Dictionary<,>
                Type type1 = valueType.GetGenericArguments()[0];
                Type type2 = valueType.GetGenericArguments()[1];
                //LOG.Info(String.Format("Found Dictionary<{0},{1}>", type1.Name, type2.Name));
                object     dictionary    = Activator.CreateInstance(valueType);
                MethodInfo addMethodInfo = valueType.GetMethod("Add");
                bool       addedElements = false;
                foreach (string key in properties.Keys)
                {
                    if (key != null && key.StartsWith(propertyName + "."))
                    {
                        // What "key" do we need to store it under?
                        string subPropertyName = key.Substring(propertyName.Length + 1);
                        string stringValue     = properties[key];
                        object newValue1       = null;
                        object newValue2       = null;
                        try {
                            newValue1 = ConvertValueToValueType(type1, subPropertyName);
                        } catch (Exception) {
                            //LOG.Error("Problem converting " + subPropertyName + " to type " + type1.FullName, e);
                        }
                        try {
                            newValue2 = ConvertValueToValueType(type2, stringValue);
                        } catch (Exception) {
                            //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e);
                        }
                        addMethodInfo.Invoke(dictionary, new object[] { newValue1, newValue2 });
                        addedElements = true;
                    }
                }
                // No need to return something that isn't filled!
                if (addedElements)
                {
                    return(dictionary);
                }
                else if (defaultValueFromConfig != null)
                {
                    return(defaultValueFromConfig);
                }
            }
            if (defaultValueFromConfig != null)
            {
                return(defaultValueFromConfig);
            }
            else
            {
                if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                {
                    // We are dealing with a generic type that is nullable
                    valueType = Nullable.GetUnderlyingType(valueType);
                }
                object newValue = null;
                try {
                    newValue = ConvertValueToValueType(valueType, propertyValue);
                } catch (Exception) {
                    newValue = null;
                    if (!defaultUsed)
                    {
                        try {
                            newValue = ConvertValueToValueType(valueType, defaultValue);
                        } catch (Exception) {
                            //LOG.Error("Problem converting " + propertyValue + " to type " + fieldType.FullName, e2);
                        }
                    }
                    else
                    {
                        //LOG.Error("Problem converting " + propertyValue + " to type " + fieldType.FullName, e1);
                    }
                }
                return(newValue);
            }
        }
예제 #2
0
        private static void FillIniSection(IniSection section)
        {
            Type   iniSectionType = section.GetType();
            string sectionName    = getSectionName(iniSectionType);
            // Get the properties for the section
            Dictionary <string, string> properties = null;

            if (sections.ContainsKey(sectionName))
            {
                properties = sections[sectionName];
            }
            else
            {
                sections.Add(sectionName, new Dictionary <string, string>());
                properties = sections[sectionName];
            }

            // Iterate over the members and fill them
            List <MemberInfo> members = new List <MemberInfo>();

            foreach (FieldInfo fieldInfo in iniSectionType.GetFields())
            {
                members.Add(fieldInfo);
            }
            foreach (PropertyInfo propertyInfo in iniSectionType.GetProperties())
            {
                members.Add(propertyInfo);
            }

            foreach (MemberInfo field in members)
            {
                if (Attribute.IsDefined(field, typeof(IniPropertyAttribute)))
                {
                    IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)field.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0];
                    string propertyName         = iniPropertyAttribute.Name;
                    string propertyDefaultValue = iniPropertyAttribute.DefaultValue;
                    string fieldSeparator       = iniPropertyAttribute.Separator;
                    // Get the type, or the underlying type for nullables
                    Type valueType;
                    if (field is FieldInfo)
                    {
                        valueType = ((FieldInfo)field).FieldType;
                    }
                    else if (field is PropertyInfo)
                    {
                        valueType = ((PropertyInfo)field).PropertyType;
                    }
                    else
                    {
                        continue;
                    }

                    // Get the value from the ini file, if there is none take the default
                    if (!properties.ContainsKey(propertyName) && propertyDefaultValue != null)
                    {
                        // Mark as dirty, we didn't use properties from the file (even defaults from the default file are allowed)
                        section.IsDirty = true;
                        //LOG.Debug("Passing default: " + propertyName + "=" + propertyDefaultValue);
                    }

                    // Try to get the field value from the properties or use the default value
                    object fieldValue = null;
                    try {
                        fieldValue = CreateValue(valueType, section, sectionName, propertyName, propertyDefaultValue, fieldSeparator);
                    } catch (Exception) {
                        //LOG.Warn("Couldn't parse field: " + sectionName + "." + propertyName, e);
                    }

                    // If still no value, e.g. due to an exception, check if the GetDefault delivers a value
                    if (fieldValue == null)
                    {
                        // Use GetDefault to fill the field if none is set
                        fieldValue = section.GetDefault(propertyName);
                    }

                    // Still no value? Log warning
                    if (fieldValue == null)
                    {
                        LOG.WarnFormat("Property {0} has no value or default value.", propertyName);
                    }

                    // Set the value
                    try {
                        if (field is FieldInfo)
                        {
                            ((FieldInfo)field).SetValue(section, fieldValue);
                        }
                        else if (field is PropertyInfo)
                        {
                            ((PropertyInfo)field).SetValue(section, fieldValue, null);;
                        }
                    } catch (Exception) {
                        //LOG.Warn("Couldn't set field: " + sectionName + "." + propertyName, e);
                    }
                }
            }
            section.AfterLoad();
        }