public static void Ctor_Visibility(DesignerSerializationVisibility visibility, bool expectedIsDefaultAttribute)
        {
            var attribute = new DesignerSerializationVisibilityAttribute(visibility);

            Assert.Equal(visibility, attribute.Visibility);
            Assert.Equal(expectedIsDefaultAttribute, attribute.IsDefaultAttribute());
        }
Пример #2
0
        CanSerializeProperty(
            MemberInfo memberInfo,
            SerializersCacheManager serializersCacheManager,
            out DesignerSerializationVisibility visibility,
            out Type serializerTypeForProperty,
            out TypeConverter typeConverterForProperty,
            out DefaultValueAttribute defaultValueAttr,
            out DesignerSerializationOptionsAttribute designerSerializationFlagsAttr
            )
        {
            bool canSerializeProperty = false;

            // The conditions that we care about in those properties are as follows
            // 1. Properties that are decorated with the DesignerSerializationVisibility
            //    and that are not hidden
            //
            visibility = DesignerSerializationVisibility.Visible;
            serializerTypeForProperty      = null;
            typeConverterForProperty       = null;
            defaultValueAttr               = null;
            designerSerializationFlagsAttr = null;

            Attribute[] attributes = Attribute.GetCustomAttributes(memberInfo);

            for (int numberOfAttributes = 0;
                 numberOfAttributes < attributes.Length;
                 numberOfAttributes++)
            {
                //
                // Based on the attribute type, different properties could be set
                //
                Attribute attribute = attributes[numberOfAttributes];


                if (attribute is DesignerSerializationVisibilityAttribute)
                {
                    visibility = ((DesignerSerializationVisibilityAttribute)attribute).Visibility;
                }
                else if (attribute is DefaultValueAttribute)
                {
                    defaultValueAttr = (DefaultValueAttribute)attribute;
                }
                else if (attribute is DesignerSerializationOptionsAttribute)
                {
                    designerSerializationFlagsAttr = (DesignerSerializationOptionsAttribute)attribute;
                }
            }

            if (visibility != DesignerSerializationVisibility.Hidden)
            {
                canSerializeProperty = true;
            }

            return(canSerializeProperty);
        }
 // Summary:
 //     Initializes a new instance of the System.ComponentModel.DesignerSerializationVisibilityAttribute
 //     class using the specified System.ComponentModel.DesignerSerializationVisibility
 //     value.
 //
 // Parameters:
 //   visibility:
 //     One of the System.ComponentModel.DesignerSerializationVisibility values.
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility)
 {
     // Summary:
     //     Gets a value indicating the basic serialization mode a serializer should
     //     use when determining whether and how to persist the value of a property.
     //
     // Returns:
     //     One of the System.ComponentModel.DesignerSerializationVisibility values.
     //     The default is System.ComponentModel.DesignerSerializationVisibility.Visible.
     return(default(DesignerSerializationVisibilityAttribute));
 }
 internal MemberReflector(XamlType type, XamlValueConverter <System.ComponentModel.TypeConverter> typeConverter)
 {
     this.Type = type;
     this._typeConverter.Value             = typeConverter;
     this._designerSerializationVisibility = DesignerSerializationVisibility.Visible;
     this._memberBits            = -65440;
     this._deferringLoader.Value = null;
     this._getter.Value          = null;
     this._setter.Value          = null;
     this._valueSerializer.Value = null;
 }
 internal MemberReflector(XamlType type, XamlValueConverter<System.ComponentModel.TypeConverter> typeConverter)
 {
     this.Type = type;
     this._typeConverter.Value = typeConverter;
     this._designerSerializationVisibility = DesignerSerializationVisibility.Visible;
     this._memberBits = -65440;
     this._deferringLoader.Value = null;
     this._getter.Value = null;
     this._setter.Value = null;
     this._valueSerializer.Value = null;
 }
    // Summary:
    //     Initializes a new instance of the System.ComponentModel.DesignerSerializationVisibilityAttribute
    //     class using the specified System.ComponentModel.DesignerSerializationVisibility
    //     value.
    //
    // Parameters:
    //   visibility:
    //     One of the System.ComponentModel.DesignerSerializationVisibility values.
    public DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility visibility) {

    // Summary:
    //     Gets a value indicating the basic serialization mode a serializer should
    //     use when determining whether and how to persist the value of a property.
    //
    // Returns:
    //     One of the System.ComponentModel.DesignerSerializationVisibility values.
    //     The default is System.ComponentModel.DesignerSerializationVisibility.Visible.
      return default(DesignerSerializationVisibilityAttribute);
    }
Пример #7
0
        ///<summary>Ctor used by directives</summary>
        internal MemberReflector(XamlType type, XamlValueConverter <TypeConverter> typeConverter)
        {
            Type = type;
            _typeConverter.Value             = typeConverter;
            _designerSerializationVisibility = DesignerSerializationVisibility.Visible;
            _memberBits = (int)BoolMemberBits.Directive | (int)BoolMemberBits.AllValid;

            // Explicitly set all the nullable references so that IsSet is true
            _deferringLoader.Value = null;
            _getter.Value          = null;
            _setter.Value          = null;
            _valueSerializer.Value = null;
        }
Пример #8
0
        private static DesignerSerializationVisibility GetSerializationVisibility(PropertyInfo prop)
        {
            if ((prop.DeclaringType == typeof(CompositeActivity)) && string.Equals(prop.Name, "Activities", StringComparison.Ordinal))
            {
                return(DesignerSerializationVisibility.Hidden);
            }
            DesignerSerializationVisibility visible = DesignerSerializationVisibility.Visible;

            DesignerSerializationVisibilityAttribute[] customAttributes = (DesignerSerializationVisibilityAttribute[])prop.GetCustomAttributes(typeof(DesignerSerializationVisibilityAttribute), true);
            if (customAttributes.Length > 0)
            {
                visible = customAttributes[0].Visibility;
            }
            return(visible);
        }
Пример #9
0
        protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj)
        {
            List <PropertyInfo> properties = new List <PropertyInfo>(base.GetProperties(serializationManager, obj));

            //Collect the internal properties, we do this so that activity change action apis don't need to expose unnecessary setters
            foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy))
            {
                DesignerSerializationVisibility visibility = Helpers.GetSerializationVisibility(property);
                if (visibility != DesignerSerializationVisibility.Hidden && property.GetSetMethod() == null && property.GetSetMethod(true) != null)
                {
                    properties.Add(property);
                }
            }

            return(properties.ToArray());
        }
Пример #10
0
        private static DesignerSerializationVisibility GetSerializationVisibility(PropertyInfo prop)
        {
            // work around!!! for Activities collection
            if (prop.DeclaringType == typeof(CompositeActivity) && string.Equals(prop.Name, "Activities", StringComparison.Ordinal))
            {
                return(DesignerSerializationVisibility.Hidden);
            }

            DesignerSerializationVisibility visibility = DesignerSerializationVisibility.Visible;

            DesignerSerializationVisibilityAttribute[] visibilityAttrs = (DesignerSerializationVisibilityAttribute[])prop.GetCustomAttributes(typeof(DesignerSerializationVisibilityAttribute), true);
            if (visibilityAttrs.Length > 0)
            {
                visibility = visibilityAttrs[0].Visibility;
            }

            return(visibility);
        }
Пример #11
0
        internal static DesignerSerializationVisibility GetSerializationVisibility(MemberInfo memberInfo)
        {
            if (memberInfo == null)
            {
                throw new ArgumentNullException("memberInfo");
            }
            DesignerSerializationVisibility visible = DesignerSerializationVisibility.Visible;

            object[] customAttributes = memberInfo.GetCustomAttributes(typeof(DesignerSerializationVisibilityAttribute), true);
            if (customAttributes.Length > 0)
            {
                return((customAttributes[0] as DesignerSerializationVisibilityAttribute).Visibility);
            }
            if (Attribute.IsDefined(memberInfo, typeof(DesignerSerializationVisibilityAttribute)))
            {
                visible = (Attribute.GetCustomAttribute(memberInfo, typeof(DesignerSerializationVisibilityAttribute)) as DesignerSerializationVisibilityAttribute).Visibility;
            }
            return(visible);
        }
Пример #12
0
 TypePropertyCache(
     PropertyInfo propertyInfo,
     DesignerSerializationVisibility visibility,
     Type serializerTypeForProperty,
     TypeConverter typeConverterForProperty,
     DefaultValueAttribute defaultValueAttr,
     DesignerSerializationOptionsAttribute designerSerializationFlagsAttr
     )
 {
     if (propertyInfo == null)
     {
         throw new ArgumentNullException("propertyInfo");
     }
     this.propertyInfo = propertyInfo;
     this.visibility   = visibility;
     this.serializerTypeForProperty      = serializerTypeForProperty;
     this.typeConverterForProperty       = typeConverterForProperty;
     this.defaultValueAttr               = defaultValueAttr;
     this.designerSerializationFlagsAttr = designerSerializationFlagsAttr;
     this.propertyValue = null;
 }
Пример #13
0
 TypeDependencyPropertyCache(
     MemberInfo memberInfo,
     Object dependencyProperty,
     DesignerSerializationVisibility visibility,
     Type serializerTypeForProperty,
     TypeConverter typeConverterForProperty,
     DefaultValueAttribute defaultValueAttr,
     DesignerSerializationOptionsAttribute designerSerializationFlagsAttr
     ) :
     base()
 {
     this.MemberInfo                       = memberInfo;
     this.DependencyProperty               = dependencyProperty;
     this.PropertyInfo                     = memberInfo as PropertyInfo;
     this.Visibility                       = visibility;
     this.SerializerTypeForProperty        = serializerTypeForProperty;
     this.TypeConverterForProperty         = typeConverterForProperty;
     this.DefaultValueAttr                 = defaultValueAttr;
     this.DesignerSerializationOptionsAttr = designerSerializationFlagsAttr;
     this.PropertyValue                    = null;
 }
Пример #14
0
        internal static DesignerSerializationVisibility GetSerializationVisibility(MemberInfo memberInfo)
        {
            if (memberInfo == null)
            {
                throw new ArgumentNullException("memberInfo");
            }

            DesignerSerializationVisibility designerSerializationVisibility = DesignerSerializationVisibility.Visible;

            // Calling GetCustomAttributes on PropertyInfo or EventInfo when the inherit parameter of GetCustomAttributes
            // is true does not walk the type hierarchy. But System.Attribute.GetCustomAttributes causes perf issues.
            object[] attributes = memberInfo.GetCustomAttributes(typeof(DesignerSerializationVisibilityAttribute), true);
            if (attributes.Length > 0)
            {
                designerSerializationVisibility = (attributes[0] as DesignerSerializationVisibilityAttribute).Visibility;
            }
            else if (Attribute.IsDefined(memberInfo, typeof(DesignerSerializationVisibilityAttribute)))
            {
                designerSerializationVisibility = (Attribute.GetCustomAttribute(memberInfo, typeof(DesignerSerializationVisibilityAttribute)) as DesignerSerializationVisibilityAttribute).Visibility;
            }

            return(designerSerializationVisibility);
        }
Пример #15
0
 public T?GetAttributeValue <T>(Type attributeType) where T : struct
 {
     if (CustomAttributeProvider != null)
     {
         object[] attributes = CustomAttributeProvider.GetCustomAttributes(attributeType, false);
         if (attributes.Length == 0)
         {
             return(null);
         }
         if (attributeType == typeof(DesignerSerializationVisibilityAttribute))
         {
             DesignerSerializationVisibility result = ((DesignerSerializationVisibilityAttribute)attributes[0]).Visibility;
             return((T)(object)result);
         }
         if (attributeType == typeof(UsableDuringInitializationAttribute))
         {
             bool result = ((UsableDuringInitializationAttribute)attributes[0]).Usable;
             return((T)(object)result);
         }
         Debug.Fail("Unexpected attribute type requested: " + attributeType.Name);
         return(null);
     }
     try
     {
         CustomAttributeData cad = GetAttribute(attributeType);
         if (cad == null)
         {
             return(null);
         }
         return(Extract <T>(cad));
     }
     catch (CustomAttributeFormatException)
     {
         CustomAttributeProvider = Member;
         return(GetAttributeValue <T>(attributeType));
     }
 }
Пример #16
0
        public bool WalkProperties(Activity activity, object obj)
        {
            Activity currentActivity = obj as Activity;

            PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                // !!Work around: no indexer property walking
                if (prop.GetIndexParameters() != null && prop.GetIndexParameters().Length > 0)
                {
                    continue;
                }

                DesignerSerializationVisibility visibility = GetSerializationVisibility(prop);
                if (visibility == DesignerSerializationVisibility.Hidden)
                {
                    continue;
                }

                //Try to see if we have dynamic property associated with the object on the same object
                //if so then we should compare if the dynamic property values match with the property type
                //if not we bail out
                object             propValue          = null;
                DependencyProperty dependencyProperty = DependencyProperty.FromName(prop.Name, obj.GetType());
                if (dependencyProperty != null && currentActivity != null)
                {
                    if (currentActivity.IsBindingSet(dependencyProperty))
                    {
                        propValue = currentActivity.GetBinding(dependencyProperty);
                    }
                    else
                    {
                        propValue = currentActivity.GetValue(dependencyProperty);
                    }
                }
                else
                {
                    try
                    {
                        propValue = prop.CanRead ? prop.GetValue(obj, null) : null;
                    }
                    catch
                    {
                        // Eat exceptions that occur while invoking the getter.
                    }
                }

                if (FoundProperty != null)
                {
                    WalkerEventArgs args = new WalkerEventArgs(activity, propValue, prop, obj);
                    FoundProperty(this, args);
                    if (args.Action == WalkerAction.Skip)
                    {
                        continue;
                    }
                    else if (args.Action == WalkerAction.Abort)
                    {
                        return(false);
                    }
                }

                if (propValue is IList)
                {
                    //We do not need to reflect on the properties of the list
                    foreach (object childObj in (IList)propValue)
                    {
                        if (FoundProperty != null)
                        {
                            WalkerEventArgs args = new WalkerEventArgs(activity, childObj, null, propValue);
                            FoundProperty(this, args);
                            if (args.Action == WalkerAction.Skip)
                            {
                                continue;
                            }
                            else if (args.Action == WalkerAction.Abort)
                            {
                                return(false);
                            }
                        }
                        if (childObj != null && IsBrowsableType(childObj.GetType()))
                        {
                            if (!WalkProperties(activity, childObj))
                            {
                                return(false);
                            }
                        }
                    }
                }
                else if (propValue != null && IsBrowsableType(propValue.GetType()))
                {
                    if (!WalkProperties(activity, propValue))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Пример #17
0
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visiblity)
 {
     this.m_visibility = visiblity;
 }
 /// <summary>Initializes a new instance of the <see cref="T:System.ComponentModel.DesignerSerializationVisibilityAttribute" /> class using the specified <see cref="T:System.ComponentModel.DesignerSerializationVisibility" /> value.</summary>
 /// <param name="visibility">One of the <see cref="T:System.ComponentModel.DesignerSerializationVisibility" /> values. </param>
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility vis)
 {
     this.visibility = vis;
 }
Пример #19
0
        internal override IEnumerable <MarkupProperty> GetProperties(bool mapToConstructorArgs)
        {
            ValueSerializer valueSerializer = ValueSerializer.GetSerializerFor(ObjectType, Context);

            if (valueSerializer != null && valueSerializer.CanConvertToString(_instance, Context))
            {
                yield return(new ElementStringValueProperty(this));

                if (_key != null)
                {
                    yield return(_key);
                }
            }
            else
            {
                Dictionary <string, string> constructorArguments = null;

                // if this markup item is the value of property in attribute form and the instance
                // it represents is a MarkupExtension, then we return any properties that are
                // constructor arguments as ElementConstructorArgument markup properties
                if (mapToConstructorArgs && _instance is MarkupExtension)
                {
                    ParameterInfo[] parameters;
                    ICollection     arguments;
                    if (TryGetConstructorInfoArguments(_instance, out parameters, out arguments))
                    {
                        int i = 0;
                        foreach (object value in arguments)
                        {
                            if (constructorArguments == null)
                            {
                                constructorArguments = new Dictionary <string, string>();
                            }
                            // store a list of the parameters that are constructor arguments
                            // so that we don't return those properties again
                            constructorArguments.Add(parameters[i].Name, parameters[i].Name);

                            yield return(new ElementConstructorArgument(value, parameters[i++].ParameterType, this));
                        }
                    }
                }
                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(_instance))
                {
                    DesignerSerializationVisibility visibility = descriptor.SerializationVisibility;

                    if (visibility != DesignerSerializationVisibility.Hidden &&
                        (!descriptor.IsReadOnly || visibility == DesignerSerializationVisibility.Content) &&
                        ShouldSerialize(descriptor, _instance, _manager))
                    {
                        if (visibility == DesignerSerializationVisibility.Content)
                        {
                            // Ensure the collection has content
                            object value = descriptor.GetValue(_instance);
                            if (value == null)
                            {
                                continue;
                            }
                            else
                            {
                                ICollection collection = value as ICollection;
                                if (collection != null && collection.Count < 1)
                                {
                                    continue;
                                }
                                IEnumerable enumerable = value as IEnumerable;
                                if (enumerable != null && !enumerable.GetEnumerator().MoveNext())
                                {
                                    continue;
                                }
                            }
                        }
                        if (constructorArguments != null)
                        {
                            ConstructorArgumentAttribute constructorArgumentAttribute = descriptor.Attributes[typeof(ConstructorArgumentAttribute)] as ConstructorArgumentAttribute;
                            if (constructorArgumentAttribute != null && constructorArguments.ContainsKey(constructorArgumentAttribute.ArgumentName))
                            {
                                // Skip this property, it has already been represented by a constructor parameter
                                continue;
                            }
                        }
                        yield return(new ElementProperty(this, descriptor));
                    }
                }
                IDictionary dictionary = _instance as IDictionary;
                if (dictionary != null)
                {
                    yield return(new ElementDictionaryItemsPseudoProperty(dictionary, typeof(IDictionary), this));
                }
                else
                {
                    IEnumerable enumerable = _instance as IEnumerable;
                    if (enumerable != null && enumerable.GetEnumerator().MoveNext())
                    {
                        yield return(new ElementItemsPseudoProperty(enumerable, typeof(IEnumerable), this));
                    }
                }

                if (_key != null)
                {
                    yield return(_key);
                }
            }
        }
        // Token: 0x0600240C RID: 9228 RVA: 0x000AFC1A File Offset: 0x000ADE1A
        internal override IEnumerable <MarkupProperty> GetProperties(bool mapToConstructorArgs)
        {
            ValueSerializer serializerFor = ValueSerializer.GetSerializerFor(this.ObjectType, this.Context);

            if (serializerFor != null && serializerFor.CanConvertToString(this._instance, this.Context))
            {
                yield return(new ElementStringValueProperty(this));

                if (this._key != null)
                {
                    yield return(this._key);
                }
            }
            else
            {
                Dictionary <string, string> constructorArguments = null;
                IEnumerator enumerator;
                if (mapToConstructorArgs && this._instance is MarkupExtension)
                {
                    ParameterInfo[] parameters;
                    ICollection     collection;
                    if (this.TryGetConstructorInfoArguments(this._instance, out parameters, out collection))
                    {
                        int i = 0;
                        foreach (object obj in collection)
                        {
                            if (constructorArguments == null)
                            {
                                constructorArguments = new Dictionary <string, string>();
                            }
                            constructorArguments.Add(parameters[i].Name, parameters[i].Name);
                            object          value = obj;
                            ParameterInfo[] array = parameters;
                            int             num   = i;
                            i = num + 1;
                            yield return(new ElementConstructorArgument(value, array[num].ParameterType, this));
                        }
                        enumerator = null;
                    }
                    parameters = null;
                }
                foreach (object obj2 in TypeDescriptor.GetProperties(this._instance))
                {
                    PropertyDescriptor propertyDescriptor = (PropertyDescriptor)obj2;
                    DesignerSerializationVisibility serializationVisibility = propertyDescriptor.SerializationVisibility;
                    if (serializationVisibility != DesignerSerializationVisibility.Hidden && (!propertyDescriptor.IsReadOnly || serializationVisibility == DesignerSerializationVisibility.Content) && ElementMarkupObject.ShouldSerialize(propertyDescriptor, this._instance, this._manager))
                    {
                        if (serializationVisibility == DesignerSerializationVisibility.Content)
                        {
                            object value2 = propertyDescriptor.GetValue(this._instance);
                            if (value2 == null)
                            {
                                continue;
                            }
                            ICollection collection2 = value2 as ICollection;
                            if (collection2 != null && collection2.Count < 1)
                            {
                                continue;
                            }
                            IEnumerable enumerable = value2 as IEnumerable;
                            if (enumerable != null && !enumerable.GetEnumerator().MoveNext())
                            {
                                continue;
                            }
                        }
                        if (constructorArguments != null)
                        {
                            ConstructorArgumentAttribute constructorArgumentAttribute = propertyDescriptor.Attributes[typeof(ConstructorArgumentAttribute)] as ConstructorArgumentAttribute;
                            if (constructorArgumentAttribute != null && constructorArguments.ContainsKey(constructorArgumentAttribute.ArgumentName))
                            {
                                continue;
                            }
                        }
                        yield return(new ElementProperty(this, propertyDescriptor));
                    }
                }
                enumerator = null;
                IDictionary dictionary = this._instance as IDictionary;
                if (dictionary != null)
                {
                    yield return(new ElementDictionaryItemsPseudoProperty(dictionary, typeof(IDictionary), this));
                }
                else
                {
                    IEnumerable enumerable2 = this._instance as IEnumerable;
                    if (enumerable2 != null && enumerable2.GetEnumerator().MoveNext())
                    {
                        yield return(new ElementItemsPseudoProperty(enumerable2, typeof(IEnumerable), this));
                    }
                }
                if (this._key != null)
                {
                    yield return(this._key);
                }
                constructorArguments = null;
            }
            yield break;
            yield break;
        }
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility)
 {
     this.visibility = visibility;
 }
Пример #22
0
        public static void Visibility(DesignerSerializationVisibility visibility)
        {
            var attribute = new DesignerSerializationVisibilityAttribute(visibility);

            Assert.Equal(visibility, attribute.Visibility);
        }
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility)
 {
     throw new NotImplementedException();
 }
 public void DefaultProperties_GetVisibility_ReturnsExpected(DesignerSerializationVisibilityAttribute attribute, DesignerSerializationVisibility expectedVisibility, bool expectedIsDefaultAttribute)
 {
     Assert.Equal(expectedVisibility, attribute.Visibility);
     Assert.Equal(expectedIsDefaultAttribute, attribute.IsDefaultAttribute());
 }
Пример #25
0
 internal MemberReflector()
 {
     _designerSerializationVisibility = VisibilityInvalid;
 }
        private protected bool SkipMember(object obj, MemberInfo member, out object value, ref DesignerSerializationVisibility visibility)
        {
            value = null;

            // skipping non-serializable members
            // Skip 1.) hidden by DesignerSerializationVisibility
            Attribute[] attrs = Attribute.GetCustomAttributes(member, typeof(DesignerSerializationVisibilityAttribute), true);
            visibility = attrs.Length > 0 ? ((DesignerSerializationVisibilityAttribute)attrs[0]).Visibility : visibility;
            if (visibility == DesignerSerializationVisibility.Hidden)
            {
                return(true);
            }

            // Skip 2.) ShouldSerialize<MemberName> method returns false
            if ((Options & XmlSerializationOptions.IgnoreShouldSerialize) == XmlSerializationOptions.None)
            {
                MethodInfo shouldSerializeMethod = member.DeclaringType?.GetMethod(XmlSerializer.MethodShouldSerialize + member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
                if (shouldSerializeMethod != null && shouldSerializeMethod.ReturnType == Reflector.BoolType && !(bool)Reflector.InvokeMethod(obj, shouldSerializeMethod))
                {
                    return(true);
                }
            }

            // Skip 3.) DefaultValue equals to property value
            bool   hasDefaultValue = false;
            object defaultValue    = null;

            if ((Options & XmlSerializationOptions.IgnoreDefaultValueAttribute) == XmlSerializationOptions.None)
            {
                attrs           = Attribute.GetCustomAttributes(member, typeof(DefaultValueAttribute), true);
                hasDefaultValue = attrs.Length > 0;
                if (hasDefaultValue)
                {
                    defaultValue = ((DefaultValueAttribute)attrs[0]).Value;
                }
            }

            PropertyInfo property   = member as PropertyInfo;
            FieldInfo    field      = property == null ? (FieldInfo)member : null;
            Type         memberType = property != null ? property.PropertyType : field.FieldType;

            if (!hasDefaultValue && (Options & XmlSerializationOptions.AutoGenerateDefaultValuesAsFallback) != XmlSerializationOptions.None)
            {
                hasDefaultValue = true;
                defaultValue    = memberType.IsValueType ? Activator.CreateInstance(memberType) : null;
            }

            value = property != null
                ? property.Get(obj)
                : field.Get(obj);

            return(hasDefaultValue && Equals(value, defaultValue));
        }
Пример #27
0
 DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
Пример #28
0
        private void SerializeObject(object obj, bool typeNeeded, XmlWriter writer, DesignerSerializationVisibility visibility)
        {
            #region Local Methods to reduce complexity

            bool TrySerializeKeyValue(ref SerializeObjectContext ctx)
            {
                // 1.) KeyValue 1: DictionaryEntry: can be serialized recursively. Just handling to avoid binary serialization.
                if (ctx.Type == Reflector.DictionaryEntryType)
                {
                    if (ctx.TypeNeeded)
                    {
                        ctx.Writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(ctx.Type));
                    }

                    SerializeMembers(ctx.Object, ctx.Writer, ctx.Visibility);
                    return(true);
                }

                // 2.) KeyValue 2: KeyValuePair: properties are read-only so special support needed
                if (ctx.Type.IsGenericTypeOf(Reflector.KeyValuePairType))
                {
                    if (ctx.TypeNeeded)
                    {
                        ctx.Writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(ctx.Type));
                    }

                    object key   = Accessors.GetPropertyValue(ctx.Object, nameof(KeyValuePair <_, _> .Key));
                    object value = Accessors.GetPropertyValue(ctx.Object, nameof(KeyValuePair <_, _> .Value));

                    ctx.Writer.WriteStartElement(nameof(KeyValuePair <_, _> .Key));
                    if (key == null)
                    {
                        ctx.Writer.WriteEndElement();
                    }
                    else
                    {
                        SerializeObject(key, key.GetType() != ctx.Type.GetGenericArguments()[0], ctx.Writer, ctx.Visibility);
                        ctx.Writer.WriteFullEndElement();
                    }

                    ctx.Writer.WriteStartElement(nameof(KeyValuePair <_, _> .Value));
                    if (value == null)
                    {
                        ctx.Writer.WriteEndElement();
                    }
                    else
                    {
                        SerializeObject(value, value.GetType() != ctx.Type.GetGenericArguments()[1], ctx.Writer, ctx.Visibility);
                        ctx.Writer.WriteFullEndElement();
                    }

                    return(true);
                }

                return(false);
            }

            bool TrySerializeComplexObject(ref SerializeObjectContext ctx)
            {
                // 1.) collection: if can be trusted in all circumstances
                if (ctx.Object is IEnumerable enumerable)
                {
                    Type elementType = null;

                    // if can be trusted in all circumstances
                    if (IsTrustedCollection(ctx.Type)
                        // or recursive is requested
                        || ((ctx.Visibility == DesignerSerializationVisibility.Content || RecursiveSerializationAsFallback)
                            // and is a supported collection or serialization is forced
                            && (ForceReadonlyMembersAndCollections || ctx.Type.IsSupportedCollectionForReflection(out var _, out var _, out elementType, out var _))))
                    {
                        SerializeCollection(enumerable, elementType ?? ctx.Type.GetCollectionElementType(), ctx.TypeNeeded, ctx.Writer, ctx.Visibility);
                        return(true);
                    }

                    if (ctx.Visibility == DesignerSerializationVisibility.Content || RecursiveSerializationAsFallback)
                    {
                        Throw.SerializationException(Res.XmlSerializationCannotSerializeUnsupportedCollection(ctx.Type, Options));
                    }
                    Throw.SerializationException(Res.XmlSerializationCannotSerializeCollection(ctx.Type, Options));
                }

                // 2.) recursive serialization of any object, if requested
                if (RecursiveSerializationAsFallback || ctx.Visibility == DesignerSerializationVisibility.Content
                    // or when it has public properties/fields only
                    || IsTrustedType(ctx.Type))
                {
                    if (ctx.TypeNeeded)
                    {
                        ctx.Writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(ctx.Type));
                    }

                    SerializeMembers(ctx.Object, ctx.Writer, ctx.Visibility);
                    return(true);
                }

                return(false);
            }

            #endregion

            if (obj == null)
            {
                return;
            }

            Type type = obj.GetType();

            // a.) If type can be natively parsed, simple writing
            if (type.CanBeParsedNatively())
            {
                if (typeNeeded)
                {
                    writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(type));
                }

                WriteStringValue(obj, writer);
                return;
            }

            // b.) IXmlSerializable
            if (obj is IXmlSerializable xmlSerializable && ProcessXmlSerializable)
            {
                if (typeNeeded)
                {
                    writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(type));
                }

                SerializeXmlSerializable(xmlSerializable, writer);
                return;
            }

            // c.) Using type converter of the type if applicable
            TypeConverter converter = TypeDescriptor.GetConverter(type);
            if (converter.CanConvertTo(Reflector.StringType) && converter.CanConvertFrom(Reflector.StringType))
            {
                if (typeNeeded)
                {
                    writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(type));
                }

                // ReSharper disable once AssignNullToNotNullAttribute
                writer.WriteString(converter.ConvertToInvariantString(obj));
                return;
            }

            var context = new SerializeObjectContext {
                Object = obj, Type = type, TypeNeeded = typeNeeded, Writer = writer, Visibility = visibility
            };

            // d.) Key/Value
            if (TrySerializeKeyValue(ref context))
            {
                return;
            }

            // e.) value type as binary only if enabled
            if (type.IsValueType && CompactSerializationOfStructures && BinarySerializer.TrySerializeValueType((ValueType)obj, out byte[] data))
		public DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility vis)
		{
			visibility = vis;
		}
Пример #30
0
        /// <summary>
        /// Serializing a collection by XmlWriter
        /// </summary>
        private void SerializeCollection(IEnumerable collection, Type elementType, bool typeNeeded, XmlWriter writer, DesignerSerializationVisibility visibility)
        {
            if (collection == null)
            {
                return;
            }

            // array collection
            if (collection is Array array)
            {
                if (typeNeeded)
                {
                    writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(collection.GetType()));
                }

                // multidimensional or nonzero-based array
                if (array.Rank > 1 || array.GetLowerBound(0) != 0)
                {
                    StringBuilder dim = new StringBuilder();
                    for (int i = 0; i < array.Rank; i++)
                    {
                        int low;
                        if ((low = array.GetLowerBound(i)) != 0)
                        {
                            dim.Append(low + ".." + (low + array.GetLength(i) - 1));
                        }
                        else
                        {
                            dim.Append(array.GetLength(i));
                        }

                        if (i < array.Rank - 1)
                        {
                            dim.Append(',');
                        }
                    }

                    writer.WriteAttributeString(XmlSerializer.AttributeDim, dim.ToString());
                }
                else
                {
                    writer.WriteAttributeString(XmlSerializer.AttributeLength, array.Length.ToString(CultureInfo.InvariantCulture));
                }

                if (array.Length == 0)
                {
                    // signing that collection is not null - now it will be at least <Collection></Collection> instead of <Collection />
                    writer.WriteString(String.Empty);
                    return;
                }

                // array of a primitive type
                if (elementType.IsPrimitive && (Options & XmlSerializationOptions.CompactSerializationOfPrimitiveArrays) != XmlSerializationOptions.None)
                {
                    byte[] data = new byte[Buffer.ByteLength(array)];
                    Buffer.BlockCopy(array, 0, data, 0, data.Length);
                    if ((Options & XmlSerializationOptions.OmitCrcAttribute) == XmlSerializationOptions.None)
                    {
                        writer.WriteAttributeString(XmlSerializer.AttributeCrc, Crc32.CalculateHash(data).ToString("X8", CultureInfo.InvariantCulture));
                    }
                    writer.WriteString(Convert.ToBase64String(data));

                    return;
                }

                // non-primitive type array or compact serialization is not enabled
                if (elementType.IsPointer)
                {
                    Throw.NotSupportedException(Res.SerializationPointerArrayTypeNotSupported(collection.GetType()));
                }
                foreach (var item in array)
                {
                    writer.WriteStartElement(XmlSerializer.ElementItem);
                    if (item == null)
                    {
                        writer.WriteEndElement();
                    }
                    else
                    {
                        SerializeObject(item, !elementType.IsSealed && item.GetType() != elementType, writer, visibility);
                        writer.WriteFullEndElement();
                    }
                }

                return;
            }

            // non-array collection
            if (typeNeeded)
            {
                writer.WriteAttributeString(XmlSerializer.AttributeType, GetTypeString(collection.GetType()));
            }

            // serializing main properties first
            SerializeMembers(collection, writer, visibility);

            // serializing items
            foreach (var item in collection)
            {
                writer.WriteStartElement(XmlSerializer.ElementItem);
                if (item == null)
                {
                    writer.WriteEndElement();
                }
                else
                {
                    SerializeObject(item, !elementType.IsSealed && item.GetType() != elementType, writer, visibility);
                    writer.WriteFullEndElement();
                }
            }
        }
 internal MemberReflector()
 {
     this._designerSerializationVisibility = (DesignerSerializationVisibility)0x7fffffff;
 }
Пример #32
0
        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);
        }
Пример #33
0
        GetClrSerializableProperties(
            SerializersCacheManager serializersCacheManager
            )
        {
            if (clrSerializableProperties == null)
            {
                PropertyInfo[] properties = type.GetProperties();

                //
                // Separate out the serializable Clr properties
                //
                int   IndexOfSerializableProperties = 0;
                int[] propertiesIndex = new int[properties.Length];
                TypePropertyCache[] cachedProperties = new TypePropertyCache[properties.Length];


                for (int indexInProperties = 0;
                     indexInProperties < properties.Length;
                     indexInProperties++)
                {
                    PropertyInfo propertyInfo = properties[indexInProperties];

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

                    if (CanSerializeProperty(propertyInfo,
                                             serializersCacheManager,
                                             out visibility,
                                             out serializerTypeForProperty,
                                             out typeConverterForProperty,
                                             out defaultValueAttr,
                                             out designerSerializationFlagsAttr) == true)
                    {
                        //
                        // Figure out the Serializer or TypeConverter associated with the
                        // type of that property. This would potentially be cached in 2
                        // different places
                        // 1. The Type Cache
                        // 2. The TypePropertyCache.
                        //
                        TypeCacheItem typeCacheItem = serializersCacheManager.GetTypeCacheItem(propertyInfo.PropertyType);

                        serializerTypeForProperty = typeCacheItem.SerializerType;
                        typeConverterForProperty  = typeCacheItem.TypeConverter;

                        //
                        // We create a cache of this property and all the information we
                        // deduced about it
                        //
                        TypePropertyCache propertyCache = new TypePropertyCache(propertyInfo,
                                                                                visibility,
                                                                                serializerTypeForProperty,
                                                                                typeConverterForProperty,
                                                                                defaultValueAttr,
                                                                                designerSerializationFlagsAttr);

                        propertiesIndex[IndexOfSerializableProperties]    = indexInProperties;
                        cachedProperties[IndexOfSerializableProperties++] = propertyCache;
                    }
                }

                clrSerializableProperties = new TypePropertyCache[IndexOfSerializableProperties];

                for (int indexInClrProperties = 0;
                     indexInClrProperties < IndexOfSerializableProperties;
                     indexInClrProperties++)
                {
                    clrSerializableProperties[indexInClrProperties] = cachedProperties[indexInClrProperties];
                }
            }

            return(clrSerializableProperties);
        }
Пример #34
0
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility)
 {
 }
Пример #35
0
 public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility v) { }
Пример #36
0
        CanSerializeProperty(
            PropertyInfo propertyInfo,
            SerializersCacheManager serializersCacheManager,
            out DesignerSerializationVisibility visibility,
            out Type serializerTypeForProperty,
            out TypeConverter typeConverterForProperty,
            out DefaultValueAttribute defaultValueAttr,
            out DesignerSerializationOptionsAttribute designerSerializationFlagsAttr
            )
        {
            bool canSerializeProperty = false;

            visibility = DesignerSerializationVisibility.Visible;
            serializerTypeForProperty      = null;
            typeConverterForProperty       = null;
            defaultValueAttr               = null;
            designerSerializationFlagsAttr = null;

            // The conditions that we care about in those properties are as follows
            // 1. Readable properties
            // 2. None Indexable Properteis.
            //    So we can't deal with properties that take name: Item OR
            //    take the form this[index1, index2, ...]
            // 3. Properties that are not backed up by a dependency property
            // 4. Properties that are decorated with the DesignerSerializationVisibility
            //    and that are not hidden
            //
            if (propertyInfo.CanRead &&
                propertyInfo.GetIndexParameters().GetLength(0) == 0)
            {
                MemberInfo memberInfo = (MemberInfo)propertyInfo;

                Attribute[] attributes = Attribute.GetCustomAttributes(memberInfo);

                for (int numberOfAttributes = 0;
                     numberOfAttributes < attributes.Length;
                     numberOfAttributes++)
                {
                    //
                    // Based on the attribute type, different properties could be set
                    //
                    Attribute attribute = attributes[numberOfAttributes];


                    if (attribute is DesignerSerializationVisibilityAttribute)
                    {
                        visibility = ((DesignerSerializationVisibilityAttribute)attribute).Visibility;
                    }
                    else if (attribute is DefaultValueAttribute)
                    {
                        defaultValueAttr = (DefaultValueAttribute)attribute;
                    }
                    else if (attribute is DesignerSerializationOptionsAttribute)
                    {
                        designerSerializationFlagsAttr = (DesignerSerializationOptionsAttribute)attribute;
                    }
                }

                object DependencyPropertyORPropertyInfo =
                    DependencyProperty.FromName(propertyInfo.Name, propertyInfo.DeclaringType);

                if (DependencyPropertyORPropertyInfo == null &&
                    visibility != DesignerSerializationVisibility.Hidden &&
                    (propertyInfo.CanWrite || visibility == DesignerSerializationVisibility.Content))
                {
                    if (visibility != DesignerSerializationVisibility.Hidden)
                    {
                        canSerializeProperty = true;
                    }
                }
            }

            return(canSerializeProperty);
        }
 internal MemberReflector()
 {
     this._designerSerializationVisibility = (DesignerSerializationVisibility) 0x7fffffff;
 }