示例#1
0
        public async Task Save_WithEvents_SavesEventsInDbContext()
        {
            // arrange
            var aggregateRootId = Guid.NewGuid();

            var events = new IEvent[]
            {
                new ProjectCreated {
                    Id = aggregateRootId, Name = "AnyName", TimeStamp = DateTimeOffset.Now, Version = 1
                },
                new ProjectModified {
                    Id = aggregateRootId, Name = "AnyName", Description = "Any Descrition", TimeStamp = DateTimeOffset.Now, Version = 2
                },
            };

            var serializer = new JsonTextSerializer();
            var publisher  = new Mock <IEventPublisher>();

            var target = new EventStore(this.context.DbContext, serializer, publisher.Object);

            // act
            await target.Save(events);

            // assert
            Assert.Equal(2, this.context.DbContext.Events.Count(e => e.AggregateId == aggregateRootId));
        }
示例#2
0
        public async Task Get_WithFromVersionSmallerThanLatestVersion_ReturnsEventsNewerThanFromVersion()
        {
            // arrange
            var aggregateRootId = Guid.NewGuid();

            var events = new IEvent[]
            {
                new ProjectCreated {
                    Id = aggregateRootId, Name = "AnyName", TimeStamp = DateTimeOffset.Now, Version = 1
                },
                new ProjectModified {
                    Id = aggregateRootId, Name = "AnyName", Description = "Any Descrition", TimeStamp = DateTimeOffset.Now, Version = 2
                },
            };

            var serializer = new JsonTextSerializer();
            var publisher  = new Mock <IEventPublisher>();

            var target = new EventStore(this.context.DbContext, serializer, publisher.Object);
            await target.Save(events);

            // act
            IEnumerable <IEvent> actual = await target.Get(aggregateRootId, 1);

            // assert
            Assert.Equal(1, actual.Count());
        }
        private IUnityContainer CreateContainer(IDomainWorkerRegistry domainRegistry)
        {
            var container = new UnityContainer();

            container.RegisterInstance <IDomainWorkerRegistry>(domainRegistry);

            // Infrastructure
            container.RegisterInstance <ISystemTime>(domainRegistry.Config.SystemTime);
            container.RegisterInstance <ITextSerializer>(new JsonTextSerializer());
            container.RegisterInstance <IMetadataProvider>(new StandardMetadataProvider());
            container.RegisterInstance <ITracer>(_tracer);

            var config = container.Resolve <IDomainWorkerRegistry>().Config;

            var serializer = container.Resolve <ITextSerializer>();
            var metadata   = container.Resolve <IMetadataProvider>();
            var tracer     = container.Resolve <ITracer>();
            var dateTime   = container.Resolve <ISystemTime>();

            var commandBus = new CommandBus(
                new MessageSender(System.Data.Entity.Database.DefaultConnectionFactory, config.EventStoreConnectionString, config.CommandBusTableName), serializer, dateTime);

            var eventBus = new EventBus(
                new MessageSender(System.Data.Entity.Database.DefaultConnectionFactory, config.EventStoreConnectionString, config.EventBusTableName), serializer);

            var commandProcessor = new CommandProcessor(
                new MessageReceiver(System.Data.Entity.Database.DefaultConnectionFactory, config.EventStoreConnectionString, config.CommandBusTableName, config.BusPollDelay, config.NumberOfProcessorsThreads, dateTime), serializer, tracer, new CommandBusTransientFaultDetector(config.EventStoreConnectionString));

            var liveEventProcessor = new EventProcessor(
                new MessageReceiver(System.Data.Entity.Database.DefaultConnectionFactory, config.EventStoreConnectionString, config.EventBusTableName, config.BusPollDelay, config.NumberOfProcessorsThreads, dateTime), serializer, tracer, new AsynchronousEventDispatcher(tracer));

            container.RegisterInstance <ICommandBus>(commandBus);
            container.RegisterInstance <IEventBus>(eventBus);
            container.RegisterInstance <ICommandHandlerRegistry>(commandProcessor);
            container.RegisterInstance <IMessageProcessor>("CommandProcessor", commandProcessor);
            container.RegisterInstance <IEventHandlerRegistry>(liveEventProcessor);
            container.RegisterInstance <IMessageProcessor>("EventProcessor", liveEventProcessor);

            var indentedSerializer = new JsonTextSerializer();

            // Event log database and handler
            //this.RegisterMessageLogger(container, indentedSerializer, metadata, liveEventProcessor, config.MessageLogConnectionString, tracer, dateTime);

            // Event Store
            container.RegisterType <EventStoreDbContext>(new TransientLifetimeManager(), new InjectionConstructor(config.EventStoreConnectionString));
            this.RegisterSnapshoter(container);
            container.RegisterType(typeof(IEventStore <>), typeof(EventStore <>), new ContainerControlledLifetimeManager());

            // Bounded Context Registration
            foreach (var registrationAction in domainRegistry.RegistrationList)
            {
                registrationAction(container, liveEventProcessor);
            }

            // Handlers
            this.RegisterCommandHandlers(container);
            this.RegisterAditionalEventHandlers(container, liveEventProcessor);

            return(container);
        }
        private IUnityContainer CreateContainer()
        {
            var container = new UnityContainer();

            try {
                container.RegisterType <ConferenceRegistrationDbContext>(new TransientLifetimeManager(),
                                                                         new InjectionConstructor("ConferenceRegistration"));
                container.RegisterType <PaymentsReadDbContext>(new TransientLifetimeManager(),
                                                               new InjectionConstructor("Payments"));

                var cache = new MemoryCache("ReadModel");
                container.RegisterType <IOrderDao, OrderDao>();
                container.RegisterType <IConferenceDao, CachingConferenceDao>(
                    new ContainerControlledLifetimeManager(),
                    new InjectionConstructor(new ResolvedParameter <ConferenceDao>(), cache));
                container.RegisterType <IPaymentDao, PaymentDao>();

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

                container.RegisterType <IBlobStorage, SqlBlobStorage>(new ContainerControlledLifetimeManager(),
                                                                      new InjectionConstructor("BlobStorage"));
                container.RegisterType <IMessageSender, MessageSender>("Commands", new TransientLifetimeManager(),
                                                                       new InjectionConstructor(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Commands"));
                container.RegisterType <ICommandBus, CommandBus>(new ContainerControlledLifetimeManager(),
                                                                 new InjectionConstructor(new ResolvedParameter <IMessageSender>("Commands"), serializer));

                return(container);
            }
            catch (Exception) {
                container.Dispose();
                throw;
            }
        }
        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)));
        }
示例#6
0
        internal static IUnityContainer ResolveCommonDependenciesForMainContainer(IUnityContainer container, bool useSignalRLog, bool verbose)
        {
            System.Data.Entity.Database.SetInitializer <EventStoreDbContext>(null);
            System.Data.Entity.Database.SetInitializer <EventQueueDbContext>(null);

            var log = useSignalRLog ? (ILogger)SignalRLogger.GetResolvedSignalRLogger(verbose) : new ConsoleLogger(verbose);

            container.RegisterInstance <ILogger>(log);

            // Only one instance of the event publisher sould be in a node.
            container.RegisterInstance <IInMemoryEventPublisher>(new InMemoryEventPublisher(log));

            var serializer = new JsonTextSerializer();

            container.RegisterInstance <ITextSerializer>(serializer);

            var time = new UtcTimeProvider() as IUtcTimeProvider;

            container.RegisterInstance <IUtcTimeProvider>(time);

            container.RegisterInstance <IGuidProvider>(new SequentialGuid());

            // Do not share this with child dependencies
            container.RegisterInstance <IBus>(new Bus());

            return(container);
        }
示例#7
0
        public void Try_deserialize_event_with_not_found_ClrType()
        {
            var textSerializer  = new JsonTextSerializer();
            var eventSerializer = new EventSerializer(textSerializer);

            var serializedData = textSerializer.Serialize(new SpokeSomething("Hi"));

            var metadata = new EventSource.Metadata(new[]
            {
                new KeyValuePair <string, object>(MetadataKeys.AggregateId, Guid.NewGuid().ToString()),
                new KeyValuePair <string, object>(MetadataKeys.StreamSequenceNumber, 1.ToString()),
                new KeyValuePair <string, object>(MetadataKeys.EventClrType, "Cars.UnitTests.EventSerializerTests+NotFoundClrType, Cars.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
            });

            var mockCommitedEvent = new Mock <ICommitedEvent>();

            mockCommitedEvent.Setup(e => e.Version).Returns(1);
            mockCommitedEvent.Setup(e => e.AggregateId).Returns(Guid.NewGuid);
            mockCommitedEvent.Setup(e => e.SerializedData).Returns(serializedData);
            mockCommitedEvent.Setup(e => e.SerializedMetadata).Returns(textSerializer.Serialize(metadata));

            Action act = () => eventSerializer.Deserialize(mockCommitedEvent.Object);

            act.ShouldThrowExactly <EventTypeNotFoundException>();
        }
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            container.RegisterType <ConferenceRegistrationDbContext>(new TransientLifetimeManager(),
                                                                     new InjectionConstructor("ConferenceRegistration"));
            container.RegisterType <PaymentsReadDbContext>(new TransientLifetimeManager(),
                                                           new InjectionConstructor("Payments"));

            var cache = new MemoryCache("ReadModel");

            container.RegisterType <IOrderDao, OrderDao>();
            container.RegisterType <IConferenceDao, CachingConferenceDao>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(new ResolvedParameter <ConferenceDao>(), cache));

            container.RegisterType <IPaymentDao, PaymentDao>();

            var serializer = new JsonTextSerializer();

            container.RegisterInstance <ITextSerializer>(serializer);

            container.RegisterType <IBlobStorage, SqlBlobStorage>(new ContainerControlledLifetimeManager(),
                                                                  new InjectionConstructor("BlobStorage"));
            container.RegisterType <IMessageSender, MessageSender>("Commands", new TransientLifetimeManager(),
                                                                   new InjectionConstructor(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Commands"));
            container.RegisterType <ICommandBus, CommandBus>(new ContainerControlledLifetimeManager(),
                                                             new InjectionConstructor(new ResolvedParameter <IMessageSender>("Commands"), serializer));


            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
示例#9
0
        private static IUnityContainer ResolveCommonDependenciesForMainContainer(bool useSignalRLog, bool verbose)
        {
            var mainContainer = new UnityContainer();

            var log = useSignalRLog ? (ILogger)SignalRLogger.GetResolvedSignalRLogger(verbose) : new ConsoleLogger(verbose);

            mainContainer.RegisterInstance <ILogger>(log);

            mainPublisher = new InMemoryEventPublisher(log);

            var serializer = new JsonTextSerializer();

            mainContainer.RegisterInstance <ITextSerializer>(serializer);

            var time = new UtcTimeProvider() as IUtcTimeProvider;

            mainContainer.RegisterInstance <IUtcTimeProvider>(time);

            mainContainer.RegisterInstance <IGuidProvider>(new SequentialGuid());

            // Do not share this with child dependencies
            mainContainer.RegisterInstance <IBus>(new Bus());

            return(mainContainer);
        }
        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);
        }
示例#11
0
        private static string Serialize(object graph)
        {
            var serializer = new JsonTextSerializer();
            var writer     = new StringWriter();

            serializer.Serialize(writer, graph);
            return(writer.ToString());
        }
示例#12
0
        public void TestMakeAppointment()
        {
            //Setup
//            var connStr = @"Server=192.168.88.79\SQLEXPRESS;Database=appointments;User Id=chinook;Password=pr0t3ct3d";
            var connStr = @"Data Source=.\SQLEXPRESS;Database=appointments;User Id=chinook;Password=pr0t3ct3d";

            IMessageSender  sender     = new SqlMessageSender(connStr, "dbo.messages");
            ITextSerializer serializer = new JsonTextSerializer();
//			IEventStore eventStore = new SqlEventStore(connStr, "dbo.events");
//
//			IEventBus eventBus = new EventBus(sender, serializer);
//			IMetadataProvider metaProvider = new StandardMetadataProvider();
            IReadModelStorage <AppointmentReadModel> readModelStorage = new InMemeoryStorage <AppointmentReadModel>();
//
//			IEventSourcedRepository<AppointmentAggregate> repo = new
//				EventSourcedRepository<AppointmentAggregate>(eventStore, eventBus, serializer, metaProvider);
//			ICommandDispatcher cmdDispatcher = new CommandDispatcher();
//			cmdDispatcher.Register(new AppointmentCommandHandler(repo));
//
//			IEventDispatcher evtDispatcher = new EventDispatcher();
//			evtDispatcher.Register(new AppointmentEventHandler(readModelStorage));
//
//			IMessageReceiver cmdReceiver = new SqlMessageReceiver(connStr, "dbo.commands");
//
//			IMessageReceiver evtReceiver = new SqlMessageReceiver(connStr, "dbo.events");
//
//			CommandProcessor commandProcessor = new CommandProcessor(cmdReceiver, serializer, cmdDispatcher);
//			EventPorcessor eventProcessor = new EventPorcessor(evtReceiver, serializer, evtDispatcher);
//
//
//			commandProcessor.Start();
//
//			eventProcessor.Start();

            ICommandBus commandBus = new CommandBus(sender, serializer);

            //Test
            var command = new MakeAppointment();

            command.Appointment           = new Appointment();
            command.Appointment.Body      = "Dental appointment";
            command.Appointment.Subject   = "Dental";
            command.Appointment.Start     = DateTimeOffset.MinValue;
            command.Appointment.End       = DateTimeOffset.MaxValue;
            command.Appointment.Organizer = "Jeff Jin";
            var cmdTask = commandBus.Publish(new [] { command });

            cmdTask.Wait();

//			var task = readModelStorage.GetAll(0, 10);
//			task.Wait();
//
//			Thread.Sleep(3000);
//
//			//Verify
//			Assert.AreEqual(1, task.Result.Count());
        }
示例#13
0
        private static string Serialize(object payload)
        {
            var serializer = new JsonTextSerializer();

            using (var writer = new StringWriter()) {
                serializer.Serialize(writer, payload);
                return(writer.ToString());
            }
        }
示例#14
0
        internal static IEventBus BuildEventBus()
        {
            var serializer = new JsonTextSerializer();

#if LOCAL
            return(new EventBus(GetMessageSender("SqlBus.Events"), serializer));
#else
            return(new EventBus(GetTopicSender("events"), new StandardMetadataProvider(), serializer));
#endif
        }
示例#15
0
        internal static ICommandBus BuildCommandBus()
        {
            var serializer = new JsonTextSerializer();

#if LOCAL
            return(new CommandBus(GetMessageSender("SqlBus.Commands"), serializer));
#else
            return(new SynchronousCommandBusDecorator(new CommandBus(GetTopicSender("commands"), new StandardMetadataProvider(), serializer)));
#endif
        }
示例#16
0
        private void RunTest(object value, int times, bool useGZip)
        {
            var vType          = value?.GetType() ?? typeof(object);
            var compressor     = useGZip ? CompressorManager.GetByEncodingType("gzip") : null;
            var memStream      = new RecycleMemoryStream();
            var jsonSerializer = new JsonTextSerializer {
                Compressor = compressor
            };
            var xmlSerializer = new XmlTextSerializer {
                Compressor = compressor
            };
            var binarySerializer = new BinaryFormatterSerializer {
                Compressor = compressor
            };
            var ut8JsonSerializer = new Utf8JsonTextSerializer {
                Compressor = compressor
            };
            var msgPackSerializer = new MsgPackSerializer {
                Compressor = compressor
            };
            var nBinarySerializer = new NBinarySerializer {
                Compressor = compressor
            };
            var rawBinarySerializer = new RawBinarySerializer {
                Compressor = compressor
            };
            var wBinarySerializer = new WBinarySerializer {
                Compressor = compressor
            };
            var pwBinarySerializer = new PWBinarySerializer {
                Compressor = compressor
            };

            Core.Log.Warning("Running Serializer Test. Use GZIP = {0}", useGZip);
            Core.Log.WriteEmptyLine();
            Core.Log.InfoBasic("By size:");
            Core.Log.InfoBasic("\tJson Bytes Count: {0}", SerializerSizeProcess(value, vType, jsonSerializer));
            Core.Log.InfoBasic("\tXml Bytes Count: {0}", SerializerSizeProcess(value, vType, xmlSerializer));
            Core.Log.InfoBasic("\tBinaryFormatter Bytes Count: {0}", SerializerSizeProcess(value, vType, binarySerializer));
            Core.Log.InfoBasic("\tUtf8Json Bytes Count: {0}", SerializerSizeProcess(value, vType, ut8JsonSerializer));
            Core.Log.InfoBasic("\tMessagePack Bytes Count: {0}", SerializerSizeProcess(value, vType, msgPackSerializer));
            Core.Log.InfoBasic("\tNBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, nBinarySerializer));
            Core.Log.InfoBasic("\tRawBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, rawBinarySerializer));
            Core.Log.InfoBasic("\tWBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, wBinarySerializer));
            Core.Log.InfoBasic("\tPortable WBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, pwBinarySerializer));
            Core.Log.WriteEmptyLine();
            Core.Log.InfoBasic("By Times: {0}", times);
            SerializerProcess("Json", value, vType, times, jsonSerializer, memStream);
            SerializerProcess("Utf8Json", value, vType, times, ut8JsonSerializer, memStream);
            SerializerProcess("NBinary", value, vType, times, nBinarySerializer, memStream);
            SerializerProcess("RawBinary", value, vType, times, rawBinarySerializer, memStream);
            SerializerProcess("WBinary", value, vType, times, wBinarySerializer, memStream);
            SerializerProcess("PWBinary", value, vType, times, pwBinarySerializer, memStream);
            Console.ReadLine();
        }
示例#17
0
        static void TestProcessEvent()
        {
            SubscriptionClient   subscriptionClient = SubscriptionClient.CreateFromConnectionString(serviceBusConnectionString, orderEventTopicPath, orderEventSubscription);
            SubscriptionReceiver receiver           = new SubscriptionReceiver(subscriptionClient);
            ITextSerializer      serializer         = new JsonTextSerializer();

            EventProcessor eventProcessor = new EventProcessor(receiver, serializer);

            eventProcessor.Register(new OrderEventHandler());
            eventProcessor.Start();
        }
示例#18
0
        static void TestProcessCommand()
        {
            SubscriptionClient   subscriptionClient = SubscriptionClient.CreateFromConnectionString(serviceBusConnectionString, commandTopicPath, commandHandlerSubscription);
            SubscriptionReceiver receiver           = new SubscriptionReceiver(subscriptionClient);
            ITextSerializer      serializer         = new JsonTextSerializer();

            CommandProcessor orderCommandProcessor = new CommandProcessor(receiver, serializer);

            orderCommandProcessor.Register(new OrderCommandHandler());

            orderCommandProcessor.Start();
        }
示例#19
0
        static partial void OnCreateContainer(UnityContainer container)
        {
            var serializer = new JsonTextSerializer();

            container.RegisterInstance <ITextSerializer>(serializer);

            container.RegisterType <IBlobStorage, SqlBlobStorage>(new ContainerControlledLifetimeManager(), new InjectionConstructor("Conference"));
            container.RegisterType <IMessageSender, MessageSender>(
                "Commands", new TransientLifetimeManager(), new InjectionConstructor("SqlBus", "SqlBus.Commands"));
            container.RegisterType <ICommandBus, CommandBus>(
                new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter <IMessageSender>("Commands"), serializer));
        }
示例#20
0
        public void CreateContainer(IServiceCollection services, ILoggerFactory loggerFactory)
        {
            var serializer = new JsonTextSerializer();

            services.AddSingleton <ITextSerializer>(serializer);

            var metadataProvider = new StandardMetadataProvider();

            services.AddSingleton <IMetadataProvider>(metadataProvider);

            //services.AddScoped(provider =>
            //{
            //    Func<string, ICommandHandler> accessor = key =>
            //    {
            //        switch (key)
            //        {
            //            case "RegistrationProcessManagerRouter":
            //                return provider.GetService<RegistrationProcessManagerRouter>();
            //            case "OrderCommandHandler":
            //                return provider.GetService<OrderCommandHandler>();
            //            case "AnchorsAvailabilityHandler":
            //                return provider.GetService<AnchorsAvailabilityHandler>();
            //            case "AnchorAssignmentsHandler":
            //                return provider.GetService<AnchorAssignmentsHandler>();
            //            default:
            //                throw new KeyNotFoundException(string.Format("Key is {0}.", key));
            //        }
            //    };

            //    return accessor;
            //});

            services.AddScoped <ICommandHandler, RegistrationProcessManagerRouter>();
            services.AddScoped <ICommandHandler, OrderCommandHandler>();
            services.AddScoped <ICommandHandler, AnchorsAvailabilityHandler>();
            //services.AddScoped<ICommandHandler, ThirdPartyProcessorPaymentCommandHandler>("ThirdPartyProcessorPaymentCommandHandler");
            services.AddScoped <ICommandHandler, AnchorAssignmentsHandler>();

            services.AddSingleton <RegistrationProcessManagerRouter>();
            services.AddSingleton <PricedOrderViewModelGenerator>();
            services.AddSingleton <WorkshopViewModelGenerator>();
            services.AddSingleton <DraftOrderViewModelGenerator>();
            services.AddSingleton <AnchorAssignmentsViewModelGenerator>();
            services.AddSingleton <AnchorAssignmentsHandler>();
            services.AddSingleton <OrderEventHandler>();
            services.AddSingleton <IPricingService, PricingService>();

            // Conference management integration
            //container.RegisterType<global::Conference.ConferenceContext>(new TransientLifetimeManager(), new InjectionConstructor("ConferenceManagement"));

            OnCreateContainer(services, serializer, metadataProvider, loggerFactory);
        }
示例#21
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
            }));
        }
示例#22
0
 public HttpTransportServer()
 {
     _httpServer = new SimpleHttpServer();
     _httpServer.BeginRequest += HttpServer_BeginRequest;
     Serializer = new JsonTextSerializer();
     Core.Status.Attach(collection =>
     {
         collection.Add(nameof(Name), Name);
         collection.Add(nameof(Port), Port);
         collection.Add(nameof(EnableGetDescriptors), EnableGetDescriptors);
         Core.Status.AttachChild(_httpServer, this);
         Core.Status.AttachChild(Serializer, this);
     });
 }
示例#23
0
        public void OnCreateContainer1(IServiceCollection services)
        {
            var serializer = new JsonTextSerializer();

            services.AddSingleton <ITextSerializer>(serializer);

            var metadataProvider = new StandardMetadataProvider();

            services.AddSingleton <IMetadataProvider>(metadataProvider);
            services.AddSingleton <IBlobStorage, SqlBlobStorage>();

            var eventBus   = new EventBus(new MessageSender(_localConnectionString, "SqlBus.Events"), serializer);
            var commandBus = new CommandBus(new MessageSender(_localConnectionString, "SqlBus.Commands"), serializer);

            var commandProcessor = new CommandProcessor(new MessageReceiver(_localConnectionString, "SqlBus.Commands"), serializer);
            var eventProcessor   = new EventProcessor(new MessageReceiver(_localConnectionString, "SqlBus.Events"), serializer);

            services.AddSingleton <IEventBus>(eventBus);
            services.AddSingleton <ICommandBus>(commandBus);
            services.AddSingleton <ICommandHandlerRegistry>(commandProcessor);
            services.AddSingleton <IEventHandlerRegistry>(eventProcessor);

            services.AddSingleton(provider =>
            {
                Func <string, IProcessor> accessor = key =>
                {
                    switch (key)
                    {
                    case "CommandProcessor":
                        return(commandProcessor);

                    case "EventProcessor":
                        return(eventProcessor);

                    default:
                        throw new KeyNotFoundException(string.Format("current {0} key wasn't found in service collection", key));
                    }
                };
                return(accessor);
            });

            // Event log database and handler.
            services.AddTransient(provider => new SqlMessageLog(provider.GetService <IDbContextScopeFactory>(),
                                                                provider.GetService <IAmbientDbContextLocator>(), serializer, metadataProvider));
            services.AddScoped <IEventHandler, SqlMessageLogHandler>();
            services.AddScoped <ICommandHandler, SqlMessageLogHandler>();

            services.AddSingleton <IPricingService, PricingService>();
        }
示例#24
0
        protected void Application_Start()
        {
            //MaintenanceMode.RefreshIsInMaintainanceMode();

            DatabaseSetup.Initialize();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            var serializer = new JsonTextSerializer();

            EventBus = new EventBus(new MessageSender("SqlBus", "SqlBus.Events"), serializer);
        }
示例#25
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()
            }));
        }
示例#26
0
        static MessageLogHelper()
        {
            var serializer = new JsonTextSerializer();

#if LOCAL
            Database.DefaultConnectionFactory = new ServiceConfigurationSettingConnectionFactory(Database.DefaultConnectionFactory);
            Database.SetInitializer <MessageLogDbContext>(null);
            eventLog   = new SqlMessageLog("MessageLog", serializer, new StandardMetadataProvider());
            commandLog = new SqlCommandMessageLog("MessageLog", serializer, new StandardMetadataProvider());
#else
            var settings = InfrastructureSettings.Read("Settings.xml").MessageLog;
            var account  = CloudStorageAccount.Parse(settings.ConnectionString);
            eventLog   = new AzureEventLogReader(account, settings.TableName, serializer);
            commandLog = new AzureCommandLogReader(account, settings.TableName, serializer);
#endif
        }
示例#27
0
 public HttpTransportServer()
 {
     _httpServer = new SimpleHttpServer();
     _httpServer.OnBeginRequest += HttpServer_OnBeginRequest;
     Serializer = new JsonTextSerializer();
     Core.Status.Attach(collection =>
     {
         collection.Add(nameof(Name), Name);
         collection.Add(nameof(Port), Port);
         collection.Add(nameof(EnableGetDescriptors), EnableGetDescriptors);
         collection.Add("Bytes Sent", Counters.BytesSent, true);
         collection.Add("Bytes Received", Counters.BytesReceived, true);
         Core.Status.AttachChild(_httpServer, this);
         Core.Status.AttachChild(Serializer, this);
     });
 }
示例#28
0
        public static IEventSourcedRepository <SeatsAvailability> GetSeatsAvailabilityRepository()
        {
            var serializer = new JsonTextSerializer();

#if LOCAL
            Func <EventStoreDbContext> ctxFactory = () => new EventStoreDbContext("EventStore");
            return(new SqlEventSourcedRepository <SeatsAvailability>(ConferenceHelper.BuildEventBus(), serializer, ctxFactory));
#else
            var settings             = InfrastructureSettings.Read("Settings.xml");
            var eventSourcingAccount = CloudStorageAccount.Parse(settings.EventSourcing.ConnectionString);
            var eventStore           = new EventStore(eventSourcingAccount, settings.EventSourcing.SeatsAvailabilityTableName);
            var publisher            = new EventStoreBusPublisher(ConferenceHelper.GetTopicSender("eventsAvailability"), eventStore, new EventStoreBusPublisherInstrumentation("worker", false));
            var metadata             = new StandardMetadataProvider();
            return(new AzureEventSourcedRepository <SeatsAvailability>(eventStore, publisher, serializer, metadata, new MemoryCache("RepositoryCache")));
#endif
        }
示例#29
0
        public override void Run()
        {
            Trace.WriteLine("Starting processing of messages");

            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            Client.OnMessage(receivedMessage =>
            {
                try
                {
                    // Process the message
                    Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());

                    ITextSerializer serializer = new JsonTextSerializer();
                    using (var stream = receivedMessage.GetBody <Stream>())
                        using (var reader = new StreamReader(stream))
                        {
                            var payload = serializer.Deserialize(reader);

                            var commandType         = payload.GetType();
                            ICommandHandler handler = null;

                            if (handlers.TryGetValue(commandType, out handler))
                            {
                                // Invoke message handler to handle the message
                                ((dynamic)handler).Handle((dynamic)payload);


                                // Finish recieving the message and dequeue
                                receivedMessage.Complete();
                            }
                            else
                            {
                                receivedMessage.DeadLetter();
                            }
                        }
                }
                catch
                {
                    // Handle any message processing specific exceptions here
                    receivedMessage.DeadLetter();
                }
            });

            CompletedEvent.WaitOne();
        }
        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);
        }