Пример #1
1
 public ArrayAdapter(IValue array)
 {
     _array = array;
     _list = array.ActualType.CreateGenericListInstance().As<IList>();
     _listType = _list.GetType().ToCachedType();
     _listType.InvokeAction("AddRange", _list, array.Instance);
 }
Пример #2
0
 public static object CreateInstance(
     CachedType type,
     Func<CachedType, object[], object> factory = null, 
     params object[] dependencies)
 {
     if (type.IsSimpleType) throw new SimpleTypeInstantiationNotSupportedException(type);
     try
     {
         if (type.IsArray) return type.CreateArray();
         if (type.IsInterface)
         {
             if (type.IsGenericListInterface) return type.CreateGenericListInstance();
             if (type.IsListInterface) return new List<object>();
             if (type.IsGenericDictionaryInterface) return type.CreateGenericDictionaryInstance();
             if (type.IsDictionaryInterface) return new Dictionary<object, object>();
             if (type.IsGenericEnumerableInterface) return type.CreateGenericListInstance();
             if (type.IsEnumerableInterface) return new List<object>();
         }
         return (factory ?? DefaultFactory)(type, dependencies.Where(x => x != null).ToArray());
     }
     catch (Exception exception)
     {
         throw new ObjectCreationException(type, exception);
     }
 }
Пример #3
0
        // Serializable nodes

        public static ObjectNodeBase CreateSerializableRoot(object @object, CachedType type, Options options, string format)
        {
            var context = new Context(options, Mode.Serialize, format);
            return CreateSerializable(
                context.Options.TypeNameConventions.GetName(type, context, true), 
                ValueFactory.Create(@object, type, true, context.Options), null, context).As<ObjectNodeBase>();
        }
        /// <summary>
        /// Creates class inherited from type, with all virtual methods overriden.
        /// </summary>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        /// <remarks>Created types are cached so they are built only once.</remarks>
        public static Type Get(Type sourceType)
        {
            if (sourceType == null)
                throw new ArgumentNullException("sourceType");

            if (sourceType.IsSealed)
                throw new ArgumentException("Cannot create synchronized wrapper around sealed type (" + sourceType.Name + ").", "sourceType");

            if (sourceType.ContainsGenericParameters)
                throw new NotSupportedException("Type " + sourceType.Name + " contains generic parameters.");

            CachedType cachedType = null;

            // Look for type in cache
            lock (typeCache) {
                if (!typeCache.TryGetValue(sourceType, out cachedType)) {
                    cachedType = new CachedType();
                    typeCache.Add(sourceType, cachedType);
                }
            }

            Debug.Assert(cachedType != null);

            lock (cachedType.SyncRoot) {
                // If type wasn't created yet build it
                if (cachedType.Type == null) {
                    cachedType.Type = BuildType(sourceType);
                }

                return cachedType.Type;
            }
        }
Пример #5
0
 public TypeContext(CachedType type, Context context, bool isRoot = false)
 {
     Type = type;
     IsRoot = isRoot;
     Format = context.Format;
     Options = context.Options;
     Mode = context.Mode;
 }
Пример #6
0
 public ArrayItemContext(CachedType type, CachedMember member, Context context)
 {
     Type = type;
     Member = member;
     Format = context.Format;
     Options = context.Options;
     Mode = context.Mode;
 }
Пример #7
0
 private FileNode(NodeType nodeType, Type type, Encoding encoding, Options options)
 {
     _type = type.ToCachedType();
     if (nodeType != NodeType.Array || !_type.IsEnumerable)
         throw new BenderException("Only arrays can be serialized.");
     _encoding = encoding ?? DefaultEncoding;
     _options = options;
 }
Пример #8
0
 private TypeContext(CachedType type, TypeContext context)
 {
     Type = type;
     IsRoot = context.IsRoot;
     Format = context.Format;
     Options = context.Options;
     Mode = context.Mode;
 }
Пример #9
0
 public FileNode(NodeType nodeType, Type type, Options options)
 {
     _options = options;
     _type = type.ToCachedType();
     if (nodeType != NodeType.Array || !_type.IsEnumerable)
         throw new BenderException("Only arrays can be serialized.");
     _rows = new List<RowNode>();
 }
Пример #10
0
 public SimpleValue(
     object instance,
     CachedType specifiedType, 
     bool @readonly = false)
 {
     Instance = instance;
     SpecifiedType = specifiedType;
     IsReadonly = @readonly;
 }
Пример #11
0
 public static CachedType GetType(Type type)
 {
     if (!Cache.ContainsKey(type))
     {
         var cachedType = new CachedType(type);
         if (Cache.TryAdd(type, cachedType)) return cachedType;
     }
     return Cache[type];
 }
Пример #12
0
 public static ObjectNodeBase CreateDeserializableRoot(string name, CachedType type, string format, Options options)
 {
     var context = new Context(options, Mode.Deserialize, format);
     var @object = ValueFactory.Create(type);
     if (!context.Options.Deserialization.IgnoreRootName)
     {
         var expectedName = context.Options.TypeNameConventions.GetName(@object.SpecifiedType, context, true);
         if (!name.Equals(expectedName, options.Deserialization.NameComparison))
             throw new InvalidRootNameDeserializationException(type, format, name, expectedName);
     }
     return CreateDeserializable(name, @object, null, context);
 }
Пример #13
0
 public DictionaryNode(
     Context context, 
     string name, 
     IValue dictionary, 
     CachedMember member,
     INode parent)
     : base(name, dictionary, member, parent, context)
 {
     _dictionary = new Lazy<IDictionary>(() =>
         dictionary.Instance.MapOrDefault(GenericDictionaryAdapter.Create));
     if (SpecifiedType.IsGenericDictionary) _itemType = SpecifiedType.GenericDictionaryTypes.Value;
     _nodes = new Lazy<IEnumerable<INode>>(EnumerateNodes);
 }
Пример #14
0
            internal static void _Precache(Assembly asm)
            {
                _Preloaded.Add(asm.GetName().Name);
                _Preloaded.Add(asm.FullName);

                try {
                    _LoadAssembly(asm.FullName);
                } catch {
                    // no-op.
                }

                foreach (Type type in asm.GetTypes())
                {
                    // Non-public type instances can still be passed / returned.

                    /*
                     * if (!type.IsPublic)
                     *  continue;
                     */

                    _Preloaded.Add(type.FullName);

                    if (!AllNamespaces.TryGetValue(type.Namespace ?? "", out CachedNamespace cns))
                    {
                        string          ns      = type.Namespace;
                        CachedNamespace cnsPrev = Global;
                        for (int i = 0, iPrev = -1; i != -1; iPrev = i, cnsPrev = cns)
                        {
                            i = ns.IndexOf('.', iPrev + 1);
                            string part = i == -1 ? ns.Substring(iPrev + 1) : ns.Substring(iPrev + 1, i - iPrev - 1);

                            if (cnsPrev.NamespaceMap.TryGetValue(part, out cns))
                            {
                                continue;
                            }

                            cns = new CachedNamespace(cnsPrev, part);
                            cnsPrev.NamespaceMap[part]  = cns;
                            AllNamespaces[cns.FullName] = cns;
                        }
                    }

                    if (!AllTypes.TryGetValue(type.FullName, out CachedType ctype))
                    {
                        string part = type.Name;
                        ctype                    = new CachedType(cns, type);
                        cns.TypeMap[part]        = ctype;
                        AllTypes[ctype.FullName] = ctype;
                    }
                }
            }
Пример #15
0
 public EnumerableNode(
     Context context, 
     string name, 
     IValue enumerable, 
     CachedMember member,
     INode parent)
     : base(name, enumerable, member, parent, context)
 {
     _list = new Lazy<IList>(() => 
         enumerable.Instance.MapOrDefault(x => enumerable.ActualType.IsArray ? 
             ArrayAdapter.Create(enumerable) : GenericListAdapter.Create(x)));
     if (SpecifiedType.IsGenericEnumerable) _itemType = enumerable.SpecifiedType.GenericEnumerableType;
     _nodes = new Lazy<IEnumerable<INode>>(EnumerateNodes);
 }
Пример #16
0
            public TypeRecord(Context context, CachedType type) : this(context)
            {
                Type    = type;
                _typeId = type.TypeId;

                foreach (var prop in type.Properties)
                {
                    if (prop.Tag == -1)
                    {
                        continue;
                    }
                    Properties.Add(EncodePropertyTag(prop.DeclaringTypeId, prop.Tag), new PropertyRecord(context, this, prop));
                }
            }
Пример #17
0
 public static object CreateInstance(
     CachedType type,
     Func <CachedType, object[], object> factory = null,
     params object[] dependencies)
 {
     if (type.IsSimpleType)
     {
         throw new SimpleTypeInstantiationNotSupportedException(type);
     }
     try
     {
         if (type.IsArray)
         {
             return(type.CreateArray());
         }
         if (type.IsInterface)
         {
             if (type.IsGenericListInterface)
             {
                 return(type.CreateGenericListInstance());
             }
             if (type.IsListInterface)
             {
                 return(new List <object>());
             }
             if (type.IsGenericDictionaryInterface)
             {
                 return(type.CreateGenericDictionaryInstance());
             }
             if (type.IsDictionaryInterface)
             {
                 return(new Dictionary <object, object>());
             }
             if (type.IsGenericEnumerableInterface)
             {
                 return(type.CreateGenericListInstance());
             }
             if (type.IsEnumerableInterface)
             {
                 return(new List <object>());
             }
         }
         return((factory ?? DefaultFactory)(type, dependencies.Where(x => x != null).ToArray()));
     }
     catch (Exception exception)
     {
         throw new ObjectCreationException(type, exception);
     }
 }
Пример #18
0
        protected virtual void Pack(Stream stream, CachedType ct, object obj)
        {
            if (obj == null)
            {
                stream.WriteInt8(0);
                return;
            }

            if (!ct.IsValueType)
            {
                stream.WriteInt8(1);
            }

            ct.WriteFunc(this, ct.Type, stream, obj);
        }
Пример #19
0
        public static ObjectNodeBase CreateDeserializableRoot(string name, CachedType type, string format, Options options)
        {
            var context = new Context(options, Mode.Deserialize, format);
            var @object = ValueFactory.Create(type);

            if (!context.Options.Deserialization.IgnoreRootName)
            {
                var expectedName = context.Options.TypeNameConventions.GetName(@object.SpecifiedType, context, true);
                if (!name.Equals(expectedName, options.Deserialization.NameComparison))
                {
                    throw new InvalidRootNameDeserializationException(type, format, name, expectedName);
                }
            }
            return(CreateDeserializable(name, @object, null, context));
        }
Пример #20
0
                private void _Crawl()
                {
                    foreach (Type type in Type.GetNestedTypes())
                    {
                        if (!type.IsNestedPublic)
                        {
                            continue;
                        }

                        string     part  = type.Name;
                        CachedType ctype = new CachedType(this, type);
                        NestedTypeMap[part]      = ctype;
                        AllTypes[ctype.FullName] = ctype;
                    }
                }
Пример #21
0
        /// <summary>Generates XMLObject structure for an array with primitive types</summary>
        /// <param name="schema">The JSON Schema of the item.</param>
        /// <param name="type">The item type.</param>
        public static void GenerateXmlObjectForItemType(this JsonSchema schema, CachedType type)
        {
            // Is done all the time for XML to be able to get type name as the element name if not there was an attribute defined since earlier
            var     attributes       = type.TypeAttributes;
            dynamic xmlTypeAttribute = attributes.FirstAssignableToTypeNameOrDefault("System.Xml.Serialization.XmlTypeAttribute");

            var itemName = GetXmlItemName(type.OriginalType);

            if (xmlTypeAttribute != null)
            {
                itemName = xmlTypeAttribute.TypeName;
            }

            GenerateXmlObject(itemName, null, false, false, schema);
        }
Пример #22
0
        internal static CachedType CacheType(Type type, int?typeId = null)
        {
            CachedType cached;

            if (!TypeDictionary.TryGetValue(type.Name, out cached))
            {
                cached = new CachedType(type);
                if (typeId.HasValue)
                {
                    Types.Add(typeId.Value, cached);
                }
                TypeDictionary.Add(type.Name, cached);
            }
            return(cached);
        }
Пример #23
0
        public CachedFileStream(CachedType type, int minCacheLength, string path,
                                FileMode mode, FileAccess access, FileShare share)
            : base(path, mode, access, share, 8192,
                   mode == FileMode.Open && access == FileAccess.Read?FileOptions.None : FileOptions.WriteThrough)
        {
            _Type           = type;
            _MinCacheLength = minCacheLength;
            _FilePath       = path;
            _FileLength     = this.Length;
            _CurPosition    = 0;

            if (_MinCacheLength > CachedFileBufferManager.BufferUnitSize)
            {
                _MinCacheLength = CachedFileBufferManager.BufferUnitSize;
            }

            _ReadOnly = mode == FileMode.Open && access == FileAccess.Read;

            if (mode != FileMode.Open || share != FileShare.Read)
            {
                _Type = CachedType.NoCache;
            }

            if (_Type != CachedType.NoCache)
            {
                int indexLength = InitCacheBufferIndex();

                if (_Type == CachedType.Full ||
                    (_Type == CachedType.Small && indexLength <= 1))
                {
                    CacheAll();
                }
            }
            else
            {
                _CacheBufferIndex = null;
                _LastOLWithBuffer = null;

                if (_ReadOnly)
                {
                    //Read index
                    if (!_FileLastAccessManager.AccessRecently(_FilePath))
                    {
                        InitNoCachedRead();
                    }
                }
            }
        }
Пример #24
0
        public string[] LoadColumns(CachedType type, Options options, string baseName = "")
        {
            var members = type.Members.Where(x =>
                                             (x.Type.IsSimpleType || !x.Type.IsEnumerable) &&
                                             (options.MemberFilter == null || options.MemberFilter(x, options)))
                          .Select(x => new {
                Member = x,
                Name   = baseName + GetMemberName(x, options)
            }).ToList();
            var simpleTypes = members.Where(x => x.Member.Type.IsSimpleType)
                              .Select(x => x.Name).ToList();
            var complexTypes = members.Where(x => !x.Member.Type.IsSimpleType)
                               .SelectMany(x => LoadColumns(x.Member.Type, options, x.Name));

            return(simpleTypes.Concat(complexTypes).ToArray());
        }
Пример #25
0
 public EnumerableNode(
     Context context,
     string name,
     IValue enumerable,
     CachedMember member,
     INode parent,
     int?index = null)
     : base(name, enumerable, member, parent, context, index)
 {
     _list = new Lazy <IList>(() =>
                              enumerable.Instance.MapOrDefault(x => enumerable.ActualType.IsArray ?
                                                               ArrayAdapter.Create(enumerable) : GenericListAdapter.Create(x)));
     if (SpecifiedType.IsGenericEnumerable)
     {
         _itemType = enumerable.SpecifiedType.GenericEnumerableType;
     }
 }
Пример #26
0
        /// <summary>
        ///     Reads the configuration and populates the given instance (or newly created one) properties according to it.<br />
        ///     By default if the instance type has a property, it is considered as mandatory in configuration and value in
        ///     configuration
        ///     should be valid.<br />
        ///     Use <see cref="PropertyConfigurationAttribute" /> or <see cref="IgnoredPropertyAttribute" />
        ///     to changed that behavior.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        /// <exception cref="MissingMandatoryConfigurationException"></exception>
        public T Read <T>(T instance) where T : class
        {
            var type        = CachedType.Get(typeof(T));
            var sectionName = GetSectionName(type);
            var section     = _configuration.GetSection(sectionName);

            if (section == null)
            {
                throw new InvalidOperationException("IConfiguration should never return null section by contract.");
            }
            // If section doesn't exists should throw or at least warn ?
            foreach (var property in type.GetProperties())
            {
                SetPropertyValue(instance, property, section);
            }
            return(instance);
        }
Пример #27
0
 private static string GetMessage(string typeDescription, CachedType type, Mode mode, string expected)
 {
     string modeNoun;
     string modeVerb;
     switch (mode)
     {
         case Mode.Deserialize: 
             modeVerb = "deserialized";
             modeNoun = "deserialization";
             break;
         default:
             modeVerb = "serialized";
             modeNoun = "serialization";
             break;
     }
     return MessageTypeFormat.ToFormat(typeDescription.ToInitialCaps(), type.FriendlyFullName, modeNoun, expected, modeVerb);
 }
Пример #28
0
 public DictionaryNode(
     Context context,
     string name,
     IValue dictionary,
     CachedMember member,
     INode parent,
     int?index = null)
     : base(name, dictionary, member, parent, context, index)
 {
     _dictionary = new Lazy <IDictionary>(() =>
                                          dictionary.Instance.MapOrDefault(GenericDictionaryAdapter.Create));
     if (SpecifiedType.IsGenericDictionary)
     {
         _itemType = SpecifiedType.GenericDictionaryTypes.Value;
     }
     _nodes = new Lazy <IEnumerable <INode> >(EnumerateNodes);
 }
Пример #29
0
        public IPacket Deserialize(string packet)
        {
            PacketOutput output     = _packetReader.Read(packet);
            CachedType   cachedType = _reflectionCache.GetCachedType(output.Header);

            if (string.IsNullOrEmpty(output.Header))
            {
                throw new InvalidOperationException("Failed to deserialize packet");
            }

            char firstChar = output.Header[0];

            if (firstChar == '$' || firstChar == '%')
            {
                string   name = output.Header.Remove(0);
                string[] args = output.Content.Split(' ');

                _logger.Debug($"[DESERIALIZER] Deserialized Command packet [Header: {firstChar} / Name {name}]");
                return(new CommandPacket
                {
                    Header = $"{firstChar}",
                    Content = output.Content,
                    Name = name,
                    Arguments = args
                });
            }

            if (cachedType == null)
            {
                _logger.Debug($"[DESERIALIZER] No type found in cache for header {output.Header}");
                return(new UnknownPacket
                {
                    Header = output.Header,
                    Content = packet
                });
            }

            var deserialized = (IPacket)_conversionFactory.ToObject(output.Content, cachedType.PacketType);

            deserialized.Header  = output.Header;
            deserialized.Content = output.Content;

            _logger.Debug($"[DESERIALIZER] {output.Header} successfully deserialized to {deserialized.GetType()}");
            return(deserialized);
        }
Пример #30
0
        public StringEnumMap(int id, string stringRepresentation, List <string> otherPossibleRepresentation = null)
        {
            CachedType = GetType();
            _id        = id;
            if (_fromId.ContainsKey(_id))
            {
                throw new DuplicateNameException(
                          $"Cannot have two options with same id ({_id}). Used by: {_fromId[id]}. Tried to set to: {stringRepresentation}.");
            }

            _fromId[_id] = this;
            // Store string repr to dictionary for access later.
            _stringRepresentation = stringRepresentation;
            if (!string.IsNullOrEmpty(_stringRepresentation))
            {
                if (_fromString.ContainsKey(_stringRepresentation))
                {
                    throw new DuplicateNameException($"Key: {_stringRepresentation} is not unique. Also belongs to: {_fromString[(_stringRepresentation)]}.");
                }

                // Store the enum to string repr.
                _toString[this] = _stringRepresentation;
                _fromString[_stringRepresentation] = this;
            }
            else
            {
                throw new TypeInitializationException(CachedType.ToString(),
                                                      new Exception("A string representation is required for elements."));
            }

            if (otherPossibleRepresentation != null)
            {
                // Store other possible strings reprs
                _otherPossibleRepresentation = otherPossibleRepresentation;
                foreach (var str in _otherPossibleRepresentation)
                {
                    if (_fromString.ContainsKey(str))
                    {
                        throw new DuplicateNameException($"Key: {str} is not unique. Also belongs to: {_fromString[str]}.");
                    }

                    _fromString[str] = this;
                }
            }
        }
Пример #31
0
        public Encoder(Stream output, Encoding encoding, 
            Options options, string format, CachedType type)
        {
            if (type.IsGenericEnumerable && options.Serialization
                .SerializationType == SerializationType.SpecifiedType)
            {
                var header = new SimpleValue(type.GenericEnumerableType);
                var context = new Context(options, Mode.Deserialize, format);
                _columns = new ObjectNode(context, null, header, null, null)
                    .Select(x => x.Name).ToArray();
            }

            _header = options.CsvHeader;
            _qualifier = options.CsvQualifier;
            _delimiter = options.CsvDelimiter;
            _newLine = options.CsvNewLine;
            _writer = new Lazy<StreamWriter>(() => new StreamWriter(output, encoding));
        }
Пример #32
0
        public void GetCachedType_MatchesTestType()
        {
            CachedType cachedType = ReflectionCache.CurrentCache.GetCachedMetaData(TestReflectionCacheTypes.TestType);

            Assert.IsTrue(cachedType.Query(AttributeLocationQueries.GetAttributes).Length == 1);

            Assert.IsTrue(cachedType.Query(ClassQueries.GetPublicFields).Count() == 2);

            Assert.IsTrue(cachedType.Query(ClassQueries.GetPublicImplementedProperties).Count() == 2);

            Assert.IsTrue(cachedType.Query(ClassQueries.GetPublicImplementedMethods).Count() == 2);

            Assert.IsTrue(cachedType.Query(ClassQueries.GetPublicImplementedEvents).Count() == 2);

            Assert.IsTrue(cachedType.Query(ClassQueries.GetPublicImplementedMethods).Count() == 2);

            Assert.IsTrue(cachedType.Query(ClassQueries.GetGenericArguments).Length == 1);
        }
Пример #33
0
        /// <summary>
        /// Get cached type data.
        /// </summary>

        static public CachedType GetCache(this Type type)
        {
            if (mTypeDict == null)
            {
                CacheTypes();
            }
            CachedType ent = null;

            if (!mTypeDict.TryGetValue(type, out ent))
            {
                ent      = new CachedType();
                ent.type = type;
                ent.name = ent.ToString();
                mCachedTypes.Add(ent);
                mTypeDict[type] = ent;
            }
            return(ent);
        }
Пример #34
0
        /// <summary>Gets the description of the given member (based on the DescriptionAttribute, DisplayAttribute or XML Documentation).</summary>
        /// <param name="type">The member info</param>
        /// <param name="attributeType">The attribute type to check.</param>
        /// <returns>The description or null if no description is available.</returns>
        public static string GetDescription(this CachedType type, DescriptionAttributeType attributeType = DescriptionAttributeType.Context)
        {
            var attributes = type is ContextualType contextualType && attributeType == DescriptionAttributeType.Context ?
                             contextualType.ContextAttributes : type.TypeAttributes;

            dynamic descriptionAttribute = attributes.FirstAssignableToTypeNameOrDefault("System.ComponentModel.DescriptionAttribute");

            if (descriptionAttribute != null && !string.IsNullOrEmpty(descriptionAttribute.Description))
            {
                return(descriptionAttribute.Description);
            }
            else
            {
                dynamic displayAttribute = attributes.FirstAssignableToTypeNameOrDefault("System.ComponentModel.DataAnnotations.DisplayAttribute");
                if (displayAttribute != null)
                {
                    // GetDescription returns null if the Description property on the attribute is not specified.
                    var description = displayAttribute.GetDescription();
                    if (description != null)
                    {
                        return(description);
                    }
                }

                if (type is ContextualMemberInfo contextualMember)
                {
                    var summary = contextualMember.GetXmlDocsSummary();
                    if (summary != string.Empty)
                    {
                        return(summary);
                    }
                }
                else if (type != null)
                {
                    var summary = type.GetXmlDocsSummary();
                    if (summary != string.Empty)
                    {
                        return(summary);
                    }
                }
            }

            return(null);
        }
        public Func <Container, object> CreateInstanceFactory(CachedType type, InjectionOptions containerInjectionOptions, InjectionOptions injectionOptions)
        {
            CachedConstructorInfo constructor =
                (injectionOptions.ChooseInjectionConstructor ?? containerInjectionOptions.ChooseInjectionConstructor)(
                    type.Query(ClassQueries.GetPublicConstructors)
                    .Select(c => (CachedConstructorInfo)c));

            var constructLamda = constructor.Query(info => lambdaGenerator.CreateConstructorInjectionLambda(info));

            List <Action <Container, object> > injectionLambdas = new List <Action <Container, object> >();

            var chooseInjectionMethods = injectionOptions.ChooseInjectionMethods ??
                                         containerInjectionOptions.ChooseInjectionMethods;

            if (chooseInjectionMethods != null)
            {
                var injectionMethods = chooseInjectionMethods(type
                                                              .Query(ClassQueries.GetPublicImplementedMethods).Select(m => (CachedMethodInfo)m));

                foreach (var cachedMethodInfo in injectionMethods)
                {
                    var methodInjectionLambda = cachedMethodInfo.Query(m =>
                                                                       lambdaGenerator.CreateMethodInjectionLambda(type, cachedMethodInfo));

                    injectionLambdas.Add(methodInjectionLambda);
                }
            }

            var chooseInjectionProperties = injectionOptions.ChooseInjectionProperties ??
                                            containerInjectionOptions.ChooseInjectionProperties;

            if (chooseInjectionProperties != null)
            {
                var injectionProperties = chooseInjectionProperties(type.Query(ClassQueries.GetPublicImplementedProperties).Select(p => (CachedPropertyInfo)p)).ToArray();

                if (injectionProperties.Length > 0)
                {
                    injectionLambdas.Add(lambdaGenerator.CreatePropertyInjectionLambda(type, injectionProperties));
                }
            }

            return(CombineConstructorInjectionAndMemberInjectionLambdas(constructLamda, injectionLambdas.ToArray()));
        }
        public static object Activate(Type t)
        {
            if (t.IsValueType)
            {
                return(System.Activator.CreateInstance(t));
            }
            else if (t.IsInterface)
            {
                return(DispatchProxy.DispatchProxy.Create(t, typeof(InterfaceProxy)));
            }
            else if (t.IsClass)
            {
                CachedType type = t;

                return(type.Query(ClassQueries.GetDefaultConstructor).Invoke(null));
            }

            return(null);
        }
Пример #37
0
        /// <summary>Gets the description of the given member (based on the DescriptionAttribute, DisplayAttribute or XML Documentation).</summary>
        /// <param name="type">The member info</param>
        /// <returns>The description or null if no description is available.</returns>
        public static string GetDescription(this CachedType type)
        {
            var attributes = type is ContextualType contextualType ? contextualType.ContextAttributes : type.InheritedAttributes;

            var description = GetDescription(attributes);

            if (description != null)
            {
                return(description);
            }

            var summary = type.GetXmlDocsSummary();

            if (summary != string.Empty)
            {
                return(summary);
            }

            return(null);
        }
Пример #38
0
        private static string GetMessage(string typeDescription,
                                         CachedType type, Mode mode, string expected)
        {
            string modeNoun;
            string modeVerb;

            switch (mode)
            {
            case Mode.Deserialize:
                modeVerb = "deserialized";
                modeNoun = "deserialization";
                break;

            default:
                modeVerb = "serialized";
                modeNoun = "serialization";
                break;
            }
            return(MessageTypeFormat.ToFormat(typeDescription.ToInitialCap(),
                                              type.FriendlyFullName, modeNoun, expected, modeVerb));
        }
Пример #39
0
        /// <summary>
        /// Creates class inherited from type, with all virtual methods overriden.
        /// </summary>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        /// <remarks>Created types are cached so they are built only once.</remarks>
        public static Type Get(Type sourceType)
        {
            if (sourceType == null)
            {
                throw new ArgumentNullException("sourceType");
            }

            if (sourceType.IsSealed)
            {
                throw new ArgumentException("Cannot create synchronized wrapper around sealed type (" + sourceType.Name + ").", "sourceType");
            }

            if (sourceType.ContainsGenericParameters)
            {
                throw new NotSupportedException("Type " + sourceType.Name + " contains generic parameters.");
            }

            CachedType cachedType = null;

            // Look for type in cache
            lock (typeCache) {
                if (!typeCache.TryGetValue(sourceType, out cachedType))
                {
                    cachedType = new CachedType();
                    typeCache.Add(sourceType, cachedType);
                }
            }

            Debug.Assert(cachedType != null);

            lock (cachedType.SyncRoot) {
                // If type wasn't created yet build it
                if (cachedType.Type == null)
                {
                    cachedType.Type = BuildType(sourceType);
                }

                return(cachedType.Type);
            }
        }
Пример #40
0
        /// <summary>Gets the description of the given member (based on the DescriptionAttribute, DisplayAttribute or XML Documentation).</summary>
        /// <param name="type">The member info</param>
        /// <param name="xmlDocsSettings">The XML Docs settings.</param>
        /// <returns>The description or null if no description is available.</returns>
        public static string GetDescription(this CachedType type, IXmlDocsSettings xmlDocsSettings)
        {
            var attributes = type is ContextualType contextualType ? contextualType.ContextAttributes : type.InheritedAttributes;

            var description = GetDescription(attributes);

            if (description != null)
            {
                return(description);
            }

            if (xmlDocsSettings.UseXmlDocumentation)
            {
                var summary = type.GetXmlDocsSummary(xmlDocsSettings.ResolveExternalXmlDocumentation);
                if (summary != string.Empty)
                {
                    return(summary);
                }
            }

            return(null);
        }
Пример #41
0
 public void should_create_generic_dictionary_instance()
 {
     var instance = new CachedType(typeof(IDictionary<string, int>)).CreateGenericDictionaryInstance();
     instance.ShouldNotBeNull();
     instance.ShouldBeType<Dictionary<string, int>>();
 }
Пример #42
0
 public void should_create_generic_list_intstance()
 {
     var instance = new CachedType(typeof(IList<string>)).CreateGenericListInstance();
     instance.ShouldNotBeNull();
     instance.ShouldBeType<List<string>>();
 }
Пример #43
0
 public SimpleValue(CachedType specifiedType)
 {
     SpecifiedType = specifiedType;
 }
Пример #44
0
        static Type GenerateSerializer(Type objType)
        {
            Type returnType;

            if (CachedType.TryGetValue(objType, out returnType))
            {
                return(returnType);
            }
            var genericType = SerializerType.MakeGenericType(objType);
            var newTypeName = objType.Name + "Serializer";
            var assembly    = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName(newTypeName + "Class")
            {
                Version = new Version(1, 0, 0, 0)
            }, AssemblyBuilderAccess.RunAndSave);
            var module = assembly.DefineDynamicModule(newTypeName + ".dll");

            var type = module.DefineType(newTypeName,
                                         TypeAttributes.Public | TypeAttributes.Serializable | TypeAttributes.Sealed,
                                         typeof(Object), new[] { genericType });



            var methodSerialize = type.DefineMethod("ISerializer.Serialize", MethodAttribute,
                                                    ByteArrayType, new[] { objType });

            var methodDeserialize = type.DefineMethod("ISerializer.Deserialize", MethodAttribute,
                                                      objType, new[] { ByteArrayType });

            var methodDeserializeStream = type.DefineMethod("ISerializer.Deserialize", MethodAttribute,
                                                            objType, new[] { StreamType });

            var methodSerializeStream = type.DefineMethod("ISerializer.Serialize", MethodAttribute,
                                                          VoidType, new[] { objType, StreamType });

            var methodSerializeIL         = methodSerialize.GetILGenerator();
            var methodDeserializeIL       = methodDeserialize.GetILGenerator();
            var methodDeserializeStreamIL = methodDeserializeStream.GetILGenerator();
            var methodSerializeStreamIL   = methodSerializeStream.GetILGenerator();

            var bufferLocal       = methodSerializeIL.DeclareLocal(BufferStreamType);
            var bufferStreamLocal = methodSerializeStreamIL.DeclareLocal(BufferStreamType);

            var returnLocal     = methodDeserializeIL.DeclareLocal(objType);
            var startIndexLocal = methodDeserializeIL.DeclareLocal(typeof(int));

            methodDeserializeIL.Emit(OpCodes.Ldc_I4_0);
            methodDeserializeIL.Emit(OpCodes.Stloc, startIndexLocal.LocalIndex);


            var returnLocalStream     = methodDeserializeStreamIL.DeclareLocal(objType);
            var startIndexLocalStream = methodDeserializeStreamIL.DeclareLocal(typeof(int));

            methodDeserializeStreamIL.Emit(OpCodes.Ldc_I4_0);
            methodDeserializeStreamIL.Emit(OpCodes.Stloc, startIndexLocalStream.LocalIndex);

            //Serialize
            methodSerializeIL.Emit(OpCodes.Newobj, BufferStreamCtor);
            methodSerializeIL.Emit(OpCodes.Stloc, bufferLocal.LocalIndex);

            GenerateSerializerCallClassMethod(type, methodSerializeIL, objType, bufferLocal.LocalIndex);

            methodSerializeIL.Emit(OpCodes.Ldloc, bufferLocal.LocalIndex);
            methodSerializeIL.Emit(OpCodes.Callvirt, BufferStreamToArrayMethod);
            methodSerializeIL.Emit(OpCodes.Ret);


            //SerializeStream
            methodSerializeStreamIL.Emit(OpCodes.Ldarg_2);
            methodSerializeStreamIL.Emit(OpCodes.Newobj, BufferStreamStreamCtor);
            methodSerializeStreamIL.Emit(OpCodes.Stloc, bufferStreamLocal.LocalIndex);

            GenerateSerializerCallClassMethod(type, methodSerializeStreamIL, objType, bufferStreamLocal.LocalIndex);


            methodSerializeStreamIL.Emit(OpCodes.Ret);

            //Deserialize
            GenerateDeserializerCallClassMethod(type, methodDeserializeIL, objType, returnLocal.LocalIndex,
                                                startIndexLocal.LocalIndex);

            methodDeserializeIL.Emit(OpCodes.Ldloc_S, returnLocal.LocalIndex);
            methodDeserializeIL.Emit(OpCodes.Ret);


            //DeserializeStream
            GenerateDeserializerCallClassMethod(type, methodDeserializeStreamIL, objType, returnLocalStream.LocalIndex,
                                                startIndexLocalStream.LocalIndex, useStream: true);

            methodDeserializeStreamIL.Emit(OpCodes.Ldloc, returnLocalStream.LocalIndex);
            methodDeserializeStreamIL.Emit(OpCodes.Ret);

            //Override interface implementation
            type.DefineMethodOverride(methodSerialize,
                                      genericType.GetMethod("Serialize", new[] { objType }));
            type.DefineMethodOverride(methodDeserialize,
                                      genericType.GetMethod("Deserialize", new[] { ByteArrayType }));
            type.DefineMethodOverride(methodDeserializeStream,
                                      genericType.GetMethod("Deserialize", new[] { StreamType }));
            type.DefineMethodOverride(methodSerializeStream,
                                      genericType.GetMethod("Serialize", new[] { objType, StreamType }));

            returnType          = type.CreateType();
            CachedType[objType] = returnType;

            if (BinarySerializer.GenerateAssembly)
            {
                assembly.Save(newTypeName + ".dll");
            }
            return(returnType);
        }
Пример #45
0
 private static string GetNullableDisplayName(CachedType type, string actual)
 {
     return((type.IsNullableType ? "Nullable" : "") + actual);
 }
Пример #46
0
 public void should_return_members(Type type)
 {
     var members = new CachedType(type).Members;
     members.ShouldTotal(2);
     members.ShouldContain(x => x.Name == "Field");
     members.ShouldContain(x => x.Name == "Property");
 }
Пример #47
0
 public InvalidRootNameDeserializationException(CachedType type, string format, string actual, string expected)
     : base(MessageFormat, FriendlyMessageFormat, format.ToInitialCaps(), actual, expected, type.FriendlyFullName)
 {
 }
Пример #48
0
 public void should_get_generic_dictionary_types()
 {
     var types = new CachedType(typeof(IDictionary<string, int>)).GenericDictionaryTypes;
     types.Key.Type.ShouldBe<string>();
     types.Value.Type.ShouldBe<int>();
 }
Пример #49
0
 private GenericDictionaryAdapter(object dictionary, CachedType type)
 {
     _dictionary = dictionary;
     _type = type;
 }
Пример #50
0
 private static TypeKind GetTypeKind(CachedType type, Options options)
 {
     return type.GetKind(
         options.TreatEnumerableImplsAsObjects,
         options.TreatDictionaryImplsAsObjects);
 }
Пример #51
0
 public SimpleTypeInstantiationNotSupportedException(CachedType type) :
     base(MessageFormat, type.FriendlyFullName)
 {
 }
Пример #52
0
 public ValueConversionException(Exception exception, object value, 
         CachedType source, CachedType target) : 
     base(exception, "Value '{0}' of type '{1}' cannot be converted to type '{2}': {3}",
         value.Truncate(50), source.FriendlyFullName, target.FriendlyFullName, exception.Message) { }
Пример #53
0
 public void should_get_generic_type_arguments()
 {
     var types = new CachedType(typeof(IDictionary<string, int>)).GenericArguments.ToList();
     types[0].Type.ShouldBe<string>();
     types[1].Type.ShouldBe<int>();
 }
Пример #54
0
 public static string GetName(this NamingConventions<TypeContext> conventions,
     CachedType type, Context context, bool isRoot = false)
 {
     return conventions.GetName(new TypeContext(type, context, isRoot));
 }
Пример #55
0
        protected Saveable(string saveKey)
        {
            if (saveKey.Length > KeyAttribute.MaxKeyLength)
            {
                throw new Exception($"Saveable key max length={KeyAttribute.MaxKeyLength} ({saveKey})");
            }

            IsModified         = false;
            SaveableProperties = new Dictionary <string, CachedProperty>();
            SaveKey            = saveKey;
            var cachedType = CachedType.Get(GetType());

            foreach (var cachedProperty in cachedType.CachedProperties)
            {
                if (cachedProperty.PropertyInfo.PropertyType.BaseType == null ||
                    cachedProperty.PropertyInfo.PropertyType.IsPrimitive ||
                    cachedProperty.PropertyInfo.PropertyType.IsClass == false ||
                    cachedProperty.PropertyInfo.PropertyType.IsValueType)
                {
                    continue;
                }

                if (cachedProperty.PropertyInfo.PropertyType.IsArray)
                {
                    Debug.LogWarning($"[mSaves] Property '{cachedProperty.PropertyInfo.Name}' in '{cachedType.Type.Name}' is array, skipped");
                    continue;
                }

                if (!cachedProperty.PropertyInfo.PropertyType.BaseType.IsGenericType)
                {
                    continue;
                }

                var enumerable = cachedProperty.PropertyInfo.GetCustomAttributes();
                var attributes = enumerable as Attribute[] ?? enumerable.ToArray();

                if (!IsSaveableValue(cachedProperty.PropertyInfo))
                {
                    // ReSharper disable once PossibleNullReferenceException
                    var genericDefenition = cachedProperty.PropertyInfo.PropertyType.BaseType
                                            .GetGenericTypeDefinition();

                    if (genericDefenition == typeof(SaveableValue <>))
                    {
                        var constructor = cachedProperty.PropertyInfo.PropertyType.GetConstructor(
                            BindingFlags.Instance |
                            BindingFlags.Public, null, Type.EmptyTypes, null);

                        if (constructor != null)
                        {
                            var expression = Expression.New(constructor);
                            var func       = (Func <SaveableValue>)Expression
                                             .Lambda(expression)
                                             .Compile();
                            _saveableValueTypes.Add(cachedProperty.PropertyInfo.PropertyType, func);
                        }
                        else
                        {
                            throw new Exception("SaveableValue must have public constructor without parameters");
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                if (attributes.OfType <IgnoreAttribute>().Any())
                {
                    Debug.Log($"[mSaves] Property '{cachedProperty.PropertyInfo.Name}' in '{cachedType.Type.Name}' marked as Ignore attribute");
                    continue;
                }

                var keyAttribute = attributes.OfType <KeyAttribute>().FirstOrDefault();
                if (keyAttribute == null)
                {
                    throw new Exception($"[mSaves] Property '{cachedProperty.PropertyInfo.Name}' in '{cachedType.Type.Name}' not have a Key attribute");
                }

                if (SaveableProperties.ContainsKey(keyAttribute.Key))
                {
                    throw new Exception($"[mSaves] Key {keyAttribute.Key} already exist");
                }

                if (cachedProperty.PropertyInfo.CanWrite)
                {
                    cachedProperty.SetValue(this,
                                            cachedProperty.GetValue(this) as SaveableValue ??
                                            _saveableValueTypes[cachedProperty.PropertyInfo.PropertyType]()
                                            );
                }

                SaveableProperties.Add(keyAttribute.Key, cachedProperty);

                //Debug.Log(string.Join("\n", new[]
                //{
                //    $"cachedProperty Name={cachedProperty.PropertyInfo.Name}",
                //    $"Value={cachedProperty.GetValue(this)} ({cachedProperty.GetValue(this)?.GetType().Name ?? "null"})",
                //    $"Type={cachedProperty.PropertyInfo.PropertyType.Name}",
                //    $"BaseType ={cachedProperty.PropertyInfo.PropertyType.BaseType}",
                //    $"HasElementType ={cachedProperty.PropertyInfo.PropertyType.HasElementType}",
                //    $"attributes = {attributes.Select(a => a.GetType().Name).Aggregate((a, b) => a + "," + b)}",
                //}));
            }
        }
Пример #56
0
 // Deserializable nodes
 public static ObjectNodeBase CreateDeserializableRoot(CachedType type, string format, Options options)
 {
     return CreateDeserializable(null, ValueFactory.Create(type), null, new Context(options, Mode.Deserialize, format));
 }
Пример #57
0
 public ObjectCreationException(CachedType type, Exception exception) :
     base(exception, MessageFormat, type.FriendlyFullName, exception.Message)
 {
 }
Пример #58
0
 public static string GetName(this NamingConventions<ArrayItemContext> conventions,
     CachedType type, CachedMember member, Context context)
 {
     return conventions.GetName(new ArrayItemContext(type, member, context));
 }
Пример #59
0
 private GenericListAdapter(object list, CachedType type)
 {
     _list = list;
     _type = type;
 }
Пример #60
0
 public static string GetName(this NamingConventions <ArrayItemContext> conventions,
                              CachedType type, CachedMember member, Context context)
 {
     return(conventions.GetName(new ArrayItemContext(type, member, context)));
 }