Esempio n. 1
0
        static void Main(string[] args)
        {
            var messageSerializer = new MessageSerializer();
              var messageBodySerializer = new MessageBodySerializer();
              var messageFactory = new MessageFactory();
              var pathFactory = new PathFactory();
              var broker = new Broker(1337,
                              messageSerializer,
                              messageBodySerializer,
                              messageFactory,
                              pathFactory);
              var messageObserver = new MessageObserver<Foo>(broker.ID,
                                                     messageBodySerializer)
                            {
                              InterceptRemoteMessagesOnly = false,
                              InterceptOnNext = foo =>
                                                {
                                                  // TODO what to do next ...
                                                }
                            };
              broker.Subscribe(messageObserver);
              broker.Start();

              broker.Publish(new Foo
                     {
                       Bar = "hello" // Not L10N
                     });

              Console.ReadLine();
        }
        public void CanDeserializeXmlWithWhitespace()
        {
            var str =
              @"<?xml version=""1.0"" encoding=""utf-8""?>
            <Messages xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://tempuri.net/NServiceBus.Serializers.XML.Test"" xmlns:baseType=""NServiceBus.Saga.ISagaMessage"">
            <MessageWithArray>
            <SagaId>6bddc475-22a5-433b-a3ed-9edf00e8e353</SagaId>
            <SomeInts>
            <Int32>1405154</Int32>
            </SomeInts>
            </MessageWithArray>
            </Messages>";

            var data = Encoding.UTF8.GetBytes(str);

            var serializer = new MessageSerializer
            {
                MessageMapper = new MessageMapper(),
                MessageTypes = new List<Type> { typeof(MessageWithArray) }
            };

            var messages = serializer.Deserialize(new MemoryStream(data));

            Assert.NotNull(messages);
            Assert.That(messages, Has.Length.EqualTo(1));

            Assert.That(messages[0], Is.TypeOf(typeof(MessageWithArray)));
            var m = (MessageWithArray)messages[0];

            Assert.IsNotNull(m.SomeInts);
            Assert.That(m.SomeInts, Has.Length.EqualTo(1));
        }
Esempio n. 3
0
 public ServiceBusClient(Uri address, IWebTokenProvider tokenManager, IWebClient webClient)
 {
     _address = address;
     _tokenManager = tokenManager;
     _webClient = webClient;
     _webRequestFactory = new WebRequestFactory(tokenManager);
     _serializer = new MessageSerializer();
 }
Esempio n. 4
0
        /// <summary>
        /// Creates a message sender.
        /// </summary>
        /// <param name="serverAddress">The address of server that messages will be send to.</param>
        public MessageSender(IPEndPoint serverAddress)
        {
            _servers = new List<ServerInfo>();
            _tcpClient = new TcpClient(serverAddress);

            var validator = new MessageValidator();
            var serializer = new MessageSerializer();
            _marshaller = new Marshaller(serializer, validator);
        }
Esempio n. 5
0
 private static object EncoderTest(MessageSerializer target, IExtensible msg)
 {
     byte[] buf1 = target.Serialize(msg);
     byte[] buf2 = target.Serialize(target.Deserialize(buf1));
     Assert.IsNotNull(buf1);
     Assert.IsNotNull(buf2);
     Assert.AreEqual(buf1.Length, buf2.Length);
     Assert.IsTrue(buf1.SequenceEqual(buf2));
     return msg;
 }
Esempio n. 6
0
        public void Using_xml_message_serialization()
        {
            IMessageMapper mapper = new MessageMapper();
            var serializer = new MessageSerializer
                                 {
                                     MessageMapper = mapper,
                                     MessageTypes = new List<Type>(new[] { typeof(TestMessage) })
                                 };

            ExecuteAndVerify(serializer);
        }
Esempio n. 7
0
        public MessageProcessorTests()
        {
            var serializer = new MessageSerializer();
            var validator = new MessageValidator();
            _marshaller = new Marshaller(serializer, validator);

            _overseer = new ComponentOverseer(5, 1);
            _workManager = new WorkManager(_overseer);

            _processor = new MessageProcessor(_overseer, _workManager);
        }
Esempio n. 8
0
 /// <summary>
 /// Publish a message.
 /// </summary>
 /// <param name="messageType">Type of the message.</param>
 /// <param name="message">The message to publish.</param>
 /// <param name="routingKey">The routingkey to use (RabbitMQ specific).</param>
 public Task PublishMessageAsync(string messageType, object message, string routingKey)
 {
     return(Task.Run(() =>
     {
         string data = MessageSerializer.Serialize(message);
         var body = Encoding.UTF8.GetBytes(data);
         IBasicProperties properties = _model.CreateBasicProperties();
         properties.Headers = new Dictionary <string, object> {
             { "MessageType", messageType }
         };
         _model.BasicPublish(_exchange, routingKey, properties, body);
     }));
 }
Esempio n. 9
0
        internal void SendMessage(Socket handler, BaseMessage message)
        {
            var messageData = MessageSerializer.SerializeAndWrapMessage(message);

            try
            {
                handler.BeginSend(messageData, 0, messageData.Length, SocketFlags.None, new AsyncCallback(SendCallback), handler);
            }
            catch (Exception e)
            {
                throw new CommunicationErrorException(CommunicationExceptionType.InvalidSocket, e);
            }
        }
        public async Task PostTransaction_GenerateInvalidMutations()
        {
            Mutation generatedMutation = MessageSerializer.DeserializeMutation(CreateMutation(invalidNamespace));

            TransactionValidator validator = CreateValidator(defaultAccounts, generatedMutation);
            ByteString           mutation  = CreateMutation(validNamespace);

            TransactionInvalidException exception = await Assert.ThrowsAsync <TransactionInvalidException>(
                () => validator.PostTransaction(mutation, new SignatureEvidence[0]));

            Assert.Equal("InvalidNamespace", exception.Reason);
            Assert.Equal(null, store.AddedTransactions);
        }
Esempio n. 11
0
        public async Task <bool> HandleMessageAsync(string messageType, string message)
        {
            JObject messageObject = MessageSerializer.Deserialize(message);

            switch (messageType)
            {
            case "CustomerRegistered":
                await HandleAsync(messageObject.ToObject <StatusReceived>());

                break;
            }
            return(true);
        }
Esempio n. 12
0
        private async Task <ByteString> AddTransaction(params Record[] records)
        {
            Mutation    mutation           = new Mutation(ByteString.Parse("0123"), records, ByteString.Parse("4567"));
            ByteString  serializedMutation = new ByteString(MessageSerializer.SerializeMutation(mutation));
            Transaction transaction        = new Transaction(
                serializedMutation,
                new DateTime(1, 2, 3, 4, 5, 6),
                ByteString.Parse("abcdef"));

            await this.store.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(transaction)) });

            return(new ByteString(MessageSerializer.ComputeHash(serializedMutation.ToByteArray())));
        }
Esempio n. 13
0
        public List <SensorInfoMessage> GetDailyReport()
        {
            var endTime   = DateTime.Now;
            var startTime = endTime.AddDays(-1);

            var endFileName   = endTime.ToString("yyyy-MM-dd") + ".txt";
            var startFileName = startTime.ToString("yyyy-MM-dd") + ".txt";

            var fileList = new List <string> {
                startFileName, endFileName
            };

            var dailyData = new List <SensorInfoMessage>();

            foreach (var fileName in fileList)
            {
                if (File.Exists(fileName))
                {
                    using (var fs = File.OpenRead(fileName))
                    {
                        using (var sr = new StreamReader(fs))
                        {
                            var lineString = sr.ReadLine();

                            while (!string.IsNullOrEmpty(lineString))
                            {
                                var args = lineString.Split(' ');

                                var messageTime = DateTime.ParseExact(args[0], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

                                if (messageTime >= startTime || messageTime <= endTime)
                                {
                                    var message = MessageSerializer.Deserialize(args[1]);

                                    message.MessageTime = messageTime;

                                    if (message is SensorInfoMessage)
                                    {
                                        dailyData.Add(message as SensorInfoMessage);
                                    }
                                }

                                lineString = sr.ReadLine();
                            }
                        }
                    }
                }
            }

            return(dailyData);
        }
        /// <summary>
        /// Prepares a message for sending based on the rules of this channel binding element.
        /// </summary>
        /// <param name="message">The message to prepare for sending.</param>
        /// <returns>
        /// True if the <paramref name="message"/> applied to this binding element
        /// and the operation was successful.  False otherwise.
        /// </returns>
        /// <remarks>
        /// Implementations that provide message protection must honor the
        /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
        /// </remarks>
        public bool PrepareMessageForSending(IProtocolMessage message)
        {
            ErrorUtilities.VerifyArgumentNotNull(message, "message");

            var extendableMessage = message as IProtocolMessageWithExtensions;

            if (extendableMessage != null)
            {
                Protocol          protocol = Protocol.Lookup(message.Version);
                MessageDictionary baseMessageDictionary = new MessageDictionary(message);

                // We have a helper class that will do all the heavy-lifting of organizing
                // all the extensions, their aliases, and their parameters.
                var extensionManager = ExtensionArgumentsManager.CreateOutgoingExtensions(protocol);
                foreach (IExtensionMessage protocolExtension in extendableMessage.Extensions)
                {
                    var extension = protocolExtension as IOpenIdMessageExtension;
                    if (extension != null)
                    {
                        // Give extensions that require custom serialization a chance to do their work.
                        var customSerializingExtension = extension as IMessageWithEvents;
                        if (customSerializingExtension != null)
                        {
                            customSerializingExtension.OnSending();
                        }

                        // OpenID 2.0 Section 12 forbids two extensions with the same TypeURI in the same message.
                        ErrorUtilities.VerifyProtocol(!extensionManager.ContainsExtension(extension.TypeUri), OpenIdStrings.ExtensionAlreadyAddedWithSameTypeURI, extension.TypeUri);

                        var extensionDictionary = MessageSerializer.Get(extension.GetType()).Serialize(extension);
                        extensionManager.AddExtensionArguments(extension.TypeUri, extensionDictionary);
                    }
                    else
                    {
                        Logger.WarnFormat("Unexpected extension type {0} did not implement {1}.", protocolExtension.GetType(), typeof(IOpenIdMessageExtension).Name);
                    }
                }

                // We use a cheap trick (for now at least) to determine whether the 'openid.' prefix
                // belongs on the parameters by just looking at what other parameters do.
                // Technically, direct message responses from Provider to Relying Party are the only
                // messages that leave off the 'openid.' prefix.
                bool includeOpenIdPrefix = baseMessageDictionary.Keys.Any(key => key.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal));

                // Add the extension parameters to the base message for transmission.
                extendableMessage.AddExtraParameters(extensionManager.GetArgumentsToSend(includeOpenIdPrefix));
                return(true);
            }

            return(false);
        }
Esempio n. 15
0
        public static TResponse SendRequest <TRequest, TResponse>(int code, TRequest request)
            where TRequest : RequestBase
            where TResponse : ResponseBase, new()
        {
            PluginEntry.Context.Logger.Info($"调用接口:【{code}】");

            var response = new TResponse();

            try
            {
                if (string.IsNullOrEmpty(request.HospitalCode))
                {
                    throw new Exception("医疗机构编号不能为空!");
                }

                if (!isInit && !PluginEntry.YibaoSetting.IsTest)
                {
                    PluginEntry.Context.Logger.Info($"接口初始化");
                    Init(request.HospitalCode);
                    isInit = true;
                }

                string inputData = MessageSerializer.SerializeRequest(request);

                PluginEntry.Context.Logger.Info($"【{code}】输入: {inputData}");
                StringBuilder retMsg = new StringBuilder(4096);
                waitHandler.WaitOne(3000);
                int result = YibaoApi.f_UserBargaingApply(code, 0, inputData, retMsg, request.HospitalCode);
                waitHandler.Set();
                string value = retMsg.ToString().Trim();
                PluginEntry.Context.Logger.Info($"【{code}】返回值: {result} 输出: {value}");

                if (result == 0)
                {
                    response = MessageSerializer.Deserialize <TResponse>(value);
                }
                else
                {
                    response.IsSuccess     = false;
                    response.ResultMessage = "交易失败";
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess     = false;
                response.ResultMessage = ex.Message;
                PluginEntry.Context.Logger.Error($"【{code}】错误", ex);
            }

            return(response);
        }
Esempio n. 16
0
        public async Task <bool> HandleMessageAsync(string messageType, string message)  // MEssage type can be refactored so that there is only one type of message, e.g NotificaiotnMessage
        {
            JObject messageObject = MessageSerializer.Deserialize(message);

            try
            {
                switch (messageType)
                {
                case "NotificationEvent":
                    await HandleAsync(messageObject.ToObject <NotificationEvent>());

                    break;

                    // All the rest will NOT be used as they are integrated with the above message type
                    #region
                case "RegisterAccountEvent":
                    await HandleAsync(messageObject.ToObject <RegisterAccountEvent>());

                    break;

                case "":
                    //await HandleAsync(messageObject.ToObject<LeaseFinalizedEvent>());
                    break;

                case "RentalPropertyStatusChangeEvent":
                    //await HandleAsync(messageObject.ToObject<RentalPropertyStatusChangeEvent>());
                    break;

                case "EnableOnlineAccessEvent":
                    await HandleAsync(messageObject.ToObject <EnableOnlineAccessEvent>());

                    break;

                    #endregion
                default:
                    Console.WriteLine("Default case");
                    break;
                }
            }
            catch (Exception ex)
            {
                string messageId = messageObject.Property("MessageId") != null?messageObject.Property("MessageId").Value <string>() : "[unknown]";

                Log.Error(ex, "Error while handling {MessageType} message with id {MessageId}.", messageType, messageId); // message to be updated
            }

            // always akcnowledge message - any errors need to be dealt with locally.
            return(true);

            //throw new NotImplementedException();
        }
Esempio n. 17
0
        private void SendToFailoverQueue(TransportMessage transportMessage, string destination)
        {
            Message toSend = new Message();

            if (transportMessage.Body == null && transportMessage.BodyStream != null)
            {
                toSend.BodyStream = transportMessage.BodyStream;
            }
            else
            {
                MessageSerializer.Serialize(transportMessage.Body, toSend.BodyStream);
            }

            if (transportMessage.CorrelationId != null)
            {
                toSend.CorrelationId = transportMessage.CorrelationId;
            }
            else
            {
                toSend.CorrelationId              = toSend.Id;
                transportMessage.CorrelationId    = toSend.Id;
                transportMessage.IdForCorrelation = toSend.Id;
            }

            toSend.Recoverable   = transportMessage.Recoverable;
            toSend.ResponseQueue = new MessageQueue(GetFullPath(transportMessage.ReturnAddress));
            FillLabel(toSend, transportMessage);

            if (transportMessage.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            {
                toSend.TimeToBeReceived = transportMessage.TimeToBeReceived;
            }

            if (transportMessage.Headers == null)
            {
                transportMessage.Headers = new List <HeaderInfo>();
            }

            transportMessage.Headers.Add(new HeaderInfo {
                Key = "destination", Value = destination
            });

            if (transportMessage.Headers != null && transportMessage.Headers.Count > 0)
            {
                MemoryStream stream = new MemoryStream();
                HeaderSerializer.Serialize(stream, transportMessage.Headers);
                toSend.Extension = stream.GetBuffer();
            }

            FailoverQueue.Send(toSend, GetTransactionTypeForSend());
        }
        public void Deserialize_EmptyMessage_ThrowsException()
        {
            // arrange
            var typeProvide = new Mock <ITypeProvider>();

            typeProvide.Setup(x => x.GetMessageType(It.IsAny <string>())).Returns(typeof(FakeMessage));
            var serializer           = new MessageSerializer(typeProvide.Object);
            var emptyBrokeredMessage = new Message();

            emptyBrokeredMessage.UserProperties.Add(CustomMessageProperties.MessageTypeProperty, "test");

            // act/assert
            Assert.Throws <ArgumentNullException>(() => serializer.Deserialize <IMessage>(emptyBrokeredMessage));
        }
Esempio n. 19
0
        internal string GetProcessesData(string origin)
        {
            List <RemoteProcessData> res = new List <RemoteProcessData>();

            foreach ((string stateName, BaseClientState _) in this.States)
            {
                if (!stateName.Equals(origin))
                {
                    res.Add(new RemoteProcessData(stateName));
                }
            }

            return(MessageSerializer.SerializeData(res));
        }
Esempio n. 20
0
    public override void Process(MessageSerializer serializer, IMessage msg)
    {
        respLogin rsp = (respLogin)msg;


        Debug.Log("SigninProcessor:" + rsp.Retcode);

        //do send message
        //Intent i = new Intent(BaseProcessor.MessageFilter);
        //i.putExtra(Intent.EXTRA_TEXT,rsp.getName() + " " + rsp.getSucc());

        ////i.setData()
        //MainActivity.Instance.sendBroadcast(i);
    }
Esempio n. 21
0
        public async Task <bool> HandleMessageAsync(MessageTypes messageType, string message)
        {
            JObject messageObject = MessageSerializer.Deserialize(message);

            switch (messageType)
            {
            case MessageTypes.RegisterOrder:
                await HandleAsync(messageObject.ToObject <OrderRegistered>());

                break;
            }

            return(true);
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            string url = "";

            if (args.Length >= 1)
            {
                url = args[0];
            }
            else
            {
                url = "127.0.0.1";//"tyrenus.gamextasy.com";
            }

            SimpleDispatcher dispatcher;
            MessageTcpClient client;

            dispatcher = SimpleDispatcher.CurrentDispatcher;
            var message = new Message {
                ID = 7, Name = "abc"
            };
            var serializer = new MessageSerializer();

            serializer.Register <Message>();

            // 初始化client
            client = new MessageTcpClient(serializer, (session, o) =>
            {
                dispatcher.Invoke(() =>
                {
                    Console.WriteLine((o as Message).ID);
                    Console.WriteLine((o as Message).Name);
                });
            });
            client.Connected += () =>
            {
                Console.WriteLine("connected");
                client.Send(message);
            };
            client.Disconnected += (e) =>
            {
                Console.WriteLine("disconnected:" + e.Message);
            };

            var ip = System.Net.Dns.GetHostAddresses(url);

            Console.WriteLine(ip.Length);
            Console.WriteLine(ip[0]);
            client.Connect(new IPEndPoint(ip[0], 9528));
            dispatcher.Run();
        }
Esempio n. 23
0
        public void can_serialize_from_message()
        {
            var serializer = new MessageSerializer();
            var data       = serializer.ToBytes(_testEvent);
            var tcpmsg2    = serializer.FromBytes(data);

            Assert.IsType <WoftamEvent>(tcpmsg2);
            var msg2 = tcpmsg2 as WoftamEvent;

            Assert.NotNull(msg2);
            // ReSharper disable once PossibleNullReferenceException
            Assert.Equal(_testEvent.Property1, msg2.Property1);
            Assert.Equal(_testEvent.Property1, ((WoftamEvent)tcpmsg2).Property1);
        }
Esempio n. 24
0
        public ServiceModelGrpcProtoServerCallTest(SomeObject payload)
        {
            var builder = new WebHostBuilder().UseStartup <Startup>();

            _server = new TestServer(builder);
            _client = _server.CreateClient();

            var proto = DomainExtensions.CopyToProto(payload);

            _request = new StubHttpRequest(
                _client,
                "/ITestService/PingPongProto",
                MessageSerializer.Create(GoogleProtoMarshallerFactory.Default, new Message <SomeObjectProto>(proto)));
        }
        object[] Extract(TransportMessage m)
        {
            if (m.Body == null || m.Body.Length == 0)
            {
                return(new object[0]);
            }

            var messageMetadata = MessageMetadataRegistry.GetMessageTypes(m);

            using (var stream = new MemoryStream(m.Body))
            {
                return(MessageSerializer.Deserialize(stream, messageMetadata.Select(metadata => metadata.MessageType).ToList()));
            }
        }
        public void Serialize_Message_ReturnsConfiguratedMessage()
        {
            // arrange
            var serializer = new MessageSerializer();
            var message    = new FakeMessage(1);

            // act
            var brokeredMessage = serializer.Serialize(message);
            var body            = new MemoryStream(brokeredMessage.Body);

            // assert
            Assert.Equal(brokeredMessage.UserProperties[CustomMessageProperties.MessageTypeProperty], message.GetType().FullName);
            Assert.NotNull(body);
        }
Esempio n. 27
0
 public override void SerializeTo(MessageSerializer serializer)
 {
     serializer.Write(this.header);
     serializer.Write(this.height);
     serializer.Write(this.width);
     serializer.WriteLength(this.fields);
     serializer.Write(this.fields);
     serializer.Write(this.is_bigendian);
     serializer.Write(this.point_step);
     serializer.Write(this.row_step);
     serializer.WriteLength(this.data);
     serializer.Write(this.data);
     serializer.Write(this.is_dense);
 }
Esempio n. 28
0
        public MessageSubscriber(string subscriptionName, string channel, ChannelType channelType, IServiceProvider serviceProvider)
        {
            _subscriptionName = subscriptionName;
            _channel          = channel;
            _serviceProvider  = serviceProvider;
            _configuration    = serviceProvider.GetRequiredService <IConfiguration>();
            _serializer       = serviceProvider.GetRequiredService <MessageSerializer <TMessageType> >();
            _logger           = serviceProvider.GetService <ILogger <MessageSubscriber <TMessageType> > >();

            if (!_configuration.IsCodeFirstServiceBus())
            {
                InitializeClients(channelType);
            }
        }
Esempio n. 29
0
        public async Task <bool> HandleMessageAsync(MessageTypes messageType, string message)
        {
            JObject messageObject = MessageSerializer.Deserialize(message);

            if (messageObject != null)
            {
                switch (messageType)
                {
                // Events registered to the database
                case MessageTypes.CustomerRegistered:
                    await HandleAsync(messageObject.ToObject <CustomerRegistered>());

                    break;

                case MessageTypes.NewProductAdded:
                    await HandleAsync(messageObject.ToObject <NewProductAdded>());

                    break;

                case MessageTypes.TransportRegistered:
                    await HandleAsync(messageObject.ToObject <TransportRegistered>());

                    break;

                case MessageTypes.OrderPlaced:
                    await HandleAsync(messageObject.ToObject <OrderPlaced>());

                    break;

                // Events updated to the database
                case MessageTypes.ProductUpdated:
                    await HandleAsync(messageObject.ToObject <ProductUpdated>());

                    break;

                case MessageTypes.TransportUpdated:
                    await HandleAsync(messageObject.ToObject <TransportUpdated>());

                    break;

                // Events deleted to the database
                case MessageTypes.TransportRemoved:
                    await HandleAsync(messageObject.ToObject <TransportRemoved>());

                    break;
                }
            }

            return(true);
        }
Esempio n. 30
0
        public async Task <QueueMessage <T> > ReceiveAsync()
        {
            using (var message = await _messageQueue.ReceiveAsync())
            {
                var item = await MessageSerializer.Deserialize((string)message.Body);

                return(new QueueMessage <T>
                {
                    MessageId = message.Id,
                    Item = item,
                    CorrelationId = message.AppSpecific
                });
            }
        }
Esempio n. 31
0
    public void SendString(string msg)
    {
        var serializer = new MessageSerializer();

        /*
         * var debug = new DebugLogMessage {
         *      message = msg
         * };
         */
        var welcome = new WelcomeMessage();
        var bytes   = serializer.SerializeMessage(welcome);

        connection.Send(new IPEndPoint(IPAddress.Broadcast, serverPort), bytes);
    }
Esempio n. 32
0
        public void ParameterNames()
        {
            this.response.ErrorMessage = "Some Error";
            this.response.Contact      = "Andrew Arnott";
            this.response.Reference    = "http://blog.nerdbank.net/";

            MessageSerializer serializer = MessageSerializer.Get(this.response.GetType());
            var fields = this.MessageDescriptions.GetAccessor(this.response).Serialize();

            Assert.AreEqual(Protocol.OpenId2Namespace, fields["ns"]);
            Assert.AreEqual("Some Error", fields["error"]);
            Assert.AreEqual("Andrew Arnott", fields["contact"]);
            Assert.AreEqual("http://blog.nerdbank.net/", fields["reference"]);
        }
        public void MessageDeserializer_JsonFromObjectWithIdNull()
        {
            var jsonObject = new JObject
            {
                ["jsonrpc"] = "2.0",
                ["result"]  = "-3",
                ["id"]      = null,
                ["error"]   = null
            };

            var jsonMessage = MessageSerializer.FromJObject(jsonObject);

            Assert.AreEqual(MessageType.Response, jsonMessage.MessageType);
        }
Esempio n. 34
0
        public override dynamic ReadValue(BinaryReader reader)
        {
            var values    = new Dictionary <string, IMessage>();
            var mapLength = reader.ReadByte();

            for (int i = 0; i < mapLength; i++)
            {
                var messageTypeName = ReadInt8String(reader);
                var messageType     = XFireAttributeFactory.Instance.GetAttribute(reader.ReadByte()).ReadValue(reader);
                var message         = MessageSerializer.Deserialize(reader, CreateMessage(messageType));
                values.Add(messageTypeName, message);
            }
            return(values);
        }
Esempio n. 35
0
        private async Task Receive(Context context)
        {
            var stream = context.TcpClient.GetStream();

            while (_running)
            {
                // First time the client connects, an opening statement of 4 bytes is sent that needs to be ignored
                if (!context.Initialized)
                {
                    var openingStatementBuffer = new byte[4];
                    await stream.ReadAsync(openingStatementBuffer, 0, openingStatementBuffer.Length);

                    context.InitializeClient();
                }

                // Header determines size of message
                var headerBuffer = new byte[2];
                var read         = await stream.ReadAsync(headerBuffer, 0, headerBuffer.Length);

                if (read == 0)
                {
                    OnDisconnection?.Invoke(context);
                    break;
                }

                var messageLength = BitConverter.ToInt16(headerBuffer, 0) - headerBuffer.Length;
                var messageBuffer = new byte[messageLength];
                read = await stream.ReadAsync(messageBuffer, 0, messageLength);

                Debug.WriteLine("RECEIVED RAW: " + BitConverter.ToString(messageBuffer));

                try
                {
                    IMessage message = MessageSerializer.Deserialize(messageBuffer);
                    Console.WriteLine("Recv message[{0},{1}]: {2}",
                                      context.User != null ? context.User.Username : "******",
                                      context.User != null ? context.User.UserId : -1,
                                      message);
                    OnReceive?.Invoke(context, message);
                }
                catch (UnknownMessageTypeException messageTypeEx)
                {
                    Debug.WriteLine(messageTypeEx.ToString());
                }
                catch (UnknownXFireAttributeTypeException attributeTypeEx)
                {
                    Debug.WriteLine(attributeTypeEx.ToString());
                }
            }
        }
Esempio n. 36
0
        protected override void ThreadFunction()
        {
            var    mini = new MiniMessagePacker();
            object message;

            while ((message = mini.Unpack(stream)) != null)
            {
                if (!(message is Dictionary <string, object>))
                {
                    continue;
                }
                Status = MessageSerializer.Serialize((Dictionary <string, object>)message);
            }
        }
        List <LogicalMessage> Extract(TransportMessage physicalMessage)
        {
            if (physicalMessage.Body == null || physicalMessage.Body.Length == 0)
            {
                return(new List <LogicalMessage>());
            }

            string messageTypeIdentifier;
            var    messageMetadata = new List <MessageMetadata>();

            if (physicalMessage.Headers.TryGetValue(Headers.EnclosedMessageTypes, out messageTypeIdentifier))
            {
                foreach (var messageTypeString in messageTypeIdentifier.Split(';'))
                {
                    var typeString = messageTypeString;

                    if (DoesTypeHaveImplAddedByVersion3(typeString))
                    {
                        continue;
                    }

                    if (IsV4OrBelowScheduledTask(typeString))
                    {
                        typeString = typeof(ScheduledTask).AssemblyQualifiedName;
                    }

                    var metadata = MessageMetadataRegistry.GetMessageMetadata(typeString);
                    if (metadata == null)
                    {
                        continue;
                    }
                    messageMetadata.Add(metadata);
                }

                if (messageMetadata.Count == 0 && physicalMessage.MessageIntent != MessageIntentEnum.Publish)
                {
                    log.WarnFormat("Could not determine message type from message header '{0}'. MessageId: {1}", messageTypeIdentifier, physicalMessage.Id);
                }
            }

            using (var stream = new MemoryStream(physicalMessage.Body))
            {
                var messageTypesToDeserialize = messageMetadata.Select(metadata => metadata.MessageType).ToList();

                return(MessageSerializer.Deserialize(stream, messageTypesToDeserialize)
                       .Select(x => LogicalMessageFactory.Create(x.GetType(), x, physicalMessage.Headers))
                       .ToList());
            }
        }
Esempio n. 38
0
        static void Main(string[] args)
        {
            string url = "";

            if (args.Length >= 1)
            {
                url = args[0];
            }
            else
            {
                url = "127.0.0.1";//"tyrenus.gamextasy.com";
            }

            SimpleDispatcher dispatcher;
            MessageTcpClient client;
            dispatcher = SimpleDispatcher.CurrentDispatcher;
            var message = new Message { ID = 7, Name = "abc" };
            var serializer = new MessageSerializer();
            serializer.Register<Message>();

            // 初始化client
            client = new MessageTcpClient(serializer, (session, o) =>
            {
                dispatcher.Invoke(() =>
                {
                    Console.WriteLine((o as Message).ID);
                    Console.WriteLine((o as Message).Name);
                });
            });
            client.Connected += () =>
            {
                Console.WriteLine("connected");
                client.Send(message);
            };
            client.Disconnected += (e) =>
            {
                Console.WriteLine("disconnected:" + e.Message);
            };

            var ip = System.Net.Dns.GetHostAddresses(url);
            Console.WriteLine(ip.Length);
            Console.WriteLine(ip[0]);
            client.Connect(new IPEndPoint(ip[0], 9528));
            dispatcher.Run();
        }
Esempio n. 39
0
        /// <summary>
        /// Creates MessageProcessor instance.
        /// </summary>
        /// <param name="componentOverseer">Component overseer module.</param>
        /// <param name="workManager">Work manager to get work from.</param>
        public MessageProcessor(IComponentOverseer componentOverseer, IWorkManager workManager)
        {
            if (componentOverseer == null)
                throw new ArgumentNullException("IComponentOverseer dependancy is null.");
            if (workManager == null)
                throw new ArgumentNullException("IWorkManager dependancy is null.");

            _inputDataQueue = new RawDataQueue();

            var serializer = new MessageSerializer();
            var validator = new MessageValidator();
            _marshaller = new Marshaller(serializer, validator);

            _componentOverseer = componentOverseer;
            _workManager = workManager;

            _processingLock = new AutoResetEvent(false);
        }
Esempio n. 40
0
        public void TestNetwork()
        {
            var dispatcher = SimpleDispatcher.CurrentDispatcher;
            var message = new Message { ID = 7, Name = "abc" };
            var serializer = new MessageSerializer();
            serializer.Register<Message>();

            bool done = false;

            // 初始化client
            client = new MessageTcpClient(serializer, (session, o) =>
            {
                dispatcher.Invoke(() =>
                {
                    Assert.AreEqual(message.ID, (o as Message).ID);
                    Assert.AreEqual(message.Name, (o as Message).Name);
                    done = true;
                    dispatcher.Shutdown();
                });
            });
            client.Connected += () =>
            {
                client.Send(message);
            };

            // 初始化service
            service = new MessageTcpService(serializer, (session, o) =>
            {
                dispatcher.Invoke(() =>
                {
                    Assert.AreEqual(message.ID, (o as Message).ID);
                    Assert.AreEqual(message.Name, (o as Message).Name);
                    Console.WriteLine(message);
                    session.Send(message);
                });
            });

            var ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            service.Listen(new IPEndPoint(ip, 9528));
            client.Connect(new IPEndPoint(ip, 9528));
            dispatcher.Run();
            Assert.IsTrue(done);
        }
Esempio n. 41
0
        static void Main(string[] args)
        {
            var dispatcher = SimpleDispatcher.CurrentDispatcher;
            var serializer = new MessageSerializer();
            serializer.Register<Message>();
            serializer.Register<string>();
            HashSet<TcpSession> sessions = new HashSet<TcpSession>();

            // 初始化service
            var service = new MessageTcpService(serializer, (session, o) =>
            {
                dispatcher.Invoke(() =>
                {
                    session.Send(o);
                });
            },
            () =>
            {
                var session = new TcpSession();
                Console.WriteLine("connected");
                sessions.Add(session);
                session.Disconnected += (e) =>
                {
                    Console.WriteLine("Disconnected:" + e.Message);
                    sessions.Remove(session);
                };
                return session;
            });
            service.MessageDeserializeFailed += (e) => { Console.WriteLine(e.Message); };
            var ip = IPAddress.Any;
            service.Listen(new IPEndPoint(ip, 9528));
            var timer = new Eddy.Timers.Timer();
            timer.Tick += () =>
            {
                Console.WriteLine("{0} clients connected.", sessions.Count);
            };
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();
            dispatcher.Run();
        }
Esempio n. 42
0
        public void CanSerializeAndBack()
        {
            var serializer = new MessageSerializer
            {
                MessageMapper = new MessageMapper(),
                MessageTypes = new List<Type> { typeof(MessageWithArray) }
            };

            var message = new MessageWithArray(Guid.NewGuid(), new int[] { 1234, 5323 });

            var stream = new MemoryStream();
            serializer.Serialize(new object[] { message }, stream);

            stream.Position = 0;

            var messages = serializer.Deserialize(stream);

            Assert.NotNull(messages);
            Assert.That(messages, Has.Length.EqualTo(1));

            Assert.That(messages[0], Is.TypeOf(typeof(MessageWithArray)));
            var m = (MessageWithArray)messages[0];

            Assert.IsNotNull(m.SomeInts);
            Assert.That(m.SomeInts, Has.Length.EqualTo(2));
            Assert.AreEqual(1234, m.SomeInts[0]);
            Assert.AreEqual(5323, m.SomeInts[1]);
        }
Esempio n. 43
0
        static void Main(string[] args)
        {
            string url = "127.0.0.1";// "tyrenus.gamextasy.com";
            int num = 2048;

            if (args.Length >= 1)
            {
                url = args[0];
            }

            if (args.Length >= 2)
            {
                num = int.Parse(args[1]);
            }

            var clients = new List<MessageTcpClient>();
            var dispatcher = SimpleDispatcher.CurrentDispatcher;
            var serializer = new MessageSerializer();
            serializer.Register<Message>();

            for (int i = 0; i < num; ++i)
            {
                var message = new Message { ID = i, Name = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" };

                // 初始化client
                var client = new MessageTcpClient(serializer, (session, o) =>
                {
                    dispatcher.Invoke(() =>
                    {
                        //Console.WriteLine((o as Message).ID);
                        session.Send(o);
                    });
                });
                var id = i;
                client.Connected += () =>
                {
                    Console.WriteLine("connected" + id);
                    client.Send(message);
                };
                client.Disconnected += (e) =>
                {
                    Console.WriteLine("disconnected:" + id + " " + e.Message);
                };
                client.MessageDeserializeFailed += (e) =>
                {
                    Console.WriteLine("MessageDeserializeFailed:" + id + " " + e.Message);
                };

                var ip = System.Net.Dns.GetHostAddresses(url);
                //Console.WriteLine(ip.Length);
                //Console.WriteLine(ip[0]);
                client.Connect(new IPEndPoint(ip[0], 9528));
                clients.Add(client);
                System.Threading.Thread.Sleep(30);
            }
            var timer = new Eddy.Timers.Timer();
            timer.Tick += () =>
            {
                Console.WriteLine("{0} clients connected.", clients.Where (x => x.IsConnected).Count ());
            };
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();
            dispatcher.Run();
        }