public void EndpointSendAndReceive()
        {
            using (var management = new RabbitEndpointManagement(_queue))
            {
                management.BindQueue(_queue.Name, _exchange.Name, ExchangeType.Fanout, "", null);
            }

            IMessageSerializer serializer = new JsonMessageSerializer();

            var message = new BugsBunny {
                Food = "Carrot"
            };

            IDuplexTransport   transport = _factory.BuildLoopback(new TransportSettings(_exchange));
            IOutboundTransport error     = _factory.BuildError(new TransportSettings(_error));

            var sendEndpoint = new Endpoint(_exchange, serializer, transport, error,
                                            new InMemoryInboundMessageTracker(5));

            sendEndpoint.Send(message);


            var receiveEndpoint = new Endpoint(_queue, serializer, transport, error,
                                               new InMemoryInboundMessageTracker(5));

            receiveEndpoint.Receive(o =>
            {
                return(b =>
                {
                    var bb = (BugsBunny)b;
                    Console.WriteLine(bb.Food);
                });
            }, TimeSpan.Zero);
        }
        public void Deserialize_private_message_with_two_unrelated_interface_without_wrapping()
        {
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(IMyEventA), typeof(IMyEventB) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new CompositeMessage
                {
                    IntValue = 42,
                    StringValue = "Answer"
                };

                Serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = Serializer.Deserialize(stream, new[] { typeof(IMyEventA), typeof(IMyEventB) });
                var a = (IMyEventA) result[0];
                var b = (IMyEventB) result[1];
                Assert.AreEqual(42, b.IntValue);
                Assert.AreEqual("Answer", a.StringValue);
            }
        }
        public RoutingSlipSendContext(T message, CancellationToken cancellationToken, Uri destinationAddress)
            : base(message, cancellationToken)
        {
            DestinationAddress = destinationAddress;

            Serializer = new JsonMessageSerializer();
        }
 public SerializationMapper(IMessageMapper mapper,Conventions conventions, ReadOnlySettings settings)
 {
     jsonSerializer = new JsonMessageSerializer(mapper);
     xmlSerializer = new XmlMessageSerializer(mapper, conventions);
     List<Type> messageTypes = settings.GetAvailableTypes().Where(conventions.IsMessageType).ToList();
     xmlSerializer.Initialize(messageTypes);
 }
Exemplo n.º 5
0
    public void Deserialize()
    {
        var messageMapper = new MessageMapper();
        var messageTypes  = new[]
        {
            typeof(IWithoutConcrete)
        };

        messageMapper.Initialize(messageTypes);
        var serializer = new JsonMessageSerializer(messageMapper, null, null, null, null);

        var message = messageMapper.CreateInstance <IWithoutConcrete>();

        message.SomeProperty = "test";
        using (var stream = new MemoryStream())
        {
            serializer.Serialize(message, stream);

            stream.Position = 0;

            var result = (IWithoutConcrete)serializer.Deserialize(stream, messageTypes)[0];

            Assert.AreEqual("test", result.SomeProperty);
        }
    }
Exemplo n.º 6
0
        private static async Task SendMessage(Envelope envelope, JsonMessageSerializer serializer)
        {
            var messageBus = new ServiceBusMessageBus(_connectionStringBuilder, serializer);
            await messageBus.Send(new ScheduledEnvelope(envelope, DateTime.UtcNow.AddMinutes(-1.0)), default);

            await messageBus.Close();
        }
Exemplo n.º 7
0
    public void Should_not_emit_UTF8_BOM_if_configured_not_to()
    {
        var messageMapper = new MessageMapper();

        Func <Stream, JsonWriter> writerCreator = stream =>
        {
            var streamWriter = new StreamWriter(stream, new UTF8Encoding(false, false));
            return(new JsonTextWriter(streamWriter)
            {
                Formatting = Formatting.None
            });
        };

        var serializer = new JsonMessageSerializer(messageMapper, null, writerCreator, null, null);

        var message = new SimpleMessage();

        using (var stream = new MemoryStream())
        {
            serializer.Serialize(message, stream);

            stream.Position = 0;

            var result  = stream.ToArray();
            var utf8bom = new UTF8Encoding(true).GetPreamble();

            for (var i = 0; i < utf8bom.Length; i++)
            {
                Assert.AreNotEqual(utf8bom[i], result[i]);
            }
        }
    }
Exemplo n.º 8
0
        public static void SendMessage(string connectionString, string queue, string messageBody, Dictionary <string, string> headers)
        {
            string insertSql = @"INSERT INTO [" + queue + "] ([Id],[Recoverable],[Headers],[Body]) VALUES (@Id,@Recoverable,@Headers,@Body)";

            using (var scope = new TransactionScope())
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand(insertSql, connection))
                    {
                        SqlParameterCollection parameters = command.Parameters;
                        command.CommandType = CommandType.Text;
                        parameters.Add("Id", SqlDbType.UniqueIdentifier).Value = Guid.NewGuid();
                        string serializeHeaders = new JsonMessageSerializer(null).SerializeObject(headers);
                        parameters.Add("Headers", SqlDbType.VarChar).Value = serializeHeaders;
                        parameters.Add("Body", SqlDbType.VarBinary).Value  = Encoding.UTF8.GetBytes(messageBody);
                        parameters.Add("Recoverable", SqlDbType.Bit).Value = true;

                        command.ExecuteNonQuery();
                    }
                }
                scope.Complete();
            }
        }
Exemplo n.º 9
0
        void VerifyMessageHeaderIsPassed(Action <ISendContext <PingMessage> > setHeaderAction,
                                         Action <IConsumeContext> checkHeaderAction)
        {
            byte[] data;
            var    serializer = new JsonMessageSerializer();

            var message = new PingMessage();

            using (var output = new MemoryStream())
            {
                var sendContext = new SendContext <PingMessage>(message);
                setHeaderAction(sendContext);

                serializer.Serialize(output, sendContext);

                data = output.ToArray();
            }

            //Trace.WriteLine(Encoding.UTF8.GetString(data));

            using (var input = new MemoryStream(data))
            {
                var receiveContext = ReceiveContext.FromBodyStream(input);
                serializer.Deserialize(receiveContext);

                checkHeaderAction(receiveContext);
            }
        }
Exemplo n.º 10
0
        public void Setup()
        {
            _mapper  = new Moq.Mock <IEventMapper>();
            _factory = new Moq.Mock <IEventFactory>();

            _serializer = new JsonMessageSerializer(_mapper.Object, _factory.Object, new Newtonsoft.Json.JsonConverter[] { });
        }
Exemplo n.º 11
0
        public EventStoreFixture()
        {
            _node = EmbeddedVNodeBuilder
                    .AsSingleNode()
                    .OnDefaultEndpoints()
                    .RunInMemory()
                    .DisableDnsDiscovery()
                    .DisableHTTPCaching()
                    //.DisableScavengeMerging()
                    .DoNotVerifyDbHashes()
                    .Build();

            _node.StartAndWaitUntilReady().Wait();

            var conns = ConnectionSettings.Create()
                        .SetDefaultUserCredentials(new EventStore.ClientAPI.SystemData.UserCredentials("admin", "changeit"))
                        .Build();

            var eventStoreConnection = EmbeddedEventStoreConnection.Create(_node, conns);

            StreamStoreConnection = new EventStoreConnectionWrapper(eventStoreConnection);

            EventSerializer   = new JsonMessageSerializer();
            StreamNameBuilder = new PrefixedCamelCaseStreamNameBuilder("masterdata");

            _repo = new StreamStoreRepository(StreamNameBuilder, StreamStoreConnection, EventSerializer);
        }
        public void Deserialize_private_message_with_two_unrelated_interface_without_wrapping()
        {
            var messageMapper = new MessageMapper();

            messageMapper.Initialize(new[] { typeof(IMyEventA), typeof(IMyEventB) });
            var serializer = new JsonMessageSerializer(messageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new CompositeMessage
                {
                    IntValue    = 42,
                    StringValue = "Answer"
                };

                serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = serializer.Deserialize(stream, new[] { typeof(IMyEventA), typeof(IMyEventB) });
                var a      = (IMyEventA)result[0];
                var b      = (IMyEventB)result[1];
                Assert.AreEqual(42, b.IntValue);
                Assert.AreEqual("Answer", a.StringValue);
            }
        }
Exemplo n.º 13
0
        public void EmptyStringDeserializedIntoNull()
        {
            var sut     = new JsonMessageSerializer(GremlinClient.DefaultMimeType);
            var ofEmpty = Encoding.UTF8.GetBytes("");

            Assert.Null(sut.DeserializeMessage <ResponseMessage>(ofEmpty));
        }
        public async Task Save_inserts_Memento_entity_correctly()
        {
            // Arrange
            var sourceId = Guid.NewGuid();
            var memento  = new FakeUserMemento();

            var serializer = new JsonMessageSerializer();

            var sut = new SqlMementoStore(
                () => new MementoStoreDbContext(_dbContextOptions),
                serializer);

            // Act
            await sut.Save <FakeUser>(sourceId, memento, default);

            // Assert
            using (var db = new MementoStoreDbContext(_dbContextOptions))
            {
                Memento actual = await db
                                 .Mementoes
                                 .AsNoTracking()
                                 .Where(m => m.AggregateId == sourceId)
                                 .SingleOrDefaultAsync();

                actual.Should().NotBeNull();
                object restored = serializer.Deserialize(actual.MementoJson);
                restored.Should().BeOfType <FakeUserMemento>();
                restored.ShouldBeEquivalentTo(memento);
            }
        }
Exemplo n.º 15
0
        public async Task TestSendAndReceiveMessage()
        {
            var lazyConnection = new Lazy <IConnection>(() =>
            {
                var cf = new ConnectionFactory();
                return(cf.CreateConnection("nats://192.168.99.100:32774")); // change to local Docker address:port that maps onto 4222
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            const string subjectPrefix = "Obvs.NATS.Tests";
            var          deserializers = new List <IMessageDeserializer <TestMessage> >
            {
                new JsonMessageDeserializer <TestMessage>()
            };
            IMessageSerializer serializer = new JsonMessageSerializer();

            var source    = new MessageSource <TestMessage>(lazyConnection, subjectPrefix, deserializers);
            var publisher = new MessagePublisher <TestMessage>(lazyConnection, subjectPrefix, serializer);

            var subscription = source.Messages.ObserveOn(Scheduler.Default).Subscribe(Console.WriteLine);

            for (var i = 0; i < 10; i++)
            {
                await publisher.PublishAsync(new TestMessage { Id = i });
            }

            await Task.Delay(TimeSpan.FromSeconds(1));

            subscription.Dispose();
        }
Exemplo n.º 16
0
        public void WorksWhenMovingToErrorQueue()
        {
            using (var messageQueue = new MsmqMessageQueue("error"))
            {
                // make sure error queue is empty
                messageQueue.PurgeInputQueue();

                adapter.Handle <Request>(req =>
                {
                    throw new ApplicationException("oh crap");
                });

                var request = new Request();
                bus.AttachHeader(request, Headers.CorrelationId, "super-unique!!!!111");
                bus.SendLocal(request);

                // let it fail
                Thread.Sleep(2.Seconds());

                var receivedTransportMessage = messageQueue.ReceiveMessage(new NoTransaction());
                receivedTransportMessage.ShouldNotBe(null);

                var serializer = new JsonMessageSerializer();
                var message    = serializer.Deserialize(receivedTransportMessage);

                message.Headers.ShouldContainKeyAndValue(Headers.CorrelationId, "super-unique!!!!111");
            }
        }
 public SerializationMapper(IMessageMapper mapper, Conventions conventions, Configure configure)
 {
     jsonSerializer = new JsonMessageSerializer(mapper);
     xmlSerializer = new XmlMessageSerializer(mapper, conventions);
     List<Type> messageTypes = configure.TypesToScan.Where(conventions.IsMessageType).ToList();
     xmlSerializer.Initialize(messageTypes);
 }
Exemplo n.º 18
0
        public async Task Start_returns_close_function()
        {
            // Arrange
            await ReceiveAndForgetAll();

            var messageBus = new MessageBus();
            var serializer = new JsonMessageSerializer();

            var envelope = new Envelope(
                messageId: Guid.NewGuid(),
                message: new Fixture().Create <SomeMessage>());

            // Act
            Func <Task> closeFunction = ServiceBusMessageMediator.Start(_connectionStringBuilder, messageBus, serializer);

            try
            {
                await closeFunction.Invoke();
                await SendMessage(envelope, serializer);

                // Assert
                await Task.WhenAny(Task.Delay(TimeSpan.FromMilliseconds(3000)), messageBus.SentMessage);

                messageBus.SentMessage.Status.Should().NotBe(TaskStatus.RanToCompletion);
            }
            finally
            {
                await closeFunction.Invoke();
            }
        }
Exemplo n.º 19
0
        public void FromScheduledEnvelope_generates_PendingScheduledCommand_correctly()
        {
            // Arrange
            var random         = new Random();
            var processManager = new FakeProcessManager();
            var messageId      = Guid.NewGuid();
            var correlationId  = Guid.NewGuid();
            var message        = new FakeCommand
            {
                Int32Value  = random.Next(),
                StringValue = Guid.NewGuid().ToString(),
            };
            var scheduledEnvelope =
                new ScheduledEnvelope(
                    new Envelope(messageId, message, correlationId: correlationId),
                    DateTime.Now.AddTicks(random.Next()));
            var serializer = new JsonMessageSerializer();

            // Act
            var actual = PendingScheduledCommand.FromScheduledEnvelope(processManager, scheduledEnvelope, serializer);

            // Assert
            actual.ProcessManagerType.Should().Be(typeof(FakeProcessManager).FullName);
            actual.ProcessManagerId.Should().Be(processManager.Id);
            actual.MessageId.Should().Be(messageId);
            actual.CorrelationId.Should().Be(correlationId);
            actual.CommandJson.Should().Be(serializer.Serialize(message));
            actual.ScheduledTimeUtc.Should().Be(scheduledEnvelope.ScheduledTimeUtc);
        }
        public void DeserializesMessageCorrectly_Presence(string messageJson, params PresenceMessage[] expectedMessages)
        {
            // Arrange
            JsonMessageSerializer serializer = new JsonMessageSerializer();
            StringBuilder         message    = new StringBuilder("{\"presence\":")
                                               .Append(messageJson).Append("}");

            Console.WriteLine(new DateTimeOffset(new DateTime(2015, 5, 5, 0, 0, 0, DateTimeKind.Utc)).ToUnixTimeInMilliseconds());

            // Act
            ProtocolMessage target = serializer.DeserializeProtocolMessage(message.ToString());

            // Assert
            Assert.NotNull(target);
            Assert.NotNull(target.Presence);
            Assert.Equal <int>(expectedMessages.Length, target.Presence.Length);
            for (int i = 0; i < expectedMessages.Length; i++)
            {
                Assert.Equal <string>(expectedMessages[i].ClientId, target.Presence[i].ClientId);
                Assert.Equal <string>(expectedMessages[i].ConnectionId, target.Presence[i].ConnectionId);
                Assert.Equal <PresenceMessage.ActionType>(expectedMessages[i].Action, target.Presence[i].Action);
                Assert.Equal <string>(expectedMessages[i].Id, target.Presence[i].Id);
                Assert.Equal <DateTimeOffset>(expectedMessages[i].Timestamp, target.Presence[i].Timestamp);
                Assert.Equal(expectedMessages[i].Data, target.Presence[i].Data);
            }
        }
Exemplo n.º 21
0
        public async Task message_handler_sends_message_not_having_contributor_correctly()
        {
            // Arrange
            await ReceiveAndForgetAll();

            var messageBus = new MessageBus();
            var serializer = new JsonMessageSerializer();

            var envelope = new Envelope(
                messageId: Guid.NewGuid(),
                message: new Fixture().Create <SomeMessage>(),
                operationId: $"{Guid.NewGuid()}",
                correlationId: Guid.NewGuid());

            // Act
            Func <Task> closeFunction = ServiceBusMessageMediator.Start(_connectionStringBuilder, messageBus, serializer);

            try
            {
                await SendMessage(envelope, serializer);

                // Assert
                await Task.WhenAny(Task.Delay(TimeSpan.FromMilliseconds(3000)), messageBus.SentMessage);

                messageBus.SentMessage.Status.Should().Be(TaskStatus.RanToCompletion);
                Envelope actual = await messageBus.SentMessage;
                actual.Should().BeEquivalentTo(envelope, opts => opts.RespectingRuntimeTypes());
            }
            finally
            {
                await closeFunction.Invoke();
            }
        }
        public void SerializesMessageCorrectly_Presence(params PresenceMessage[] messages)
        {
            // Arrange
            JsonMessageSerializer serializer = new JsonMessageSerializer();
            ProtocolMessage       message    = new ProtocolMessage()
            {
                Presence = messages
            };
            StringBuilder expectedMessage = new StringBuilder("{\"action\":0,\"msgSerial\":0");

            expectedMessage.Append(",\"presence\":[");
            foreach (PresenceMessage msg in messages)
            {
                expectedMessage.AppendFormat("{{\"action\":{0}}},", (byte)msg.Action);
            }
            expectedMessage.Remove(expectedMessage.Length - 1, 1) // last comma
            .Append("]}");

            // Act
            object result = serializer.SerializeProtocolMessage(message);

            // Assert
            Assert.IsType <string>(result);
            Assert.Equal <string>(expectedMessage.ToString(), result as string);
        }
        public void SerializesMessageCorrectly_Messages(params Message[] messages)
        {
            // Arrange
            JsonMessageSerializer serializer = new JsonMessageSerializer();
            ProtocolMessage       message    = new ProtocolMessage()
            {
                Messages = messages
            };
            StringBuilder expectedMessage = new StringBuilder("{\"action\":0,\"msgSerial\":0");
            var           validMessages   = messages.Where(c => !string.IsNullOrEmpty(c.Name));

            if (validMessages.Any())
            {
                expectedMessage.Append(",\"messages\":[");
                foreach (Message msg in validMessages)
                {
                    expectedMessage.AppendFormat("{{\"name\":\"{0}\"}},", msg.Name);
                }
                expectedMessage.Remove(expectedMessage.Length - 1, 1) // last comma
                .Append("]");
            }
            expectedMessage.Append("}");

            // Act
            object result = serializer.SerializeProtocolMessage(message);

            // Assert
            Assert.IsType <string>(result);
            Assert.Equal <string>(expectedMessage.ToString(), result as string);
        }
        public void Deserialize_messages_wrapped_in_array_from_older_endpoint()
        {
            var messageMapper            = new MessageMapper();
            var serializer               = new JsonMessageSerializer(messageMapper);
            var jsonWithMultipleMessages = @"
[
  {
    $type: 'NServiceBus.Serializers.Json.Tests.JsonMessageSerializerTest+SimpleMessage1, NServiceBus.Core.Tests',
    PropertyOnMessage1: 'Message1'
  },
  {
    $type: 'NServiceBus.Serializers.Json.Tests.JsonMessageSerializerTest+SimpleMessage2, NServiceBus.Core.Tests',
    PropertyOnMessage2: 'Message2'
  }
]";

            using (var stream = new MemoryStream())
            {
                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(jsonWithMultipleMessages);
                streamWriter.Flush();
                stream.Position = 0;
                var result = serializer.Deserialize(stream, new[]
                {
                    typeof(SimpleMessage2),
                    typeof(SimpleMessage1)
                });

                Assert.AreEqual(2, result.Length);
                Assert.AreEqual("Message1", ((SimpleMessage1)result[0]).PropertyOnMessage1);
                Assert.AreEqual("Message2", ((SimpleMessage2)result[1]).PropertyOnMessage2);
            }
        }
        public void ItHasBeenFixed()
        {
            using (var adapter = new BuiltinContainerAdapter())
            {
                adapter.Handle <string>(s =>
                {
                    throw new ApplicationException("Will trigger that the message gets moved to the error queue");
                });

                Configure.With(adapter)
                .Transport(t => t.UseRabbitMq(ConnectionString, "test.input", "test.error")
                           .UseExchange("AlternativeExchange"))
                .CreateBus()
                .Start();

                adapter.Bus.SendLocal("hello there!!!");

                // wait until we're sure
                Thread.Sleep(2.Seconds());

                using (var errorQueue = new RabbitMqMessageQueue(ConnectionString, "test.error"))
                {
                    var serializer = new JsonMessageSerializer();
                    var receivedTransportMessage = errorQueue.ReceiveMessage(new NoTransaction());
                    receivedTransportMessage.ShouldNotBe(null);

                    var errorMessage = serializer.Deserialize(receivedTransportMessage);
                    errorMessage.Messages.Length.ShouldBe(1);
                    errorMessage.Messages[0].ShouldBeOfType <string>();
                    ((string)errorMessage.Messages[0]).ShouldBe("hello there!!!");
                }
            }
        }
        public void Deserialize_message_with_concrete_implementation_and_interface()
        {
            var map           = new[] { typeof(SuperMessageWithConcreteImpl), typeof(ISuperMessageWithConcreteImpl) };
            var messageMapper = new MessageMapper();

            messageMapper.Initialize(map);
            var serializer = new JsonMessageSerializer(messageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new SuperMessageWithConcreteImpl
                {
                    SomeProperty = "test"
                };

                serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = (ISuperMessageWithConcreteImpl)serializer.Deserialize(stream, map)[0];

                Assert.IsInstanceOf <SuperMessageWithConcreteImpl>(result);
                Assert.AreEqual("test", result.SomeProperty);
            }
        }
Exemplo n.º 27
0
 public JsonSerializerFacade(params Type[] objectTypes)
 {
     this.objectTypes = objectTypes;
     mapper           = new MessageMapper();
     serializer       = new JsonMessageSerializer(mapper);
     mapper.Initialize(objectTypes);
 }
Exemplo n.º 28
0
        public async Task SerializeAsJson_Action_PayloadSerialized()
        {
            var message = new TestEventOne {
                Content = "Hello MQTT!"
            };
            var serializer = new JsonMessageSerializer <TestEventOne>
            {
                Options = new JsonSerializerOptions
                {
                    WriteIndented = true
                }
            };
            var messageBytes = (await serializer.SerializeAsync(
                                    message,
                                    new MessageHeaderCollection(),
                                    MessageSerializationContext.Empty)).ReadAll();
            var builder = new MqttLastWillMessageBuilder();

            builder
            .ProduceTo("testaments")
            .SerializeAsJson(
                serializerBuilder => serializerBuilder
                .WithOptions(
                    new JsonSerializerOptions
            {
                WriteIndented = true
            }))
            .Message(message);

            var willMessage = builder.Build();

            willMessage.Payload.Should().NotBeNullOrEmpty();
            willMessage.Payload.Should().BeEquivalentTo(messageBytes);
        }
Exemplo n.º 29
0
        public bool Handle(IMiramarTaskProvider taskProvider, IMiramarScheduleProvider scheduleProvider, IMiramarContextProvider contextProvider, IIstaMessage message)
        {
            var request = JsonMessageSerializer.DeserializeType <TaskScheduleRequestModel>(message.Body);

            if (request == null)
            {
                return(false);
            }

            var requestedTask = taskProvider.LoadTaskConfiguration(request.TaskId);

            if (requestedTask == null)
            {
                return(false);
            }

            var schedule = request.Type.Equals("continuous", StringComparison.OrdinalIgnoreCase)
                               ? CreateContinuousSchedule(request)
                               : CreateDateTimeSchedule(request);

            if (request.Items != null && request.Items.Count != 0)
            {
                foreach (var item in request.Items)
                {
                    schedule.AddScheduleItem(new TaskScheduleItemModel
                    {
                        Order  = item.Order,
                        TaskId = item.TaskId,
                    });
                }
            }

            scheduleProvider.PopTaskFromConsideration(request.TaskId);
            return(true);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Configures Rebus to use <see cref="JsonMessageSerializer"/> to serialize messages. A <see cref="JsonSerializationOptions"/>
        /// object is returned, which can be used to configure details around how the JSON serialization should work
        /// </summary>
        public JsonSerializationOptions UseJsonSerializer()
        {
            var jsonMessageSerializer = new JsonMessageSerializer();

            Use(jsonMessageSerializer);
            return(new JsonSerializationOptions(jsonMessageSerializer));
        }
        public static void SerializeWrappedNativeMessag()
        {
            var serializer = new JsonMessageSerializer(new SimpleMessageMapper());
            var serializedMessage = serializer.SerializeObject(new NativeMessage
            {
                Content = "Hello from native sender",
                SendOnUtc = DateTime.UtcNow
            });
            Debug.WriteLine("Serialized message:\n");
            Debug.WriteLine($"@\"{serializedMessage.Replace("\"", "\"\"")}\"");

            var headers = new Dictionary<string, string>
            {
                { "NServiceBus.EnclosedMessageTypes", typeof(NativeMessage).FullName },
                { "NServiceBus.MessageIntent", "Send" }
            };

            var toSend = new MessageWrapper
            {
                Id = Guid.NewGuid().ToString(),
                Body = Encoding.UTF8.GetBytes(serializedMessage),
                Headers = headers,
                MessageIntent = MessageIntentEnum.Send,
                ReplyToAddress = "native-sender"
            };

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(toSend, stream);
                var st = Encoding.UTF8.GetString(stream.ToArray());

                Console.WriteLine("\nWrapped message:\n");
                Debug.WriteLine($"@\"{st.Replace("\"", "\"\"")}\"");
            }
        }
Exemplo n.º 32
0
        public async Task Send_SendsMessageToServiceBus()
        {
            var id         = Guid.NewGuid();
            var serializer = new JsonMessageSerializer();
            var encoder    = new Utf8Encoder();
            var messenger  = new ServiceBusDomainMessenger(
                new [] { new GlobalUserPropertyStrategy("Id") },
                serializer, encoder, _fixture.Sender);

            var client = _fixture.CreateClient(id);

            TestDomainEvent domainEvent = null;

            client.RegisterMessageHandler((msg, token) =>
            {
                var json    = System.Text.Encoding.UTF8.GetString(msg.Body);
                domainEvent = serializer.DeserializeObject <TestDomainEvent>(json);

                return(Task.CompletedTask);
            }, new MessageHandlerOptions(args => Task.CompletedTask)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            });

            await messenger.SendAsync(new TestDomainEvent(id));

            while (domainEvent?.Id != id)
            {
                Thread.Sleep(2000);
            }

            domainEvent.Id.Should().Be(id);
        }
Exemplo n.º 33
0
    public void Should_throw_for_array()
    {
        var xml = @"[{
$type: ""IA, NServiceBus.Core.Tests"",
Data: ""rhNAGU4dr/Qjz6ocAsOs3wk3ZmxHMOg="",
S: ""kalle"",
I: 42,
B: {
}
}, {
$type: ""IA, NServiceBus.Core.Tests"",
Data: ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="",
S: ""kalle"",
I: 42,
B: {
}
}]";

        using (var stream = new MemoryStream())
        {
            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(xml);
            streamWriter.Flush();
            stream.Position = 0;

            var messageMapper = new MessageMapper();
            var serializer    = new JsonMessageSerializer(messageMapper, null, null, null, null);
            var exception     = Assert.Throws <Exception>(() => serializer.Deserialize(stream, new List <Type>()));
            Approvals.Verify(exception.Message);
        }
    }
Exemplo n.º 34
0
        public void JsonNullDeserializedIntoNull()
        {
            var sut    = new JsonMessageSerializer(GremlinClient.DefaultMimeType);
            var ofNull = Encoding.UTF8.GetBytes("null");

            Assert.Null(sut.DeserializeMessage <ResponseMessage>(ofNull));
        }
        public ServiceControlBackend(ISendMessages messageSender)
        {
            this.messageSender = messageSender;
            serializer = new JsonMessageSerializer(new SimpleMessageMapper());

            serviceControlBackendAddress = GetServiceControlAddress();
            VerifyIfServiceControlQueueExists();
        }
Exemplo n.º 36
0
        public void TestMethod()
        {
            int msgCount = 5000;
            IMessageSerializer json = new JsonMessageSerializer();
            IMessageSerializer bson = new BsonMessageSerializer();
            long elapsed1;
            long elapsed2;

            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < msgCount; i++)
            {
                IMessage msg = new MessageSerDes() { Content = "Hello world people" };
                using (MemoryStream ms = new MemoryStream())
                {
                    json.Serialize(msg, ms);

                    if (ms.CanSeek)
                        ms.Seek(0, SeekOrigin.Begin);

                    var des = json.Deserialize(ms);
                    if ((des as MessageSerDes).Content != (msg as MessageSerDes).Content ||
                        (des as MessageSerDes).Id != (msg as MessageSerDes).Id ||
                        (des as MessageSerDes).Age != (msg as MessageSerDes).Age)
                        Assert.Fail();
                }
                msg = null;
            }

            sw.Stop();
            elapsed1 = sw.ElapsedMilliseconds;
            sw.Reset();

            sw.Start();
            for (int i = 0; i < msgCount; i++)
            {
                IMessage msg = new MessageSerDes() { Content = "Hello world people" };
                using (MemoryStream ms = new MemoryStream())
                {
                    bson.Serialize(msg, ms);

                    if (ms.CanSeek)
                        ms.Seek(0, SeekOrigin.Begin);

                    var des = bson.Deserialize(ms);
                    if ((des as MessageSerDes).Content != (msg as MessageSerDes).Content ||
                        (des as MessageSerDes).Id != (msg as MessageSerDes).Id ||
                        (des as MessageSerDes).Age != (msg as MessageSerDes).Age)
                        Assert.Fail();
                }
                msg = null;
            }
            sw.Stop();
            elapsed2 = sw.ElapsedMilliseconds;

            Assert.AreNotEqual(elapsed1, elapsed2);
        }
 public static void SerializeNativeMessage()
 {
     var serializer = new JsonMessageSerializer(new SimpleMessageMapper());
     var serializedMessage = serializer.SerializeObject(new NativeMessage
     {
         Content = "Hello from native sender",
         SendOnUtc = DateTime.UtcNow
     });
     Debug.WriteLine("Serialized message to paste in code:\n");
     Debug.WriteLine($"@\"{serializedMessage.Replace("\"", "\"\"")}\"");
 }
        public static ServiceInfo LoadFromDisk(string serviceName)
        {
            var ser = new JsonMessageSerializer();

            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, serviceName + ".json");
            if (File.Exists(path))
            {
                var data = File.ReadAllBytes(path);
                return ser.DeserializeObject<ServiceInfo>(data);
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 39
0
		public void An_interface_message_is_bound()
		{
			_serializer = new JsonMessageSerializer();

			var message = new A {TextA = "ValueA"};

			using(var buffer = new MemoryStream())
			{
				_serializer.Serialize<A>(buffer, message.ToSendContext());

				_message = Encoding.UTF8.GetString(buffer.ToArray());

			//	Trace.WriteLine(_message);
			}
		}
        public  ServiceControlBackend(ISendMessages messageSender, Configure configure, CriticalError criticalError)
        {
            this.configure = configure;
            this.criticalError = criticalError;
            this.messageSender = messageSender;
            serializer = new JsonMessageSerializer(new SimpleMessageMapper());

            serviceControlBackendAddress = GetServiceControlAddress();
            VerifyIfServiceControlQueueExists();

            circuitBreaker =
            new RepeatedFailuresOverTimeCircuitBreaker("ServiceControlConnectivity", TimeSpan.FromMinutes(2),
                ex =>
                    criticalError.Raise(
                        "This endpoint is repeatedly unable to contact the ServiceControl backend to report endpoint information. You have the ServiceControl plugins installed in your endpoint. However, please ensure that the Particular ServiceControl service is installed on this machine, " +
                                   "or if running ServiceControl on a different machine, then ensure that your endpoint's app.config / web.config, AppSettings has the following key set appropriately: ServiceControl/Queue. \r\n" +
                                   @"For example: <add key=""ServiceControl/Queue"" value=""particular.servicecontrol@machine""/>" +
                                   "\r\n", ex));
        }
        public void TestMany()
        {
            var xml = @"[{
    $type: ""NServiceBus.Serializers.Json.Tests.IA, NServiceBus.Core.Tests"",
    Data: ""rhNAGU4dr/Qjz6ocAsOs3wk3ZmxHMOg="",
    S: ""kalle"",
    I: 42,
    B: {
        BString: ""BOO"",
        C: {
            $type: ""NServiceBus.Serializers.Json.Tests.C, NServiceBus.Core.Tests"",
            Cstr: ""COO""
        }
    }
}, {
    $type: ""NServiceBus.Serializers.Json.Tests.IA, NServiceBus.Core.Tests"",
    Data: ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="",
    S: ""kalle"",
    I: 42,
    B: {
        BString: ""BOO"",
        C: {
            $type: ""NServiceBus.Serializers.Json.Tests.C, NServiceBus.Core.Tests"",
            Cstr: ""COO""
        }
    }
}]";
            using (var stream = new MemoryStream())
            {
                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(xml);
                streamWriter.Flush();
                stream.Position = 0;

                MessageMapper = new MessageMapper();
                MessageMapper.Initialize(new[] { typeof(IAImpl), typeof(IA) });
                Serializer = new JsonMessageSerializer(MessageMapper);

                var result = Serializer.Deserialize(stream, new[] { typeof(IAImpl) });
                Assert.IsNotEmpty(result);
                Assert.That(result, Has.Length.EqualTo(2));

                Assert.That(result[0], Is.AssignableTo(typeof(IA)));
                var a = ((IA) result[0]);

                Assert.AreEqual(23, a.Data.Length);
                Assert.AreEqual(42, a.I);
                Assert.AreEqual("kalle", a.S);
                Assert.IsNotNull(a.B);
                Assert.AreEqual("BOO", a.B.BString);
                Assert.AreEqual("COO", ((C) a.B.C).Cstr);
            }

        }
Exemplo n.º 42
0
        public static void Startup(TestContext context)
        {
            messageMapper = new TypeMapper();
            messageSerializer = new JsonMessageSerializer(messageMapper);
            objectSerializer = new JsonObjectSerializer();

            testMessage = new MyEventMessage(DateTime.Now, Guid.NewGuid(), "Hello there");

            messageMapper.Initialize(testMessage.GetType().GetInterfaces());
        }
 public JsonMessageSerializerTester()
 {
     _serializer = new JsonMessageSerializer(new TransportSettings());
 }
        public void Serialize_message_without_concrete_implementation()
        {
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                Serializer.Serialize(MessageMapper.CreateInstance<ISuperMessageWithoutConcreteImpl>(), stream);

                stream.Position = 0;
                var result = new StreamReader(stream).ReadToEnd();

                Assert.That(!result.Contains("$type"), result);
                Assert.That(result.Contains("SomeProperty"), result);
            }
        }
		public void send_and_receive_on_conversation_channel() {
			var myQ = Broker.CreateQueue("MyQueue");
			var myMessage = Broker.CreateMessageType("System.String");
			var myContract = Broker.CreateContract("MyContract2", new [] { myMessage }, new[] { myMessage });
			var myService = myQ.CreateService("MyQueue", myContract);

			var c1 = Broker.BeginConversation(myService, myService, myContract);

			var channel = Broker.OpenConversationChannel(c1);
			channel.Send("Hello World");

			var json = new JsonMessageSerializer();
			ServiceBrokerMessageHandler getHelloSendGoodbye = (c, t, b) => {
				Check.That(() => json.Deserialize(b, t).ToString() == "Hello World");
				Broker.OpenConversationChannel(c).Send("Goodbye World!");
			};
			 
			Check.That(() => myQ.TryReceive(getHelloSendGoodbye, TimeSpan.Zero));

			Action<string,object> checkGoodbye = (t, b) => Check.That(() => (string)b == "Goodbye World!"); 
			Check.That(() => channel.TryReceive(checkGoodbye, TimeSpan.Zero));
		}
        public void Deserialize_message_with_concrete_implementation_and_interface()
        {
            var map = new[] {typeof(SuperMessageWithConcreteImpl), typeof(ISuperMessageWithConcreteImpl)};
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(map);
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new SuperMessageWithConcreteImpl
                {
                    SomeProperty = "test"
                };

                Serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = (ISuperMessageWithConcreteImpl)Serializer.Deserialize(stream, map)[0];

                Assert.IsInstanceOf<SuperMessageWithConcreteImpl>(result);
                Assert.AreEqual("test", result.SomeProperty);
            }
        }
        public void Deserialize_message_without_concrete_implementation()
        {
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = MessageMapper.CreateInstance<ISuperMessageWithoutConcreteImpl>();
                msg.SomeProperty = "test";

                Serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = (ISuperMessageWithoutConcreteImpl)Serializer.Deserialize(stream, new[] { typeof(ISuperMessageWithoutConcreteImpl) })[0];

                Assert.AreEqual("test", result.SomeProperty);
            }
        }
 public void Setup()
 {
     Serializer = new JsonMessageSerializer(MessageMapper);
 }
 public static void SaveToDisk(ServiceInfo ms)
 {
     var ser = new JsonMessageSerializer();
     var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ms.Name + ".json");
     File.WriteAllBytes(path, ser.SerializeObject(ms));
 }
 public SerializationMapper(IMessageMapper mapper)
 {
     jsonSerializer = new JsonMessageSerializer(mapper);
     binarySerializer = new BinaryMessageSerializer();
 }
        public void TestInterfaces()
        {
            var output = new MemoryStream();

            var obj = MessageMapper.CreateInstance<IA>(
              x =>
              {
                  x.S = "kalle";
                  x.I = 42;
                  x.Data = new byte[23];
                  x.B = new B { BString = "BOO", C = new C { Cstr = "COO" } };
              }
              );

            new Random().NextBytes(obj.Data);

            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(IA), typeof(IAImpl) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            Serializer.Serialize(obj, output);

            output.Position = 0;

            var filename = string.Format("{0}.{1}.txt", GetType().Name, MethodBase.GetCurrentMethod().Name);

            File.WriteAllBytes(filename, output.ToArray());

            output.Position = 0;

            var result = Serializer.Deserialize(output, new[] { typeof(IAImpl) });

            Assert.DoesNotThrow(() => output.Position = 0, "Stream should still be open");

            Assert.IsNotEmpty(result);
            Assert.That(result, Has.Length.EqualTo(1));

            Assert.That(result[0], Is.AssignableTo(typeof(IA)));
            var a = ((IA)result[0]);

            Assert.AreEqual(a.Data, obj.Data);
            Assert.AreEqual(42, a.I);
            Assert.AreEqual("kalle", a.S);
            Assert.IsNotNull(a.B);
            Assert.AreEqual("BOO", a.B.BString);
            Assert.AreEqual("COO", ((C)a.B.C).Cstr);
        }
        public void Test()
        {
            var expectedDate = new DateTime(2010, 10, 13, 12, 32, 42, DateTimeKind.Unspecified);
            var expectedDateLocal = new DateTime(2010, 10, 13, 12, 32, 42, DateTimeKind.Local);
            var expectedDateUtc = new DateTime(2010, 10, 13, 12, 32, 42, DateTimeKind.Utc);
            var expectedGuid = Guid.NewGuid();

            var obj = new A
                        {
                            AGuid = expectedGuid,
                            Data = new byte[32],
                            I = 23,
                            S = "Foo",
                            Ints = new List<int> { 12, 42 },
                            Bs = new List<B> { new B { BString = "aaa", C = new C { Cstr = "ccc" } }, new BB { BString = "bbbb", C = new C { Cstr = "dddd" }, BBString = "BBStr"} },
                            DateTime = expectedDate,
                            DateTimeLocal = expectedDateLocal,
                            DateTimeUtc = expectedDateUtc
                        };

            new Random().NextBytes(obj.Data);

            var output = new MemoryStream();

            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(IA), typeof(A) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            Serializer.Serialize(obj, output);

            output.Position = 0;

            var result = Serializer.Deserialize(output, new[] { typeof(A) });

            Assert.DoesNotThrow(() => output.Position = 0, "Stream should still be open");

            Assert.That(result[0], Is.TypeOf(typeof(A)));
            var a = ((A)result[0]);

            Assert.AreEqual(obj.Data, a.Data);
            Assert.AreEqual(23, a.I);
            Assert.AreEqual("Foo", a.S);
            Assert.AreEqual(expectedDate.Kind, a.DateTime.Kind);
            Assert.AreEqual(expectedDate, a.DateTime);
            Assert.AreEqual(expectedDateLocal.Kind, a.DateTimeLocal.Kind);
            Assert.AreEqual(expectedDateLocal, a.DateTimeLocal);
            Assert.AreEqual(expectedDateUtc.Kind, a.DateTimeUtc.Kind);
            Assert.AreEqual(expectedDateUtc, a.DateTimeUtc);
            Assert.AreEqual("ccc", ((C)a.Bs[0].C).Cstr);
            Assert.AreEqual(expectedGuid, a.AGuid);

            Assert.IsInstanceOf<B>(a.Bs[0]);
            Assert.IsInstanceOf<BB>(a.Bs[1]);
        }