Esempio n. 1
0
        public static IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            return(_serializerCache.GetOrAdd(
                       Tuple.Create(type, encryptAttribute, options),
                       _ =>
            {
                Func <Type, IXmlSerializerInternal> createDictionarySerializer =
                    genericDictionaryInterface =>
                {
                    var genericArguments = genericDictionaryInterface.GetGenericArguments();
                    var keyType = genericArguments[0];
                    var valueType = genericArguments[1];
                    return (IXmlSerializerInternal)Activator.CreateInstance(typeof(DictionarySerializer <, ,>).MakeGenericType(type, keyType, valueType), encryptAttribute, options);
                };

                if (type.IsAssignableToGenericIDictionary())
                {
                    return createDictionarySerializer(type.GetGenericIDictionaryType());
                }

                if (type.IsAssignableToNonGenericIDictionary())
                {
                    return (IXmlSerializerInternal)Activator.CreateInstance(typeof(DictionarySerializer <>).MakeGenericType(type), encryptAttribute, options);
                }

                if (type.IsReadOnlyDictionary())
                {
                    return createDictionarySerializer(type.GetIReadOnlyDictionaryInterface());
                }

                throw new InvalidOperationException(string.Format("Cannot create a DictionarySerializer of type '{0}'.", type.FullName));
            }));
        }
        internal int CreateKey(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            unchecked
            {
                var key = type.GetHashCode();

                key = (key * 397) ^ (string.IsNullOrWhiteSpace(options.DefaultNamespace) ? "" : options.DefaultNamespace).GetHashCode();

                if (options.ExtraTypes != null)
                {
                    key = options.ExtraTypes
                          .Where(extraType => extraType != null)
                          .Distinct(EqualityComparer <Type> .Default)
                          .OrderBy(extraType => extraType.FullName)
                          .Aggregate(key, (current, extraType) => (current * 397) ^ extraType.GetHashCode());
                }

                key = (key * 397) ^ (string.IsNullOrWhiteSpace(options.RootElementName) ? type.Name : options.RootElementName).GetHashCode();

                if (options.RedactAttribute != null)
                {
                    key = (key * 397) ^ options.RedactAttribute.GetHashCode();
                }

                key = (key * 397) ^ (encryptAttribute != null).GetHashCode();

                key = (key * 397) ^ options.TreatEmptyElementAsString.GetHashCode();

                return(key);
            }
        }
Esempio n. 3
0
 public XmlTextSerializer(Type type, RedactAttribute redactAttribute, EncryptAttribute encryptAttribute, Type[] extraTypes)
 {
     _encryptAttribute = encryptAttribute;
     if (!ValueTypes.TryGetValueConverter(type, redactAttribute, extraTypes, out _valueConverter))
     {
         _valueConverter = SimpleTypeValueConverter.Create(type, redactAttribute);
     }
 }
Esempio n. 4
0
 public XmlTextSerializer(Type type, RedactAttribute redactAttribute, EncryptAttribute encryptAttribute, Type[] extraTypes)
 {
     _encryptAttribute = encryptAttribute;
     if (!ValueTypes.TryGetValueConverter(type, redactAttribute, extraTypes, out _valueConverter))
     {
         _valueConverter = SimpleTypeValueConverter.Create(type, redactAttribute);
     }
 }
        public XmlAttributeSerializer(Type type, string attributeName, RedactAttribute redactAttribute, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            _attributeName = attributeName;
            _encryptAttribute = encryptAttribute;

            if (!ValueTypes.TryGetValueConverter(type, redactAttribute, options.ExtraTypes, out _valueConverter))
            {
                _valueConverter = SimpleTypeValueConverter.Create(type, redactAttribute);
            }
        }
        public XmlAttributeSerializer(Type type, string attributeName, RedactAttribute redactAttribute, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            _attributeName    = attributeName;
            _encryptAttribute = encryptAttribute;

            if (!ValueTypes.TryGetValueConverter(type, redactAttribute, options.ExtraTypes, out _valueConverter))
            {
                _valueConverter = SimpleTypeValueConverter.Create(type, redactAttribute);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Maybe sets the <see cref="XSerializerXmlTextWriter.IsEncryptionEnabled"/> property of
        /// <paramref name="reader"/> to true. Returns true if the value was changed to true, false
        /// if it was not changed to true.
        /// </summary>
        internal static bool MaybeSetIsDecryptionEnabledToTrue(this XSerializerXmlReader reader,
                                                               EncryptAttribute encryptAttribute, ISerializeOptions options)
        {
            if (options.ShouldEncrypt && encryptAttribute != null && !reader.IsDecryptionEnabled)
            {
                reader.IsDecryptionEnabled = true;
                return(true);
            }

            return(false);
        }
Esempio n. 8
0
        public static IXmlSerializerInternal GetSerializer <T>(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            var serializer = new DynamicSerializer(encryptAttribute, options);

            if (typeof(T) == typeof(object))
            {
                return(serializer);
            }

            if (typeof(T) == typeof(ExpandoObject))
            {
                return(new DynamicSerializerExpandoObjectProxy(serializer));
            }

            throw new InvalidOperationException("The only valid generic arguments for DynamicSerializer.GetSerializer<T> are object, dynamic, and ExpandoObject");
        }
Esempio n. 9
0
        public IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            var getSerializer = _getSerializerMap.GetOrAdd(
                type,
                t =>
            {
                var getSerializerMethod =
                    typeof(XmlSerializerFactory)
                    .GetMethod("GetSerializer", new[] { typeof(EncryptAttribute), typeof(IXmlSerializerOptions) })
                    .MakeGenericMethod(type);

                return((Func <EncryptAttribute, IXmlSerializerOptions, IXmlSerializerInternal>)Delegate.CreateDelegate(typeof(Func <EncryptAttribute, IXmlSerializerOptions, IXmlSerializerInternal>), this, getSerializerMethod));
            });

            return(getSerializer(encryptAttribute, options));
        }
Esempio n. 10
0
        public XmlElementSerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            if (!typeof(T).IsPrimitiveLike() && !typeof(T).IsNullablePrimitiveLike() && !ValueTypes.IsRegistered(typeof(T)))
            {
                throw new InvalidOperationException("Generic argument of XmlElementSerializer<T> must be an primitive, like a primitive (e.g. Guid, DateTime), a nullable of either, or one of: Enum, Type, or Uri.");
            }

            _elementName      = options.RootElementName;
            _alwaysEmitNil    = options.ShouldAlwaysEmitNil;
            _encryptAttribute = encryptAttribute;

            if (!ValueTypes.TryGetValueConverter(typeof(T), options.RedactAttribute, options.ExtraTypes, out _valueConverter))
            {
                _valueConverter = SimpleTypeValueConverter.Create(typeof(T), options.RedactAttribute);
            }
        }
Esempio n. 11
0
 public static IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
 {
     return _serializerCache.GetOrAdd(
         XmlSerializerFactory.Instance.CreateKey(type, encryptAttribute, options),
         _ =>
         {
             try
             {
                 return (IXmlSerializerInternal)Activator.CreateInstance(typeof(CustomSerializer<>).MakeGenericType(type), encryptAttribute, options);
             }
             catch (TargetInvocationException ex) // True exception gets masked due to reflection. Preserve stacktrace and rethrow
             {
                 PreserveStackTrace(ex.InnerException);
                 throw ex.InnerException;
             }
         });
 }
Esempio n. 12
0
 public static IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
 {
     return(_serializerCache.GetOrAdd(
                XmlSerializerFactory.Instance.CreateKey(type, encryptAttribute, options),
                _ =>
     {
         try
         {
             return (IXmlSerializerInternal)Activator.CreateInstance(typeof(CustomSerializer <>).MakeGenericType(type), encryptAttribute, options);
         }
         catch (TargetInvocationException ex)     // True exception gets masked due to reflection. Preserve stacktrace and rethrow
         {
             PreserveStackTrace(ex.InnerException);
             throw ex.InnerException;
         }
     }));
 }
Esempio n. 13
0
        protected DictionarySerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            // ReSharper disable DoNotCallOverridableMethodsInConstructor

            _encryptAttribute =
                encryptAttribute
                ?? KeyType.GetCustomAttribute <EncryptAttribute>()
                ?? ValueType.GetCustomAttribute <EncryptAttribute>();

            _options         = options;
            _keySerializer   = XmlSerializerFactory.Instance.GetSerializer(KeyType, null, _options.WithRootElementName("Key").WithRedactAttribute(null));
            _valueSerializer = XmlSerializerFactory.Instance.GetSerializer(ValueType, null, _options.WithRootElementName("Value"));

            if (DictionaryType.IsReadOnlyDictionary())
            {
                _createDictionary   = DefaultDictionaryType.CreateDefaultConstructorFunc <object>();
                _finalizeDictionary = FinalizeCollectionIntoReadOnlyDictionary;
            }
            else if (DictionaryType.IsInterface || DictionaryType.IsAbstract)
            {
                if (DictionaryType.IsAssignableFrom(DefaultDictionaryType))
                {
                    _createDictionary = DefaultDictionaryType.CreateDefaultConstructorFunc <object>();
                }
                else
                {
                    var dictionaryInheritorType =
                        _options.ExtraTypes.FirstOrDefault(t =>
                                                           !t.IsInterface &&
                                                           !t.IsAbstract &&
                                                           DictionaryType.IsAssignableFrom(t) &&
                                                           t.HasDefaultConstructor());
                    _createDictionary = dictionaryInheritorType.CreateDefaultConstructorFunc <object>();
                }
            }
            else if (DictionaryType.HasDefaultConstructor())
            {
                _createDictionary = DictionaryType.CreateDefaultConstructorFunc <object>();
            }
            else
            {
                throw new ArgumentException("Unable to find suitable dictionary to create.");
            }
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }
        protected DictionarySerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            // ReSharper disable DoNotCallOverridableMethodsInConstructor

            _encryptAttribute =
                encryptAttribute
                ?? (EncryptAttribute)Attribute.GetCustomAttribute(KeyType, typeof(EncryptAttribute))
                ?? (EncryptAttribute)Attribute.GetCustomAttribute(ValueType, typeof(EncryptAttribute));

            _options = options;
            _keySerializer = XmlSerializerFactory.Instance.GetSerializer(KeyType, null, _options.WithRootElementName("Key").WithRedactAttribute(null));
            _valueSerializer = XmlSerializerFactory.Instance.GetSerializer(ValueType, null, _options.WithRootElementName("Value"));

            if (DictionaryType.IsReadOnlyDictionary())
            {
                _createDictionary = DefaultDictionaryType.CreateDefaultConstructorFunc<object>();
                _finalizeDictionary = FinalizeCollectionIntoReadOnlyDictionary;
            }
            else if (DictionaryType.IsInterface || DictionaryType.IsAbstract)
            {
                if (DictionaryType.IsAssignableFrom(DefaultDictionaryType))
                {
                    _createDictionary = DefaultDictionaryType.CreateDefaultConstructorFunc<object>();
                }
                else
                {
                    var dictionaryInheritorType =
                        _options.ExtraTypes.FirstOrDefault(t =>
                            !t.IsInterface
                            && !t.IsAbstract
                            && DictionaryType.IsAssignableFrom(t)
                            && t.HasDefaultConstructor());
                    _createDictionary = dictionaryInheritorType.CreateDefaultConstructorFunc<object>();
                }
            }
            else if (DictionaryType.HasDefaultConstructor())
            {
                _createDictionary = DictionaryType.CreateDefaultConstructorFunc<object>();
            }
            else
            {
                throw new ArgumentException("Unable to find suitable dictionary to create.");
            }
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }
Esempio n. 15
0
        public static IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options, string itemElementName)
        {
            return _serializerCache.GetOrAdd(
                XmlSerializerFactory.Instance.CreateKey(type, encryptAttribute, options.WithRootElementName(options.RootElementName + "<>" + itemElementName)),
                _ =>
                {
                    if (type.IsAssignableToGenericIEnumerable())
                    {
                        var itemType = type.GetGenericIEnumerableType().GetGenericArguments()[0];
                        return (IXmlSerializerInternal)Activator.CreateInstance(typeof(ListSerializer<,>).MakeGenericType(type, itemType), encryptAttribute, options, itemElementName);
                    }
                        
                    if (type.IsAssignableToNonGenericIEnumerable())
                    {
                        return (IXmlSerializerInternal)Activator.CreateInstance(typeof(ListSerializer<>).MakeGenericType(type), encryptAttribute, options, itemElementName);
                    }

                    throw new InvalidOperationException(string.Format("Cannot create a ListSerializer of type '{0}'.", type.FullName));
                });
        }
Esempio n. 16
0
        public static IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options, string itemElementName)
        {
            return(_serializerCache.GetOrAdd(
                       XmlSerializerFactory.Instance.CreateKey(type, encryptAttribute, options.WithRootElementName(options.RootElementName + "<>" + itemElementName)),
                       _ =>
            {
                if (type.IsAssignableToGenericIEnumerable())
                {
                    var itemType = type.GetGenericIEnumerableType().GetGenericArguments()[0];
                    return (IXmlSerializerInternal)Activator.CreateInstance(typeof(ListSerializer <,>).MakeGenericType(type, itemType), encryptAttribute, options, itemElementName);
                }

                if (type.IsAssignableToNonGenericIEnumerable())
                {
                    return (IXmlSerializerInternal)Activator.CreateInstance(typeof(ListSerializer <>).MakeGenericType(type), encryptAttribute, options, itemElementName);
                }

                throw new InvalidOperationException(string.Format("Cannot create a ListSerializer of type '{0}'.", type.FullName));
            }));
        }
Esempio n. 17
0
        // ReSharper disable DoNotCallOverridableMethodsInConstructor
        protected ListSerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options, string itemElementName)
        {
            _encryptAttribute = encryptAttribute ?? ItemType.GetCustomAttribute<EncryptAttribute>();
            _options = options;
            _itemElementName = string.IsNullOrEmpty(itemElementName) ? DefaultItemElementName : itemElementName;
            _itemSerializer = XmlSerializerFactory.Instance.GetSerializer(ItemType, null, _options.WithRootElementName(_itemElementName).AlwaysEmitNil());

            if (CollectionType.IsArray)
            {
                _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc<object>();
            }
            else if (CollectionType.IsReadOnlyCollection())
            {
                _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc<object>();
            }
            else if (CollectionType.IsInterface || CollectionType.IsAbstract)
            {
                if (CollectionType.IsAssignableFrom(DefaultCollectionType))
                {
                    _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc<object>();
                }
                else
                {
                    var collectionInheritorType =
                        _options.ExtraTypes.FirstOrDefault(t =>
                            !t.IsInterface
                            && !t.IsAbstract
                            && CollectionType.IsAssignableFrom(t)
                            && t.HasDefaultConstructor());
                    _createCollection = collectionInheritorType.CreateDefaultConstructorFunc<object>();
                }
            }
            else if (CollectionType.HasDefaultConstructor())
            {
                _createCollection = CollectionType.CreateDefaultConstructorFunc<object>();
            }
            else
            {
                throw new ArgumentException("Unable to find suitable collection to create.");
            }
        }
Esempio n. 18
0
        protected ListSerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options, string itemElementName)                                                             // ReSharper disable DoNotCallOverridableMethodsInConstructor
        {
            _encryptAttribute = encryptAttribute ?? (EncryptAttribute)Attribute.GetCustomAttribute(ItemType, typeof(EncryptAttribute));
            _options          = options;
            _itemElementName  = string.IsNullOrEmpty(itemElementName) ? DefaultItemElementName : itemElementName;
            _itemSerializer   = XmlSerializerFactory.Instance.GetSerializer(ItemType, null, _options.WithRootElementName(_itemElementName).AlwaysEmitNil());

            if (CollectionType.IsArray)
            {
                _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc <object>();
            }
            else if (CollectionType.IsReadOnlyCollection())
            {
                _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc <object>();
            }
            else if (CollectionType.IsInterface || CollectionType.IsAbstract)
            {
                if (CollectionType.IsAssignableFrom(DefaultCollectionType))
                {
                    _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc <object>();
                }
                else
                {
                    var collectionInheritorType =
                        _options.ExtraTypes.FirstOrDefault(t =>
                                                           !t.IsInterface &&
                                                           !t.IsAbstract &&
                                                           CollectionType.IsAssignableFrom(t) &&
                                                           t.HasDefaultConstructor());
                    _createCollection = collectionInheritorType.CreateDefaultConstructorFunc <object>();
                }
            }
            else if (CollectionType.HasDefaultConstructor())
            {
                _createCollection = CollectionType.CreateDefaultConstructorFunc <object>();
            }
            else
            {
                throw new ArgumentException("Unable to find suitable collection to create.");
            }
        }                                                                                                                                           // ReSharper restore DoNotCallOverridableMethodsInConstructor
Esempio n. 19
0
        public IXmlSerializerInternal GetSerializer <T>(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            return(_serializerCache.GetOrAdd(
                       Tuple.Create(typeof(T), encryptAttribute, options),
                       _ =>
            {
                var type = typeof(T);

                if (type == typeof(object) || type == typeof(ExpandoObject))
                {
                    return DynamicSerializer.GetSerializer <T>(encryptAttribute, options);
                }

                IXmlSerializerInternal serializer;

                if (type.IsPrimitiveLike() ||
                    type.IsNullablePrimitiveLike() ||
                    ValueTypes.IsRegistered(type))
                {
                    serializer = new XmlElementSerializer <T>(encryptAttribute, options);
                }
                else if (type.IsAssignableToNonGenericIDictionary() || type.IsAssignableToGenericIDictionary() || type.IsReadOnlyDictionary())
                {
                    serializer = DictionarySerializer.GetSerializer(type, encryptAttribute, options);
                }
                else if (type.IsAssignableToNonGenericIEnumerable() || type.IsAssignableToGenericIEnumerable())
                {
                    serializer = ListSerializer.GetSerializer(type, encryptAttribute, options, null);
                }
                else
                {
                    serializer = CustomSerializer.GetSerializer(type, encryptAttribute, options);
                }

                return serializer;
            }));
        }
Esempio n. 20
0
 public DynamicSerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
 {
     _encryptAttribute = encryptAttribute;
     _options          = options;
 }
        public SerializableProperty(PropertyInfo propertyInfo, IXmlSerializerOptions options)
        {
            _encryptAttribute =
                (EncryptAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(EncryptAttribute))
                ?? (EncryptAttribute)Attribute.GetCustomAttribute(propertyInfo.PropertyType, typeof(EncryptAttribute));
            _isListDecoratedWithXmlElement =
                typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType) &&
                !(propertyInfo.PropertyType == typeof(string)) &&
                Attribute.GetCustomAttributes(propertyInfo, typeof(XmlElementAttribute)).Any();

            _getValueFunc = DynamicMethodFactory.CreateFunc <object>(propertyInfo.GetGetMethod());

            if (!propertyInfo.DeclaringType.IsAnonymous() &&
                !(propertyInfo.IsReadOnlyProperty() && propertyInfo.PropertyType.IsGenericIEnumerable()))
            {
                if (propertyInfo.IsSerializableReadOnlyProperty())
                {
                    _setValueFunc = GetSerializableReadonlyPropertySetValueFunc(propertyInfo);
                }
                else
                {
                    if (IsListProperty(propertyInfo))
                    {
                        var setValue  = DynamicMethodFactory.CreateAction(propertyInfo.GetSetMethod());
                        var addValues = GetAddEnumerableValuesAction(propertyInfo.PropertyType);

                        var targetType = propertyInfo.PropertyType;

                        _setValueFunc = (destinationInstance, sourceCollection) =>
                        {
                            sourceCollection = sourceCollection.ConvertIfNecessary(targetType);

                            if (_getValueFunc(destinationInstance) == null)
                            {
                                setValue(destinationInstance, sourceCollection);
                            }
                            else
                            {
                                addValues(destinationInstance, sourceCollection);
                            }
                        };
                    }
                    else
                    {
                        var setMethod = propertyInfo.GetSetMethod();
                        if (setMethod != null)
                        {
                            _setValueFunc = DynamicMethodFactory.CreateAction(setMethod);
                        }
                        else
                        {
                            _setValueFunc = null;
                        }
                    }
                }
            }

            _shouldSerializeFunc  = GetShouldSerializeFunc(propertyInfo);
            _readsPastLastElement = () => false;
            _serializer           = new Lazy <IXmlSerializerInternal>(GetCreateSerializerFunc(propertyInfo, options));
        }
        public static IXmlSerializerInternal GetSerializer(Type type, EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            return _serializerCache.GetOrAdd(
                XmlSerializerFactory.Instance.CreateKey(type, encryptAttribute, options),
                _ =>
                {
                    Func<Type, IXmlSerializerInternal> createDictionarySerializer =
                        genericDictionaryInterface =>
                        {
                            var genericArguments = genericDictionaryInterface.GetGenericArguments();
                            var keyType = genericArguments[0];
                            var valueType = genericArguments[1];
                            return (IXmlSerializerInternal)Activator.CreateInstance(typeof(DictionarySerializer<,,>).MakeGenericType(type, keyType, valueType), encryptAttribute, options);
                        };

                    if (type.IsAssignableToGenericIDictionary())
                    {
                        return createDictionarySerializer(type.GetGenericIDictionaryType());
                    }

                    if (type.IsAssignableToNonGenericIDictionary())
                    {
                        return (IXmlSerializerInternal)Activator.CreateInstance(typeof(DictionarySerializer<>).MakeGenericType(type), encryptAttribute, options);
                    }

                    if (type.IsReadOnlyDictionary())
                    {
                        return createDictionarySerializer(type.GetIReadOnlyDictionaryInterface());
                    }

                    throw new InvalidOperationException(string.Format("Cannot create a DictionarySerializer of type '{0}'.", type.FullName));
                });
        }