public void Configure()
        {
            TypeConfig.CreateAll(config);

            services.AddMvc();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(SwaggerConfig.Current.Version,
                             new Info
                {
                    Title   = SwaggerConfig.Current.Title,
                    Version = SwaggerConfig.Current.Version
                }
                             );
            });
            services.AddDbContext <CodeCamperDataContext>(c =>
            {
                try
                {
                    // Requires LocalDB which can be installed with SQL Server Express 2016
                    // https://www.microsoft.com/en-us/download/details.aspx?id=54284
                    //c.UseSqlServer(Configuration.GetConnectionString("CatalogConnection"));
                    c.UseLoggerFactory(loggerFactory);
                    c.UseSqlServer(@"Data Source=VEDRAN-PC\SQLEXPRESS2017;Initial Catalog=CoreCodeCamper;Integrated Security=True;");
                }
                catch (System.Exception ex)
                {
                    var message = ex.Message;
                }
            });
        }
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="type">原类型</param>
        /// <returns></returns>
        public static TypeConfig GetConfig(Type type)
        {
            TypeConfig typeConfig = new TypeConfig
            {
                FullName     = type.FullName,
                AssemblyName = type.Assembly.FullName,
                Attributes   = GetAttributeConfigs(type),
                Properties   = type.GetProperties().Select(x => new PropertyConfig
                {
                    PropertyName = x.Name,
                    Attributes   = GetAttributeConfigs(x),
                    PropertyType = x.PropertyType
                }).ToList()
            };

            return(typeConfig);

            List <AttributeConfig> GetAttributeConfigs(MemberInfo theType)
            {
                return(theType.GetCustomAttributesData().Select(y => new AttributeConfig
                {
                    Attribute = y.AttributeType,
                    ConstructorArgs = y.ConstructorArguments.Select(x => x.Value).ToList(),
                    Properties = y.NamedArguments.Select(x => (x.MemberName, x.TypedValue.Value)).ToList()
                }).ToList());
            }
Example #3
0
 public Schema(bool isPrimary, Type type, TypeConfig typeConfig, bool isStatic)
 {
     IsPrimary  = isPrimary;
     Type       = type;
     TypeConfig = typeConfig;
     IsStatic   = isStatic;
 }
        internal static Dictionary<string, TypeAccessor> GetTypeAccessorMap(TypeConfig typeConfig, ITypeSerializer serializer)
        {
            var type = typeConfig.Type;

            var propertyInfos = type.GetSerializableProperties();
            if (propertyInfos.Length == 0) return null;

            var map = new Dictionary<string, TypeAccessor>(StringComparer.OrdinalIgnoreCase);

            var isDataContract = type.IsDto();
            foreach (var propertyInfo in propertyInfos)
            {
                var propertyName = propertyInfo.Name;
                if (isDataContract)
                {
                    var dcsDataMember = propertyInfo.GetDataMember();
                    if (dcsDataMember != null && dcsDataMember.Name != null)
                    {
                        propertyName = dcsDataMember.Name;
                    }
                }
                map[propertyName] = TypeAccessor.Create(serializer, typeConfig, propertyInfo);
            }
            return map;
        }
Example #5
0
        internal static KeyValuePair <string, TypeAccessor>[] GetCachedTypeAccessors(Type type, ITypeSerializer serializer)
        {
            if (TypeAccessorsCache.TryGetValue(type, out var typeAccessors))
            {
                return(typeAccessors);
            }

            var typeConfig = new TypeConfig(type);

            typeAccessors = GetTypeAccessors(typeConfig, serializer);

            Dictionary <Type, KeyValuePair <string, TypeAccessor>[]> snapshot, newCache;

            do
            {
                snapshot = TypeAccessorsCache;
                newCache = new Dictionary <Type, KeyValuePair <string, TypeAccessor>[]>(TypeAccessorsCache)
                {
                    [type] = typeAccessors
                };
            } while (!ReferenceEquals(
                         Interlocked.CompareExchange(ref TypeAccessorsCache, newCache, snapshot), snapshot));

            return(typeAccessors);
        }
Example #6
0
        internal static Dictionary <string, TypeAccessor> GetTypeAccessorMap(TypeConfig typeConfig, ITypeSerializer serializer)
        {
            var type = typeConfig.Type;

            var propertyInfos = type.GetSerializableProperties();

            if (propertyInfos.Length == 0)
            {
                return(null);
            }

            var map = new Dictionary <string, TypeAccessor>(StringComparer.OrdinalIgnoreCase);

            var isDataContract = type.IsDto();

            foreach (var propertyInfo in propertyInfos)
            {
                var propertyName = propertyInfo.Name;
                if (isDataContract)
                {
                    var dcsDataMember = propertyInfo.GetDataMember();
                    if (dcsDataMember != null && dcsDataMember.Name != null)
                    {
                        propertyName = dcsDataMember.Name;
                    }
                }
                map[propertyName] = TypeAccessor.Create(serializer, typeConfig, propertyInfo);
            }
            return(map);
        }
Example #7
0
        protected void Application_Start(object sender, EventArgs e)
        {
            IContainer container = TypeConfig.RegisterTypes();

            DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));

            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
Example #8
0
        public void SqlTable_WithMultipleUniqueKey_SetsUniqueKey()
        {
            var typeConfig = new TypeConfig("Product");

            var builder = typeConfig.SqlTable("product", new [] { "id", "key" });

            builder.SqlTableConfig.UniqueKey.Should().Contain(new[] { "id", "key" });
        }
Example #9
0
        public void SqlTable_WithTableName_SetsTable()
        {
            var typeConfig = new TypeConfig("Product");

            var builder = typeConfig.SqlTable("product", "id");

            builder.SqlTableConfig.Table(null, null).Should().Be("product");
        }
Example #10
0
 public static TypeConfig AddValidator <T>(this TypeConfig config, Action <T> validator)
 {
     if (validator == null)
     {
         return(config);
     }
     return(config.AddValidator((t, o) => validator(o.AssertCast <T>())));
 }
Example #11
0
 public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, PropertyInfo propertyInfo)
 {
     return(new TypeAccessor
     {
         GetProperty = serializer.GetParseFn(propertyInfo.PropertyType),
         SetProperty = GetSetPropertyMethod(typeConfig, propertyInfo),
     });
 }
 public static TypeConfig AfterDeserialize <T>(this TypeConfig config, Func <T, Object> afterDeserialize, double weight = 1.0)
 {
     if (afterDeserialize == null)
     {
         return(config);
     }
     return(config.AfterDeserialize((t, o) => afterDeserialize(o.AssertCast <T>()), weight));
 }
 public static TypeConfig BeforeSerialize <T>(this TypeConfig config, Func <T, Object> beforeSerialize, double weight = 1.0)
 {
     if (beforeSerialize == null)
     {
         return(config);
     }
     return(config.BeforeSerialize((t, o) => beforeSerialize(o.AssertCast <T>()), weight));
 }
Example #14
0
        public void SqlTable_WithSingleUniqueKey_SetsUniqueKey()
        {
            var typeConfig = new TypeConfig("Product");

            var builder = typeConfig.SqlTable("product", "id");

            builder.SqlTableConfig.UniqueKey.Should().Contain("id");
        }
Example #15
0
 public static TypeConfig Engine(this TypeConfig config, Func <Json, Object> deserialize, Func <Object, Json> serialize)
 {
     if (deserialize == null || serialize == null)
     {
         return(config);
     }
     config.Hash[typeof(LambdaTypeEngine)] = new LambdaTypeEngine(deserialize, serialize);
     return(config);
 }
Example #16
0
 public static TypeConfig Engine <T>(this TypeConfig config, Func <Json, T> deserialize, Func <T, Json> serialize)
 {
     if (deserialize == null || serialize == null)
     {
         return(config);
     }
     return(config.Engine((t, j) => deserialize(j).AssertCast <T>(),
                          (t, o) => serialize(o.AssertCast <T>())));
 }
Example #17
0
        private static SetMemberDelegate GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo)
        {
            if (typeConfig.Type != fieldInfo.DeclaringType)
            {
                fieldInfo = fieldInfo.DeclaringType.GetFieldInfo(fieldInfo.Name);
            }

            return(PclExport.Instance.CreateSetter(fieldInfo));
        }
Example #18
0
 public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, FieldInfo fieldInfo)
 {
     return(new TypeAccessor
     {
         PropertyType = fieldInfo.FieldType,
         GetProperty = serializer.GetParseStringSegmentFn(fieldInfo.FieldType),
         SetProperty = GetSetFieldMethod(typeConfig, fieldInfo),
     });
 }
        private static MemberSetter GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo)
        {
            if (typeConfig.Type != fieldInfo.DeclaringType)
            {
                fieldInfo = fieldInfo.DeclaringType.GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            }

            return(ReflectionOptimizer.Instance.CreateSetter(fieldInfo));
        }
Example #20
0
        private static SetPropertyDelegate GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo)
        {
            if (fieldInfo.ReflectedType() != fieldInfo.DeclaringType)
            {
                fieldInfo = fieldInfo.DeclaringType.GetFieldInfo(fieldInfo.Name);
            }

            return(PclExport.Instance.GetSetFieldMethod(fieldInfo));
        }
Example #21
0
        private static SetMemberDelegate GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo)
        {
            if (typeConfig.Type != fieldInfo.DeclaringType)
            {
                fieldInfo = fieldInfo.DeclaringType.GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            }

            return(PclExport.Instance.CreateSetter(fieldInfo));
        }
        public override void Modify(TypeConfig type)
        {
            type.Description       = Description;
            type.DeprecationReason = DeprecationReason;

            if (IsTypeOf != null)
            {
                type.IsTypeOfFunc = t => IsTypeOf.IsAssignableFrom(t.GetType());
            }
        }
Example #23
0
        protected void Application_Start()
        {
            IContainer container = TypeConfig.RegisterTypes();

            DependencyResolver.SetResolver(new StructureMapResolver(container));

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Example #24
0
        internal static KeyValuePair <string, TypeAccessor>[] GetTypeAccessors(TypeConfig typeConfig, ITypeSerializer serializer)
        {
            var type = typeConfig.Type;

            var propertyInfos = type.GetSerializableProperties();
            var fieldInfos    = type.GetSerializableFields();

            if (propertyInfos.Length == 0 && fieldInfos.Length == 0)
            {
                return(default);
Example #25
0
        public static TypeConfig AddValidator(this TypeConfig config, Action <Type, Object> validator)
        {
            if (validator == null)
            {
                return(config);
            }
            var validators = config.Hash.GetOrCreate(typeof(LambdaTypeValidator), () => new List <LambdaTypeValidator>()).AssertCast <List <LambdaTypeValidator> >();

            validators.Add(new LambdaTypeValidator(validator));
            return(config);
        }
        private object GetInstanceByConstructorType(TypeConfig config, Func<TypeConfig, ConstructorInfo> constructorSelector)
        {
            ConstructorInfo constructorInfo = constructorSelector.Invoke(config);

            if (constructorInfo == null)
            {
                throw new MissingAppropriateConstructor();
            }

            return GetInstanceByConstructor(constructorInfo, config);
        }
        private static void ParseTypeConfig(TypeConfig cfg)
        {
            if (cfg.Methods != null)
            {
                var list = new List <WhitelistMethodDefine>();
                foreach (var m in cfg.Methods)
                {
                    try
                    {
                        list.Add(MethodParser.ParseOrThrow(m));
                    }
                    catch (ParseException e)
                    {
                        Logger.ErrorS("res.typecheck", $"Parse exception for '{m}': {e}");
                    }
                }

                cfg.MethodsParsed = list.ToArray();
            }
            else
            {
                cfg.MethodsParsed = Array.Empty <WhitelistMethodDefine>();
            }

            if (cfg.Fields != null)
            {
                var list = new List <WhitelistFieldDefine>();
                foreach (var f in cfg.Fields)
                {
                    try
                    {
                        list.Add(FieldParser.ParseOrThrow(f));
                    }
                    catch (ParseException e)
                    {
                        Logger.ErrorS("res.typecheck", $"Parse exception for '{f}': {e}");
                    }
                }

                cfg.FieldsParsed = list.ToArray();
            }
            else
            {
                cfg.FieldsParsed = Array.Empty <WhitelistFieldDefine>();
            }

            if (cfg.NestedTypes != null)
            {
                foreach (var nested in cfg.NestedTypes.Values)
                {
                    ParseTypeConfig(nested);
                }
            }
        }
Example #28
0
        CreateTypeConf <TImplementedInterface, TSuperClass, TWrappedInterface>(string className = null)
        {
            ITypeConfig <TImplementedInterface, TSuperClass, TWrappedInterface> result =
                new TypeConfig <TImplementedInterface, TSuperClass, TWrappedInterface>(this, className);

            CheckAlreadyHasType(result.ClassName);

            this.AllCreatedTypes.Add(result);

            return(result);
        }
        private object GetInstanceByConstructor(ConstructorInfo constructorInfo, TypeConfig config)
        {
            ParameterInfo[] constructorParametersInfo = constructorInfo.GetParameters();
            object[] constructorParameters = new object[constructorParametersInfo.Length];
            object instance = null;
            var tuple = new Tuple<Type, Type>(config.TargetType, config.AttributeSelector);

            this.resolvingObjectsRepository.Add(tuple);

            for (int i = 0; i < constructorParameters.Length; i++)
            {
                object parameterValue = this.GetParameterValueFromPropertyInfo(constructorParametersInfo[i], config);

                if (parameterValue != null)
                {
                    constructorParameters[i] = parameterValue;
                }
                else
                {
                    Type parameterType = constructorParametersInfo[i].ParameterType;
                    Type colorAttributeType = this.GetColorAtributeFromParameter(constructorParametersInfo[i]);

                    constructorParameters[i] = this.GetInstance(parameterType, colorAttributeType);
                }
            }

            switch (config.Lifecycle)
            {
                case Lifecycle.PerRequest:
                    instance = this.resolvedObjectsRepository.ContainsKey(tuple) ? this.resolvedObjectsRepository[tuple] : constructorInfo.Invoke(constructorParameters);
                    break;
                case Lifecycle.Singleton:
                    if (this.singletonsRepository.ContainsKey(tuple))
                    {
                        instance = this.singletonsRepository[tuple];
                    }
                    else
                    {
                        instance = constructorInfo.Invoke(constructorParameters);
                        this.singletonsRepository.Add(tuple, instance);
                    }

                    break;
            }

            this.resolvingObjectsRepository.Remove(tuple);

            if (config.InitializeObjectWith != null)
            {
                config.InitializeObjectWith.Invoke(instance);
            }

            return instance;
        }
Example #30
0
 static TypeConfig[] InitTypeConfigs()
 {
     TypeConfig[] types = new TypeConfig[System.Enum.GetValues(typeof(ValueType)).Length];
     types[(int)ValueType.Float]   = new TypeConfig("float");
     types[(int)ValueType.Bool]    = new TypeConfig("bool");
     types[(int)ValueType.Int]     = new TypeConfig("int");
     types[(int)ValueType.Vector2] = new TypeConfig("Vector2", "new Vector2({0}, {1})", new[] { ".x", ".y" });
     types[(int)ValueType.Vector3] = new TypeConfig("Vector3", "new Vector3({0}, {1}, {2})", new[] { ".x", ".y", ".z" });
     types[(int)ValueType.Vector4] = new TypeConfig("Vector4", "new Vector4({0}, {1}, {2}, {3})", new[] { ".x", ".y", ".z", ".w" });
     types[(int)ValueType.Color]   = new TypeConfig("Color", "new Color({0}, {1}, {2}, {3})", new[] { ".r", ".g", ".b", ".a" });
     return(types);
 }
Example #31
0
            public TemplateMatcher(string name, List <string> patterns, IDictionary <string, string> slots, TypeConfig typeConfig)
            {
                this.name       = name;
                this.slots      = slots;
                this.typeconfig = typeConfig;
                this.templates  = new List <Template>();

                foreach (string patternStr in patterns)
                {
                    this.templates.Add(GenerateTemplate(patternStr, this.slots, typeConfig));
                }
            }
        private static SetPropertyDelegate GetSetPropertyMethod(TypeConfig typeConfig, PropertyInfo propertyInfo)
        {
            if (propertyInfo.ReflectedType() != propertyInfo.DeclaringType)
            {
                propertyInfo = propertyInfo.DeclaringType.GetPropertyInfo(propertyInfo.Name);
            }

            if (!propertyInfo.CanWrite && !typeConfig.EnableAnonymousFieldSetterses)
            {
                return(null);
            }

            FieldInfo fieldInfo = null;

            if (!propertyInfo.CanWrite)
            {
                //TODO: What string comparison is used in SST?
                string fieldNameFormat = Env.IsMono ? "<{0}>" : "<{0}>i__Field";
                var    fieldName       = string.Format(fieldNameFormat, propertyInfo.Name);

                var fieldInfos = typeConfig.Type.GetWritableFields();
                foreach (var f in fieldInfos)
                {
                    if (f.IsInitOnly && f.FieldType == propertyInfo.PropertyType && f.Name == fieldName)
                    {
                        fieldInfo = f;
                        break;
                    }
                }

                if (fieldInfo == null)
                {
                    return(null);
                }
            }

#if SILVERLIGHT || MONOTOUCH || XBOX
            if (propertyInfo.CanWrite)
            {
                var setMethodInfo = propertyInfo.SetMethod();
                return((instance, value) => setMethodInfo.Invoke(instance, new[] { value }));
            }
            if (fieldInfo == null)
            {
                return(null);
            }
            return((instance, value) => fieldInfo.SetValue(instance, value));
#else
            return(propertyInfo.CanWrite
                ? CreateIlPropertySetter(propertyInfo)
                : CreateIlFieldSetter(fieldInfo));
#endif
        }
    public void TestCannotGenerateTemplateWithoutTemplate()
    {
        string pattern = "a ${ingredient1}";
        Dictionary <string, string> slots = new Dictionary <string, string>()
        {
            { "ingredient1", "ingredient" }
        };
        TypeConfig typeconfig = new TypeConfig();

        Assert.That(() => TemplateMatcher.GenerateTemplate(pattern, slots, typeconfig),
                    Throws.TypeOf <System.InvalidOperationException>());
    }
 internal object ResolveInstance(TypeConfig config, Func<Type, Type, object> injectorGetInstance)
 {
     switch (config.ConstructorType)
     {
         case ConstructorType.DefaultConstructor:
             break;
         case ConstructorType.MatchedArgumentsConstructor:
             break;
         case ConstructorType.NoArgumentsConstructor:
             break;
         case ConstructorType.LongestResolvableConstructor:
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
        internal static object StringToType(
        Type type,
        string strType,
        EmptyCtorDelegate ctorFn,
        Dictionary<string, TypeAccessor> typeAccessorMap)
        {
            var index = 0;

            if (strType == null)
                return null;

            //if (!Serializer.EatMapStartChar(strType, ref index))
            for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline
            if (strType[index++] != JsWriter.MapStartChar)
                throw DeserializeTypeRef.CreateSerializationError(type, strType);

            if (JsonTypeSerializer.IsEmptyMap(strType, index)) return ctorFn();

            object instance = null;

            var strTypeLength = strType.Length;
            while (index < strTypeLength)
            {
                var propertyName = JsonTypeSerializer.ParseJsonString(strType, ref index);

                //Serializer.EatMapKeySeperator(strType, ref index);
                for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline
                if (strType.Length != index) index++;

                var propertyValueStr = Serializer.EatValue(strType, ref index);
                var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1;

                //if we already have an instance don't check type info, because then we will have a half deserialized object
                //we could throw here or just use the existing instance.
                if (instance == null && possibleTypeInfo && propertyName == JsWriter.TypeAttr)
                {
                    var explicitTypeName = Serializer.ParseString(propertyValueStr);
                    var explicitType = AssemblyUtils.FindType(explicitTypeName);
#if NETFX_CORE
                    if (explicitType != null && !explicitType.GetTypeInfo().IsInterface && !explicitType.GetTypeInfo().IsAbstract)
#else
                    if (explicitType != null && !explicitType.IsInterface && !explicitType.IsAbstract)
#endif
                    {
                        instance = explicitType.CreateInstance();
                    }

                    if (instance == null)
                    {
                        Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr);
                    }
                    else
                    {
                        //If __type info doesn't match, ignore it.
#if NETFX_CORE
                        if (!type.IsInstanceOf(instance.GetType()))
#else
                        if (!type.IsInstanceOfType(instance))
#endif
                        {
                            instance = null;
                        }
                        else
                        {
                            var derivedType = instance.GetType();
                            if (derivedType != type)
                            {
                                var derivedTypeConfig = new TypeConfig(derivedType);
                                var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer);
                                if (map != null)
                                {
                                    typeAccessorMap = map;
                                }
                            }
                        }
                    }

                    Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                    continue;
                }

                if (instance == null) instance = ctorFn();

                var typeAccessor = PropertyNameResolver.GetTypeAccessorForProperty(propertyName, typeAccessorMap);

                var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null;
                if (propType != null)
                {
                    try
                    {
                        if (typeAccessor != null)
                        {
                            //var parseFn = Serializer.GetParseFn(propType);
                            var parseFn = JsonReader.GetParseFn(propType);

                            var propertyValue = parseFn(propertyValueStr);
                            typeAccessor.SetProperty(instance, propertyValue);
                        }

                        //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                        for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline
                        if (index != strType.Length)
                        {
                            var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar;
                            index++;
                            if (success)
                                for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline
                        }

                        continue;
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        else Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr);
                    }
                }

                if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null)
                {
                    try
                    {
                        var propertyValue = typeAccessor.GetProperty(propertyValueStr);
                        typeAccessor.SetProperty(instance, propertyValue);
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, typeAccessor.PropertyType, e);
                        else Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr);
                    }
                }

                //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline
                if (index != strType.Length)
                {
                    var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar;
                    index++;
                    if (success)
                        for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline
                }

            }

            return instance;
        }
Example #36
0
        internal static object StringToType(
            Type type,
            string strType,
            EmptyCtorDelegate ctorFn,
            Dictionary<string, TypeAccessor> typeAccessorMap)
        {
            var index = 0;

            if (strType == null)
                return null;

            //if (!Serializer.EatMapStartChar(strType, ref index))
            if (strType[index++] != JsWriter.MapStartChar)
                throw DeserializeTypeRef.CreateSerializationError(type, strType);

            if (JsonTypeSerializer.IsEmptyMap(strType)) return ctorFn();

            object instance = null;

            var propertyResolver = JsConfig.PropertyConvention == PropertyConvention.Lenient
                ? ParseUtils.LenientPropertyNameResolver
                : ParseUtils.DefaultPropertyNameResolver;

            var strTypeLength = strType.Length;
            while (index < strTypeLength)
            {
                var propertyName = Serializer.EatMapKey(strType, ref index);

                //Serializer.EatMapKeySeperator(strType, ref index);
                index++;

                var propertyValueStr = Serializer.EatValue(strType, ref index);
                var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1;

                if (possibleTypeInfo && propertyName == JsWriter.TypeAttr)
                {
                    var explicitTypeName = Serializer.ParseString(propertyValueStr);
                    var explicitType = AssemblyUtils.FindType(explicitTypeName);

                    if (explicitType != null && !explicitType.IsInterface() && !explicitType.IsAbstract())
                    {
                        instance = explicitType.CreateInstance();
                    }

                    if (instance == null)
                    {
                        Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr);
                    }
                    else
                    {
                        //If __type info doesn't match, ignore it.
                        if (!type.InstanceOfType(instance))
                        {
                            instance = null;
                        }
                        else
                        {
                            var derivedType = instance.GetType();
                            if (derivedType != type)
                            {
                                var derivedTypeConfig = new TypeConfig(derivedType);
                                var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer);
                                if (map != null)
                                {
                                    typeAccessorMap = map;
                                }
                            }
                        }
                    }

                    //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                    if (index != strType.Length) index++;

                    continue;
                }

                if (instance == null) instance = ctorFn();

                var typeAccessor = propertyResolver.GetTypeAccessorForProperty(propertyName, typeAccessorMap);

                var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null;
                if (propType != null)
                {
                    try
                    {
                        if (typeAccessor != null)
                        {
                            var parseFn = Serializer.GetParseFn(propType);
                            var propertyValue = parseFn(propertyValueStr);
                            typeAccessor.SetProperty(instance, propertyValue);
                        }

                        //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                        if (index != strType.Length) index++;

                        continue;
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        else Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr);
                    }
                }

                if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null)
                {
                    try
                    {
                        var propertyValue = typeAccessor.GetProperty(propertyValueStr);
                        typeAccessor.SetProperty(instance, propertyValue);
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        else Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr);
                    }
                }

                //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                if (index != strType.Length) index++;
            }

            return instance;
        }
Example #37
0
        internal static object StringToType(
            TypeConfig typeConfig,
            string strType,
            EmptyCtorDelegate ctorFn,
            Dictionary<string, TypeAccessor> typeAccessorMap)
        {
            var index = 0;
            var type = typeConfig.Type;

            if (strType == null)
                return null;

            //if (!Serializer.EatMapStartChar(strType, ref index))
            if (strType[index++] != JsWriter.MapStartChar)
                throw DeserializeTypeRef.CreateSerializationError(type, strType);

            if (JsonTypeSerializer.IsEmptyMap(strType)) return ctorFn();

            object instance = null;

            var strTypeLength = strType.Length;
            while (index < strTypeLength)
            {
                var propertyName = Serializer.EatMapKey(strType, ref index);

                //Serializer.EatMapKeySeperator(strType, ref index);
                index++;

                var propertyValueStr = Serializer.EatValue(strType, ref index);
                var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1;

                if (possibleTypeInfo && propertyName == JsWriter.TypeAttr)
                {
                    var explicitTypeName = Serializer.ParseString(propertyValueStr);
                    var explicitType = AssemblyUtils.FindType(explicitTypeName);

                    if (explicitType == null || explicitType.IsInterface() || explicitType.IsAbstract())
                    {
                        Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr);
                    }
                    else if (!type.IsAssignableFrom(explicitType))
                    {
                        Tracer.Instance.WriteWarning("Could not assign type: " + propertyValueStr);
                    }
                    else
                    {
                        instance = explicitType.CreateInstance();
                    }

                    if (instance != null)
                    {
                        var derivedType = instance.GetType();
                        if (derivedType != type)
                        {
                            var derivedTypeConfig = new TypeConfig(derivedType);
                            var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer);
                            if (map != null)
                            {
                                typeAccessorMap = map;
                            }
                        }
                    }
                    
                    //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                    if (index != strType.Length) index++;

                    continue;
                }

                if (instance == null) instance = ctorFn();

                TypeAccessor typeAccessor;
                typeAccessorMap.TryGetValue(propertyName, out typeAccessor);

                var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null;
                if (propType != null)
                {
                    try
                    {
                        if (typeAccessor != null)
                        {
                            var parseFn = Serializer.GetParseFn(propType);
                            var propertyValue = parseFn(propertyValueStr);
                            if (typeConfig.OnDeserializing != null)
                            {
                                propertyValue = typeConfig.OnDeserializing(instance, propertyName, propertyValue);
                            }
                            typeAccessor.SetProperty(instance, propertyValue);
                        }

                        //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                        if (index != strType.Length) index++;

                        continue;
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.HasOnDeserializationErrorHandler) JsConfig.OnDeserializationError(instance, propType, propertyName, propertyValueStr, e);
                        if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        
                        Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr);
                    }
                }

                if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null)
                {
                    try
                    {
                        var propertyValue = typeAccessor.GetProperty(propertyValueStr);
                        if (typeConfig.OnDeserializing != null)
                        {
                            propertyValue = typeConfig.OnDeserializing(instance, propertyName, propertyValue);
                        }
                        typeAccessor.SetProperty(instance, propertyValue);
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.HasOnDeserializationErrorHandler) JsConfig.OnDeserializationError(instance, typeAccessor.PropertyType, propertyName, propertyValueStr, e);
                        if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, typeAccessor.PropertyType, e);
                        
                        Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr);
                    }
                }
                else if (typeConfig.OnDeserializing != null)
                {
                    // the property is not known by the DTO
                    typeConfig.OnDeserializing(instance, propertyName, propertyValueStr);
                }

                //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                if (index != strType.Length) index++;
            }

            return instance;
        }