Inheritance: System.Attribute, System.Runtime.InteropServices._Attribute
        public static void Equals(DefaultValueAttribute attr1, object obj, bool expected)
        {
            Assert.Equal(expected, attr1.Equals(obj));

            DefaultValueAttribute attr2 = obj as DefaultValueAttribute;
            if (attr2 != null)
            {
                Assert.Equal(expected, attr1.GetHashCode() == attr2.GetHashCode());
            }
        }
 public static IEnumerable<object[]> Equals_TestData()
 {
     var attr = new DefaultValueAttribute(42);
     yield return new object[] { attr, attr, true };
     yield return new object[] { attr, new DefaultValueAttribute(42), true };
     yield return new object[] { attr, new DefaultValueAttribute(43), false };
     yield return new object[] { attr, new DefaultValueAttribute(null), false };
     yield return new object[] { attr, null, false };
     yield return new object[] { new DefaultValueAttribute(null), new DefaultValueAttribute(null), true };
 }
        public static void TestEqual()
        {
            DefaultValueAttribute attr;

            attr = new DefaultValueAttribute(42);
            Assert.Equal(attr, attr);
            Assert.True(attr.Equals(attr));
            Assert.Equal(attr.GetHashCode(), attr.GetHashCode());
            Assert.Equal(attr, new DefaultValueAttribute(42));
            Assert.Equal(attr.GetHashCode(), new DefaultValueAttribute(42).GetHashCode());
            Assert.NotEqual(new DefaultValueAttribute(43), attr);
            Assert.NotEqual(new DefaultValueAttribute(null), attr);
            Assert.False(attr.Equals(null));

            attr = new DefaultValueAttribute(null);
            Assert.Equal(new DefaultValueAttribute(null), attr);
            Assert.Equal(attr.GetHashCode(), new DefaultValueAttribute(null).GetHashCode());
        }
Beispiel #4
0
        public static void Ctor_DefaultTypeConverter_Null(Type type)
        {
            DefaultValueAttribute attr = new DefaultValueAttribute(type, "42");

            Assert.Null(attr.Value);
        }
Beispiel #5
0
        static void GeneratePropertiesDocs(Type type, StringBuilder sb)
        {
            List <PropertyInfo> properties = new List <PropertyInfo>(type.GetProperties(
                                                                         BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly
                                                                         ));

            if (properties.Count == 0)
            {
                return;
            }

            properties.Sort(delegate(PropertyInfo x, PropertyInfo y) {
                if (IsStatic(x) == IsStatic(y))
                {
                    return(x.Name.CompareTo(y.Name));
                }
                else
                {
                    return(IsStatic(x) ? -1 : 1);
                }
            });

            sb.AppendLine("");
            sb.AppendLine("Properties");
            sb.AppendLine("^^^^^^^^^^");

            List <string[]> values = new List <string[]>();

            values.Add(new string[] { "*Name*", "*Info*", "*Description*" });

            foreach (PropertyInfo pinfo in properties)
            {
                values.Add(new string[] { }); // marks a new entry
                DescriptionAttribute descAttr = Attribute.GetCustomAttribute(pinfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
                //OLVDocAttribute docAttr = Attribute.GetCustomAttribute(pinfo, typeof(OLVDocAttribute)) as OLVDocAttribute;
                values.Add(new string[] {
                    GetName(pinfo),
                    String.Format("* Type: {0}", GetTypeName(pinfo.PropertyType)),
                    (descAttr == null ? "" : descAttr.Description)
                });
                DefaultValueAttribute defaultValueAttr = Attribute.GetCustomAttribute(pinfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
                if (defaultValueAttr != null)
                {
                    values.Add(new string[] {
                        String.Empty,
                        String.Format("* Default: {0}", Convert.ToString(defaultValueAttr.Value)),
                        String.Empty
                    });
                }
                CategoryAttribute categoryAttr = Attribute.GetCustomAttribute(pinfo, typeof(CategoryAttribute)) as CategoryAttribute;
                values.Add(new string[] {
                    String.Empty,
                    String.Format("* IDE?: {0}", (categoryAttr == null || categoryAttr.Category != "ObjectListView" ? "No" : "Yes")),
                    String.Empty
                });
                values.Add(new string[] {
                    String.Empty,
                    String.Format("* Access: {0}", GetAccessLevel(pinfo)),
                    String.Empty
                });
                values.Add(new string[] {
                    String.Empty,
                    String.Format("* Writeable: {0}", (pinfo.CanWrite ? "Read-Write" : "Read")),
                    String.Empty
                });
            }
            GenerateTable(sb, values);
        }
 private static IPropertyDefaultFacet Create(DefaultValueAttribute attribute, ISpecification holder) => attribute is null ? null : new PropertyDefaultFacetAnnotation(attribute.Value, holder);
        public void DefaultValueAttribute_InitializingConstructorWithNull()
        {
            var defaultValueAttribute = new DefaultValueAttribute(null);

            Assert.IsNull(defaultValueAttribute.Value);
        }
        /// <summary>
        /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
        /// </summary>
        /// <param name="memberSerialization">The member's parent <see cref="MemberSerialization"/>.</param>
        /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
        /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
        protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = new JsonProperty();

            property.PropertyType  = ReflectionUtils.GetMemberUnderlyingType(member);
            property.ValueProvider = CreateMemberValueProvider(member);

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter = JsonTypeReflector.GetJsonConverter(member, property.PropertyType);

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(member.DeclaringType);

            DataMemberAttribute dataMemberAttribute;
            if (dataContractAttribute != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetAttribute <DataMemberAttribute>(member);
            }
            else
            {
                dataMemberAttribute = null;
            }
#endif

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(member);
            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(member) != null);

            string mappedName;
            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
#endif
            else
            {
                mappedName = member.Name;
            }

            property.PropertyName = ResolvePropertyName(mappedName);

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.Required;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null)
            {
                property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
            }
#endif
            else
            {
                property.Required = Required.Default;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (memberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null
#if !PocketPC && !NET20
                                 && dataMemberAttribute == null
#endif
                                ));

            bool allowNonPublicAccess = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (propertyAttribute != null)
            {
                allowNonPublicAccess = true;
            }
#if !PocketPC && !NET20
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
            }
#endif

            property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
            property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess);

            property.MemberConverter = JsonTypeReflector.GetJsonConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(member);
            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.TypeNameHandling       = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            property.ShouldSerialize = CreateShouldSerializeTest(member);

            return(property);
        }
        // ReSharper disable UnusedMember.Local
        static TValue GetMetadataValue <TValue>(IDictionary <string, object> metadata, string name, DefaultValueAttribute defaultValue)
        // ReSharper restore UnusedMember.Local
        {
            object result;

            if (metadata.TryGetValue(name, out result))
            {
                return((TValue)result);
            }

            if (defaultValue != null)
            {
                return((TValue)defaultValue.Value);
            }

            throw new DependencyResolutionException(
                      string.Format(CultureInfo.CurrentCulture, MetadataViewProviderResources.MissingMetadata, name));
        }
Beispiel #10
0
        public void GetPropertiesFiltersByAttribute()
        {
            var defaultValueAttribute = new DefaultValueAttribute(DescriptorTestComponent.DefaultPropertyValue);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });

            Assert.Equal(1, properties.Count);
        }
        /// <summary>
        ///  This retrieves the value of this property.  If the property returns false
        ///  from ShouldSerializeValue (indicating the ambient value for this property)
        ///  This will look for an AmbientValueAttribute and use it if it can.
        /// </summary>
        private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue)
        {
            object propertyValue = null;

            validValue = true;
            try
            {
                if (!property.ShouldSerializeValue(value))
                {
                    // We aren't supposed to be serializing this property, but we decided to do
                    // it anyway.  Check the property for an AmbientValue attribute and if we
                    // find one, use it's value to serialize.
                    AmbientValueAttribute attr = (AmbientValueAttribute)property.Attributes[typeof(AmbientValueAttribute)];

                    if (attr != null)
                    {
                        return(attr.Value);
                    }
                    else
                    {
                        DefaultValueAttribute defAttr = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];

                        if (defAttr != null)
                        {
                            return(defAttr.Value);
                        }
                        else
                        {
                            // nope, we're not valid...
                            //
                            validValue = false;
                        }
                    }
                }

                propertyValue = property.GetValue(value);
            }
            catch (Exception e)
            {
                // something failed -- we don't have a valid value
                validValue = false;

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, property.Name, e.Message), manager));
            }

            if ((propertyValue != null) && (!propertyValue.GetType().IsValueType) && !(propertyValue is Type))
            {
                // DevDiv2 (Dev11) bug 187766 : property whose type implements ISupportInitialize is not
                // serialized with Begin/EndInit.
                Type type = TypeDescriptor.GetProvider(propertyValue).GetReflectionType(typeof(object));
                if (!type.IsDefined(typeof(ProjectTargetFrameworkAttribute), false))
                {
                    // TargetFrameworkProvider is not attached
                    TypeDescriptionProvider typeProvider = CodeDomSerializerBase.GetTargetFrameworkProvider(manager, propertyValue);
                    if (typeProvider != null)
                    {
                        TypeDescriptor.AddProvider(typeProvider, propertyValue);
                    }
                }
            }

            return(propertyValue);
        }
        private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute)
        {
            hasExplicitAttribute = false;

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);

            MemberInfo memberInfo = null;
#if !(NETFX_CORE || PORTABLE)
            memberInfo = attributeProvider as MemberInfo;
#else
            memberInfo = attributeProvider.UnderlyingObject as MemberInfo;
#endif

            DataMemberAttribute dataMemberAttribute;
            if (dataContractAttribute != null && memberInfo != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo);
            }
            else
            {
                dataMemberAttribute = null;
            }
#endif

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);
            if (propertyAttribute != null)
            {
                hasExplicitAttribute = true;
            }

            string mappedName;
            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
#endif
            else
            {
                mappedName = name;
            }

            property.PropertyName   = ResolvePropertyName(mappedName);
            property.UnderlyingName = name;

            if (propertyAttribute != null)
            {
                property._required = propertyAttribute._required;
                property.Order     = propertyAttribute._order;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null)
            {
                property._required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
                property.Order     = (dataMemberAttribute.Order != -1) ? (int?)dataMemberAttribute.Order : null;
            }
#endif

            bool hasJsonIgnoreAttribute =
                JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
                || JsonTypeReflector.GetAttribute <NonSerializedAttribute>(attributeProvider) != null
#endif
            ;

            if (memberSerialization != MemberSerialization.OptIn)
            {
                // ignored if it has JsonIgnore or NonSerialized attributes
                property.Ignored = hasJsonIgnoreAttribute;
            }
            else
            {
                // ignored if it has JsonIgnore/NonSerialized or does not have DataMember or JsonProperty attributes
                property.Ignored =
                    hasJsonIgnoreAttribute ||
                    (propertyAttribute == null
#if !PocketPC && !NET20
                     && dataMemberAttribute == null
#endif
                    );
            }

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter       = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider);
            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.TypeNameHandling       = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            property.ItemIsReference = (propertyAttribute != null) ? propertyAttribute._itemIsReference : null;
            property.ItemConverter   =
                (propertyAttribute != null && propertyAttribute.ItemConverterType != null)
          ? JsonConverterAttribute.CreateJsonConverterInstance(propertyAttribute.ItemConverterType)
          : null;
            property.ItemReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._itemReferenceLoopHandling : null;
            property.ItemTypeNameHandling      = (propertyAttribute != null) ? propertyAttribute._itemTypeNameHandling : null;

            allowNonPublicAccess = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (propertyAttribute != null)
            {
                allowNonPublicAccess = true;
            }
            if (memberSerialization == MemberSerialization.Fields)
            {
                allowNonPublicAccess = true;
            }

#if !PocketPC && !NET20
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
                hasExplicitAttribute = true;
            }
#endif
        }
Beispiel #13
0
 private static IActionDefaultsFacet Create(DefaultValueAttribute attribute, ISpecification holder) => attribute == null ? null : new ActionDefaultsFacetAnnotation(attribute.Value, holder);
Beispiel #14
0
        private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute)
        {
            hasExplicitAttribute = false;

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);

            if (propertyAttribute != null)
            {
                hasExplicitAttribute = true;
            }

            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null);

            string mappedName;

            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
            else
            {
                mappedName = name;
            }

            property.PropertyName   = ResolvePropertyName(mappedName);
            property.UnderlyingName = name;

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.Required;
                property.Order    = propertyAttribute._order;
            }
            else
            {
                property.Required = Required.Default;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (memberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null
                                ));

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter       = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider);

            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.TypeNameHandling       = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            allowNonPublicAccess = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (propertyAttribute != null)
            {
                allowNonPublicAccess = true;
            }
        }
Beispiel #15
0
                public override Expression BindArgument(int srcarg, ParameterInfo targetparam = null)
                {
                    Debug.Assert(srcarg >= 0);

                    // cache the argument value

                    var key = new TmpVarKey()
                    {
                        Priority = 0 /*first*/, ArgIndex = srcarg, Prefix = "arg"
                    };
                    TmpVarValue value;

                    if (!_tmpvars.TryGetValue(key, out value))
                    {
                        value = new TmpVarValue();

                        value.TrueInitializer  = Expression.ArrayIndex(_argsarray, Expression.Constant(srcarg));
                        value.FalseInitializer = ConvertExpression.BindDefault(value.TrueInitializer.Type); // ~ default(_argsarray.Type.GetElementType())
                        value.Expression       = Expression.Variable(value.TrueInitializer.Type, "arg_" + srcarg);

                        //
                        _tmpvars[key] = value;
                    }

                    if (targetparam != null)
                    {
                        DefaultValueAttribute defaultValueAttr = null;

                        // create specialized variable with default value
                        if (targetparam.HasDefaultValue) // || (defaultValueAttr = targetparam.GetCustomAttribute<DefaultValueAttribute>()) != null)
                        {
                            var @default         = targetparam.DefaultValue;
                            var defaultValueExpr = Expression.Constant(@default);
                            var defaultValueStr  = @default != null? @default.ToString() : "NULL";

                            //
                            var key2 = new TmpVarKey()
                            {
                                Priority = 1 /*after key*/, ArgIndex = srcarg, Prefix = "arg(" + defaultValueStr + ")"
                            };
                            TmpVarValue value2;
                            if (!_tmpvars.TryGetValue(key2, out value2))
                            {
                                value2 = new TmpVarValue();

                                value2.TrueInitializer  = ConvertExpression.Bind(value.Expression, targetparam.ParameterType, _ctx);   // reuse the value already obtained from argv
                                value2.FalseInitializer = ConvertExpression.Bind(defaultValueExpr, value2.TrueInitializer.Type, _ctx); // ~ default(targetparam)
                                value2.Expression       = Expression.Variable(value2.TrueInitializer.Type, "arg_" + srcarg + "_" + defaultValueStr);

                                //
                                _tmpvars[key2] = value2;
                            }

                            return(value2.Expression);   // already converted to targetparam.ParameterType
                        }
                        else
                        {
                            defaultValueAttr = targetparam.GetCustomAttribute <DefaultValueAttribute>();
                            if (defaultValueAttr != null)
                            {
                                return(ConvertExpression.Bind(BindDefaultValue(defaultValueAttr), targetparam.ParameterType, _ctx));
                            }
                        }
                    }

                    return((targetparam == null)
                        ? value.Expression
                        : ConvertExpression.Bind(value.Expression, targetparam.ParameterType, _ctx));
                }
        private static object DeserializeInternal(string name, Type type, object defaultvalue, IniDictionary ini, string groupName, bool rootObject, IniCollectionSettings collectionSettings)
        {
            string fullname = groupName;

            if (!rootObject)
            {
                if (!string.IsNullOrEmpty(fullname))
                {
                    fullname += '.';
                }
                fullname += name;
            }
            if (!ini.ContainsKey(groupName))
            {
                return(defaultvalue);
            }
            Dictionary <string, string> group = ini[groupName];

            if (!type.IsComplexType())
            {
                if (group.ContainsKey(name))
                {
                    object converted = type.ConvertFromString(group[name]);
                    group.Remove(name);
                    if (converted != null)
                    {
                        return(converted);
                    }
                }
                return(defaultvalue);
            }
            Type generictype;

            if (type.IsArray)
            {
                Type valuetype = type.GetElementType();
                int  maxind    = int.MinValue;
                if (!IsComplexType(valuetype))
                {
                    switch (collectionSettings.Mode)
                    {
                    case IniCollectionMode.Normal:
                        foreach (IniNameValue item in group)
                        {
                            if (item.Key.StartsWith(name + "[", StringComparison.Ordinal))
                            {
                                int key = int.Parse(item.Key.Substring(name.Length + 1, item.Key.Length - (name.Length + 2)));
                                maxind = Math.Max(key, maxind);
                            }
                        }
                        break;

                    case IniCollectionMode.IndexOnly:
                        foreach (IniNameValue item in group)
                        {
                            int key;
                            if (int.TryParse(item.Key, out key))
                            {
                                maxind = Math.Max(key, maxind);
                            }
                        }
                        break;

                    case IniCollectionMode.NoSquareBrackets:
                        foreach (IniNameValue item in group)
                        {
                            if (item.Key.StartsWith(name, StringComparison.Ordinal))
                            {
                                int key;
                                if (int.TryParse(item.Key.Substring(name.Length), out key))
                                {
                                    maxind = Math.Max(key, maxind);
                                }
                            }
                        }
                        break;

                    case IniCollectionMode.SingleLine:
                        string[] items = group[name].Split(new[] { collectionSettings.Format }, StringSplitOptions.None);
                        Array    _obj  = Array.CreateInstance(valuetype, items.Length);
                        for (int i = 0; i < items.Length; i++)
                        {
                            _obj.SetValue(valuetype.ConvertFromString(items[i]), i);
                        }
                        group.Remove(name);
                        break;
                    }
                }
                else
                {
                    switch (collectionSettings.Mode)
                    {
                    case IniCollectionMode.Normal:
                        foreach (IniNameGroup item in ini)
                        {
                            if (item.Key.StartsWith(fullname + "[", StringComparison.Ordinal))
                            {
                                int key = int.Parse(item.Key.Substring(fullname.Length + 1, item.Key.Length - (fullname.Length + 2)));
                                maxind = Math.Max(key, maxind);
                            }
                        }
                        break;

                    case IniCollectionMode.IndexOnly:
                        foreach (IniNameGroup item in ini)
                        {
                            int key;
                            if (int.TryParse(item.Key, out key))
                            {
                                maxind = Math.Max(key, maxind);
                            }
                        }
                        break;

                    case IniCollectionMode.NoSquareBrackets:
                        foreach (IniNameGroup item in ini)
                        {
                            if (item.Key.StartsWith(fullname, StringComparison.Ordinal))
                            {
                                int key = int.Parse(item.Key.Substring(fullname.Length));
                                maxind = Math.Max(key, maxind);
                            }
                        }
                        break;

                    case IniCollectionMode.SingleLine:
                        throw new InvalidOperationException("Cannot deserialize type " + valuetype + " with IniCollectionMode.SingleLine!");
                    }
                }
                if (maxind == int.MinValue)
                {
                    return(Array.CreateInstance(valuetype, 0));
                }
                int   length = maxind + 1 - (collectionSettings.Mode == IniCollectionMode.SingleLine ? 0 : collectionSettings.StartIndex);
                Array obj    = Array.CreateInstance(valuetype, length);
                if (!IsComplexType(valuetype))
                {
                    switch (collectionSettings.Mode)
                    {
                    case IniCollectionMode.Normal:
                        for (int i = 0; i < length; i++)
                        {
                            if (group.ContainsKey(name + "[" + (i + collectionSettings.StartIndex).ToString() + "]"))
                            {
                                obj.SetValue(valuetype.ConvertFromString(group[name + "[" + (i + collectionSettings.StartIndex).ToString() + "]"]), i);
                                group.Remove(name + "[" + (i + collectionSettings.StartIndex).ToString() + "]");
                            }
                            else
                            {
                                obj.SetValue(valuetype.GetDefaultValue(), i);
                            }
                        }
                        break;

                    case IniCollectionMode.IndexOnly:
                        for (int i = 0; i < length; i++)
                        {
                            if (group.ContainsKey((i + collectionSettings.StartIndex).ToString()))
                            {
                                obj.SetValue(valuetype.ConvertFromString(group[(i + collectionSettings.StartIndex).ToString()]), i);
                                group.Remove((i + collectionSettings.StartIndex).ToString());
                            }
                            else
                            {
                                obj.SetValue(valuetype.GetDefaultValue(), i);
                            }
                        }
                        break;

                    case IniCollectionMode.NoSquareBrackets:
                        for (int i = 0; i < length; i++)
                        {
                            if (group.ContainsKey(name + (i + collectionSettings.StartIndex).ToString()))
                            {
                                obj.SetValue(valuetype.ConvertFromString(group[name + (i + collectionSettings.StartIndex).ToString()]), i);
                                group.Remove(name + (i + collectionSettings.StartIndex).ToString());
                            }
                            else
                            {
                                obj.SetValue(valuetype.GetDefaultValue(), i);
                            }
                        }
                        break;
                    }
                }
                else
                {
                    switch (collectionSettings.Mode)
                    {
                    case IniCollectionMode.Normal:
                        for (int i = 0; i < length; i++)
                        {
                            obj.SetValue(DeserializeInternal("value", valuetype, valuetype.GetDefaultValue(), ini, fullname + "[" + (i + collectionSettings.StartIndex).ToString() + "]", true, defaultCollectionSettings), i);
                        }
                        break;

                    case IniCollectionMode.IndexOnly:
                        for (int i = 0; i < length; i++)
                        {
                            obj.SetValue(DeserializeInternal("value", valuetype, valuetype.GetDefaultValue(), ini, (i + collectionSettings.StartIndex).ToString(), true, defaultCollectionSettings), i);
                        }
                        break;

                    case IniCollectionMode.NoSquareBrackets:
                        for (int i = 0; i < length; i++)
                        {
                            obj.SetValue(DeserializeInternal("value", valuetype, valuetype.GetDefaultValue(), ini, fullname + (i + collectionSettings.StartIndex).ToString(), true, defaultCollectionSettings), i);
                        }
                        break;
                    }
                }
                return(obj);
            }
            if (ImplementsGenericDefinition(type, typeof(IList <>), out generictype))
            {
                object obj       = Activator.CreateInstance(type);
                Type   valuetype = generictype.GetGenericArguments()[0];
                CollectionDeserializer deserializer = (CollectionDeserializer)Activator.CreateInstance(typeof(ListDeserializer <>).MakeGenericType(valuetype));
                deserializer.Deserialize(obj, group, groupName, collectionSettings, name, ini, fullname);
                return(obj);
            }
            if (type.ImplementsGenericDefinition(typeof(IDictionary <,>), out generictype))
            {
                object obj       = Activator.CreateInstance(type);
                Type   keytype   = generictype.GetGenericArguments()[0];
                Type   valuetype = generictype.GetGenericArguments()[1];
                if (keytype.IsComplexType())
                {
                    return(obj);
                }
                CollectionDeserializer deserializer = (CollectionDeserializer)Activator.CreateInstance(typeof(DictionaryDeserializer <,>).MakeGenericType(keytype, valuetype));
                deserializer.Deserialize(obj, group, groupName, collectionSettings, name, ini, fullname);
                return(obj);
            }
            object     result     = Activator.CreateInstance(type);
            MemberInfo collection = null;

            foreach (MemberInfo member in type.GetMembers(BindingFlags.Public | BindingFlags.Instance))
            {
                if (Attribute.GetCustomAttribute(member, typeof(IniIgnoreAttribute), true) != null)
                {
                    continue;
                }
                string membername = member.Name;
                if (Attribute.GetCustomAttribute(member, typeof(IniNameAttribute), true) != null)
                {
                    membername = ((IniNameAttribute)Attribute.GetCustomAttribute(member, typeof(IniNameAttribute), true)).Name;
                }
                IniCollectionSettings  colset  = defaultCollectionSettings;
                IniCollectionAttribute colattr = (IniCollectionAttribute)Attribute.GetCustomAttribute(member, typeof(IniCollectionAttribute), true);
                if (colattr != null)
                {
                    colset = colattr.Settings;
                }
                switch (member.MemberType)
                {
                case MemberTypes.Field:
                    FieldInfo field = (FieldInfo)member;
                    if (colset.Mode == IniCollectionMode.IndexOnly && typeof(ICollection).IsAssignableFrom(field.FieldType))
                    {
                        if (collection != null)
                        {
                            throw new Exception("IniCollectionMode.IndexOnly cannot be used on multiple members of a Type.");
                        }
                        collection = member;
                        continue;
                    }
                    object defval = field.FieldType.GetDefaultValue();
                    DefaultValueAttribute defattr = (DefaultValueAttribute)Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute), true);
                    if (defattr != null)
                    {
                        defval = defattr.Value;
                    }
                    field.SetValue(result, DeserializeInternal(membername, field.FieldType, defval, ini, fullname, false, colset));
                    break;

                case MemberTypes.Property:
                    PropertyInfo property = (PropertyInfo)member;
                    if (property.GetIndexParameters().Length > 0)
                    {
                        continue;
                    }
                    if (colset.Mode == IniCollectionMode.IndexOnly && typeof(ICollection).IsAssignableFrom(property.PropertyType))
                    {
                        if (collection != null)
                        {
                            throw new Exception("IniCollectionMode.IndexOnly cannot be used on multiple members of a Type.");
                        }
                        collection = member;
                        continue;
                    }
                    defval  = property.PropertyType.GetDefaultValue();
                    defattr = (DefaultValueAttribute)Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute), true);
                    if (defattr != null)
                    {
                        defval = defattr.Value;
                    }
                    object     propval   = DeserializeInternal(membername, property.PropertyType, defval, ini, fullname, false, colset);
                    MethodInfo setmethod = property.GetSetMethod();
                    if (setmethod == null)
                    {
                        continue;
                    }
                    setmethod.Invoke(result, new object[] { propval });
                    break;
                }
            }
            if (collection != null)
            {
                switch (collection.MemberType)
                {
                case MemberTypes.Field:
                    FieldInfo field = (FieldInfo)collection;
                    field.SetValue(result, DeserializeInternal(collection.Name, field.FieldType, field.FieldType.GetDefaultValue(), ini, fullname, false, ((IniCollectionAttribute)Attribute.GetCustomAttribute(collection, typeof(IniCollectionAttribute), true)).Settings));
                    break;

                case MemberTypes.Property:
                    PropertyInfo property  = (PropertyInfo)collection;
                    object       propval   = DeserializeInternal(collection.Name, property.PropertyType, property.PropertyType.GetDefaultValue(), ini, fullname, false, ((IniCollectionAttribute)Attribute.GetCustomAttribute(collection, typeof(IniCollectionAttribute), true)).Settings);
                    MethodInfo   setmethod = property.GetSetMethod();
                    if (setmethod == null)
                    {
                        break;
                    }
                    setmethod.Invoke(result, new object[] { propval });
                    break;
                }
            }
            ini.Remove(rootObject ? string.Empty : name);
            return(result);
        }
Beispiel #17
0
        private static Possible <object, Failure> ConvertTo(this ICacheConfigData cacheData, Type targetType, string configName)
        {
            object target = Activator.CreateInstance(targetType);

            foreach (var propertyInfo in target.GetType().GetProperties())
            {
                object value;
                if (cacheData.TryGetValue(propertyInfo.Name, out value))
                {
                    var nestedValue = value as ICacheConfigData;

                    if (nestedValue != null)
                    {
                        if (propertyInfo.PropertyType == typeof(ICacheConfigData))
                        {
                            propertyInfo.SetValue(target, nestedValue);
                        }
                        else
                        {
                            var nestedTarget = nestedValue.ConvertTo(propertyInfo.PropertyType, configName);
                            if (nestedTarget.Succeeded)
                            {
                                propertyInfo.SetValue(target, nestedTarget.Result);
                            }
                            else
                            {
                                return(nestedTarget.Failure);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            // For cacheId property, the string value retrieved from the configuration has to be lifted to a CacheId
                            if (propertyInfo.Name == DictionaryKeyFactoryCacheId && (value == null || value is string))
                            {
                                string cacheId = (string)value;
                                propertyInfo.SetValue(target, cacheId == null ? CacheId.Invalid : new CacheId(cacheId));
                            }
                            else
                            {
                                propertyInfo.SetValue(target, Convert.ChangeType(value, propertyInfo.PropertyType, CultureInfo.InvariantCulture));
                            }
                        }
                        catch (Exception e)
                        {
                            return(new IncorrectJsonConfigDataFailure("{0} Json configuration field '{1}' can not be set to '{2}'\n{3}", configName, propertyInfo.Name, value, e.GetLogEventMessage()));
                        }
                    }
                }
                else
                {
                    object defaultValue = propertyInfo.GetValue(target);
                    DefaultValueAttribute defaultValueAttribute =
                        propertyInfo.GetCustomAttributes(true).OfType <DefaultValueAttribute>().FirstOrDefault();

                    if (defaultValueAttribute != null)
                    {
                        try
                        {
                            propertyInfo.SetValue(target, Convert.ChangeType(defaultValueAttribute.Value, propertyInfo.PropertyType, CultureInfo.InvariantCulture));
                        }
                        catch (Exception e)
                        {
                            return
                                (new IncorrectJsonConfigDataFailure(
                                     "{0} Json configuration field '{1}' can not be set to the default value of '{2}'\n{3}",
                                     configName,
                                     propertyInfo.Name,
                                     defaultValueAttribute.Value,
                                     e.GetLogEventMessage()));
                        }
                    }
                    else if (defaultValue == null)
                    {
                        return(new IncorrectJsonConfigDataFailure("{0} requires a value for '{1}' in Json configuration data", configName, propertyInfo.Name));
                    }
                }
            }

            // We used to validate that the JSON config had no fields that did not correspond to a field in our config, but this caused issues when we added new flags, since old versions of the cache would break
            //  when used with newer configs. Because of that, we removed that validation.
            return(target);
        }
        public TypedPropertyDescriptor(XmlElement elem, ItemGroup group, TypedClassDescriptor klass) : base(elem, group, klass)
        {
            this.klass = klass;
            string propertyName = elem.GetAttribute("name");
            int    dot          = propertyName.IndexOf('.');

            if (dot != -1)
            {
                // Sub-property (eg, "Alignment.Value")
                memberInfo        = FindProperty(klass.WrapperType, klass.WrappedType, propertyName.Substring(0, dot));
                isWrapperProperty = memberInfo.DeclaringType.IsSubclassOf(typeof(ObjectWrapper));
                gladeProperty     = new TypedPropertyDescriptor(isWrapperProperty ? klass.WrapperType : klass.WrappedType, memberInfo.Name);
                propertyInfo      = FindProperty(memberInfo.PropertyType, propertyName.Substring(dot + 1));
            }
            else
            {
                // Basic simple property
                propertyInfo      = FindProperty(klass.WrapperType, klass.WrappedType, propertyName);
                isWrapperProperty = propertyInfo.DeclaringType.IsSubclassOf(typeof(ObjectWrapper));
            }

            // Wrapper properties that override widgets properties (using the same name)
            // must be considered runtime properties (will be available at run-time).
            if (!isWrapperProperty || klass.WrappedType.GetProperty(propertyName) != null)
            {
                isRuntimeProperty = true;
            }

            if (!IsInternal && propertyInfo.PropertyType.IsEnum &&
                Registry.LookupEnum(propertyInfo.PropertyType.FullName) == null)
            {
                throw new ArgumentException("No EnumDescriptor for " + propertyInfo.PropertyType.FullName + "(" + klass.WrappedType.FullName + "." + propertyName + ")");
            }

            pspec = FindPSpec(propertyInfo);

            if (isWrapperProperty && pspec == null)
            {
                PropertyInfo pinfo = klass.WrappedType.GetProperty(propertyInfo.Name, flags);
                if (pinfo != null)
                {
                    pspec = FindPSpec(pinfo);
                }
            }

            if (pspec != null)
            {
                // This information will be overridden by what's specified in the xml file
                description = pspec.Blurb;
                minimum     = pspec.Minimum;
                maximum     = pspec.Maximum;
                label       = propertyName;
                if (!elem.HasAttribute("ignore-default"))
                {
                    hasDefault = Type.GetTypeCode(PropertyType) != TypeCode.Object || PropertyType.IsEnum;
                }
            }
            else
            {
                label         = propertyInfo.Name;
                gladeOverride = true;
            }

            string typeName = elem.GetAttribute("editor");

            if (typeName.Length > 0)
            {
                editorType = Registry.GetType(typeName, false);
            }

            // Look for a default value attribute

            object[] ats = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (ats.Length > 0)
            {
                DefaultValueAttribute at = (DefaultValueAttribute)ats [0];
                defaultValue = at.Value;
            }

            // Load default data
            Load(elem);
        }
        // This must be called with _readerWriterLock held for Write
        private static Type GenerateInterfaceViewProxyType(Type viewType)
        {
            // View type is an interface let's cook an implementation
            Type        proxyType;
            TypeBuilder proxyTypeBuilder;

            Type[] interfaces = { viewType };

            proxyTypeBuilder = ProxyModuleBuilder.DefineType(
                string.Format(CultureInfo.InvariantCulture, "_proxy_{0}_{1}", viewType.FullName, Guid.NewGuid()),
                TypeAttributes.Public,
                typeof(object),
                interfaces);

            // Implement Constructor
            ILGenerator  proxyCtorIL   = proxyTypeBuilder.CreateGeneratorForPublicConstructor(CtorArgumentTypes);
            LocalBuilder exception     = proxyCtorIL.DeclareLocal(typeof(Exception));
            LocalBuilder exceptionData = proxyCtorIL.DeclareLocal(typeof(IDictionary));
            LocalBuilder sourceType    = proxyCtorIL.DeclareLocal(typeof(Type));
            LocalBuilder value         = proxyCtorIL.DeclareLocal(typeof(object));

            Label tryConstructView = proxyCtorIL.BeginExceptionBlock();

            // Implement interface properties
            foreach (PropertyInfo propertyInfo in viewType.GetAllProperties())
            {
                string fieldName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}", propertyInfo.Name, Guid.NewGuid());

                // Cache names and type for exception
                string propertyName = string.Format(CultureInfo.InvariantCulture, "{0}", propertyInfo.Name);

                Type[] propertyTypeArguments = new Type[] { propertyInfo.PropertyType };
                Type[] optionalModifiers     = null;
                Type[] requiredModifiers     = null;

#if !SILVERLIGHT
                // PropertyInfo does not support GetOptionalCustomModifiers and GetRequiredCustomModifiers on Silverlight
                optionalModifiers = propertyInfo.GetOptionalCustomModifiers();
                requiredModifiers = propertyInfo.GetRequiredCustomModifiers();
                Array.Reverse(optionalModifiers);
                Array.Reverse(requiredModifiers);
#endif
                Type[] parameterType = (propertyInfo.CanWrite) ? propertyTypeArguments : null;

                Type[][] parameterRequiredModifiers = new Type[1][] { requiredModifiers };
                Type[][] parameterOptionalModifiers = new Type[1][] { optionalModifiers };

                // Generate field
                FieldBuilder proxyFieldBuilder = proxyTypeBuilder.DefineField(
                    fieldName,
                    propertyInfo.PropertyType,
                    FieldAttributes.Private);

                // Generate property
                PropertyBuilder proxyPropertyBuilder = proxyTypeBuilder.DefineProperty(
                    propertyName,
                    PropertyAttributes.None,
                    propertyInfo.PropertyType,
                    propertyTypeArguments);

                // Generate constructor code for retrieving the metadata value and setting the field
                Label doneGettingDefaultValue = proxyCtorIL.DefineLabel();

                // In constructor set the backing field with the value from the dictionary
                proxyCtorIL.Emit(OpCodes.Ldarg_1);
                proxyCtorIL.Emit(OpCodes.Ldstr, propertyInfo.Name);
                proxyCtorIL.Emit(OpCodes.Ldloca, value);
                proxyCtorIL.Emit(OpCodes.Callvirt, _mdvDictionaryTryGet);
                proxyCtorIL.Emit(OpCodes.Brtrue, doneGettingDefaultValue);
#if !SILVERLIGHT
                object[] attrs = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
                if (attrs.Length > 0)
                {
                    DefaultValueAttribute defaultAttribute = (DefaultValueAttribute)attrs[0];
                    proxyCtorIL.LoadValue(defaultAttribute.Value);
                    if ((defaultAttribute.Value != null) && (defaultAttribute.Value.GetType().IsValueType))
                    {
                        proxyCtorIL.Emit(OpCodes.Box, defaultAttribute.Value.GetType());
                    }
                    proxyCtorIL.Emit(OpCodes.Stloc, value);
                }
#endif
                proxyCtorIL.MarkLabel(doneGettingDefaultValue);

                Label tryCastValue = proxyCtorIL.BeginExceptionBlock();
                proxyCtorIL.Emit(OpCodes.Ldarg_0);
                proxyCtorIL.Emit(OpCodes.Ldloc, value);

                proxyCtorIL.Emit(propertyInfo.PropertyType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, propertyInfo.PropertyType);
                proxyCtorIL.Emit(OpCodes.Stfld, proxyFieldBuilder);
                proxyCtorIL.Emit(OpCodes.Leave, tryCastValue);

                // catch blocks for tryCast start here
                proxyCtorIL.BeginCatchBlock(typeof(NullReferenceException));
                {
                    proxyCtorIL.Emit(OpCodes.Stloc, exception);

                    proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
                    proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemKey, propertyName);
                    proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemTargetType, propertyInfo.PropertyType);
                    proxyCtorIL.Emit(OpCodes.Rethrow);
                }

                proxyCtorIL.BeginCatchBlock(typeof(InvalidCastException));
                {
                    proxyCtorIL.Emit(OpCodes.Stloc, exception);

                    proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
                    proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemKey, propertyName);
                    proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemTargetType, propertyInfo.PropertyType);
                    proxyCtorIL.Emit(OpCodes.Rethrow);
                }
                proxyCtorIL.EndExceptionBlock();


                if (propertyInfo.CanWrite)
                {
                    // The MetadataView '{0}' is invalid because property '{1}' has a property set method.
                    throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
                                                                  Strings.InvalidSetterOnMetadataField,
                                                                  viewType,
                                                                  propertyName));
                }
                if (propertyInfo.CanRead)
                {
                    // Generate "get" method implementation.
                    MethodBuilder getMethodBuilder = proxyTypeBuilder.DefineMethod(
                        string.Format(CultureInfo.InvariantCulture, "get_{0}", propertyName),
                        MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
                        CallingConventions.HasThis,
                        propertyInfo.PropertyType,
                        requiredModifiers,
                        optionalModifiers,
                        Type.EmptyTypes, null, null);

                    proxyTypeBuilder.DefineMethodOverride(getMethodBuilder, propertyInfo.GetGetMethod());
                    ILGenerator getMethodIL = getMethodBuilder.GetILGenerator();
                    getMethodIL.Emit(OpCodes.Ldarg_0);
                    getMethodIL.Emit(OpCodes.Ldfld, proxyFieldBuilder);
                    getMethodIL.Emit(OpCodes.Ret);

                    proxyPropertyBuilder.SetGetMethod(getMethodBuilder);
                }
            }

            proxyCtorIL.Emit(OpCodes.Leave, tryConstructView);

            // catch blocks for constructView start here
            proxyCtorIL.BeginCatchBlock(typeof(NullReferenceException));
            {
                proxyCtorIL.Emit(OpCodes.Stloc, exception);

                proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
                proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataViewType, viewType);
                proxyCtorIL.Emit(OpCodes.Rethrow);
            }
            proxyCtorIL.BeginCatchBlock(typeof(InvalidCastException));
            {
                proxyCtorIL.Emit(OpCodes.Stloc, exception);

                proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
                proxyCtorIL.Emit(OpCodes.Ldloc, value);
                proxyCtorIL.Emit(OpCodes.Call, ObjectGetType);
                proxyCtorIL.Emit(OpCodes.Stloc, sourceType);
                proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataViewType, viewType);
                proxyCtorIL.AddLocalToLocalDictionary(exceptionData, MetadataItemSourceType, sourceType);
                proxyCtorIL.AddLocalToLocalDictionary(exceptionData, MetadataItemValue, value);
                proxyCtorIL.Emit(OpCodes.Rethrow);
            }
            proxyCtorIL.EndExceptionBlock();

            // Finished implementing interface and constructor
            proxyCtorIL.Emit(OpCodes.Ret);
            proxyType = proxyTypeBuilder.CreateType();

            return(proxyType);
        }
Beispiel #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        public static object GetDefaultValue(PropertyDescriptor property)
        {
            DefaultValueAttribute attr = property.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;

            return(attr != null ? attr.Value : null);
        }
Beispiel #21
0
        /// <summary>
        ///     This method is called on demand when we need to get at one or
        ///     more attributes for this property.  Because obtaining attributes
        ///     can be costly, we wait until now to do the job.
        /// </summary>
        private void MergeAttributes()
        {
            AttributeCollection baseAttributes;

            if (_property != null)
            {
                baseAttributes = _property.Attributes;
            }
            else
            {
                baseAttributes = GetAttachedPropertyAttributes();
            }

            List <Attribute> newAttributes = new List <Attribute>(baseAttributes.Count + 1);

            bool readOnly = false;

            foreach (Attribute a in baseAttributes)
            {
                Attribute             attrToAdd = a;
                DefaultValueAttribute defAttr   = a as DefaultValueAttribute;

                if (defAttr != null)
                {
                    // DP metadata always overrides CLR metadata for
                    // default value.
                    attrToAdd = null;
                }
                else
                {
                    ReadOnlyAttribute roAttr = a as ReadOnlyAttribute;
                    if (roAttr != null)
                    {
                        // DP metata is the merge of CLR metadata for
                        // read only
                        readOnly  = roAttr.IsReadOnly;
                        attrToAdd = null;
                    }
                }

                if (attrToAdd != null)
                {
                    newAttributes.Add(attrToAdd);
                }
            }

            // Always include the metadata choice
            readOnly |= _dp.ReadOnly;

            // If we are an attached property and non-read only, the lack of a
            // set method will make us read only.
            if (_property == null && !readOnly && GetAttachedPropertySetMethod(_dp) == null)
            {
                readOnly = true;
            }

            // Add our own DependencyPropertyAttribute
            DependencyPropertyAttribute dpa = new DependencyPropertyAttribute(_dp, (_property == null));

            newAttributes.Add(dpa);

            // Add DefaultValueAttribute if the DP has a default
            // value
            if (_metadata.DefaultValue != DependencyProperty.UnsetValue)
            {
                newAttributes.Add(new DefaultValueAttribute(_metadata.DefaultValue));
            }

            // And add a read only attribute if needed
            if (readOnly)
            {
                newAttributes.Add(new ReadOnlyAttribute(true));
            }

            // Inject these attributes into our attribute array.  There
            // is a quirk to the way this works.  Attributes as they
            // are returned by the CLR and by AttributeCollection are in
            // priority order with the attributes at the front of the list
            // taking precidence over those at the end.  Attributes
            // handed to MemberDescriptor's AttributeArray, however, are
            // in reverse priority order so the "last one in wins".  Therefore
            // we need to reverse the array.

            Attribute[] attrArray = newAttributes.ToArray();
            for (int idx = 0; idx < attrArray.Length / 2; idx++)
            {
                int       swap = attrArray.Length - idx - 1;
                Attribute t    = attrArray[idx];
                attrArray[idx]  = attrArray[swap];
                attrArray[swap] = t;
            }

            AttributeArray = attrArray;
        }
Beispiel #22
0
        /// <summary>
        /// Update DB attribute values.
        /// </summary>
        /// <param name="attributes"></param>
        /// <param name="s"></param>
        private static void UpdateAttributes(Type type, object[] attributes, GXSerializedItem s)
        {
            int          value = 0;
            PropertyInfo pi    = s.Target as PropertyInfo;

            if (pi != null && pi.Name == "Id")
            {
                foreach (var i in type.GetInterfaces())
                {
                    if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IUnique <>))
                    {
                        value |= (int)(Attributes.Id | Attributes.PrimaryKey);
                        break;
                    }
                }
            }
            foreach (object att in attributes)
            {
                //If field is ignored.
                if (att is IgnoreAttribute && (((IgnoreAttribute)att).IgnoreType & IgnoreType.Db) != 0)
                {
                    value |= (int)Attributes.Ignored;
                }
                else
                {
                    if (att is DefaultValueAttribute)
                    {
                        DefaultValueAttribute def = att as DefaultValueAttribute;
                        s.DefaultValue = def.Value;
                    }
                    //Is property indexed.
                    if (att is IndexAttribute || att is IndexCollectionAttribute)
                    {
                        value |= (int)Attributes.Index;
                    }
                    //Is property auto indexed value.
                    else if (att is AutoIncrementAttribute)
                    {
                        value |= (int)Attributes.AutoIncrement;
                    }
                    //Primary key value.
                    else if (att is PrimaryKeyAttribute)
                    {
                        value |= (int)Attributes.PrimaryKey;
                    }
                    //Foreign key value.
                    else if (att is ForeignKeyAttribute fk)
                    {
                        value |= (int)Attributes.ForeignKey;
                        if (fk.AllowNull)
                        {
                            value |= (int)Attributes.AllowNull;
                        }
                    }
                    //Relation field.
                    else if (att is RelationAttribute)
                    {
                        value |= (int)Attributes.Relation;
                    }
                    else if (att is StringLengthAttribute)
                    {
                        value |= (int)Attributes.StringLength;
                    }
                    else if (att is DataMemberAttribute)
                    {
                        DataMemberAttribute n = att as DataMemberAttribute;
                        if (n.IsRequired)
                        {
                            value |= (int)Attributes.IsRequired;
                        }
                    }
                    else if (att is DefaultValueAttribute)
                    {
                        value |= (int)Attributes.DefaultValue;
                    }
                }
            }
            s.Attributes = (Attributes)value;
        }
Beispiel #23
0
        public bool Load(string folderPath, string fileName, string sectionName)
        {
            this.FolderPath  = folderPath;
            this.FileName    = fileName;
            this.SectionName = sectionName;
            _isReadFile      = true;
            try
            {
                IniFile iniFile = new IniFile(folderPath, fileName);
                if (iniFile.GetSectionNames().Where(x => x == sectionName).Count() == 0)
                {
                    //找不到參數自動寫入預設值
                    Save(folderPath, fileName, sectionName);
                }
                PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var property in properties)
                {
                    NonMemberAttribute nonMemberAttribute =
                        (NonMemberAttribute)Attribute.GetCustomAttribute(property, typeof(NonMemberAttribute));
                    if (nonMemberAttribute != null)
                    {
                        continue;
                    }

                    string defaultValue      = string.Empty;
                    object readInstanceValue = property.GetValue(this, null);
                    if (readInstanceValue != null)
                    {
                        defaultValue = PropertyHelper.PropertyInfoGetValue(this, property);
                        if (defaultValue == null)
                        {
                            //HalconDotNet.HObject不進行讀寫
                            continue;
                        }
                    }
                    DefaultValueAttribute defaultValueAttribute =
                        (DefaultValueAttribute)Attribute.GetCustomAttribute(property, typeof(DefaultValueAttribute));
                    if (defaultValueAttribute != null)
                    {
                        defaultValue = defaultValueAttribute.Value.ToString();
                    }
                    string readValue = iniFile.GetString(sectionName, property.Name, defaultValue);
                    if (string.IsNullOrEmpty(readValue))
                    {
                        continue;
                    }
                    PropertyHelper.PropertyInfoSetValue(this, property, readValue);
                }
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("ParameterINI.Load({0}, {1}, {2}) Error", folderPath, fileName, sectionName));
                ExceptionHelper.MessageBoxShow(ex, "SystemHint");
                return(false);
            }
            finally
            {
                _isReadFile = false;
            }
        }
Beispiel #24
0
        public void Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            lock (this.initializeLock)
            {
                Dictionary <string, FieldInfo>     rowFields;
                Dictionary <string, IPropertyInfo> rowProperties;
                GetRowFieldsAndProperties(out rowFields, out rowProperties);

                var expressionSelector  = new DialectExpressionSelector(connectionKey);
                var rowCustomAttributes = this.rowType.GetCustomAttributes().ToList();

                foreach (var fieldInfo in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (fieldInfo.FieldType.IsSubclassOf(typeof(Field)))
                    {
                        var field = (Field)fieldInfo.GetValue(this);

                        IPropertyInfo property;
                        if (!rowProperties.TryGetValue(fieldInfo.Name, out property))
                        {
                            property = null;
                        }

                        ColumnAttribute         column           = null;
                        DisplayNameAttribute    display          = null;
                        SizeAttribute           size             = null;
                        ExpressionAttribute     expression       = null;
                        ScaleAttribute          scale            = null;
                        MinSelectLevelAttribute selectLevel      = null;
                        ForeignKeyAttribute     foreignKey       = null;
                        LeftJoinAttribute       leftJoin         = null;
                        InnerJoinAttribute      innerJoin        = null;
                        DefaultValueAttribute   defaultValue     = null;
                        TextualFieldAttribute   textualField     = null;
                        DateTimeKindAttribute   dateTimeKind     = null;
                        PermissionAttributeBase readPermission   = null;
                        PermissionAttributeBase insertPermission = null;
                        PermissionAttributeBase updatePermission = null;

                        FieldFlags addFlags    = (FieldFlags)0;
                        FieldFlags removeFlags = (FieldFlags)0;

                        OriginPropertyDictionary propertyDictionary = null;

                        if (property != null)
                        {
                            var origin = property.GetAttribute <OriginAttribute>();

                            column  = property.GetAttribute <ColumnAttribute>();
                            display = property.GetAttribute <DisplayNameAttribute>();
                            size    = property.GetAttribute <SizeAttribute>();

                            var expressions = property.GetAttributes <ExpressionAttribute>();
                            if (expressions.Any())
                            {
                                expression = expressionSelector.GetBestMatch(expressions, x => x.Dialect);
                            }

                            scale       = property.GetAttribute <ScaleAttribute>();
                            selectLevel = property.GetAttribute <MinSelectLevelAttribute>();
                            foreignKey  = property.GetAttribute <ForeignKeyAttribute>();
                            leftJoin    = property.GetAttributes <LeftJoinAttribute>()
                                          .FirstOrDefault(x => x.ToTable == null && x.OnCriteria == null);
                            innerJoin = property.GetAttributes <InnerJoinAttribute>()
                                        .FirstOrDefault(x => x.ToTable == null && x.OnCriteria == null);
                            defaultValue     = property.GetAttribute <DefaultValueAttribute>();
                            textualField     = property.GetAttribute <TextualFieldAttribute>();
                            dateTimeKind     = property.GetAttribute <DateTimeKindAttribute>();
                            readPermission   = property.GetAttribute <ReadPermissionAttribute>();
                            insertPermission = property.GetAttribute <InsertPermissionAttribute>() ??
                                               property.GetAttribute <ModifyPermissionAttribute>() ?? readPermission;
                            updatePermission = property.GetAttribute <UpdatePermissionAttribute>() ??
                                               property.GetAttribute <ModifyPermissionAttribute>() ?? readPermission;

                            if (origin != null)
                            {
                                propertyDictionary = propertyDictionary ?? OriginPropertyDictionary.GetPropertyDictionary(this.rowType);
                                try
                                {
                                    if (!expressions.Any() && expression == null)
                                    {
                                        expression = new ExpressionAttribute(propertyDictionary.OriginExpression(
                                                                                 property.Name, origin, expressionSelector, "", rowCustomAttributes));
                                    }

                                    if (display == null)
                                    {
                                        display = new DisplayNameAttribute(propertyDictionary.OriginDisplayName(property.Name, origin));
                                    }

                                    if (size == null)
                                    {
                                        size = propertyDictionary.OriginAttribute <SizeAttribute>(property.Name, origin);
                                    }

                                    if (scale == null)
                                    {
                                        scale = propertyDictionary.OriginAttribute <ScaleAttribute>(property.Name, origin);
                                    }
                                }
                                catch (DivideByZeroException)
                                {
                                    throw new InvalidProgramException(String.Format(
                                                                          "Infinite recursion detected while determining origins " +
                                                                          "for property '{0}' on row type '{1}'",
                                                                          property.Name, rowType.FullName));
                                }
                            }

                            var insertable = property.GetAttribute <InsertableAttribute>();
                            var updatable  = property.GetAttribute <UpdatableAttribute>();

                            if (insertable != null && !insertable.Value)
                            {
                                removeFlags |= FieldFlags.Insertable;
                            }

                            if (updatable != null && !updatable.Value)
                            {
                                removeFlags |= FieldFlags.Updatable;
                            }

                            foreach (var attr in property.GetAttributes <SetFieldFlagsAttribute>())
                            {
                                addFlags    |= attr.Add;
                                removeFlags |= attr.Remove;
                            }
                        }

                        if (ReferenceEquals(null, field))
                        {
                            if (property == null)
                            {
                                throw new InvalidProgramException(String.Format(
                                                                      "Field {0} in type {1} is null and has no corresponding property in entity!",
                                                                      fieldInfo.Name, rowType.Name));
                            }

                            object[] prm = new object[7];
                            prm[0] = this; // owner
                            prm[1] = column == null ? property.Name : (column.Name.TrimToNull() ?? property.Name);
                            prm[2] = display != null ? new LocalText(display.DisplayName) : null;
                            prm[3] = size != null ? size.Value : 0;

                            var defaultFlags = FieldFlags.Default;
                            if (fieldInfo.FieldType.GetCustomAttribute <NotMappedAttribute>() != null)
                            {
                                defaultFlags |= FieldFlags.NotMapped;
                            }

                            prm[4] = (defaultFlags ^ removeFlags) | addFlags;
                            prm[5] = null;
                            prm[6] = null;

                            FieldInfo storage;
                            if (rowFields.TryGetValue("_" + property.Name, out storage) ||
                                rowFields.TryGetValue("m_" + property.Name, out storage) ||
                                rowFields.TryGetValue(property.Name, out storage))
                            {
                                prm[5] = CreateFieldGetMethod(storage);
                                prm[6] = CreateFieldSetMethod(storage);
                            }

                            field = (Field)Activator.CreateInstance(fieldInfo.FieldType, prm);
                            fieldInfo.SetValue(this, field);
                        }
                        else
                        {
                            if (size != null)
                            {
                                throw new InvalidProgramException(String.Format(
                                                                      "Field size '{0}' in type {1} can't be overridden by Size attribute!",
                                                                      fieldInfo.Name, rowType.FullName));
                            }

                            if (display != null)
                            {
                                field.Caption = new LocalText(display.DisplayName);
                            }

                            if ((int)addFlags != 0 || (int)removeFlags != 0)
                            {
                                field.Flags = (field.Flags ^ removeFlags) | addFlags;
                            }

                            if (column != null && String.Compare(column.Name, field.Name, StringComparison.OrdinalIgnoreCase) != 0)
                            {
                                throw new InvalidProgramException(String.Format(
                                                                      "Field name '{0}' in type {1} can't be overridden by Column name attribute!",
                                                                      fieldInfo.Name, rowType.FullName));
                            }
                        }

                        if (scale != null)
                        {
                            field.Scale = scale.Value;
                        }

                        if (defaultValue != null)
                        {
                            field.DefaultValue = defaultValue.Value;
                        }

                        if (selectLevel != null)
                        {
                            field.MinSelectLevel = selectLevel.Value;
                        }

                        if (expression != null)
                        {
                            field.Expression = expression.Value;
                        }

                        if (foreignKey != null)
                        {
                            field.ForeignTable = foreignKey.Table;
                            field.ForeignField = foreignKey.Field;
                        }

                        if ((leftJoin != null || innerJoin != null) && field.ForeignTable.IsEmptyOrNull())
                        {
                            throw new InvalidProgramException(String.Format("Property {0} of row type {1} has a [LeftJoin] or [InnerJoin] attribute " +
                                                                            "but its foreign table is undefined. Make sure it has a valid [ForeignKey] attribute!",
                                                                            fieldInfo.Name, rowType.FullName));
                        }

                        if ((leftJoin != null || innerJoin != null) && field.ForeignField.IsEmptyOrNull())
                        {
                            throw new InvalidProgramException(String.Format("Property {0} of row type {1} has a [LeftJoin] or [InnerJoin] attribute " +
                                                                            "but its foreign field is undefined. Make sure it has a valid [ForeignKey] attribute!",
                                                                            fieldInfo.Name, rowType.FullName));
                        }

                        if (leftJoin != null)
                        {
                            field.ForeignJoinAlias = new LeftJoin(this.joins, field.ForeignTable, leftJoin.Alias,
                                                                  new Criteria(leftJoin.Alias, field.ForeignField) == new Criteria(field));
                        }

                        if (innerJoin != null)
                        {
                            field.ForeignJoinAlias = new InnerJoin(this.joins, field.ForeignTable, innerJoin.Alias,
                                                                   new Criteria(innerJoin.Alias, field.ForeignField) == new Criteria(field));
                        }

                        if (textualField != null)
                        {
                            field.textualField = textualField.Value;
                        }

                        if (dateTimeKind != null && field is DateTimeField)
                        {
                            ((DateTimeField)field).DateTimeKind = dateTimeKind.Value;
                        }

                        if (readPermission != null)
                        {
                            field.readPermission = readPermission.Permission ?? "?";
                        }

                        if (insertPermission != null)
                        {
                            field.insertPermission = insertPermission.Permission ?? "?";
                        }

                        if (updatePermission != null)
                        {
                            field.updatePermission = updatePermission.Permission ?? "?";
                        }

                        if (property != null)
                        {
                            if (property.PropertyType != null &&
                                field is IEnumTypeField)
                            {
                                if (property.PropertyType.IsEnum)
                                {
                                    (field as IEnumTypeField).EnumType = property.PropertyType;
                                }
                                else
                                {
                                    var nullableType = Nullable.GetUnderlyingType(property.PropertyType);
                                    if (nullableType != null && nullableType.IsEnum)
                                    {
                                        (field as IEnumTypeField).EnumType = nullableType;
                                    }
                                }
                            }

                            foreach (var attr in property.GetAttributes <LeftJoinAttribute>())
                            {
                                if (attr.ToTable != null && attr.OnCriteria != null)
                                {
                                    new LeftJoin(this.joins, attr.ToTable, attr.Alias,
                                                 new Criteria(attr.Alias, attr.OnCriteria) == new Criteria(field));
                                }
                            }

                            foreach (var attr in property.GetAttributes <InnerJoinAttribute>())
                            {
                                if (attr.ToTable != null && attr.OnCriteria != null)
                                {
                                    new InnerJoin(this.joins, attr.ToTable, attr.Alias,
                                                  new Criteria(attr.Alias, attr.OnCriteria) == new Criteria(field));
                                }
                            }

                            field.PropertyName = property.Name;
                            this.byPropertyName[field.PropertyName] = field;

                            field.customAttributes = property.GetAttributes <Attribute>().ToArray();
                        }
                    }
                }

                foreach (var attr in rowCustomAttributes.OfType <LeftJoinAttribute>())
                {
                    new LeftJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.OnCriteria));
                }

                foreach (var attr in rowCustomAttributes.OfType <InnerJoinAttribute>())
                {
                    new InnerJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.OnCriteria));
                }

                foreach (var attr in rowCustomAttributes.OfType <OuterApplyAttribute>())
                {
                    new OuterApply(this.joins, attr.InnerQuery, attr.Alias);
                }

#if !COREFX
                var propertyDescriptorArray = new PropertyDescriptor[this.Count];
                for (int i = 0; i < this.Count; i++)
                {
                    var field = this[i];
                    propertyDescriptorArray[i] = new FieldDescriptor(field);
                }

                this.propertyDescriptors = new PropertyDescriptorCollection(propertyDescriptorArray);
#endif

                InferTextualFields();
                AfterInitialize();
            }

            isInitialized = true;
        }
Beispiel #25
0
        protected virtual bool PrepareMember(MemberDescriptorBase member)
        {
            var memberType = member.Type;

            // Start with DataContractAttribute.DefaultMemberMode (if set)
            member.Mode = DefaultMemberMode;
            member.Mask = 1;


            // Gets the style
            var styleAttribute = AttributeRegistry.GetAttribute <DataStyleAttribute>(member.MemberInfo);

            if (styleAttribute != null)
            {
                member.Style       = styleAttribute.Style;
                member.ScalarStyle = styleAttribute.ScalarStyle;
            }

            // Handle member attribute
            var memberAttribute = AttributeRegistry.GetAttribute <DataMemberAttribute>(member.MemberInfo);

            if (memberAttribute != null)
            {
                ((IMemberDescriptor)member).Mask = memberAttribute.Mask;
                if (!member.HasSet)
                {
                    if (memberAttribute.Mode == DataMemberMode.Assign ||
                        (memberType.IsValueType && member.Mode == DataMemberMode.Content))
                    {
                        throw new ArgumentException($"{memberType.FullName} {member.OriginalName} is not writeable by {memberAttribute.Mode.ToString()}.");
                    }
                }

                member.Mode  = memberAttribute.Mode;
                member.Order = memberAttribute.Order;
            }

            // If mode is Default, let's resolve to the actual mode depending on getter/setter existence and object type
            if (member.Mode == DataMemberMode.Default)
            {
                // The default mode is Content, which will not use the setter to restore value if the object is a class (but behave like Assign for value types)
                member.Mode = DataMemberMode.Content;
                if (!member.HasSet && (memberType == typeof(string) || !memberType.IsClass) && !memberType.IsInterface && !Type.IsAnonymous())
                {
                    // If there is no setter, and the value is a string or a value type, we won't write the object at all.
                    member.Mode = DataMemberMode.Never;
                }
            }

            // Process all attributes just once instead of getting them one by one
            var attributes = AttributeRegistry.GetAttributes(member.MemberInfo);
            DefaultValueAttribute defaultValueAttribute = null;

            foreach (var attribute in attributes)
            {
                var valueAttribute = attribute as DefaultValueAttribute;
                if (valueAttribute != null)
                {
                    defaultValueAttribute = valueAttribute;
                    continue;
                }

                var yamlRemap = attribute as DataAliasAttribute;
                if (yamlRemap != null)
                {
                    if (member.AlternativeNames == null)
                    {
                        member.AlternativeNames = new List <string>();
                    }
                    if (!string.IsNullOrWhiteSpace(yamlRemap.Name))
                    {
                        member.AlternativeNames.Add(yamlRemap.Name);
                    }
                }
            }


            // If it's a private member, check it has a YamlMemberAttribute on it
            if (!member.IsPublic)
            {
                if (memberAttribute == null)
                {
                    return(false);
                }
            }

            if (member.Mode == DataMemberMode.Binary)
            {
                if (!memberType.IsArray)
                {
                    throw new InvalidOperationException($"{memberType.FullName} {member.OriginalName} of {Type.FullName} is not an array. Can not be serialized as binary.");
                }
                if (!memberType.GetElementType().IsPureValueType())
                {
                    throw new InvalidOperationException($"{memberType.GetElementType()} is not a pure ValueType. {memberType.FullName} {member.OriginalName} of {Type.FullName} can not serialize as binary.");
                }
            }

            // If this member cannot be serialized, remove it from the list
            if (member.Mode == DataMemberMode.Never)
            {
                return(false);
            }

            // ShouldSerialize
            //	  YamlSerializeAttribute(Never) => false
            //	  ShouldSerializeSomeProperty => call it
            //	  DefaultValueAttribute(default) => compare to it
            //	  otherwise => true
            var shouldSerialize = Type.GetMethod("ShouldSerialize" + member.OriginalName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null)
            {
                member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray);
            }

            if (defaultValueAttribute != null && member.ShouldSerialize == null && !emitDefaultValues)
            {
                object defaultValue = defaultValueAttribute.Value;
                Type   defaultType  = defaultValue?.GetType();
                if (defaultType.IsNumeric() && defaultType != memberType)
                {
                    defaultValue = memberType.CastToNumericType(defaultValue);
                }
                member.ShouldSerialize = obj => !Equals(defaultValue, member.Get(obj));
            }

            if (member.ShouldSerialize == null)
            {
                member.ShouldSerialize = ShouldSerializeDefault;
            }

            member.Name = !string.IsNullOrEmpty(memberAttribute?.Name) ? memberAttribute.Name : NamingConvention.Convert(member.OriginalName);

            return(true);
        }
Beispiel #26
0
        private static object GetPropertyDefaultValue(PropertyDescriptor propertyDescriptor)
        {
            DefaultValueAttribute attr = propertyDescriptor.Attributes.OfType <DefaultValueAttribute>().FirstOrDefault();

            return((attr != null) ? attr.Value : null);
        }
Beispiel #27
0
        protected virtual DataTable GetDataImplementation(object parameters, string loadMethod)
        {
            MethodInfo selectMethod;
            object     target;

            if (_adapter != null)
            {
                target = _adapter;
                if (String.IsNullOrEmpty(loadMethod))
                {
                    selectMethod = _defaultFillMethod;
                }
                else
                {
                    selectMethod = _fillMethods[loadMethod] as MethodInfo;
                    if (selectMethod == null)
                    {
                        throw new ArgumentOutOfRangeException("loadMethod",
                                                              String.Format(CultureInfo.CurrentCulture, "Method {0} is not available on the data service.", loadMethod));
                    }
                }
            }
            else
            {
                target       = this;
                selectMethod = GetDataMethod(DataObjectMethodType.Select, loadMethod);
            }
            if (selectMethod == null)
            {
                throw new InvalidOperationException("The Data Service must implement one method marked with the DataObjectMethod(DataObjectMethodType.Select) attribute or have a DataAdapterAttribute.");
            }
            object    data  = InvokeMethod(selectMethod, target, parameters);
            DataTable table = data as DataTable;

            if (table == null)
            {
                table        = new DataTable("data");
                table.Locale = CultureInfo.CurrentCulture;
                IEnumerable enumerableData = data as IEnumerable;
                if (enumerableData == null)
                {
                    throw new InvalidOperationException("The data returned by a select method must be IEnumerable or a DataTable.");
                }
                IEnumerator enumerator = enumerableData.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    object       firstRow    = enumerator.Current;
                    MemberInfo[] dataColumns = GetDataObjectFields(firstRow);
                    if (dataColumns.Length == 0)
                    {
                        // Just construct a one-column table
                        DataColumn column = new DataColumn("_rowObject", firstRow.GetType());
                        table.Columns.Add(column);
                        foreach (object row in enumerableData)
                        {
                            DataRow dataRow = table.NewRow();
                            dataRow[0] = row;
                            table.Rows.Add(dataRow);
                        }
                    }
                    else
                    {
                        List <DataColumn> keys = new List <DataColumn>();
                        foreach (PropertyInfo propertyInfo in dataColumns)
                        {
                            DataColumn column = new DataColumn(propertyInfo.Name, propertyInfo.PropertyType);
                            if (((DataObjectFieldAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(DataObjectFieldAttribute))).PrimaryKey)
                            {
                                keys.Add(column);
                            }
                            DefaultValueAttribute defaultAttribute =
                                (DefaultValueAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(DefaultValueAttribute));
                            if (defaultAttribute != null)
                            {
                                column.DefaultValue = defaultAttribute.Value;
                            }
                            table.Columns.Add(column);
                        }
                        table.PrimaryKey = keys.ToArray();
                        foreach (object row in enumerableData)
                        {
                            DataRow dataRow = table.NewRow();
                            foreach (PropertyInfo propertyInfo in dataColumns)
                            {
                                dataRow[propertyInfo.Name] = propertyInfo.GetValue(row, null);
                            }
                            table.Rows.Add(dataRow);
                        }
                    }
                }
            }
            return(table);
        }
Beispiel #28
0
        private static TValue GetMetadataValue <TValue>(IDictionary <string, object> metadata, string name, DefaultValueAttribute defaultValue)
        {
            object result;

            if (metadata.TryGetValue(name, out result))
            {
                return((TValue)result);
            }

            if (defaultValue != null)
            {
                return((TValue)defaultValue.Value);
            }

            // This could be significantly improved by describing the target metadata property.
            var message = string.Format(Properties.Resources.MetadataViewProvider_MissingMetadata, name);

            throw ThrowHelper.CompositionException(message);
        }
Beispiel #29
0
        internal ConfigurationProperty(PropertyInfo info)
        {
            Debug.Assert(info != null, "info != null");

            ConfigurationPropertyAttribute propertyAttribute    = null;
            DescriptionAttribute           descriptionAttribute = null;

            // For compatibility we read the component model default value attribute. It is only
            // used if ConfigurationPropertyAttribute doesn't provide the default value.
            DefaultValueAttribute defaultValueAttribute = null;

            TypeConverter typeConverter          = null;
            ConfigurationValidatorBase validator = null;

            // Look for relevant attributes
            foreach (Attribute attribute in Attribute.GetCustomAttributes(info))
            {
                if (attribute is TypeConverterAttribute)
                {
                    typeConverter = TypeUtil.CreateInstance <TypeConverter>(((TypeConverterAttribute)attribute).ConverterTypeName);
                }
                else if (attribute is ConfigurationPropertyAttribute)
                {
                    propertyAttribute = (ConfigurationPropertyAttribute)attribute;
                }
                else if (attribute is ConfigurationValidatorAttribute)
                {
                    if (validator != null)
                    {
                        // We only allow one validator to be specified on a property.
                        //
                        // Consider: introduce a new validator type ( CompositeValidator ) that is a
                        // list of validators and executes them all

                        throw new ConfigurationErrorsException(
                                  SR.Format(SR.Validator_multiple_validator_attributes, info.Name));
                    }

                    ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute;
                    validatorAttribute.SetDeclaringType(info.DeclaringType);
                    validator = validatorAttribute.ValidatorInstance;
                }
                else if (attribute is DescriptionAttribute)
                {
                    descriptionAttribute = (DescriptionAttribute)attribute;
                }
                else if (attribute is DefaultValueAttribute)
                {
                    defaultValueAttribute = (DefaultValueAttribute)attribute;
                }
            }

            Type propertyType = info.PropertyType;

            // If the property is a Collection we need to look for the ConfigurationCollectionAttribute for
            // additional customization.
            if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType))
            {
                // Look for the ConfigurationCollection attribute on the property itself, fall back
                // on the property type.
                ConfigurationCollectionAttribute collectionAttribute =
                    Attribute.GetCustomAttribute(info,
                                                 typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ??
                    Attribute.GetCustomAttribute(propertyType,
                                                 typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;

                if (collectionAttribute != null)
                {
                    if (collectionAttribute.AddItemName.IndexOf(',') == -1)
                    {
                        AddElementName = collectionAttribute.AddItemName;                                                     // string.Contains(char) is .NetCore2.1+ specific
                    }
                    RemoveElementName = collectionAttribute.RemoveItemName;
                    ClearElementName  = collectionAttribute.ClearItemsName;
                }
            }

            // This constructor shouldn't be invoked if the reflection info is not for an actual config property
            Debug.Assert(propertyAttribute != null, "attribProperty != null");

            ConstructorInit(propertyAttribute.Name,
                            info.PropertyType,
                            propertyAttribute.Options,
                            validator,
                            typeConverter);

            // Figure out the default value
            InitDefaultValueFromTypeInfo(propertyAttribute, defaultValueAttribute);

            // Get the description
            if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
            {
                Description = descriptionAttribute.Description;
            }
        }
Beispiel #30
0
        public void CargarListView()
        {
            LVElementos.Items.Clear();
            if (mLista == null)
            {
                return;
            }
            for (int i = 0; i < mLista.Count; i++)
            {
                Type           t  = mLista[i].GetType();
                PropertyInfo[] pr = t.GetProperties(flags);
                PropertyDescriptorCollection props   = null;
                AttributeCollection          attribs = null;
                BrowsableAttribute           bra     = null;
                ReadOnlyAttribute            roa     = null;

                ListViewItem mItem = new ListViewItem();

                int col = 0;
                foreach (PropertyInfo m in pr)
                {
                    object propertyValue = m.GetValue(mLista[i], null);
                    string propertyName  = m.Name;
                    props = TypeDescriptor.GetProperties(mLista[i]);

                    attribs = props[m.Name].Attributes;
                    bra     = (BrowsableAttribute)attribs[BrowsableAttribute.Default.GetType()];
                    roa     = (ReadOnlyAttribute)attribs[ReadOnlyAttribute.Default.GetType()];
                    DefaultValueAttribute dva = null;
                    dva = (DefaultValueAttribute)attribs[typeof(DefaultValueAttribute)];
                    string Valor = "";

                    if (bra.Browsable && ((!roa.IsReadOnly) || (m.PropertyType.BaseType.Equals(typeof(BaseCode.DB_BASE)))))
                    {
                        if (propertyValue == null)
                        {
                            Valor = "";
                        }
                        else
                        {
                            if (propertyValue.GetType().BaseType.Equals(typeof(BaseCode.DB_BASE)))
                            {
                                /*
                                 * PropertyInfo[] pr2 = propertyValue.GetType().GetProperties(flags);
                                 * PropertyDescriptorCollection props2 = TypeDescriptor.GetProperties(propertyValue);
                                 * foreach (PropertyInfo m2 in pr2)
                                 * {
                                 *   object mValor = m2.GetValue(propertyValue, null);
                                 *
                                 *
                                 *   if (!mValor.ToString().Equals("") )
                                 *   {
                                 *       AttributeCollection attribs2 = props2[m2.Name].Attributes;
                                 *       BrowsableAttribute bra2 = (BrowsableAttribute)attribs2[BrowsableAttribute.Default.GetType()];
                                 *       if (bra2.Browsable)
                                 *       {
                                 *           DisplayNameAttribute dna = (DisplayNameAttribute)attribs2[DisplayNameAttribute.Default.GetType()];
                                 *           Valor = Valor + dna.DisplayName + ":" + mValor.ToString() + ";";
                                 *       }
                                 *   }
                                 *
                                 * }
                                 */
                                Valor = props[m.Name].Converter.ConvertTo(propertyValue, typeof(String)).ToString();
                            }
                            else
                            {
                                Valor = propertyValue.ToString();
                            }
                        }
                        if (propertyValue != null)
                        {
                            if (propertyValue.GetType().Equals(typeof(double)))
                            {
                                if (Valor.Equals(""))
                                {
                                    Valor = "0";
                                }
                                try
                                {
                                    Decimal nValor = Decimal.Parse(Valor);
                                    Valor = nValor.ToString("###,##0.00#");
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.ToString());
                                }
                                finally
                                {
                                    Valor = Utility.Completa(Valor, 10, "", Utility.Lado.Izquierdo);
                                }
                            }
                        }

                        if (col == 0)
                        {
                            mItem.Text = Valor;
                        }
                        else
                        {
                            mItem.SubItems.Add(Valor);
                        }
                        col++;
                    }
                }

                LVElementos.Items.Add(mItem);
            }
            AutoTamanoColumnas();
            LbTotalRegistros.Text = LVElementos.Items.Count.ToString();
        }
Beispiel #31
0
        private static Possible <object, Failure> ConvertTo(this ICacheConfigData cacheData, Type targetType, string configName)
        {
            object target = Activator.CreateInstance(targetType);

            foreach (var propertyInfo in target.GetType().GetProperties())
            {
                object value;
                if (cacheData.TryGetValue(propertyInfo.Name, out value))
                {
                    var nestedValue = value as ICacheConfigData;

                    if (nestedValue != null)
                    {
                        if (propertyInfo.PropertyType == typeof(ICacheConfigData))
                        {
                            propertyInfo.SetValue(target, nestedValue);
                        }
                        else
                        {
                            var nestedTarget = nestedValue.ConvertTo(propertyInfo.PropertyType, configName);
                            if (nestedTarget.Succeeded)
                            {
                                propertyInfo.SetValue(target, nestedTarget.Result);
                            }
                            else
                            {
                                return(nestedTarget.Failure);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            propertyInfo.SetValue(target, Convert.ChangeType(value, propertyInfo.PropertyType, CultureInfo.InvariantCulture));
                        }
                        catch (Exception e)
                        {
                            return(new IncorrectJsonConfigDataFailure("{0} Json configuration field '{1}' can not be set to '{2}'\n{3}", configName, propertyInfo.Name, value, e.GetLogEventMessage()));
                        }
                    }
                }
                else
                {
                    object defaultValue = propertyInfo.GetValue(target);
                    DefaultValueAttribute defaultValueAttribute =
                        propertyInfo.GetCustomAttributes(true).OfType <DefaultValueAttribute>().FirstOrDefault();

                    if (defaultValueAttribute != null)
                    {
                        try
                        {
                            propertyInfo.SetValue(target, Convert.ChangeType(defaultValueAttribute.Value, propertyInfo.PropertyType, CultureInfo.InvariantCulture));
                        }
                        catch (Exception e)
                        {
                            return
                                (new IncorrectJsonConfigDataFailure(
                                     "{0} Json configuration field '{1}' can not be set to the default value of '{2}'\n{3}",
                                     configName,
                                     propertyInfo.Name,
                                     defaultValueAttribute.Value,
                                     e.GetLogEventMessage()));
                        }
                    }
                    else if (defaultValue == null)
                    {
                        return(new IncorrectJsonConfigDataFailure("{0} requires a value for '{1}' in Json configuration data", configName, propertyInfo.Name));
                    }
                }
            }

            foreach (string key in cacheData.Keys)
            {
                switch (key)
                {
                case DictionaryKeyFactoryTypeName:
                case DictionaryKeyFactoryAssemblyName:
                    break;

                default:

                    if (target.GetType().GetProperty(key) == null)
                    {
                        return(new IncorrectJsonConfigDataFailure("{0} does not support setting '{1}' in Json configuration data", configName, key));
                    }

                    break;
                }
            }

            return(target);
        }
Beispiel #32
0
        public void Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            lock (this.initializeLock)
            {
                Dictionary <string, FieldInfo>    rowFields;
                Dictionary <string, PropertyInfo> rowProperties;
                GetRowFieldsAndProperties(out rowFields, out rowProperties);

                foreach (var fieldInfo in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (fieldInfo.FieldType.IsSubclassOf(typeof(Field)))
                    {
                        var field = (Field)fieldInfo.GetValue(this);

                        PropertyInfo property;
                        if (!rowProperties.TryGetValue(fieldInfo.Name, out property))
                        {
                            property = null;
                        }

                        ColumnAttribute         column       = null;
                        DisplayNameAttribute    display      = null;
                        SizeAttribute           size         = null;
                        ExpressionAttribute     expression   = null;
                        ScaleAttribute          scale        = null;
                        MinSelectLevelAttribute selectLevel  = null;
                        ForeignKeyAttribute     foreignKey   = null;
                        LeftJoinAttribute       foreignJoin  = null;
                        DefaultValueAttribute   defaultValue = null;
                        TextualFieldAttribute   textualField = null;
                        DateTimeKindAttribute   dateTimeKind = null;

                        FieldFlags addFlags    = (FieldFlags)0;
                        FieldFlags removeFlags = (FieldFlags)0;

                        if (property != null)
                        {
                            column       = property.GetCustomAttribute <ColumnAttribute>(false);
                            display      = property.GetCustomAttribute <DisplayNameAttribute>(false);
                            size         = property.GetCustomAttribute <SizeAttribute>(false);
                            expression   = property.GetCustomAttribute <ExpressionAttribute>(false);
                            scale        = property.GetCustomAttribute <ScaleAttribute>(false);
                            selectLevel  = property.GetCustomAttribute <MinSelectLevelAttribute>(false);
                            foreignKey   = property.GetCustomAttribute <ForeignKeyAttribute>(false);
                            foreignJoin  = property.GetCustomAttributes <LeftJoinAttribute>(false).FirstOrDefault(x => x.ToTable == null && x.OnCriteria == null);
                            defaultValue = property.GetCustomAttribute <DefaultValueAttribute>(false);
                            textualField = property.GetCustomAttribute <TextualFieldAttribute>(false);
                            dateTimeKind = property.GetCustomAttribute <DateTimeKindAttribute>(false);

                            var insertable = property.GetCustomAttribute <InsertableAttribute>(false);
                            var updatable  = property.GetCustomAttribute <UpdatableAttribute>(false);

                            if (insertable != null && !insertable.Value)
                            {
                                removeFlags |= FieldFlags.Insertable;
                            }

                            if (updatable != null && !updatable.Value)
                            {
                                removeFlags |= FieldFlags.Updatable;
                            }

                            foreach (var attr in property.GetCustomAttributes <SetFieldFlagsAttribute>(false))
                            {
                                addFlags    |= attr.Add;
                                removeFlags |= attr.Remove;
                            }
                        }

                        if (ReferenceEquals(null, field))
                        {
                            if (property == null)
                            {
                                throw new InvalidProgramException(String.Format(
                                                                      "Field {0} in type {1} is null and has no corresponding property in entity!",
                                                                      fieldInfo.Name, rowType.Name));
                            }

                            object[] prm = new object[7];
                            prm[0] = this; // owner
                            prm[1] = column == null ? property.Name : (column.Name.TrimToNull() ?? property.Name);
                            prm[2] = display != null ? new LocalText(display.DisplayName) : null;
                            prm[3] = size != null ? size.Value : 0;
                            prm[4] = (FieldFlags.Default ^ removeFlags) | addFlags;
                            prm[5] = null;
                            prm[6] = null;

                            FieldInfo storage;
                            if (rowFields.TryGetValue("_" + property.Name, out storage) ||
                                rowFields.TryGetValue("m_" + property.Name, out storage) ||
                                rowFields.TryGetValue(property.Name, out storage))
                            {
                                prm[5] = CreateFieldGetMethod(storage);
                                prm[6] = CreateFieldSetMethod(storage);
                            }

                            field = (Field)Activator.CreateInstance(fieldInfo.FieldType, prm);
                            fieldInfo.SetValue(this, field);
                        }
                        else
                        {
                            if (size != null)
                            {
                                throw new InvalidProgramException(String.Format(
                                                                      "Field size '{0}' in type {1} can't be overridden by Size attribute!",
                                                                      fieldInfo.Name, rowType.Name));
                            }

                            if (display != null)
                            {
                                field.Caption = new LocalText(display.DisplayName);
                            }

                            if ((int)addFlags != 0 || (int)removeFlags != 0)
                            {
                                field.Flags = (field.Flags ^ removeFlags) | addFlags;
                            }

                            if (column != null && String.Compare(column.Name, field.Name, StringComparison.OrdinalIgnoreCase) != 0)
                            {
                                throw new InvalidProgramException(String.Format(
                                                                      "Field name '{0}' in type {1} can't be overridden by Column name attribute!",
                                                                      fieldInfo.Name, rowType.Name));
                            }
                        }

                        if (scale != null)
                        {
                            field.Scale = scale.Value;
                        }

                        if (defaultValue != null)
                        {
                            field.DefaultValue = defaultValue.Value;
                        }

                        if (selectLevel != null)
                        {
                            field.MinSelectLevel = selectLevel.Value;
                        }

                        if (expression != null)
                        {
                            field.Expression = expression.Value;
                        }

                        if (foreignKey != null)
                        {
                            field.ForeignTable = foreignKey.Table;
                            field.ForeignField = foreignKey.Field;
                        }

                        if (foreignJoin != null)
                        {
                            field.ForeignJoinAlias = new LeftJoin(this.joins, field.ForeignTable, foreignJoin.Alias,
                                                                  new Criteria(foreignJoin.Alias, field.ForeignField) == new Criteria(field));
                        }

                        if (textualField != null)
                        {
                            field.textualField = textualField.Value;
                        }

                        if (dateTimeKind != null && field is DateTimeField)
                        {
                            ((DateTimeField)field).DateTimeKind = dateTimeKind.Value;
                        }

                        if (property != null)
                        {
                            if (property.PropertyType != null &&
                                field is IEnumTypeField)
                            {
                                if (property.PropertyType.IsEnum)
                                {
                                    (field as IEnumTypeField).EnumType = property.PropertyType;
                                }
                                else
                                {
                                    var nullableType = Nullable.GetUnderlyingType(property.PropertyType);
                                    if (nullableType != null && nullableType.IsEnum)
                                    {
                                        (field as IEnumTypeField).EnumType = nullableType;
                                    }
                                }
                            }

                            foreach (var attr in property.GetCustomAttributes <LeftJoinAttribute>())
                            {
                                if (attr.ToTable != null && attr.OnCriteria != null)
                                {
                                    new LeftJoin(this.joins, attr.ToTable, attr.Alias,
                                                 new Criteria(attr.Alias, attr.OnCriteria) == new Criteria(field));
                                }
                            }

                            field.PropertyName = property.Name;
                            this.byPropertyName[field.PropertyName] = field;

                            field.CustomAttributes = property.GetCustomAttributes(false);
                        }
                    }
                }

                foreach (var attr in this.rowType.GetCustomAttributes <LeftJoinAttribute>())
                {
                    new LeftJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.OnCriteria));
                }

                foreach (var attr in this.rowType.GetCustomAttributes <OuterApplyAttribute>())
                {
                    new OuterApply(this.joins, attr.InnerQuery, attr.Alias);
                }

                var propertyDescriptorArray = new PropertyDescriptor[this.Count];
                for (int i = 0; i < this.Count; i++)
                {
                    var field = this[i];
                    propertyDescriptorArray[i] = new FieldDescriptor(field);
                }

                this.propertyDescriptors = new PropertyDescriptorCollection(propertyDescriptorArray);

                InferTextualFields();
                AfterInitialize();
            }

            isInitialized = true;
        }
        GetTypeDependencyPropertiesCacheItem(
            Object serializableObject
            )
        {
            if (serializableObject == null)
            {
                throw new ArgumentNullException("serializableObject");
            }

            Type type = serializableObject.GetType();

            TypeDependencyPropertiesCacheItem
                cachedItem = (TypeDependencyPropertiesCacheItem)_typesDependencyPropertiesCacheTable[type];

            if (cachedItem == null)
            {
                //
                // This means that the type was not seen before
                // We have to create a new entry to that type
                //
                DependencyObject objectAsDependencyObject = serializableObject as DependencyObject;

                if (objectAsDependencyObject != null)
                {
                    //
                    // First we have to figure out if this dependency
                    // object has any dependency properties that can be
                    // serializable and this has to happen before creating
                    // any cache
                    //
                    DependencyPropertyList list = new DependencyPropertyList(1);

                    for (LocalValueEnumerator localValues = objectAsDependencyObject.GetLocalValueEnumerator();
                         localValues.MoveNext();)
                    {
                        DependencyProperty dependencyProperty = localValues.Current.Property;

                        list.Add(dependencyProperty);
                    }

                    if (list.Count > 0)
                    {
                        int numOfSerializableDependencyProperties = 0;

                        TypeDependencyPropertyCache[] dependencyPropertiesCache = new TypeDependencyPropertyCache[list.Count];

                        for (int indexInDependencyPropertyList = 0;
                             indexInDependencyPropertyList < list.Count;
                             indexInDependencyPropertyList++)
                        {
                            DependencyProperty dependencyProperty = list.List[indexInDependencyPropertyList];

                            DesignerSerializationVisibility visibility      = DesignerSerializationVisibility.Visible;
                            Type                  serializerTypeForProperty = null;
                            TypeConverter         typeConverterForProperty  = null;
                            DefaultValueAttribute defaultValueAttr          = null;
                            DesignerSerializationOptionsAttribute
                                 designerSerializationFlagsAttr = null;
                            Type propertyType = dependencyProperty.PropertyType;

                            //
                            // Get the static setter member for the DependencyProperty
                            //
                            MemberInfo memberInfo = dependencyProperty.
                                                    OwnerType.
                                                    GetMethod("Get" + dependencyProperty.Name,
                                                              BindingFlags.Public | BindingFlags.NonPublic |
                                                              BindingFlags.Static | BindingFlags.FlattenHierarchy);

                            // Note: This is because the IService model does not abide
                            // by this pattern of declaring the DependencyProperty on
                            // the OwnerType. That is the only exception case.
                            if (memberInfo == null)
                            {
                                //
                                // Create a PropertyInfo
                                //

                                PropertyInfo propertyInfo = null;

                                PropertyInfo[] properties = dependencyProperty.OwnerType.GetProperties();

                                String name = dependencyProperty.Name;

                                for (int i = 0;
                                     i < properties.Length && propertyInfo == null;
                                     i++)
                                {
                                    if (properties[i].Name == name)
                                    {
                                        propertyInfo = properties[i];
                                    }
                                }

                                if (propertyInfo != null)
                                {
                                    Debug.Assert(propertyInfo.PropertyType == dependencyProperty.PropertyType,
                                                 "The property type of the CLR wrapper must match that of the DependencyProperty itself.");

                                    memberInfo = propertyInfo;

                                    //
                                    // We have to special case Print Tickets here.
                                    // Print Tickets are defined on as dependency properties on
                                    // fixed objects of types:
                                    // o FixedDocumentSequence
                                    // o FixedDocument
                                    // o FixedPage
                                    // and in order to eliminate the dependency between
                                    // PresentationFramework and System.printing assemblies,
                                    // those dependency properties are defined as of type "object"
                                    // and hence if we are here and we have a property of name
                                    // "PrintTicket" and owned by one of the above mentioned types
                                    // we try to get the serializer for the PrintTicket object
                                    //
                                    if (propertyInfo.Name == XpsNamedProperties.PrintTicketProperty &&
                                        ((dependencyProperty.OwnerType == typeof(System.Windows.Documents.FixedPage)) ||
                                         (dependencyProperty.OwnerType == typeof(System.Windows.Documents.FixedDocument)) ||
                                         (dependencyProperty.OwnerType == typeof(System.Windows.Documents.FixedDocumentSequence))))
                                    {
                                        propertyType = typeof(PrintTicket);
                                    }
                                }
                            }

                            if (memberInfo != null &&
                                TypeDependencyPropertyCache.
                                CanSerializeProperty(memberInfo,
                                                     this,
                                                     out visibility,
                                                     out serializerTypeForProperty,
                                                     out typeConverterForProperty,
                                                     out defaultValueAttr,
                                                     out designerSerializationFlagsAttr) == true)
                            {
                                TypeCacheItem typeCacheItem = GetTypeCacheItem(propertyType);
                                serializerTypeForProperty = serializerTypeForProperty == null ? typeCacheItem.SerializerType : serializerTypeForProperty;
                                typeConverterForProperty  = typeConverterForProperty == null ? typeCacheItem.TypeConverter : typeConverterForProperty;

                                TypeDependencyPropertyCache
                                    dependencyPropertyCache = new TypeDependencyPropertyCache(memberInfo,
                                                                                              dependencyProperty,
                                                                                              visibility,
                                                                                              serializerTypeForProperty,
                                                                                              typeConverterForProperty,
                                                                                              defaultValueAttr,
                                                                                              designerSerializationFlagsAttr);

                                dependencyPropertiesCache[numOfSerializableDependencyProperties++] = dependencyPropertyCache;
                            }
                        }

                        if (numOfSerializableDependencyProperties > 0)
                        {
                            TypeDependencyPropertyCache[] serializableDependencyPropertiesCache =
                                new TypeDependencyPropertyCache[numOfSerializableDependencyProperties];

                            for (int indexInSerializableProperties = 0;
                                 indexInSerializableProperties < numOfSerializableDependencyProperties;
                                 indexInSerializableProperties++)
                            {
                                serializableDependencyPropertiesCache[indexInSerializableProperties] =
                                    dependencyPropertiesCache[indexInSerializableProperties];
                            }

                            cachedItem = new TypeDependencyPropertiesCacheItem(type,
                                                                               serializableDependencyPropertiesCache);

                            _typesDependencyPropertiesCacheTable[type] = cachedItem;
                        }
                    }
                }
            }

            return(cachedItem);
        }
        private static void SerializeInternal(string name, object value, IniDictionary ini, string groupName, bool rootObject, IniCollectionSettings collectionSettings)
        {
            IniGroup group = ini[groupName];

            if (value == null || value == DBNull.Value)
            {
                return;
            }
            if (!value.GetType().IsComplexType())
            {
                group.Add(name, value.ConvertToString());
                return;
            }
            if (value is IList)
            {
                int i = collectionSettings.StartIndex;
                switch (collectionSettings.Mode)
                {
                case IniCollectionMode.Normal:
                    foreach (object item in (IList)value)
                    {
                        SerializeInternal(name + "[" + (i++).ToString() + "]", item, ini, groupName, false, defaultCollectionSettings);
                    }
                    return;

                case IniCollectionMode.IndexOnly:
                    foreach (object item in (IList)value)
                    {
                        SerializeInternal((i++).ToString(), item, ini, groupName, false, defaultCollectionSettings);
                    }
                    return;

                case IniCollectionMode.NoSquareBrackets:
                    foreach (object item in (IList)value)
                    {
                        SerializeInternal(name + (i++).ToString(), item, ini, groupName, false, defaultCollectionSettings);
                    }
                    return;

                case IniCollectionMode.SingleLine:
                    List <string> line = new List <string>();
                    foreach (object item in (IList)value)
                    {
                        line.Add(item.ConvertToString());
                    }
                    group.Add(name, string.Join(collectionSettings.Format, line.ToArray()));
                    return;
                }
            }
            if (value is IDictionary)
            {
                switch (collectionSettings.Mode)
                {
                case IniCollectionMode.Normal:
                    foreach (DictionaryEntry item in (IDictionary)value)
                    {
                        SerializeInternal(name + "[" + item.Key.ConvertToString() + "]", item.Value, ini, groupName, false, defaultCollectionSettings);
                    }
                    return;

                case IniCollectionMode.IndexOnly:
                    foreach (DictionaryEntry item in (IDictionary)value)
                    {
                        SerializeInternal(item.Key.ConvertToString(), item.Value, ini, groupName, false, defaultCollectionSettings);
                    }
                    return;

                case IniCollectionMode.NoSquareBrackets:
                    foreach (DictionaryEntry item in (IDictionary)value)
                    {
                        SerializeInternal(name + item.Key.ConvertToString(), item.Value, ini, groupName, false, defaultCollectionSettings);
                    }
                    return;

                case IniCollectionMode.SingleLine:
                    throw new InvalidOperationException("Cannot serialize IDictionary with IniCollectionMode.SingleLine!");
                }
            }
            string newgroup = groupName;

            if (!rootObject)
            {
                if (!string.IsNullOrEmpty(newgroup))
                {
                    newgroup += '.';
                }
                newgroup += name;
                ini.Add(newgroup, new Dictionary <string, string>());
            }
            foreach (MemberInfo member in value.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance))
            {
                if (Attribute.GetCustomAttribute(member, typeof(IniIgnoreAttribute), true) != null)
                {
                    continue;
                }
                string membername = member.Name;
                if (Attribute.GetCustomAttribute(member, typeof(IniNameAttribute), true) != null)
                {
                    membername = ((IniNameAttribute)Attribute.GetCustomAttribute(member, typeof(IniNameAttribute), true)).Name;
                }
                object item;
                object defval;
                switch (member.MemberType)
                {
                case MemberTypes.Field:
                    FieldInfo field = (FieldInfo)member;
                    item   = field.GetValue(value);
                    defval = field.FieldType.GetDefaultValue();
                    break;

                case MemberTypes.Property:
                    PropertyInfo property = (PropertyInfo)member;
                    defval = property.PropertyType.GetDefaultValue();
                    if (property.GetIndexParameters().Length > 0)
                    {
                        continue;
                    }
                    MethodInfo getmethod = property.GetGetMethod();
                    if (getmethod == null)
                    {
                        continue;
                    }
                    item = getmethod.Invoke(value, null);
                    break;

                default:
                    continue;
                }
                DefaultValueAttribute defattr = (DefaultValueAttribute)Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute), true);
                if (defattr != null)
                {
                    defval = defattr.Value;
                }
                if (Attribute.GetCustomAttribute(member, typeof(IniAlwaysIncludeAttribute), true) != null || !Equals(item, defval))
                {
                    IniCollectionSettings  settings = defaultCollectionSettings;
                    IniCollectionAttribute attr     = (IniCollectionAttribute)Attribute.GetCustomAttribute(member, typeof(IniCollectionAttribute));
                    if (attr != null)
                    {
                        settings = attr.Settings;
                    }
                    SerializeInternal(membername, item, ini, newgroup, false, settings);
                }
            }
        }
Beispiel #35
0
        public void GetEventsFiltersByAttribute()
        {
            var defaultValueAttribute = new DefaultValueAttribute(null);
            EventDescriptorCollection events = TypeDescriptor.GetEvents(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });

            Assert.Equal(1, events.Count);
        }