Ejemplo n.º 1
0
        public IHttpAction Execute(string str)
        {
            try
            {
                Request    = new Request(str);
                Parameters = GetParameters();

                Controller = ControllerRegistry.Get(Request.Uri.Controller);

                try
                {
                    ControllerMethod = GetControllerMethod();
                }
                catch (Exception)
                {
                    return(new MethodNotAllowed());
                }

                if (ControllerMethod.GetParameters().Length > 0 && Request.Body.Length > 0)
                {
                    var serializer = SerializerRegistry.Get(Request.GetField("Content-Type"));
                    var bodyType   = ControllerMethod.GetParameters().Last().ParameterType;
                    Parameters[Parameters.Count - 1] = serializer.Deserialize((string)Parameters[Parameters.Count - 1], bodyType);
                }

                return((IHttpAction)ControllerMethod.Invoke(Controller, Request.Parameters));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(new BadRequest());
            }
        }
Ejemplo n.º 2
0
        public override object Deserialize(BinaryTypesReader br, Type type, SerializerSettings settings, ISerializerArg serializerArg)
        {
            var classMap = SerializerRegistry.GetClassMap(type); //todo: also base types?

            var fastReflectionClassMap = GetFastReflectionClassMap(type);
            var propNames = fastReflectionClassMap.PropertyInfos.Keys.ToList();
            var instance  = fastReflectionClassMap.CreateInstance(Type.EmptyTypes); //Activator.CreateInstance(type);

            foreach (var propName in propNames)
            {
                MemberMap memberMap = classMap?.GetMemberMap(propName);
                if (memberMap?.Ignored == true)
                {
                    continue;
                }

                var pInfo = fastReflectionClassMap.PropertyInfos[propName];
                pInfo.Setter(
                    ref instance,
                    Serializer.DeserializeObject(br, pInfo.PropertyType, settings, memberMap?.Serializer, memberMap?.SerializerArg));
            }


            return(instance);
        }
Ejemplo n.º 3
0
        protected override JsonConverter CreateGenericConverter <T>(Type type, SerializerRegistry registry)
        {
            var info = new RefInfo(type, registry);

            Type converterType = typeof(RefConverter <,>)
                                 .MakeGenericType(info.TargetType, info.IDType);

            return((JsonConverter)Activator.CreateInstance(converterType, info.IDConverter));
        }
Ejemplo n.º 4
0
        public override object Deserialize(BinaryTypesReader br, Type type, SerializerSettings settings, ISerializerArg serializerArg)
        {
            if (br.ReadBoolean() == false) //null
            {
                return(null);
            }
            var nullableUnderlyingType = Nullable.GetUnderlyingType(type);
            var serializer             = SerializerRegistry.GetSerializer(nullableUnderlyingType);

            return(Serializer.DeserializeObject(br, nullableUnderlyingType, settings, serializer, serializerArg));
        }
Ejemplo n.º 5
0
        public override void Serialize(BinaryTypesWriter bw, Type type, SerializerSettings settings, ISerializerArg serializerArg, object value)
        {
            bw.Write(value != null);
            if (value == null)
            {
                return;
            }
            var nullableUnderlyingType = Nullable.GetUnderlyingType(type);
            var serializer             = SerializerRegistry.GetSerializer(nullableUnderlyingType);

            Serializer.SerializeObject(nullableUnderlyingType, value, bw, settings, serializer, serializerArg);
        }
Ejemplo n.º 6
0
            public RefInfo(Type type, SerializerRegistry registry)
            {
                TargetType = Ref.GetTargetType(type);
                IDType     = Ref.GetIdentifierType(TargetType);

                if (!registry.TryGetConverter(IDType, out IDConverter !))
                {
                    throw new InvalidOperationException(
                              $"Can not serialize type 'Ref<{TargetType.Name}>'. The given 'SerializerRegistry' " +
                              $"does not contain a serializer for IDs of type '{IDType.Name}'.");
                }
            }
Ejemplo n.º 7
0
        public TArg GetSerializerArg <TArg>(Type type, SerializerSettings settings, ISerializerArg serializerArg) where TArg : class, ISerializerArg
        {
            if (serializerArg == null && settings != null)
            {
                settings.SerializerArgMap.TryGetValue(type, out serializerArg);
            }

            if (serializerArg == null)
            {
                serializerArg = SerializerRegistry.GetSerializerArg(type);
            }

            return(serializerArg as TArg);
        }
Ejemplo n.º 8
0
    public void Start()
    {
        SerializerRegistry.Add <Foo, FooSerializer>("Foo", 329702953);

        var foo = new Foo()
        {
            Bar = "asdf",
            Qux = new Vector3(1, 2, 3)
        };

        var xmlStr = SerializationManager.SerializeToXml("Foo", foo).ToString();

        Debug.Log("Xml: " + xmlStr);
    }
Ejemplo n.º 9
0
        public void Test3()
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "mdbx");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // register serializer for our custom type
            SerializerRegistry.Register(new BasicTest3PayloadSerializer());

            using (MdbxEnvironment env = new MdbxEnvironment())
            {
                env.Open(path, EnvironmentFlag.NoTLS, Convert.ToInt32("666", 8));


                // mdbx_put
                using (MdbxTransaction tran = env.BeginTransaction())
                {
                    MdbxDatabase db = tran.OpenDatabase();
                    db.Put("ana_key", new BasicTest3Payload()
                    {
                        Person = "Ana", Age = 50
                    });
                    tran.Commit();
                }


                // mdbx_get
                using (MdbxTransaction tran = env.BeginTransaction(TransactionOption.ReadOnly))
                {
                    MdbxDatabase db = tran.OpenDatabase();

                    BasicTest3Payload payload = db.Get <string, BasicTest3Payload>("ana_key");
                    Assert.NotNull(payload);
                    Assert.Equal("Ana", payload.Person);
                    Assert.Equal(50, payload.Age);
                }



                env.Close();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Called internally by Photon when the application is just about to finish startup.
        /// </summary>
        protected sealed override void Setup()
        {
            //We utilize the internal Photon Setup() method
            //as a vector to provide various services to the consumer of this abstract class
            //Ways to register payload types and provide access to other internal services.
            //Not great design but it's better than exposing them as properties and relying on consumers
            //to deal with them there.

            //We also should handle registering network message types
            SerializerRegistry.Register(typeof(NetworkMessage));
            SerializerRegistry.Register(typeof(RequestMessage));
            SerializerRegistry.Register(typeof(ResponseMessage));
            SerializerRegistry.Register(typeof(EventMessage));
            SerializerRegistry.Register(typeof(StatusMessage));

            ServerSetup();
            SetupSerializationRegistration(SerializerRegistry);
        }
Ejemplo n.º 11
0
        public byte[] GetResponse(IHttpAction httpAction)
        {
            if (httpAction.Object != null)
            {
                var serializer = SerializerRegistry.Get(Request.GetField("Accept"));

                var datareq = Encoding.UTF8.GetBytes(serializer.Serialize(httpAction.Object, httpAction.Object.GetType()));

                Response = new Response(ResponseStatus.Get(httpAction.Code), datareq);
                Response.Fields.Add("Content-Type", serializer.Mime);
            }
            else
            {
                Response = new Response(ResponseStatus.Get(httpAction.Code), null);
            }

            return(CreateByteResponse());
        }
Ejemplo n.º 12
0
        public override void Serialize(BinaryTypesWriter bw, Type type, SerializerSettings settings, ISerializerArg serializerArg, object value)
        {
            var classMap = SerializerRegistry.GetClassMap(type); //todo: also base types?

            var props = value.GetType().GetProperties()
                        .OrderBy(x => x.MetadataToken)
                        .ToList();

            foreach (var prop in props)
            {
                MemberMap memberMap = classMap?.GetMemberMap(prop.Name);
                if (memberMap?.Ignored == true)
                {
                    continue;
                }

                var val = prop.GetValue(value);
                Serializer.SerializeObject(prop.PropertyType, val, bw, settings, memberMap?.Serializer, memberMap?.SerializerArg);
            }
        }
        public void Test_ClassMapIgnore2()
        {
            SerializerRegistry.RegisterClassMap(typeof(PocoSimple), new ClassMap <PocoSimple>(cm =>
            {
                cm.MapProperty(p => p.Str).Ignored = true;
            }));

            var val = new PocoSimple()
            {
                Int = 1,
                Str = "2",
            };

            var buf    = BinaryConvert.SerializeObject(val);
            var cloned = BinaryConvert.DeserializeObject <PocoSimple>(buf);

            Assert.AreEqual(val, cloned); //Note: comparer use class map, so ite return equal even that they are not!
            Assert.AreEqual(cloned.Int, 1);
            Assert.AreEqual(cloned.Str, null);
        }
Ejemplo n.º 14
0
        public override void Serialize(BinaryTypesWriter bw, Type type, SerializerSettings settings, ISerializerArg serializerArg, object value)
        {
            var classMap = SerializerRegistry.GetClassMap(type); //todo: also base types?

            var fastReflectionClassMap = GetFastReflectionClassMap(type);
            var propNames = fastReflectionClassMap.PropertyInfos.Keys.ToList();

            foreach (var propName in propNames)
            {
                MemberMap memberMap = classMap?.GetMemberMap(propName);
                if (memberMap?.Ignored == true)
                {
                    continue;
                }

                var pInfo = fastReflectionClassMap.PropertyInfos[propName];

                var val = pInfo.Getter(value);

                Serializer.SerializeObject(pInfo.PropertyType, val, bw, settings, memberMap?.Serializer, memberMap?.SerializerArg);
            }
        }
Ejemplo n.º 15
0
        public override object Deserialize(BinaryTypesReader br, Type type, SerializerSettings settings, ISerializerArg serializerArg)
        {
            var classMap = SerializerRegistry.GetClassMap(type); //todo: also base types?

            var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .OrderBy(x => x.MetadataToken);

            var instance = Activator.CreateInstance(type);


            foreach (var prop in props)
            {
                MemberMap memberMap = classMap?.GetMemberMap(prop.Name);
                if (memberMap?.Ignored == true)
                {
                    continue;
                }

                prop.SetValue(instance, Serializer.DeserializeObject(br, prop.PropertyType, settings, memberMap?.Serializer, memberMap?.SerializerArg));
            }

            return(instance);
        }
Ejemplo n.º 16
0
        private static void Main(string[] args)
        {
            var controllerRegistry = new ControllersRegistry();

            controllerRegistry.Reg("Users", new UsersController());
            controllerRegistry.Reg("Categories", new CategoriesController());
            controllerRegistry.Reg("Posts", new PostsController());
            controllerRegistry.Reg("Reviews", new ReviewsController());

            var serializerRegistry = new SerializerRegistry();

            serializerRegistry.RegDefault(new JsonSerializer());
            serializerRegistry.Reg(new List <string> {
                "application/json", "text/json"
            }, new JsonSerializer());
            serializerRegistry.Reg(new List <string> {
                "application/xml", "text/xml"
            }, new XmlSerializer());

            var serv = new TcpServer("127.0.0.1", 8000, serializerRegistry, controllerRegistry);

            serv.Start();
            Console.ReadKey();
        }
 public CustomTypeMapper(CustomSerializer serializer, SerializerRegistry registry)
 => (_serializer, _registry) = (serializer, registry);
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var orig = new Record
            {
                Id        = 7,
                Time      = new DateTime((DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond),
                Comment   = null,//"Bla!",
                SubRecord = new SubRecord
                {
                    Bool0  = false,
                    Bool1  = true,
                    Byte   = 1,
                    SByte  = -2,
                    Int16  = -3,
                    UInt16 = 4,
                    Int32  = 5,
                    UInt32 = 6,
                    Int64  = 7,
                    UInt64 = 8,
                    Char   = 'a',
                },
                Dec1   = 1234567890.987654m,
                Real32 = 17890.987654321f,
                Real64 = 167890.987654321,
                //TestEnum = (TestEnum)(17)//.Val1,
                TestEnum = TestEnum.Val1,
                IntList  = new List <int> {
                    1, 4, 9, 16
                },
                SubRecordList = new List <SubRecord>
                {
                    new SubRecord
                    {
                        Bool0  = false,
                        Bool1  = true,
                        Byte   = 11,
                        SByte  = -12,
                        Int16  = -13,
                        UInt16 = 14,
                        Int32  = 15,
                        UInt32 = 16,
                        Int64  = 17,
                        UInt64 = 18,
                        Char   = 'b',
                    }
                },
                IntDict = new Dictionary <int, int>
                {
                    { 0, 0 },
                    { 1, 1 },
                    { 2, 4 },
                    { 3, 9 },
                    { 4, 16 },
                },
                SubRecordDict = new Dictionary <string, SubRecord>
                {
                    { "key1", new SubRecord {
                          Bool0 = true, Char = (char)11
                      } },
                    { "key2", new SubRecord {
                          Bool1 = true, Char = 'x'
                      } },
                }
            };

            //orig.SubRecordDict = null;

            var settings = new SerializerSettings();

            //settings.SerializerArgMap[typeof(DateTime)] = new DateTimeSerializerArg() { TickResolution = TimeSpan.TicksPerDay };// RegisterSerializerArg(typeof(DateTime), );

            SerializerRegistry.RegisterClassMap(typeof(Record), new ClassMap <Record>(cm =>
            {
                //cm.MapProperty(p => p.Time).Ignored = true;
                cm.MapProperty(p => p.Time).SerializerArg = new DateTimeSerializerArg()
                {
                    TickResolution = TimeSpan.TicksPerMinute
                };
            }));

            var buf = BinaryConvert.SerializeObject(orig, settings);

            var cloned = BinaryConvert.DeserializeObject <Record>(buf, settings);

            var strOrig   = JsonConvert.SerializeObject(orig);
            var strCloned = JsonConvert.SerializeObject(cloned);

            Console.WriteLine($"==================================================================");
            Console.WriteLine($"buf len:\r\n{buf.Length}");
            Console.WriteLine($"==================================================================");
            Console.WriteLine($"strOrig:\r\n {strOrig}");
            Console.WriteLine($"==================================================================");
            Console.WriteLine($"strCloned:\r\n {strCloned}");
            Console.WriteLine($"==================================================================");
        }
Ejemplo n.º 19
0
 public HttpServer(ControllersRegistry controllersRegistry, SerializerRegistry serializerRegistry)
 {
     ControllerRegistry = controllersRegistry;
     SerializerRegistry = serializerRegistry;
 }
 public JsonSchemaContractResolver(SerializerRegistry serializers)
 => _serializers = Check.NotNull(serializers, nameof(serializers));
Ejemplo n.º 21
0
 public override JsonConverter CreateConverter(Type type, SerializerRegistry registry)
 => IDJsonConverter.Instnace;
Ejemplo n.º 22
0
 public void testInit()
 {
     SerializerRegistry.UnregisterClassMap(typeof(PocoSimple));
 }
Ejemplo n.º 23
0
 public override string GenerateSchema(Type type, SerializerRegistry registry) => @"{
         ""type"": ""string"",
         ""format"": ""guid""
     }";
Ejemplo n.º 24
0
 protected override string GenerateGenericSchema <T>(Type type, SerializerRegistry registry)
 {
     throw new NotImplementedException(
               "We do not use a custom TypeMapper to generate the OpenAPI schema but we directly modify " +
               "the Type of Ref properties via a custom IReflectionService.");
 }
        public void Test_ClassMapSerializerArgTime()
        {
            SerializerRegistry.RegisterClassMap(typeof(PocoComplex), new ClassMap <PocoComplex>(cm =>
            {
                cm.MapProperty(p => p.Time1).SerializerArg = new DateTimeSerializerArg()
                {
                    TickResolution = TimeSpan.TicksPerDay
                };
                cm.MapProperty(p => p.Time2).SerializerArg = new DateTimeSerializerArg()
                {
                    TickResolution = TimeSpan.TicksPerMinute
                };
            }));

            var val = new PocoComplex()
            {
                Id        = 7,
                Time1     = new DateTime(2010, 10, 10, 10, 10, 10),
                Time2     = new DateTime(2010, 10, 10, 10, 10, 10),
                Comment   = null,//"Bla!",
                SubRecord = new PocoWithAllPrimitives()
                {
                    Byte   = 1,
                    SByte  = -2,
                    Int16  = -3,
                    UInt16 = 4,
                    Int32  = 5,
                    UInt32 = 6,
                    Int64  = 7,
                    UInt64 = 8,
                    Char   = 'a',
                },
                Dec1     = 1234567890.954m,
                Real32   = 17890.9f,
                Real64   = 167890.1,
                TestEnum = TestEnum.Val1,
                IntList  = new List <int> {
                    1, 4, 9, 16
                },
                SubRecordList = new List <PocoWithAllPrimitives>
                {
                    new PocoWithAllPrimitives()
                    {
                        Byte   = 11,
                        SByte  = -12,
                        Int16  = -13,
                        UInt16 = 14,
                        Int32  = 15,
                        UInt32 = 16,
                        Int64  = 17,
                        UInt64 = 18,
                        Char   = 'b',
                    }
                },
                IntDict = new Dictionary <int, int>
                {
                    { 0, 0 },
                    { 1, 1 },
                    { 2, 4 },
                    { 3, 9 },
                    { 4, 16 },
                },
                SubRecordDict = new Dictionary <string, PocoSimple>
                {
                    { "key1", new PocoSimple {
                          Int = 1, Str = null
                      } },
                    { "key2", new PocoSimple {
                          Int = -1, Str = "str"
                      } },
                }
            };

            var buf    = BinaryConvert.SerializeObject(val);
            var cloned = BinaryConvert.DeserializeObject <PocoComplex>(buf);

            Assert.AreEqual(val, cloned); //Note: comparer use class map, so ite return equal even that they are not!

            Assert.AreEqual(cloned.Time1.Second, 0);
            Assert.AreEqual(cloned.Time1.Minute, 0);
            Assert.AreEqual(cloned.Time1.Hour, 0);

            Assert.AreEqual(cloned.Time2.Second, 0);
            Assert.AreEqual(cloned.Time2.Minute, 10);
            Assert.AreEqual(cloned.Time2.Hour, 10);
        }