Пример #1
0
        public void ProtobufSerializeChatPacket()
        {
            //---------------------------------------------------------------------
            //Setup
            //---------------------------------------------------------------------
            ProtoBufSerializer serializer = new ProtoBufSerializer();
            ChatMessagePacket  packet     = new ChatMessagePacket("This is a test", "Tester");

            byte[] data;
            byte[] expectedData = { 162, 6, 16, 26, 14, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 8, 2, 18, 6, 84, 101, 115, 116, 101, 114 };

            //---------------------------------------------------------------------
            //Run Test
            //---------------------------------------------------------------------
            data = serializer.Serialize(packet);

            //---------------------------------------------------------------------
            //Gather Output
            //---------------------------------------------------------------------

            //---------------------------------------------------------------------
            //Assert
            //---------------------------------------------------------------------
            Assert.IsNotNull(data);
            Assert.AreEqual(expectedData, data);
        }
        static void Main(string[] args)
        {
            // Instantiate Protocol Buffer based serializer.
            ISerializer aSerializer = new ProtoBufSerializer();

            // Create message receiver receiving 'MyRequest' and receiving 'MyResponse'.
            // The receiver will use Protocol Buffers to serialize/deserialize messages.
            IDuplexTypedMessagesFactory aReceiverFactory = new DuplexTypedMessagesFactory(aSerializer);
            myReceiver = aReceiverFactory.CreateDuplexTypedMessageReceiver<MyResponse, MyRequest>();

            // Subscribe to handle messages.
            myReceiver.MessageReceived += OnMessageReceived;

            // Create TCP messaging.
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();

            IDuplexInputChannel anInputChannel
                = aMessaging.CreateDuplexInputChannel("tcp://127.0.0.1:8060/");

            // Attach the input channel and start to listen to messages.
            myReceiver.AttachDuplexInputChannel(anInputChannel);

            Console.WriteLine("The service is running. To stop press enter.");
            Console.ReadLine();

            // Detach the input channel and stop listening.
            // It releases the thread listening to messages.
            myReceiver.DetachDuplexInputChannel();
        }
Пример #3
0
        public RpcTcpMessage <RpcResponse> GetResponse()
        {
            var h = ProtoBufSerializer.FromByteArray <RpcResponseHeader>(_headerBuffer);

            int         offset   = IdentityLength + HeaderLength;
            RpcResponse response = new RpcResponse()
            {
                ErrorCode = (RpcErrorCode)h.ResponseCode,
                Options   = (RpcMessageOptions)h.Option,
            };
            int len = h.BodyLength - 1;

            if (len > 0)
            {
                response.BodyBuffer           = new RpcBodyBuffer(_bodyBuffer);
                response.BodyBuffer.TextError = true;
                offset += len;
            }
            else if (len == 0)
            {
                response.BodyBuffer = RpcBodyBuffer.EmptyBody;
            }
            else
            {
                response.BodyBuffer = null;
            }
            var message = new RpcTcpMessage <RpcResponse>()
            {
                Sequence = h.Sequence,
                Message  = response,
            };

            return(message);
        }
Пример #4
0
        private void SaveItems(object param)
        {
            Directory.Delete(ItemsPath, true);
            Directory.CreateDirectory(ItemsPath);
            // directory creation might take some time -> wait until it is definitively created
            while (!Directory.Exists(ItemsPath))
            {
                Thread.Sleep(100);
                Directory.CreateDirectory(ItemsPath);
            }

            int i = 0;

            T[] items = GetStorableItems(itemListViewItemMapping.Keys);

            foreach (T item in items)
            {
                try {
                    i++;
                    SetEnabledStateOfContentViews(item, false);
                    var ser = new ProtoBufSerializer();
                    ser.Serialize(item, ItemsPath + Path.DirectorySeparatorChar + i.ToString("00000000") + ".hl");
                    OnItemSaved(item, progressBar.Maximum / listView.Items.Count);
                }
                catch (Exception) { }
                finally {
                    SetEnabledStateOfContentViews(item, true);
                }
            }
            OnAllItemsSaved();
        }
Пример #5
0
        public void ProtobufDeserializeChatPacket()
        {
            //---------------------------------------------------------------------
            //Setup
            //---------------------------------------------------------------------
            ProtoBufSerializer serializer     = new ProtoBufSerializer();
            ChatMessagePacket  Expectedpacket = new ChatMessagePacket("This is a test", "Tester");
            List <Packet>      packet         = new List <Packet>();

            byte[] data = { 162, 6, 16, 26, 14, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 8, 2, 18, 6, 84, 101, 115, 116, 101, 114 };

            //---------------------------------------------------------------------
            //Run Test
            //---------------------------------------------------------------------
            packet.Add(serializer.Deserialize(data));

            //---------------------------------------------------------------------
            //Gather Output
            //---------------------------------------------------------------------
            ChatMessagePacket output = (ChatMessagePacket)packet[0];

            //---------------------------------------------------------------------
            //Assert
            //---------------------------------------------------------------------
            Assert.IsNotNull(data);
            Assert.AreEqual(Expectedpacket.message, output.message);
            Assert.AreEqual(Expectedpacket.sender, output.sender);
            Assert.AreEqual(Expectedpacket.type, output.type);
        }
 private static ISerializer<Event<IUserCommand>> ConstructSerializer()
 {
     var protoBufModel = TypeModel.Create();
     protoBufModel.Add(typeof(IUserCommand), true).AddSubType(1, typeof(UpdateName));
     var serializer = new ProtoBufSerializer<Event<IUserCommand>>(protoBufModel);
     return serializer;
 }
Пример #7
0
        public void SendResponse <T>(RpcResponseHeader header, T results)
        {
            HttpListenerResponse response = _httpContext.Response;

            response.StatusCode  = 200;
            response.ContentType = "multipart/byteranges";
            if (!header.HasBody)
            {
                response.Headers.Add("Null", "true");
                response.ContentLength64 = 0;
            }
            else
            {
                byte[] buffer = ProtoBufSerializer.ToByteArray <T>(results);
                if (buffer.Length > 0)
                {
                    response.ContentLength64 = buffer.Length;
                    response.OutputStream.Write(buffer, 0, buffer.Length);
                    response.OutputStream.Close();
                }
                else
                {
                    response.ContentLength64 = 0;
                }
            }
            response.Close();
        }
Пример #8
0
        public void ProtoBufSerializer_Deserialize_GivenNullInput_ShouldReturnNull()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var result = protoBufSerializer.Deserialize<object>(null);

            Assert.IsNull(result);
        }
Пример #9
0
        public static void WriteStream <T>(PipeStream stream, RpcPipeContext context, T data)
        {
            byte[] contextBuffer = ProtoBufSerializer.ToByteArray <RpcPipeContext>(context);
            byte[] bodyBuffer    = null;
            if (typeof(T) != typeof(RpcNull))
            {
                bodyBuffer = ProtoBufSerializer.ToByteArray <T>(data);
            }
            else
            {
                bodyBuffer = EmptyBuffer;
            }

            RpcPipeHeader header;

            header.Mark        = RpcPipeHeader.MagicMark;
            header.ContextSize = contextBuffer.Length;
            header.BodySize    = bodyBuffer.Length;

            byte[] headerBuffer = RpcPipeHeader.ToByteArray(header);
            stream.Write(headerBuffer, 0, headerBuffer.Length);
            stream.Write(contextBuffer, 0, contextBuffer.Length);

            if (header.BodySize > 0)
            {
                stream.Write(bodyBuffer, 0, bodyBuffer.Length);
            }

            stream.Flush();
        }
Пример #10
0
 public void ProtoBuf()
 {
     var serializer     = new ProtoBufSerializer <LogIn>();
     var bytes          = BinaryProtocol.FromObject(_loginCmd, "LogIn", serializer);
     var receivedPacket = new BinaryProtocol(bytes.GetDataToSend());
     var obj            = serializer.Deserialize(receivedPacket.Data);
 }
Пример #11
0
        public static void WriteStreamEx(PipeStream stream, RpcPipeContext context, Exception ex)
        {
            byte[] contextBuffer = ProtoBufSerializer.ToByteArray <RpcPipeContext>(context);
            byte[] bodyBuffer    = null;
            if (ex != null)
            {
                bodyBuffer = BinarySerializer.ToByteArray(ex);
            }
            else
            {
                bodyBuffer = EmptyBuffer;
            }

            RpcPipeHeader header;

            header.Mark        = RpcPipeHeader.MagicMark;
            header.ContextSize = contextBuffer.Length;
            header.BodySize    = bodyBuffer.Length;

            byte[] headerBuffer = RpcPipeHeader.ToByteArray(header);
            stream.Write(headerBuffer, 0, headerBuffer.Length);
            stream.Write(contextBuffer, 0, contextBuffer.Length);

            if (header.BodySize > 0)
            {
                stream.Write(bodyBuffer, 0, bodyBuffer.Length);
            }

            stream.Flush();
        }
Пример #12
0
        public void TestLoadingRunAndStoreSamples()
        {
            CreateAllSamples();
            var path       = SamplesUtils.SamplesDirectory;
            var serializer = new ProtoBufSerializer();

            foreach (var fileName in Directory.EnumerateFiles(path, "*.hl"))
            {
                var original = serializer.Deserialize(fileName);

                var exec = original as IExecutable;
                if (exec != null)
                {
                    exec.Paused += (sender, e) => {
                        serializer.Serialize(exec, fileName + "_paused.proto");
                        Console.WriteLine("Serialized paused file: " + fileName);
                        File.Delete(fileName + "_paused.proto");
                    };
                    exec.Stopped += (sender, e) => {
                        serializer.Serialize(exec, fileName + "_stopped.proto");
                        Console.WriteLine("Serialized stopped file: " + fileName);
                        File.Delete(fileName + "_stopped.proto");
                    };
                    var t = exec.StartAsync();
                    System.Threading.Thread.Sleep(20000);              // wait 20 secs
                    if (exec.ExecutionState == ExecutionState.Started) // only if not already stopped
                    {
                        exec.Pause();
                    }
                }
            }
        }
Пример #13
0
    public bool DeserializeMessage(StreamBuffer streamBuffer, int start, int len,
                                   ref int msgLen, ref HjSendMsgDef msgObj)
    {
        msgObj = default(HjSendMsgDef);
        msgLen = 0;
        if (len < sizeof(int))
        {
            return(false);
        }

        byte[] data = streamBuffer.GetBuffer();
        int    _len = BitConverter.ToInt32(data, start);

        if (len < _len + sizeof(int))
        {
            return(false);
        }
        msgLen = _len + sizeof(int);

        start += sizeof(int);
        MemoryStream ms = streamBuffer.memStream;
        BinaryReader br = streamBuffer.binaryReader;

        ms.Seek(start, SeekOrigin.Begin);

        uint requestSeq = br.ReadUInt32();

        msgObj.requestSeq = requestSeq;
        msgObj.msgProto   = ProtoBufSerializer.Deserialize(ms, typeof(ntf_battle_frame_data), _len - sizeof(int));
        return(true);
    }
Пример #14
0
        private bool IsSerializable(KeyValuePair <string, object> variable)
        {
            Type type         = null;
            bool serializable = false;

            if (variable.Value != null)
            {
                type = variable.Value.GetType();
                if (serializableLookup.TryGetValue(type, out serializable))
                {
                    return(serializable);
                }
                if (StorableTypeAttribute.IsStorableType(type))
                {
                    return(serializableLookup[type] = true);
                }
            }

            var ser = new ProtoBufSerializer();

            try {
                using (var memStream = new MemoryStream()) {
                    ser.Serialize(variable.Value, memStream); // try to serialize to memory stream
                    serializable = true;
                }
            } catch (PersistenceException) {
                serializable = false;
            }

            if (type != null)
            {
                serializableLookup[type] = serializable;
            }
            return(serializable);
        }
Пример #15
0
        public void TestProtoBufSerializerSerialize()
        {
            // Arrange
            ProtoBufSerializerTestEntity entity = new ProtoBufSerializerTestEntity
            {
                PartitionKey = "KE",
                RowKey = "Hello",
                Name = "Kevin",
                Number = 5
            };
            ProtoBufSerializer serializer = new ProtoBufSerializer();

            // Act
            byte[] b = serializer.Serialize(entity);

            // Assert
            Assert.AreEqual(9, b.Length);
            Assert.AreEqual(10, b[0]);
            Assert.AreEqual(5, b[1]);
            Assert.AreEqual(75, b[2]);
            Assert.AreEqual(101, b[3]);
            Assert.AreEqual(118, b[4]);
            Assert.AreEqual(105, b[5]);
            Assert.AreEqual(110, b[6]);
            Assert.AreEqual(16, b[7]);
            Assert.AreEqual(5, b[8]);
        }
Пример #16
0
 public void OnAfterDeserialize()
 {
     if (bytes != null)
     {
         logs = ProtoBufSerializer.DeserializeFromBytes <LogCollection>(bytes);
     }
 }
Пример #17
0
        static void Main(string[] args)
        {
            // Create ProtoBuf serializer.
            ISerializer aSerializer = new ProtoBufSerializer();

            // Create message receiver.
            IDuplexTypedMessagesFactory aReceiverFactory = new DuplexTypedMessagesFactory(aSerializer);
            IDuplexTypedMessageReceiver<ResponseMessage, RequestMessage> aReceiver =
                aReceiverFactory.CreateDuplexTypedMessageReceiver<ResponseMessage, RequestMessage>();

            // Subscribe to process request messages.
            aReceiver.MessageReceived += OnMessageReceived;

            // Use TCP for the communication.
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            IDuplexInputChannel anInputChannel =
                aMessaging.CreateDuplexInputChannel("tcp://127.0.0.1:4502/");

            // Attach the input channel to the receiver and start listening.
            aReceiver.AttachDuplexInputChannel(anInputChannel);

            Console.WriteLine("The calculator service is running. Press ENTER to stop.");
            Console.ReadLine();

            // Detach the input channel to stop listening.
            aReceiver.DetachDuplexInputChannel();
        }
Пример #18
0
        public void ProtoBufSerializer_Deserialize_GivenNullInput_ShouldReturnNull()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var result             = protoBufSerializer.Deserialize <object>(null);

            Assert.IsNull(result);
        }
        protected override IStorableContent LoadContent(string filename, out Info info)
        {
            bool             useOldPersistence = XmlParser.CanOpen(filename);
            IStorableContent content           = null;

            if (useOldPersistence)
            {
                var sw = new Stopwatch();
                sw.Start();
                content = XmlParser.Deserialize <IStorableContent>(filename);
                sw.Stop();
                info = new Info(filename, sw.Elapsed);
            }
            else
            {
                var ser = new ProtoBufSerializer();
                content = (IStorableContent)ser.Deserialize(filename, out SerializationInfo serInfo);
                info    = new Info(filename, serInfo);
            }
            if (content == null)
            {
                throw new PersistenceException($"Cannot deserialize root element of {filename}");
            }
            return(content);
        }
Пример #20
0
        private static IServiceProxyManager Init(string host, int port, string localHost, int?localPort)
        {
            var proxyName = "XNodeDemoService";

            LoggerManager.ClientLoggerFactory.AddConsole(LogLevel.Information);
            var serializer = new ProtoBufSerializer(LoggerManager.ClientLoggerFactory);      //new MsgPackSerializer(LoggerManager.ClientLoggerFactory);
            var nodeClientParametersList = new List <NodeClientParameters>()
            {
                new NodeClientParameters()
                {
                    Host          = host,
                    Port          = port,
                    LocalHost     = localHost,
                    LocalPort     = localPort,
                    Serializer    = serializer,
                    Communication = new DotNettyClient(host, port),
                    LoginHandler  = new DefaultLoginHandler(new DefaultLoginHandlerConfig()
                    {
                        AccountName = "Test01",
                        AccountKey  = "123456"
                    }, serializer)
                }
            };

            var nodeClientContainer = new DefaultNodeClientContainer();

            foreach (var c in nodeClientParametersList)
            {
                nodeClientContainer.Add(new DefaultNodeClient(c));
            }

            var serviceProxy = new ServiceProxy(proxyName, null, null, nodeClientContainer)
                               .AddService <ICustomerService>()
                               .AddService <OrderService>()
                               .EnableAll();

            var serviceProxyManager = new ServiceProxyManager();

            serviceProxyManager.Regist(serviceProxy);

            serviceProxyManager.ConnectAsync().Wait();

            var builder = new ContainerBuilder();

            builder.Register(c => new ServiceProxyInterceptor(serviceProxyManager));
            builder.RegisterType <CustomerService>()
            .As <ICustomerService>()
            .EnableInterfaceInterceptors()          //接口拦截
            .InterceptedBy(typeof(ServiceProxyInterceptor))
            .SingleInstance();
            builder.RegisterType <OrderService>()
            //.As<IOrderService>()
            .EnableClassInterceptors()              //类拦截
            .InterceptedBy(typeof(ServiceProxyInterceptor))
            .SingleInstance();

            container = builder.Build();
            return(serviceProxyManager);
        }
Пример #21
0
        public void Deserialize()
        {
            var serializer = new ProtoBufSerializer();

            using (var memStream = new MemoryStream(buffer)) {
                var obj = serializer.Deserialize(memStream);
            }
        }
Пример #22
0
 private void LoadSample(string name, Assembly assembly, ListViewGroup group, int count)
 {
     using (var stream = assembly.GetManifestResourceStream(name)) {
         var serializer = new ProtoBufSerializer();
         var item       = (NamedItem)serializer.Deserialize(stream, false);
         OnSampleLoaded(item, group, 1.0 / count);
     }
 }
Пример #23
0
        public static byte[] Serialize(object obj, out IEnumerable <Type> types)
        {
            var ser   = new ProtoBufSerializer();
            var bytes = ser.Serialize(obj, out SerializationInfo info);

            types = info.SerializedTypes;
            return(bytes);
        }
Пример #24
0
        public void ProtoBufSerializer_Serialize_GivenValidReferenceTypeInput_ShouldReturnBytes()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var input = "test";
            var result = protoBufSerializer.Serialize(input);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Length > 0);
        }
Пример #25
0
        public void ProtoBufSerializer_Serialize_GivenValidReferenceTypeInput_ShouldReturnBytes()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var input  = "test";
            var result = protoBufSerializer.Serialize(input);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Length > 0);
        }
Пример #26
0
        private static IServiceProxyManager InitWithConfig()
        {
            string path = Path.Combine(Directory.GetCurrentDirectory(), "config_simple.json");

            var configRoot = new ConfigurationBuilder()
                             .AddJsonFile(path)
                             .Build();

            var globalConfig = configRoot.GetGlobalConfig();

            GlobalSettings.Apply(globalConfig);

            var clientConfig = configRoot.GetClientConfig();

            LoggerManager.ClientLoggerFactory.AddConsole(LogLevel.Error);

            //var serializer = new MsgPackSerializer(LoggerManager.ClientLoggerFactory);
            var serializer = new ProtoBufSerializer(LoggerManager.ClientLoggerFactory);

            var serviceCaller = new ServiceCallerBuilder()
                                .UseDefault()
                                .Build();

            var serviceProxyManager = new ServiceProxyManager();

            foreach (var serviceProxyConfig in clientConfig.ServiceProxies)
            {
                var serviceProxy = new ServiceProxy(
                    serviceProxyConfig.ProxyName,
                    serviceProxyConfig?.Services,
                    serviceCaller)
                                   .AddServices(serviceProxyConfig.ProxyTypes)
                                   .AddClients(
                    new NodeClientBuilder()
                    .ConfigConnections(serviceProxyConfig.Connections)
                    .ConfigSerializer(serializer)
                    .ConfigLoginHandler(new DefaultLoginHandler(configRoot.GetDefaultLoginHandlerConfig(serviceProxyConfig.ProxyName), serializer))
                    .UseDotNetty()
                    .Build()
                    );
                serviceProxyManager.Regist(serviceProxy);
            }

            serviceProxyManager.ConnectAsync().Wait();

            var builder = new ContainerBuilder();

            builder.Register(c => new ServiceProxyInterceptor(serviceProxyManager));
            builder.RegisterType <SimpleService>()
            .As <ISimpleService>()
            .EnableInterfaceInterceptors()          //接口拦截
            .InterceptedBy(typeof(ServiceProxyInterceptor))
            .SingleInstance();

            container = builder.Build();
            return(serviceProxyManager);
        }
Пример #27
0
        void IRpcClientTransaction.SendRequest <T>(RpcRequestHeader request, T args, Action <RpcResponseHeader> callback, int timeout)
        {
            _callback   = callback;
            _serviceUrl = string.Format("{0}/{1}.{2}", request.ServerUri, request.Service, request.Method);

            _webRequest             = HttpWebRequest.Create(_serviceUrl);
            _webRequest.Method      = "POST";
            _webRequest.Proxy       = null;
            _webRequest.ContentType = "multipart/byteranges";
            _webRequest.Headers.Add(HttpRequestHeader.From, request.ServiceAtComputer);
            _webRequest.Headers.Add(HttpRequestHeader.Pragma, _serviceUrl);
            _webRequest.Headers.Add(HttpRequestHeader.Cookie, "to=" + ObjectHelper.ToString(request.ToUri));

            byte[] buffer = null;
            if (!request.HasBody)
            {
                _webRequest.Headers.Add("Null", "true");
                _webRequest.ContentLength = 0;
            }
            else
            {
                buffer = ProtoBufSerializer.ToByteArray <T>(args);
                _webRequest.ContentLength = buffer.Length;
            }

            timeout = timeout > 0 ? timeout : _channel.Timeout;

            if (timeout > 0)
            {
                _waitHandle = new ManualResetEvent(false);
                ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(TimeoutCallback), this, timeout, true);
            }
            if (_webRequest.ContentLength == 0)
            {
                _webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
            }
            else
            {
                _webRequest.BeginGetRequestStream(
                    delegate(IAsyncResult asyncResult) {
                    try {
                        Stream stream = _webRequest.EndGetRequestStream(asyncResult);
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Close();
                        _webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
                    } catch (Exception ex) {
                        var resp = RpcResponseHeader.CreateError(RpcErrorCode.SendFailed, ex);
                        _callback(resp);
                    }
                },
                    this
                    );
            }
        }
 public T ReceiveResponse <T>()
 {
     if (_context.HasBody)
     {
         return(ProtoBufSerializer.FromByteArray <T>(_bodyBuffer));
     }
     else
     {
         return(default(T));
     }
 }
Пример #29
0
        public void ProtoBufSerializer_Deserialize_GivenValidValueType_ShouldReturnValueType()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var input = 123;
            var serialized = protoBufSerializer.Serialize(input);

            var deserialized = protoBufSerializer.Deserialize<int>(serialized);

            Assert.IsNotNull(deserialized);
            Assert.AreEqual(123, deserialized);
        }
Пример #30
0
        public void ProtoBufSerializer_Deserialize_GivenValidReferenceType_ShouldReturnReferenceType()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var input      = "test";
            var serialized = protoBufSerializer.Serialize(input);

            var deserialized = protoBufSerializer.Deserialize <string>(serialized);

            Assert.IsNotNull(deserialized);
            Assert.AreEqual("test", deserialized);
        }
Пример #31
0
        public void ProtoBufSerializer_Deserialize_GivenValidValueType_ShouldReturnValueType()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var input      = 123;
            var serialized = protoBufSerializer.Serialize(input);

            var deserialized = protoBufSerializer.Deserialize <int>(serialized);

            Assert.IsNotNull(deserialized);
            Assert.AreEqual(123, deserialized);
        }
Пример #32
0
        public void ProtoBufSerializer_Deserialize_GivenValidReferenceType_ShouldReturnReferenceType()
        {
            var protoBufSerializer = new ProtoBufSerializer();
            var input = "test";
            var serialized = protoBufSerializer.Serialize(input);

            var deserialized = protoBufSerializer.Deserialize<string>(serialized);

            Assert.IsNotNull(deserialized);
            Assert.AreEqual("test", deserialized);
        }
Пример #33
0
 protected T CloneByPersistence <T>(T value)
 {
     using (var serializerStream = new MemoryStream()) {
         var serializer = new ProtoBufSerializer();
         serializer.Serialize(value, serializerStream, disposeStream: false);
         var bytes = serializerStream.GetBuffer();
         using (var deserializerStream = new MemoryStream(bytes)) {
             return((T)serializer.Deserialize(deserializerStream));
         }
     }
 }
Пример #34
0
        public void ProtoBufSerializer_Primitives <T>(T value)
        {
            // arrange
            var serializer = new ProtoBufSerializer();

            // act
            var data   = serializer.Serialize(value);
            var result = serializer.Deserialize(data, typeof(T));

            result.Should().Be(value);
        }
 public T ReceiceRequest <T>()
 {
     if (_context.HasBody)
     {
         return(ProtoBufSerializer.FromByteArray <T>(_buffer));
     }
     else
     {
         return(default(T));
     }
 }
Пример #36
0
 public T ReceiceRequest <T>()
 {
     if (_httpContext.Request.ContentLength64 == 0)
     {
         return(ProtoBufSerializer.Deserialize <T>(RpcNull.EmptyStream));
     }
     else
     {
         return(ProtoBufSerializer.Deserialize <T>(_httpContext.Request.InputStream));
     }
 }
Пример #37
0
        public void TestSerialize()
        {
            var serializer = new ProtoBufSerializer();

            var t = serializer.Serialize(new VPb
            {
                A = 10,
                B = 20,
            });

            Assert.AreNotEqual(t, null);
        }
Пример #38
0
        public void ProtoBufSerializer_Pocco()
        {
            // arrange
            var serializer = new ProtoBufSerializer();
            var item       = SerializerPoccoSerializable.Create();

            // act
            var data   = serializer.Serialize(item);
            var result = serializer.Deserialize(data, item.GetType());

            result.ShouldBeEquivalentTo(item);
        }
Пример #39
0
        public void TestProtoBufSerializerDeserialize()
        {
            // Arrange
            byte[] b = { 10, 5, 75, 101, 118, 105, 110, 16, 5 };
            ProtoBufSerializer serializer = new ProtoBufSerializer();

            // Act
            ProtoBufSerializerTestEntity entity = serializer.Deserialize<ProtoBufSerializerTestEntity>(b);

            // Assert
            Assert.AreEqual("Kevin", entity.Name);
            Assert.AreEqual(5, entity.Number);
        }
Пример #40
0
        public Cache CreateCache()
        {
            ISerializer serializer = null;
            switch (this._serializerType)
            {
                case SerializerType.ProtoBufNet:
                    serializer = new ProtoBufSerializer();
                    break;
                case SerializerType.Json:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            ILocalCacheAdapter firstLevelCache = null;

            switch (this._firstLevelCacheType)
            {
                case FirstLevelCacheType.None:
                    break;
                case FirstLevelCacheType.ConcurrentDictionary:
                    firstLevelCache = new DictionaryCacheAdapter();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }

            IDistributedCacheAdapter secondLevelCache = null;
            IMessenger messenger = null;
            switch (this._secondLevelCacheType)
            {
                case SecondLevelCacheType.None:
                    break;
                case SecondLevelCacheType.Redis:
                    if (this._redisInstances == null || !this._redisInstances.Any())
                        throw new ArgumentNullException("Missing redis instances configurations");
                    var redis = new RedisCacheAdapter(this._redisInstances, this._redisDatabase, serializer);
                    secondLevelCache = redis;
                    messenger = redis;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return new Cache(firstLevelCache, secondLevelCache, messenger);
        }
Пример #41
0
        private void OpenConnection()
        {
            // Create Protocol Buffers serializer.
            ISerializer aSerializer = new ProtoBufSerializer();

            // Create the synchronous message sender.
            // It will wait max 5 seconds for the response.
            // To wait infinite time use TimeSpan.FromMiliseconds(-1) or
            // default constructor new DuplexTypedMessagesFactory()
            IDuplexTypedMessagesFactory aSenderFactory =
                new DuplexTypedMessagesFactory(TimeSpan.FromSeconds(5), aSerializer);
            mySender = aSenderFactory.CreateSyncDuplexTypedMessageSender<ResponseMessage, RequestMessage>();

            // Use TCP for the communication.
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            IDuplexOutputChannel anOutputChannel =
                aMessaging.CreateDuplexOutputChannel("tcp://127.0.0.1:4502/");

            // Attach the output channel and be able to send messages
            // and receive response messages.
            mySender.AttachDuplexOutputChannel(anOutputChannel);
        }
Пример #42
0
        static void Main(string[] args)
        {
            // Create ProtoBuf serializer.
            ISerializer aSerializer = new ProtoBufSerializer();

            // Create the broker.
            IDuplexBrokerFactory aBrokerFactory = new DuplexBrokerFactory(aSerializer);
            IDuplexBroker aBroker = aBrokerFactory.CreateBroker();

            // Create the Input channel receiving messages via Tcp.
            // Note: You can also choose NamedPipes or Http.
            //       (if you choose http, do not forget to execute it with sufficient user rights)
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            IDuplexInputChannel aBrokerInputChannel = aMessaging.CreateDuplexInputChannel("tcp://127.0.0.1:7091/");

            aBroker.AttachDuplexInputChannel(aBrokerInputChannel);

            // Attach the input channel to the broker and start listening.
            Console.WriteLine("The broker application is running. Press ENTER to stop.");
            Console.ReadLine();

            aBroker.DetachDuplexInputChannel();
        }
        private IDuplexTypedMessagesFactory CreateReceiverFactory()
        {
            ISerializer protoBufSerializer = new ProtoBufSerializer();

               // ISerializer wrappingSerializer = _proxyGenerator.CreateInterfaceProxyWithTarget<ISerializer>(jsonSerializer, this);

            return new DuplexTypedMessagesFactory(protoBufSerializer);
        }