public void when_message_fails_to_deserialize_then_dead_letters_message()
        {
            var waiter    = new ManualResetEventSlim();
            var sender    = new TopicSender(this.Settings, this.Topic);
            var processor = new FakeProcessor(
                waiter,
                new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription),
                new JsonTextSerializer());

            processor.Start();

            var data = new JsonTextSerializer().Serialize(new Data());

            data = data.Replace(typeof(Data).FullName, "Some.TypeName.Cannot.Resolve");
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(data));

            stream.Position = 0;

            sender.SendAsync(() => new BrokeredMessage(stream, true));

            waiter.Wait(5000);

            var deadReceiver = this.Settings.CreateMessageReceiver(this.Topic, this.Subscription);
            var deadMessage  = deadReceiver.Receive(TimeSpan.FromSeconds(5));

            processor.Dispose();

            Assert.NotNull(deadMessage);
            var payload = new StreamReader(deadMessage.GetBody <Stream>()).ReadToEnd();

            Assert.Contains("Some.TypeName.Cannot.Resolve", payload);
        }
        partial void OnCreateContainer(UnityContainer container)
        {
            var metadata   = container.Resolve <IMetadataProvider>();
            var serializer = container.Resolve <ITextSerializer>();

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString);

            container.RegisterInstance <IBlobStorage>(new SqlBlobStorage("BlobStorage"));

            var commandBus  = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path), metadata, serializer);
            var topicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path);

            container.RegisterInstance <IMessageSender>(topicSender);
            var eventBus = new EventBus(topicSender, metadata, serializer);

            var commandProcessor =
                new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, "all", false, new SubscriptionReceiverInstrumentation("all", this.instrumentationEnabled)), serializer);

            container.RegisterInstance <ICommandBus>(commandBus);

            container.RegisterInstance <IEventBus>(eventBus);
            container.RegisterInstance <IProcessor>("CommandProcessor", commandProcessor);

            RegisterRepository(container);
            RegisterEventProcessors(container);
            RegisterCommandHandlers(container, commandProcessor);
        }
Exemplo n.º 3
0
        public void when_sending_message_then_can_receive_it()
        {
            var             sender  = new TopicSender(this.settings, this.topic);
            BrokeredMessage message = null;
            var             data    = new Data {
                Id = Guid.NewGuid(), Title = "Foo"
            };

            using (var receiver = new SubscriptionReceiver(this.settings, this.topic, this.subscription))
            {
                var signal = new ManualResetEventSlim();

                receiver.MessageReceived += (o, e) =>
                {
                    message = e.Message;
                    signal.Set();
                };

                receiver.Start();

                sender.Send(new BrokeredMessage(data));

                signal.Wait();
            }

            Assert.NotNull(message);

            var received = message.GetBody <Data>();

            Assert.Equal(data.Id, received.Id);
            Assert.Equal(data.Title, received.Title);
        }
Exemplo n.º 4
0
        public void when_sending_message_then_can_receive_it()
        {
            var  sender = new TopicSender(this.Settings, this.Topic);
            Data data   = new Data {
                Id = Guid.NewGuid(), Title = "Foo"
            };
            Data received = null;

            using (var receiver = new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription))
            {
                var signal = new ManualResetEventSlim();

                receiver.Start(
                    m =>
                {
                    received = m.GetBody <Data>();
                    signal.Set();
                    return(MessageReleaseAction.CompleteMessage);
                });

                sender.SendAsync(() => new BrokeredMessage(data));

                signal.Wait();
            }

            Assert.NotNull(received);
            Assert.Equal(data.Id, received.Id);
            Assert.Equal(data.Title, received.Title);
        }
Exemplo n.º 5
0
        public void when_creating_processor_then_receives_from_specified_subscription()
        {
            this.sut.Initialize();

            var waiter     = new ManualResetEventSlim();
            var handler    = new Mock <IEventHandler <AnEvent> >();
            var serializer = new JsonTextSerializer();
            var ev         = new AnEvent();

            handler.Setup(x => x.Handle(It.IsAny <AnEvent>()))
            .Callback(() => waiter.Set());

            var processor = this.sut.CreateEventProcessor("log", handler.Object, serializer);

            processor.Start();

            var sender = new TopicSender(this.settings, this.settings.Topics.First(t => t.Path.StartsWith("conference/events")).Path);
            var bus    = new EventBus(sender, new StandardMetadataProvider(), serializer);

            bus.Publish(ev);

            waiter.Wait(5000);

            handler.Verify(x => x.Handle(It.Is <AnEvent>(e => e.SourceId == ev.SourceId)));
        }
        public void when_message_received_then_calls_process_message()
        {
            var waiter    = new ManualResetEventSlim();
            var sender    = new TopicSender(this.Settings, this.Topic);
            var processor = new FakeProcessor(
                waiter,
                new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription),
                new JsonTextSerializer());

            processor.Start();

            var messageId     = Guid.NewGuid().ToString();
            var correlationId = Guid.NewGuid().ToString();
            var stream        = new MemoryStream();

            new JsonTextSerializer().Serialize(new StreamWriter(stream), "Foo");
            stream.Position = 0;
            sender.SendAsync(() => new BrokeredMessage(stream, true)
            {
                MessageId = messageId, CorrelationId = correlationId
            });

            waiter.Wait(5000);

            Assert.NotNull(processor.Payload);
            Assert.Equal(messageId, processor.MessageId);
            Assert.Equal(correlationId, processor.CorrelationId);
        }
        partial void OnCreateContainer(UnityContainer container)
        {
            var metadata   = container.Resolve <IMetadataProvider>();
            var serializer = container.Resolve <ITextSerializer>();

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString);

            container.RegisterInstance <IBlobStorage>(new CloudBlobStorage(blobStorageAccount, azureSettings.BlobStorage.RootContainerName));

            var commandBus        = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path), metadata, serializer);
            var eventsTopicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path);

            container.RegisterInstance <IMessageSender>("events", eventsTopicSender);
            container.RegisterInstance <IMessageSender>("orders", new TopicSender(azureSettings.ServiceBus, Topics.EventsOrders.Path));
            container.RegisterInstance <IMessageSender>("seatsavailability", new TopicSender(azureSettings.ServiceBus, Topics.EventsAvailability.Path));
            var eventBus = new EventBus(eventsTopicSender, metadata, serializer);

            var sessionlessCommandProcessor =
                new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Sessionless, false, new SubscriptionReceiverInstrumentation(Topics.Commands.Subscriptions.Sessionless, this.instrumentationEnabled)), serializer);
            var seatsAvailabilityCommandProcessor =
                new CommandProcessor(new SessionSubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Seatsavailability, false, new SessionSubscriptionReceiverInstrumentation(Topics.Commands.Subscriptions.Seatsavailability, this.instrumentationEnabled)), serializer);

            var synchronousCommandBus = new SynchronousCommandBusDecorator(commandBus);

            container.RegisterInstance <ICommandBus>(synchronousCommandBus);

            container.RegisterInstance <IEventBus>(eventBus);
            container.RegisterInstance <IProcessor>("SessionlessCommandProcessor", sessionlessCommandProcessor);
            container.RegisterInstance <IProcessor>("SeatsAvailabilityCommandProcessor", seatsAvailabilityCommandProcessor);

            RegisterRepositories(container);
            RegisterEventProcessors(container);
            RegisterCommandHandlers(container, sessionlessCommandProcessor, seatsAvailabilityCommandProcessor);

            // handle order commands inline, as they do not have competition.
            synchronousCommandBus.Register(container.Resolve <ICommandHandler>("OrderCommandHandler"));

            // message log
            var messageLogAccount = CloudStorageAccount.Parse(azureSettings.MessageLog.ConnectionString);

            container.RegisterInstance <IProcessor>("EventLogger", new AzureMessageLogListener(
                                                        new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                        new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Events.Path, Topics.Events.Subscriptions.Log)));

            container.RegisterInstance <IProcessor>("OrderEventLogger", new AzureMessageLogListener(
                                                        new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                        new SubscriptionReceiver(azureSettings.ServiceBus, Topics.EventsOrders.Path, Topics.EventsOrders.Subscriptions.LogOrders)));

            container.RegisterInstance <IProcessor>("SeatsAvailabilityEventLogger", new AzureMessageLogListener(
                                                        new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                        new SubscriptionReceiver(azureSettings.ServiceBus, Topics.EventsAvailability.Path, Topics.EventsAvailability.Subscriptions.LogAvail)));

            container.RegisterInstance <IProcessor>("CommandLogger", new AzureMessageLogListener(
                                                        new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                        new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Log)));
        }
        public async Task Send()
        {
            var msg = new BrokeredMessage();
            var m = NamespaceManager.CreateFromConnectionString(connection);
            var client = Substitute.For<IBusTopicClient>();
            client.Send(msg);

            var q = new TopicSender(Guid.NewGuid().ToString(), m, client);
            await q.Send(msg);

            client.Received().Send(msg);
        }
Exemplo n.º 9
0
        public CommandHandlerService()
        {
            serializer = new JsonSerializer();

            var eventSender = new TopicSender(settings, "proto/events");
            var eventBus    = new EventBus(eventSender, new DummyMetadataProvider(), serializer);

            eventStore = new EventStore("tenant", EventStoreConnectionString, serializer, eventBus);

            InitializeConsumer();
            InitializeCommandHandlers();
        }
Exemplo n.º 10
0
        static void TestSendCommand()
        {
            TopicClient commandClient = TopicClient.CreateFromConnectionString(serviceBusConnectionString, commandTopicPath);
            TopicSender sender        = new TopicSender(commandClient);
            //sender.Send( () => { return new BrokeredMessage( "Hello CQRS" ); } );
            ITextSerializer serializer = new JsonTextSerializer();
            CommandBus      bus        = new CommandBus(sender, serializer);

            bus.Send(new Envelope <ICommand>(new PlaceOrder()
            {
                ProductId = 1, Quantity = 10
            }));
        }
Exemplo n.º 11
0
 public SyntheticMessageCreator(string serviceBusConnectionString, string monitoringTopicName, ILogger log)
 {
     _servicebusConnectionString = serviceBusConnectionString;
     _monitoringTopicName        = monitoringTopicName;
     if (ts is null)
     {
         ts = new TopicSender(_servicebusConnectionString, _monitoringTopicName, log);
     }
     if (_logger is null)
     {
         _logger = log;
     }
 }
Exemplo n.º 12
0
        static void TestSendEvent()
        {
            TopicClient     eventClient = TopicClient.CreateFromConnectionString(serviceBusConnectionString, orderEventTopicPath);
            TopicSender     sender      = new TopicSender(eventClient);
            ITextSerializer serializer  = new JsonTextSerializer();

            EventBus eventBus = new EventBus(sender, serializer);

            eventBus.Publish(new Envelope <IEvent>(new OrderPlaced()
            {
                ProductId = 1,
                Quantity  = 2,
                SourceId  = Guid.NewGuid()
            }));
        }
        public void when_processing_throws_then_sends_message_to_dead_letter()
        {
            var failCount = 0;
            var waiter    = new ManualResetEventSlim();
            var sender    = new TopicSender(this.Settings, this.Topic);
            var processor = new Mock <MessageProcessor>(
                new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription), new JsonTextSerializer())
            {
                CallBase = true
            };

            processor.Protected()
            .Setup("ProcessMessage", ItExpr.IsAny <string>(), ItExpr.IsAny <object>(), ItExpr.IsAny <string>(), ItExpr.IsAny <string>())
            .Callback(() =>
            {
                failCount++;
                if (failCount == 5)
                {
                    waiter.Set();
                }

                throw new ArgumentException();
            });

            processor.Object.Start();

            var stream = new MemoryStream();

            new JsonTextSerializer().Serialize(new StreamWriter(stream), "Foo");
            stream.Position = 0;
            sender.SendAsync(() => new BrokeredMessage(stream, true));

            waiter.Wait(5000);

            var deadReceiver = this.Settings.CreateMessageReceiver(this.Topic, this.Subscription);

            var deadMessage = deadReceiver.Receive(TimeSpan.FromSeconds(5));

            processor.Object.Dispose();

            Assert.NotNull(deadMessage);
            var data = new JsonTextSerializer().Deserialize(new StreamReader(deadMessage.GetBody <Stream>()));

            Assert.Equal("Foo", (string)data);
        }
Exemplo n.º 14
0
        public void when_message_receivedthen_calls_process_message()
        {
            var waiter    = new ManualResetEventSlim();
            var sender    = new TopicSender(this.Settings, this.Topic);
            var processor = new FakeProcessor(
                waiter,
                new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription),
                new BinarySerializer());

            processor.Start();

            var stream = new MemoryStream();

            new BinarySerializer().Serialize(stream, "Foo");
            stream.Position = 0;
            sender.Send(new BrokeredMessage(stream, true));

            waiter.Wait(5000);

            Assert.NotNull(processor.Payload);
        }
Exemplo n.º 15
0
        public void TestTopic()
        {
            var  exchangeName = "test.topic";
            byte queueCount   = 4;

            ITopicSender publisher       = new TopicSender(_conn, exchangeName, queueCount, confirmEnabled: true, debugEnabled: true);
            var          sentMessageDict = new ConcurrentDictionary <string, Tuple <bool, IMessageTransportationContext> >();

            publisher.OnMessageSent += (sender, e) =>
            {
                sentMessageDict.TryAdd(e.Context.GetMessageId(), new Tuple <bool, IMessageTransportationContext>(false, e.Context));
            };
            publisher.OnMessageSendingSucceeded += (sender, e) =>
            {
                sentMessageDict.AddOrUpdate(e.Context.GetMessageId(), new Tuple <bool, IMessageTransportationContext>(true, e.Context), (key, originVal) => new Tuple <bool, IMessageTransportationContext>(true, originVal.Item2));
            };
            int sendSequence = 0;

            while (true)
            {
                try
                {
                    sendSequence++;
                    if (sendSequence % 3 == 0)
                    {
                        var message = new Message01(new Guid("58437EDC-87B7-4995-A5C0-BB5FD0FE49E0"))
                        {
                            Sequence = random.Next(1, 20)
                        };
                        Envelope envelopedMessage = Envelope.Create(message, $"{message.HostingFilialeId}_{Guid.NewGuid()}");
                        Task.Run(() => publisher.SendMessage(envelopedMessage));
                    }
                    else if (sendSequence % 3 == 1)
                    {
                        var message = new Message02(new Guid("7AE62AF0-EB1F-49C6-8FD1-128D77C84698"));
                        Task.Run(() => publisher.SendMessage(Envelope.Create(message, $"{message.SaleFilialeId}")));
                    }
                    else
                    {
                        var message = new Message03(new Guid("4AE62AF0-EB1F-49C6-8FD1-128D77C84698"));
                        Task.Run(() => publisher.SendMessage(Envelope.Create(message, $"{message.SaleFilialeId}")));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.GetType().FullName}");
                }
                if (sendSequence == 10000000)
                {
                    Thread.Sleep(3000);
                    Task.Run(() =>
                    {
                        publisher.Dispose();
                    });
                    break;
                }
            }
            var timeout        = sendSequence / 10;
            var executeSeconds = 0;

            while (sentMessageDict.Count != sendSequence || sentMessageDict.Values.Any(w => !w.Item1 && w.Item2.LastException == null))
            {
                if (executeSeconds > timeout)
                {
                    break;
                }
                Thread.Sleep(1000);
                executeSeconds++;
            }
            var failList = sentMessageDict.Values.Where(w => !w.Item1).ToList();
        }
Exemplo n.º 16
0
        static partial void OnCreateContainer(UnityContainer container)
        {
            var serializer = new JsonTextSerializer();

            container.RegisterInstance <ITextSerializer>(serializer);
            var metadata = new StandardMetadataProvider();

            container.RegisterInstance <IMetadataProvider>(metadata);

            var instrumentationEnabled = CloudConfigurationManager.GetSetting("InstrumentationEnabled") == "true";

            // command bus

            var settings = InfrastructureSettings.Read(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml"));

            if (!Conference.Common.MaintenanceMode.IsInMaintainanceMode)
            {
                new ServiceBusConfig(settings.ServiceBus).Initialize();
            }
            var commandBus = new CommandBus(new TopicSender(settings.ServiceBus, "conference/commands"), metadata, serializer);

            var synchronousCommandBus = new SynchronousCommandBusDecorator(commandBus);

            container.RegisterInstance <ICommandBus>(synchronousCommandBus);
            container.RegisterInstance <ICommandHandlerRegistry>(synchronousCommandBus);

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(settings.BlobStorage.ConnectionString);

            container.RegisterInstance <IBlobStorage>(new CloudBlobStorage(blobStorageAccount, settings.BlobStorage.RootContainerName));

            // support for inline command processing

            container.RegisterType <ICommandHandler, OrderCommandHandler>("OrderCommandHandler");
            container.RegisterType <ICommandHandler, ThirdPartyProcessorPaymentCommandHandler>("ThirdPartyProcessorPaymentCommandHandler");
            container.RegisterType <ICommandHandler, SeatAssignmentsHandler>("SeatAssignmentsHandler");

            container.RegisterType <DbContext, PaymentsDbContext>("payments", new TransientLifetimeManager(), new InjectionConstructor("Payments"));
            container.RegisterType <IDataContext <ThirdPartyProcessorPayment>, SqlDataContext <ThirdPartyProcessorPayment> >(
                new TransientLifetimeManager(),
                new InjectionConstructor(new ResolvedParameter <Func <DbContext> >("payments"), typeof(IEventBus)));

            container.RegisterType <IPricingService, PricingService>(new ContainerControlledLifetimeManager());

            var topicSender = new TopicSender(settings.ServiceBus, "conference/events");

            container.RegisterInstance <IMessageSender>(topicSender);
            var eventBus = new EventBus(topicSender, metadata, serializer);

            container.RegisterInstance <IEventBus>(eventBus);

            var eventSourcingAccount = CloudStorageAccount.Parse(settings.EventSourcing.ConnectionString);
            var eventStore           = new EventStore(eventSourcingAccount, settings.EventSourcing.OrdersTableName);

            container.RegisterInstance <IEventStore>(eventStore);
            container.RegisterInstance <IPendingEventsQueue>(eventStore);
            container.RegisterType <IEventStoreBusPublisher, EventStoreBusPublisher>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new TopicSender(settings.ServiceBus, "conference/eventsOrders"),
                    typeof(IPendingEventsQueue),
                    new EventStoreBusPublisherInstrumentation("web.public - orders", instrumentationEnabled)));
            container.RegisterType(
                typeof(IEventSourcedRepository <>),
                typeof(AzureEventSourcedRepository <>),
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(typeof(IEventStore), typeof(IEventStoreBusPublisher), typeof(ITextSerializer), typeof(IMetadataProvider), new InjectionParameter <ObjectCache>(null)));

            // to satisfy the IProcessor requirements.
            container.RegisterType <IProcessor, PublisherProcessorAdapter>("EventStoreBusPublisher", new ContainerControlledLifetimeManager());
        }
Exemplo n.º 17
0
        public void TestPubsub2()
        {
            var           exchangeName    = "test.pubsub";
            var           subscriberNames = new string[] { "wms", "erp" };
            byte          queueCount      = 2;
            IPubsubSender publisher       = new PubsubSender(_conn, exchangeName, subscriberNames, publishToExchange: true, publishToExchangeQueueCount: queueCount, debugEnabled: true);
            var           sentMessageDict = new ConcurrentDictionary <string, Tuple <bool, IMessageTransportationContext> >();

            publisher.OnMessageSent += (sender, e) =>
            {
                sentMessageDict.TryAdd(e.Context.GetMessageId(), new Tuple <bool, IMessageTransportationContext>(false, e.Context));
            };
            publisher.OnMessageSendingSucceeded += (sender, e) =>
            {
                sentMessageDict.AddOrUpdate(e.Context.GetMessageId(), new Tuple <bool, IMessageTransportationContext>(true, e.Context), (key, originVal) => new Tuple <bool, IMessageTransportationContext>(true, originVal.Item2));
            };
            foreach (var subscriberName in publisher.SubscriberNameQueueOrExchangeNameMapping.Keys)
            {
                var topicPublisher = new TopicSender(_conn, publisher.SubscriberNameQueueOrExchangeNameMapping[subscriberName], queueCount, sourceExchangeName: publisher.ExchangeName);
            }
            int sendSequence = 0;

            while (true)
            {
                try
                {
                    sendSequence++;
                    if (sendSequence % 4 != 0)
                    {
                        var message = new Message01(new Guid("58437EDC-87B7-4995-A5C0-BB5FD0FE49E0"))
                        {
                            Sequence = random.Next(1, 20)
                        };
                        Envelope envelopedMessage = Envelope.Create(message, $"{message.HostingFilialeId}_{Guid.NewGuid()}");
                        Task.Run(() => publisher.SendMessage(envelopedMessage));
                        Console.WriteLine($"{sendSequence}. send Message01 sequence={message.Sequence} ");
                    }
                    else
                    {
                        var message = new Message02(new Guid("7AE62AF0-EB1F-49C6-8FD1-128D77C84698"));
                        Task.Run(() => publisher.SendMessage(Envelope.Create(message, $"{message.SaleFilialeId}")));
                        Console.WriteLine($"{sendSequence}. send Message02 no sequence");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.Message}");
                }
                if (sendSequence == 1000)
                {
                    Thread.Sleep(3000);
                    Task.Run(() =>
                    {
                        publisher.Dispose();
                    });
                    break;
                }
            }
            var timeout        = sendSequence / 10;
            var executeSeconds = 0;

            while (sentMessageDict.Count != sendSequence || sentMessageDict.Values.Any(w => !w.Item1 && w.Item2.LastException == null))
            {
                if (executeSeconds > timeout)
                {
                    break;
                }
                Thread.Sleep(1000);
                executeSeconds++;
            }
            var failList = sentMessageDict.Values.Where(w => !w.Item1).ToList();
        }
 public async Task SaveBrokeredMessageNull()
 {
     var queue = new TopicSender(Guid.NewGuid().ToString(), connection);
     await queue.Send((BrokeredMessage)null);
 }
        public void when_sending_message_batch_then_succeeds()
        {
            var sender = new TopicSender(this.settings, this.topic);

            sender.Send(new[] { new BrokeredMessage(Guid.NewGuid()), new BrokeredMessage(Guid.NewGuid()) });
        }
        public async Task SendThrowsMessagingException()
        {
            var msg = new BrokeredMessage();
            var m = NamespaceManager.CreateFromConnectionString(connection);
            var first = true;
            var client = Substitute.For<IBusTopicClient>();
            client.When(c => c.Send(msg)).Do(x =>
            {
                var tmp = first;
                first = false;
                throw new MessagingException(Guid.NewGuid().ToString(), tmp, new Exception());
            });

            var q = new TopicSender(Guid.NewGuid().ToString(), m, client);
            await q.Send(msg);
        }
 public async Task SaveObjectNull()
 {
     var queue = new TopicSender(Guid.NewGuid().ToString(), connection);
     await queue.Send((object)null);
 }
        public void HandleTransientErrorNull()
        {
            this.exception = null;
            var ex = new MessagingException("hahaha");

            var bq = new TopicSender(Guid.NewGuid().ToString(), connection);
            bq.TransientErrorOccured += this.Error;
            bq.HandleTransientError(null);

            Assert.IsNull(this.exception);
        }
Exemplo n.º 23
0
        partial void OnCreateContainer(IServiceCollection services, ITextSerializer serializer, IMetadataProvider metadata, ILoggerFactory loggerFactory)
        {
            var azureSettings = InfrastructureSettings.Read("Application\\Settings.xml");

            var busConfig = new ServiceBusConfig(azureSettings.ServiceBus, loggerFactory);

            busConfig.Initialize();

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString);

            services.AddSingleton <IBlobStorage>(new CloudBlobStorage(blobStorageAccount, azureSettings.BlobStorage.RootContainerName, loggerFactory.CreateLogger <CloudBlobStorage>()));
            var topicLogger       = loggerFactory.CreateLogger <TopicSender>();
            var commandBus        = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path, topicLogger), metadata, serializer);
            var eventsTopicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path, topicLogger);

            services.AddSingleton <IMessageSender>(eventsTopicSender);
            services.AddSingleton <IMessageSender>(/*"orders", */ new TopicSender(azureSettings.ServiceBus, Topics.EventsOrders.Path, topicLogger));
            services.AddSingleton <IMessageSender>(/*"seatsavailability",*/ new TopicSender(azureSettings.ServiceBus, Topics.EventsAvailability.Path, topicLogger));
            var eventBus = new EventBus(eventsTopicSender, metadata, serializer);

            var subscriptionLogger          = loggerFactory.CreateLogger <SubscriptionReceiver>();
            var sessionSubscriptionLogger   = loggerFactory.CreateLogger <SessionSubscriptionReceiver>();
            var sessionlessCommandProcessor =
                new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Sessionless, false, subscriptionLogger), serializer, loggerFactory.CreateLogger <CommandProcessor>());
            var anchorsAvailabilityCommandProcessor =
                new CommandProcessor(new SessionSubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Anchorsavailability, false, sessionSubscriptionLogger), serializer, loggerFactory.CreateLogger <CommandProcessor>());

            var synchronousCommandBus = new SynchronousCommandBusDecorator(commandBus, loggerFactory.CreateLogger <SynchronousCommandBusDecorator>());

            services.AddSingleton <ICommandBus>(synchronousCommandBus);

            services.AddSingleton <IEventBus>(eventBus);
            services.AddSingleton <IProcessor>(/*"SessionlessCommandProcessor", */ sessionlessCommandProcessor);
            services.AddSingleton <IProcessor>(/*"AnchorsAvailabilityCommandProcessor", */ anchorsAvailabilityCommandProcessor);

            RegisterRepositories(services, azureSettings, loggerFactory);

            var serviceProvider = services.BuildServiceProvider();

            RegisterEventProcessors(services, serviceProvider, busConfig, serializer, loggerFactory);

            var commandHandlers = serviceProvider.GetServices <ICommandHandler>().ToList();

            RegisterCommandHandlers(services, commandHandlers, sessionlessCommandProcessor, anchorsAvailabilityCommandProcessor);

            // handle order commands inline, as they do not have competition.
            // TODO: Get exactly OrderCommandHandler
            synchronousCommandBus.Register(commandHandlers.First(s => s.GetType() == typeof(OrderCommandHandler)));

            // message log
            var messageLogAccount = CloudStorageAccount.Parse(azureSettings.MessageLog.ConnectionString);

            services.AddSingleton <IProcessor>(/*"EventLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Events.Path, Topics.Events.Subscriptions.Log, true, subscriptionLogger)));

            services.AddSingleton <IProcessor>(/*"OrderEventLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.EventsOrders.Path, Topics.EventsOrders.Subscriptions.LogOrders, true, subscriptionLogger)));

            services.AddSingleton <IProcessor>(/*"SeatsAvailabilityEventLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.EventsAvailability.Path, Topics.EventsAvailability.Subscriptions.LogAvail, true, subscriptionLogger)));

            services.AddSingleton <IProcessor>(/*"CommandLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Log, true, subscriptionLogger)));
        }
Exemplo n.º 24
0
        static void TestSendEvent()
        {
            TopicClient eventClient = TopicClient.CreateFromConnectionString( serviceBusConnectionString, orderEventTopicPath );
            TopicSender sender = new TopicSender( eventClient );
            ITextSerializer serializer = new JsonTextSerializer();

            EventBus eventBus = new EventBus( sender, serializer );
            eventBus.Publish( new Envelope<IEvent>( new OrderPlaced()
            {
                ProductId = 1,
                Quantity = 2,
                SourceId = Guid.NewGuid()
            } ) );
        }
Exemplo n.º 25
0
        static void TestSendCommand()
        {
            TopicClient commandClient = TopicClient.CreateFromConnectionString( serviceBusConnectionString, commandTopicPath );
            TopicSender sender = new TopicSender( commandClient );
            //sender.Send( () => { return new BrokeredMessage( "Hello CQRS" ); } );
            ITextSerializer serializer = new JsonTextSerializer();
            CommandBus bus = new CommandBus( sender, serializer );

            bus.Send( new Envelope<ICommand>( new PlaceOrder() { ProductId = 1, Quantity = 10 } ) );
        }
Exemplo n.º 26
0
 public TopicController(TopicSender TopicSender)
 {
     _TopicSender = TopicSender;
 }