Example #1
0
        protected void Application_Start()
        {
            Database.DefaultConnectionFactory = new ServiceConfigurationSettingConnectionFactory(Database.DefaultConnectionFactory);

            AreaRegistration.RegisterAllAreas();

            Database.SetInitializer<ConferenceContext>(null);

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

            var serializer = new JsonTextSerializer();
#if LOCAL
            EventBus = new EventBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer);
#else
            var settings = InfrastructureSettings.ReadMessaging(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml"));

            EventBus = new EventBus(new TopicSender(settings, "conference/events"), new MetadataProvider(), serializer);
#endif

            if (Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.IsAvailable)
            {
                System.Diagnostics.Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
                System.Diagnostics.Trace.AutoFlush = true;
            }
        }
Example #2
0
        private static UnityContainer CreateContainer()
        {
            var container = new UnityContainer();

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

#if LOCAL
            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));
#else
            var settings = InfrastructureSettings.ReadMessaging(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml"));
            var commandBus = new CommandBus(new TopicSender(settings, "conference/commands"), new MetadataProvider(), serializer);

            container.RegisterInstance<ICommandBus>(commandBus);
#endif

            // repository

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

            container.RegisterType<IOrderDao, OrderDao>();
            container.RegisterType<IConferenceDao, ConferenceDao>();
            container.RegisterType<IPaymentDao, PaymentDao>();

            return container;
        }
        static partial void OnCreateContainer(UnityContainer container)
        {
            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));
        }
Example #4
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
        }
        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<object>())
                .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);
        }
        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());
        }
Example #7
0
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.

            // Web API routes
            config.MapHttpAttributeRoutes();

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            config.Filters.Add(new ExceptionHandlingAttribute());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var container = new UnityContainer();

            try
            {
                // repositories used by the application

                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>();

                // configuration specific settings

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

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


                config.DependencyResolver = new UnityResolver(container);

                IEventBus eventBus = null;
//#if LOCAL
            eventBus = new Infrastructure.Sql.Messaging.EventBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer);
//#else
//                var settings = InfrastructureSettings.Read(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml")).ServiceBus;

//                if (!MaintenanceMode.IsInMaintainanceMode)
//                {
//                    new ServiceBusConfig(settings).Initialize();
//                }

//                eventBus = new Infrastructure.Azure.Messaging.EventBus(new TopicSender(settings, "conference/events"), new StandardMetadataProvider(), serializer);
//#endif

                container.RegisterInstance<IEventBus>(eventBus);

                var conferenceService = new ConferenceService(eventBus);

                container.RegisterInstance<ConferenceService>(conferenceService);
            }
            catch
            {
                container.Dispose();
                throw;
            }
        }
 private static string Serialize(object graph)
 {
     var serializer = new JsonTextSerializer();
     var writer = new StringWriter();
     serializer.Serialize(writer, graph);
     return writer.ToString();
 }
Example #9
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
        }
Example #10
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
        }
        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);
        }
        protected void Application_Start()
        {
            RoleEnvironment.Changed +=
                (s, a) =>
                {
                    var changes = a.Changes.OfType<RoleEnvironmentConfigurationSettingChange>().ToList();
                    if (changes.Any(x => x.ConfigurationSettingName != MaintenanceMode.MaintenanceModeSettingName))
                    {
                        RoleEnvironment.RequestRecycle();
                    }
                    else
                    {
                        if (changes.Any(x => x.ConfigurationSettingName == MaintenanceMode.MaintenanceModeSettingName))
                        {
                            MaintenanceMode.RefreshIsInMaintainanceMode();
                        }
                    }
                };
            MaintenanceMode.RefreshIsInMaintainanceMode();

            Database.DefaultConnectionFactory = new ServiceConfigurationSettingConnectionFactory(Database.DefaultConnectionFactory);

            AreaRegistration.RegisterAllAreas();

            Database.SetInitializer<ConferenceContext>(null);

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

            var serializer = new JsonTextSerializer();
#if LOCAL
            EventBus = new EventBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer);
#else
            var settings = InfrastructureSettings.Read(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml")).ServiceBus;
            new ServiceBusConfig(settings).Initialize();

            EventBus = new EventBus(new TopicSender(settings, "conference/events"), new StandardMetadataProvider(), serializer);
#endif

            if (Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.IsAvailable)
            {
                System.Diagnostics.Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
                System.Diagnostics.Trace.AutoFlush = true;
            }
        }
        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)));
        }
Example #14
0
        protected void Application_Start()
        {
#if AZURESDK
            Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.Changed +=
                (s, a) =>
                {
                    Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.RequestRecycle();
                };
#endif
            MaintenanceMode.RefreshIsInMaintainanceMode();

            DatabaseSetup.Initialize();

            AreaRegistration.RegisterAllAreas();

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

            var serializer = new JsonTextSerializer();
#if LOCAL
            EventBus = new EventBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer);
#else
            var settings = InfrastructureSettings.Read(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml")).ServiceBus;

            if (!MaintenanceMode.IsInMaintainanceMode)
            {
            new ServiceBusConfig(settings).Initialize();
            }

            EventBus = new EventBus(new TopicSender(settings, "conference/events"), new StandardMetadataProvider(), serializer);
#endif

#if AZURESDK
            if (Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.IsAvailable)
            {
                System.Diagnostics.Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
                System.Diagnostics.Trace.AutoFlush = true;
            }
#endif
        }