コード例 #1
0
        public ProtobufMessageSerializer(IEnumerable <Message> messages, IEnumerable <MessageHeader> headers)
        {
            _model = TypeModel.Create();
            _model.AllowParseableTypes             = true;
            _model[typeof(Message)].UseConstructor = false;

            foreach (var message in messages)
            {
                if (message.GetType() == typeof(Message))
                {
                    continue;
                }

                var type = message.GetType();
                _model[typeof(Message)].AddSubType(GenerateId(type), type);
                _model[type].UseConstructor = false;
            }


            _model[typeof(MessageHeader)].UseConstructor = false;

            foreach (var header in headers)
            {
                if (header.GetType() == typeof(MessageHeader))
                {
                    continue;
                }

                var type = header.GetType();
                _model[typeof(MessageHeader)].AddSubType(GenerateId(type), type);
                _model[type].UseConstructor = false;
            }

            _model.CompileInPlace();
        }
コード例 #2
0
        public ProtobufMessageSerializer(params Assembly[] protocolAssemblies)
        {
            var types = protocolAssemblies.SelectMany(assembly => assembly.GetTypes());

            _model = TypeModel.Create();
            _model.AllowParseableTypes             = true;
            _model[typeof(Message)].UseConstructor = false;

            foreach (var type in types.Where(t => typeof(Message).IsAssignableFrom(t) && t != typeof(Message)))
            {
                _model[typeof(Message)].AddSubType(GenerateId(type), type);
                _model[type].UseConstructor = false;
            }


            _model[typeof(MessageHeader)].UseConstructor = false;

            foreach (var type in types.Where(t => typeof(MessageHeader).IsAssignableFrom(t) && t != typeof(MessageHeader)))
            {
                _model[typeof(MessageHeader)].AddSubType(GenerateId(type), type);
                _model[type].UseConstructor = false;
            }

            _model.CompileInPlace();
        }
コード例 #3
0
        public static void Test <T, TCreate>(RuntimeTypeModel model, bool compile = false, params Type[] extraTypes)
            where TCreate : T, new()
            where T : ICallbackTest
        {
            model.Add(typeof(TCreate), true);
            if (extraTypes != null)
            {
                for (int i = 0; i < extraTypes.Length; i++)
                {
                    model.Add(extraTypes[i], true);
                }
            }
            model.AutoCompile = false;
            Test <T, TCreate>(model, "Runtime");

            if (compile)
            {
                string name = typeof(TCreate).FullName + "Ser";
                model.Compile(name, name + ".dll");
                PEVerify.AssertValid(name + ".dll");
            }

            model.CompileInPlace();
            Test <T, TCreate>(model, "CompileInPlace");

            if (compile)
            {
                Test <T, TCreate>(model.Compile(), "Compile"); // <===== lots of private members etc
            }
        }
コード例 #4
0
        public static void TestModel(RuntimeTypeModel model, object value, string hex)
        {
            byte[] raw;
            using (MemoryStream ms = new MemoryStream())
            {
                model.Serialize(ms, value);
                raw = ms.ToArray();
            }

            Assert.Equal(hex, GetHex(raw));

            model.CompileInPlace();
            using (MemoryStream ms = new MemoryStream())
            {
                model.Serialize(ms, value);
                raw = ms.ToArray();
            }

            Assert.Equal(hex, GetHex(raw));

            TypeModel compiled = model.Compile("compiled", "compiled.dll");

            PEVerify.Verify("compiled.dll");
            using (MemoryStream ms = new MemoryStream())
            {
                compiled.Serialize(ms, value);
                raw = ms.ToArray();
            }
            Assert.Equal(hex, GetHex(raw));
        }
コード例 #5
0
        public void Execute()
        {
            WriteHeading(".NET version");
#if !COREFX
            Console.WriteLine(Environment.Version);
#endif
            RuntimeTypeModel orderModel = TypeModel.Create();
            orderModel.Add(typeof(OrderHeader), true);
            orderModel.Add(typeof(OrderDetail), true);

            PurgeWithGusto("OrderSerializer.dll");
            orderModel.Compile("OrderSerializer", "OrderSerializer.dll");
            PEVerify.Verify("OrderSerializer.dll");
            RuntimeTypeModel model = BuildMeta();
            Customer         cust1 = new Customer();
            CustomerStruct   cust2 = new CustomerStruct
            {
                Id   = cust1.Id = 123,
                Name = cust1.Name = "Fred"
            };
#if !FX11
            cust1.HasValue = cust2.HasValue = true;
            cust1.HowMuch  = cust2.HowMuch = 0.123;
#endif
            WriteCustomer(model, "Runtime - class", cust1);
            WriteCustomer(model, "Runtime - struct", cust2);

#if FEAT_COMPILER && !FX11
            model.CompileInPlace();
            WriteCustomer(model, "InPlace- class", cust1);
            WriteCustomer(model, "InPlace - struct", cust2);
#endif
#if FEAT_COMPILER
#if !COREFX
            PurgeWithGusto("CustomerModel.dll");
            TypeModel compiled = model.Compile("CustomerModel", "CustomerModel.dll");
            PEVerify.Verify("CustomerModel.dll");
            WriteCustomer(compiled, "Compiled - class", cust2);
            WriteCustomer(compiled, "Compiled - struct", cust2);
#endif

            /*
             * CustomerModel serializer = new CustomerModel();
             * using (MemoryStream ms = new MemoryStream())
             * {
             *  Customer cust = new Customer();
             *  cust.Id = 123;
             *  cust.Name = "Fred";
             *  serializer.Serialize(ms, cust);
             *  ms.Position = 0;
             *  Customer clone = (Customer)serializer.Deserialize(ms, null, typeof(Customer));
             *  Console.WriteLine(clone.Id);
             *  Console.WriteLine(clone.Name);
             * }
             */
#endif
        }
コード例 #6
0
 public InitialLoadBusiness(IAzureBlobStorageRepository azureBlobStorageRepository, IWriteRawEventStorage writeRawEventStorage, IDataEnrichmentBusiness dataEnrichmentBusiness, ILogger logger)
 {
     _azureBlobStorageRepository = azureBlobStorageRepository;
     _writeRawEventStorage       = writeRawEventStorage;
     _dataEnrichmentBusiness     = dataEnrichmentBusiness;
     _model = ModelBuilder.GetModel();
     _model.CompileInPlace();
     _logger = logger;
 }
コード例 #7
0
        static Command()
        {
            try
            {
                // Get all CommandHandler subclasses in the CSM.Commands.Handler namespace
                Type[] handlers = typeof(Command).Assembly.GetTypes()
                                  .Where(t => t.Namespace != null)
                                  .Where(t => t.Namespace.StartsWith("CSM.Commands.Handler", StringComparison.Ordinal))
                                  .Where(t => t.IsSubclassOf(typeof(CommandHandler)))
                                  .Where(t => !t.IsAbstract)
                                  .ToArray();

                // Create a protobuf model
                RuntimeTypeModel model = TypeModel.Create();

                // Set type surrogates
                model[typeof(Vector3)].SetSurrogate(typeof(Vector3Surrogate));
                model[typeof(NetTool.ControlPoint)].SetSurrogate(typeof(ControlPointSurrogate));

                // Add Quaternion Surrogate
                model[typeof(Quaternion)].SetSurrogate(typeof(QuaternionSurrogate));

                // Add Color Surrogate
                model[typeof(Color)].SetSurrogate(typeof(ColorSurrogate));

                // Add base command to the protobuf model with all attributes
                model.Add(typeof(CommandBase), true);
                MetaType baseCmd = model[typeof(CommandBase)];

                // Lowest id of the subclasses
                int id = 100;

                // Create instances of the handlers, initialize mappings and register command subclasses in the protobuf model
                foreach (Type type in handlers)
                {
                    CommandHandler handler = (CommandHandler)Activator.CreateInstance(type);
                    _cmdMapping.Add(handler.GetDataType(), handler);

                    // Add subtype to the protobuf model with all attributes
                    baseCmd.AddSubType(id, handler.GetDataType());
                    model.Add(handler.GetDataType(), true);

                    id++;
                }

                // Compile the protobuf model
                model.CompileInPlace();

                Model = model;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Failed to initialize data model");
            }
        }
コード例 #8
0
        public DatasourceRecordSerializer()
        {
            _serializer = TypeModel.Create();
            _serializer.Add(typeof(List <DatasourceRecord>), true);

            _serializer[typeof(DatasourceRecord)]
            .AddSubType(8, typeof(EventRecord))
            .Add(1, "DatasourceId")
            .Add(2, "Timestamp")
            .Add(3, "IntervalSeconds")
            .Add(5, "Value")
            .Add(6, "EncodedDataType");

            _serializer.CompileInPlace();
        }
コード例 #9
0
        private void Initialize()
        {
            if (_Model.GetTypes() != null)
            {
                return;
            }

            _Model.Add(_primaryType, true);
            foreach (var knownType in _secondaryTypes)
            {
                _Model.Add(knownType, true);
            }

            _Model.CompileInPlace();
        }
コード例 #10
0
        static ProtobufSerializer()
        {
#if !UNITY_EDITOR
            Assembly typeModelAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(asm => asm.FullName.Contains("RTSLTypeModel")).FirstOrDefault();
            Type     type = null;
            if (typeModelAssembly != null)
            {
                type = typeModelAssembly.GetTypes().Where(t => t.Name.Contains("RTSLTypeModel")).FirstOrDefault();
            }

            if (type != null)
            {
                model = Activator.CreateInstance(type) as TypeModel;
            }

            if (model == null)
            {
                UnityEngine.Debug.LogError("RTSLTypeModel was not found. Please build type model using the Build All button available through the Tools->Runtime SaveLoad->Config menu item in Unity Editor.");
            }
#endif
            if (model == null)
            {
                model = CreateTypeModel();
            }

            model.DynamicTypeFormatting += (sender, args) =>
            {
                if (args.FormattedName == null)
                {
                    return;
                }

                if (Type.GetType(args.FormattedName) == null)
                {
                    args.Type = typeof(NilContainer);
                }
            };

#if UNITY_EDITOR
            RuntimeTypeModel runtimeTypeModel = model as RuntimeTypeModel;
            if (runtimeTypeModel != null)
            {
                runtimeTypeModel.CompileInPlace();
            }
#endif
        }
コード例 #11
0
        private void PrepareSerializer <T>(RuntimeTypeModel model)
        {
            model.CompileInPlace();

            try
            {
                if (_targetType != typeof(TypeMetaData))
                {
                    model.Compile();
                }
            }
            catch (InvalidOperationException ex)
            {
                throw new SerializationException(
                          string.Format(
                              "The model {0} could not be serialized, this could be because private members in the type (or down its graph) are decorated with the 'DataMember attribute', check inner exception for more details.",
                              _targetType.FullName), ex);
            }
        }
コード例 #12
0
        static ProtobufSerializer()
        {
#if !UNITY_EDITOR
            Type type = Type.GetType("RTSLTypeModel, RTSLTypeModel");

            if (type != null)
            {
                model = Activator.CreateInstance(type) as TypeModel;
            }

            if (model == null)
            {
                UnityEngine.Debug.LogError("RTSLTypeModel.dll was not found. Please build type model using Tools->Runtime SaveLoad->Build All menu item from Unity Editor");
            }
#endif
            if (model == null)
            {
                model = TypeModelCreator.Create();
            }

            model.DynamicTypeFormatting += (sender, args) =>
            {
                if (args.FormattedName == null)
                {
                    return;
                }

                if (Type.GetType(args.FormattedName) == null)
                {
                    args.Type = typeof(NilContainer);
                }
            };

            #if UNITY_EDITOR
            RuntimeTypeModel runtimeTypeModel = model as RuntimeTypeModel;
            if (runtimeTypeModel != null)
            {
                runtimeTypeModel.CompileInPlace();
            }
            #endif
        }
コード例 #13
0
        public void Initialize(IEnumerable <Type> types)
        {
            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;

            _protobufModel = RuntimeTypeModel.Default;
            var index = 1;

            foreach (var type in types)
            {
                var metaType = _protobufModel.Add(type, false);
                foreach (var field in type.GetTypeInfo().GetFields(bindingFlags))
                {
                    metaType.Add(index++, field.Name);
                }
                foreach (var prop in type.GetTypeInfo().GetProperties(bindingFlags))
                {
                    metaType.Add(index++, prop.Name);
                }
            }
            _protobufModel.CompileInPlace();
        }
コード例 #14
0
        private static void AddMassiveTransitTypes()
        {
            _protobufModel = RuntimeTypeModel.Default;
            //Right order...
            AddTypeToModel <AddPeerSubscriptionMessage>();
            AddTypeToModel <AddPeerMessage>();
            AddTypeToModel <RemovePeerMessage>();
            AddTypeToModel <PeerMessage>();

            AddTypeToModel <PeerSubscriptionMessage>();
            AddTypeToModel <SubscriptionAddedMessage>();
            AddTypeToModel <SubscriptionRemovedMessage>();
            AddTypeToModel <RemovePeerSubscriptionMessage>();
            AddTypeToModel <SubscribeToMessage>();
            AddTypeToModel <UnsubscribeFromMessage>();
            AddTypeToModel <SubscriptionMessage>();

            MetaType metaEnvelope = AddTypeToModel <Envelope>();

            //Property 'Message' is a object, we need DynamicType
            metaEnvelope.GetFields()[6].DynamicType = true;
            //Compile all types
            _protobufModel.CompileInPlace();
        }
コード例 #15
0
 public static void Compile()
 {
     _protobufModel.CompileInPlace();
 }