partial void OnCreating()
        {
            azureSettings = InfrastructureSettings.Read("Settings.xml");
            busConfig     = new ServiceBusConfig(azureSettings.ServiceBus);

            busConfig.Initialize();
        }
        partial void OnCreating()
        {
            this.azureSettings = InfrastructureSettings.Read("Settings.xml");
            this.azureSettings.ServiceBus.Topics.First(t => t.IsEventBus).Subscriptions.AddRange(
                new[]
            {
                new SubscriptionSettings {
                    Name = "Registration.RegistrationProcessRouter", RequiresSession = true
                },
                new SubscriptionSettings {
                    Name = "Registration.OrderViewModelGenerator", RequiresSession = true
                },
                new SubscriptionSettings {
                    Name = "Registration.PricedOrderViewModelGenerator", RequiresSession = true
                },
                new SubscriptionSettings {
                    Name = "Registration.SeatAssignmentsViewModelGenerator", RequiresSession = true
                },
            });
            this.azureSettings.ServiceBus.Topics.First(t => !t.IsEventBus).Subscriptions.AddRange(
                new[]
            {
                new SubscriptionSettings {
                    Name = "all", RequiresSession = false
                }
            });

            this.busConfig = new ServiceBusConfig(this.azureSettings.ServiceBus);

            busConfig.Initialize();
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            var migrator           = new Migrator();
            var dbConnectionString = "DbContext.ConferenceManagement";

            var settings = InfrastructureSettings.Read("Settings.xml");
            var eventSourcingSettings  = settings.EventSourcing;
            var eventSourcingAccount   = CloudStorageAccount.Parse(eventSourcingSettings.ConnectionString);
            var originalEventStoreName = "ConferenceEventStore"; // should use the real one. No longer in the updated Settings.xml
            var newEventStoreName      = eventSourcingSettings.TableName;
            var messageLogSettings     = settings.MessageLog;
            var messageLogAccount      = CloudStorageAccount.Parse(messageLogSettings.ConnectionString);

            migrator.GeneratePastEventLogMessagesForConferenceManagement(
                messageLogAccount.CreateCloudTableClient(),
                messageLogSettings.TableName,
                dbConnectionString,
                new StandardMetadataProvider(),
                new JsonTextSerializer());
            migrator.MigrateEventSourcedAndGeneratePastEventLogs(
                messageLogAccount.CreateCloudTableClient(),
                messageLogSettings.TableName,
                eventSourcingAccount.CreateCloudTableClient(),
                originalEventStoreName,
                eventSourcingAccount.CreateCloudTableClient(),
                newEventStoreName,
                new StandardMetadataProvider(),
                new JsonTextSerializer());

            var logReader = new AzureEventLogReader(messageLogAccount, messageLogSettings.TableName, new JsonTextSerializer());

            migrator.RegenerateViewModels(logReader, dbConnectionString);
        }
        public void when_reading_topic_settings_then_sets_default_value_from_schema()
        {
            // Setup XSD validation so that we can load an XDocument with PSVI information
            var schema         = XmlSchema.Read(typeof(InfrastructureSettings).Assembly.GetManifestResourceStream("Infrastructure.Azure.Settings.xsd"), null);
            var readerSettings = new XmlReaderSettings {
                ValidationType = ValidationType.Schema
            };

            readerSettings.Schemas.Add(schema);
            readerSettings.Schemas.Compile();

            using (var reader = XmlReader.Create("Settings.Template.xml", readerSettings))
            {
                var doc = XDocument.Load(reader);
                // Even if the attribute is not in the XML file, we can access the
                // attribute because the XSD validation is adding the default value
                // post validation.
                var defaultValue = doc.Root.Descendants(
                    XNamespace.Get(InfrastructureSettings.XmlNamespace) + "Topic")
                                   .Skip(1)
                                   .First()
                                   .Attribute("DuplicateDetectionHistoryTimeWindow")
                                   .Value;

                var settings = InfrastructureSettings.Read("Settings.Template.xml").ServiceBus;

                Assert.Equal(
                    TimeSpan.Parse(defaultValue),
                    settings.Topics[1].DuplicateDetectionHistoryTimeWindow);
            }
        }
        public void when_reading_service_bus_from_file_then_succeeds()
        {
            var settings = InfrastructureSettings.Read("Settings.Template.xml").ServiceBus;

            Assert.NotNull(settings);
            Assert.Equal(4, settings.Topics.Count);
            Assert.Equal(3, settings.Topics[0].Subscriptions.Count);
        }
Exemplo n.º 6
0
        public given_blob_storage()
        {
            var settings = InfrastructureSettings.Read("Settings.xml").BlobStorage;

            this.account           = CloudStorageAccount.Parse(settings.ConnectionString);
            this.rootContainerName = Guid.NewGuid().ToString();
            this.sut = new CloudBlobStorage(account, this.rootContainerName);
        }
Exemplo n.º 7
0
        private static IBlobStorage GetBlobStorage()
        {
#if LOCAL
            IBlobStorage blobStorage = new SqlBlobStorage("BlobStorage");
#else
            var          azureSettings      = InfrastructureSettings.Read("Settings.xml");
            var          blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString);
            IBlobStorage blobStorage        = new CloudBlobStorage(blobStorageAccount, azureSettings.BlobStorage.RootContainerName);
#endif
            return(blobStorage);
        }
Exemplo n.º 8
0
        public given_an_empty_event_log()
        {
            this.tableName = "AzureEventLogFixture" + new Random((int)DateTime.Now.Ticks).Next();
            var settings = InfrastructureSettings.Read("Settings.xml").EventSourcing;

            this.account = CloudStorageAccount.Parse(settings.ConnectionString);

            this.eventA = new EventA();
            this.eventB = new EventB();
            this.eventC = new EventC();

            this.metadata = Mock.Of <IMetadataProvider>(x =>
                                                        x.GetMetadata(eventA) == new Dictionary <string, string>
            {
                { StandardMetadata.SourceId, eventA.SourceId.ToString() },
                { StandardMetadata.SourceType, "SourceA" },
                { StandardMetadata.Kind, StandardMetadata.EventKind },
                { StandardMetadata.AssemblyName, "A" },
                { StandardMetadata.Namespace, "Namespace" },
                { StandardMetadata.FullName, "Namespace.EventA" },
                { StandardMetadata.TypeName, "EventA" },
            } &&
                                                        x.GetMetadata(eventB) == new Dictionary <string, string>
            {
                { StandardMetadata.SourceId, eventB.SourceId.ToString() },
                { StandardMetadata.SourceType, "SourceB" },
                { StandardMetadata.Kind, StandardMetadata.EventKind },
                { StandardMetadata.AssemblyName, "B" },
                { StandardMetadata.Namespace, "Namespace" },
                { StandardMetadata.FullName, "Namespace.EventB" },
                { StandardMetadata.TypeName, "EventB" },
            } &&
                                                        x.GetMetadata(eventC) == new Dictionary <string, string>
            {
                { StandardMetadata.SourceId, eventC.SourceId.ToString() },
                { StandardMetadata.SourceType, "SourceC" },
                { StandardMetadata.Kind, StandardMetadata.EventKind },
                { StandardMetadata.AssemblyName, "B" },
                { StandardMetadata.Namespace, "AnotherNamespace" },
                { StandardMetadata.FullName, "AnotherNamespace.EventC" },
                { StandardMetadata.TypeName, "EventC" },
            });

            this.serializer = new JsonTextSerializer();
            this.writer     = new AzureMessageLogWriter(this.account, this.tableName);
            this.sut        = new AzureEventLogReader(this.account, this.tableName, new JsonTextSerializer());

            this.startEnqueueTime = new DateTime(2012, 06, 30, 23, 59, 0, DateTimeKind.Utc);
            Save(eventA, startEnqueueTime);
            Save(eventB, startEnqueueTime.AddMinutes(5));
            Save(eventC, startEnqueueTime.AddMinutes(6));
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var migrator           = new Migrator();
            var dbConnectionString = "DbContext.ConferenceManagement";

            var settings           = InfrastructureSettings.Read("Settings.xml");
            var messageLogSettings = settings.MessageLog;
            var messageLogAccount  = CloudStorageAccount.Parse(messageLogSettings.ConnectionString);
            var blobStorageAccount = CloudStorageAccount.Parse(settings.BlobStorage.ConnectionString);

            DatabaseSetup.Initialize();
            MigrationToV3.Migration.Initialize();


            Console.WriteLine("Creating new read model subscriptions");

            migrator.CreateV3ReadModelSubscriptions(settings.ServiceBus);

            Console.WriteLine("Creating new read model tables");

            migrator.CreateV3ReadModelTables(ConfigurationManager.ConnectionStrings[dbConnectionString].ConnectionString);

            Console.WriteLine("Waiting to let the new subscriptions fill up with events. This will take {0:F0} minutes.", WaitTime.TotalMinutes);

            Thread.Sleep(WaitTime);

            Console.WriteLine("Replaying events to regenerate read models");

            var logReader   = new AzureEventLogReader(messageLogAccount, messageLogSettings.TableName, new JsonTextSerializer());
            var blobStorage = new CloudBlobStorage(blobStorageAccount, settings.BlobStorage.RootContainerName);

            var maxEventTime = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(WaitTime.TotalSeconds / 2));

            migrator.RegenerateV3ViewModels(logReader, blobStorage, dbConnectionString, maxEventTime);

            Console.WriteLine("Set the MaintenanceMode flag to true in the worker role for v2 through the Windows Azure portal, but let the websites keep running. Make sure that the status for the worker role is updated before continuing.");
            Console.WriteLine("Press enter to start processing events.");
            Console.ReadLine();

            using (var processor = new ConferenceProcessor(false))
            {
                processor.Start();

                Console.WriteLine("Started processing events to keep the v2 read models up to date, so there is no downtime until v3 starts functioning.");
                Console.WriteLine("Set the MaintenanceMode flag to false in all the v3 roles. Once you verify that the v3 roles are working correctly in the Staging area, you can do a VIP swap so the public website points to v3.");
                Console.WriteLine("Press enter to finish and stop processing v2 read models (only do this once v3 is in the Production slot). You can also stop the v2 deployment that should be in the Staging slot after the VIP swap");
                Console.ReadLine();

                processor.Stop();
            }
        }
Exemplo n.º 10
0
        public given_blob_storage_with_existing_root_container()
        {
            var settings = InfrastructureSettings.Read("Settings.xml").BlobStorage;

            this.account           = CloudStorageAccount.Parse(settings.ConnectionString);
            this.rootContainerName = Guid.NewGuid().ToString();

            var client             = this.account.CreateCloudBlobClient();
            var containerReference = client.GetContainerReference(this.rootContainerName);

            containerReference.Create();

            this.sut = new CloudBlobStorage(account, this.rootContainerName);
        }
Exemplo n.º 11
0
        public static void RegisterComponents(UnityContainer container)
        {
            #region Infrastructures

            string serviceBusSetting = AppDomain.CurrentDomain.BaseDirectory + "InfrastructureSetting.xml";

            MobileOAuthSettings infrastructureSetting = InfrastructureSettings.Read <MobileOAuthSettings>(serviceBusSetting);
            ServiceBusConfig    serviceBusConfig      = new ServiceBusConfig(infrastructureSetting.ServiceBus);
            RedisCacheSetting   redisCacheConfig      = infrastructureSetting.RedisCache;
            serviceBusConfig.Initialize();

            container.RegisterInstance <ITextSerializer>(new JsonTextSerializer());
            container.RegisterInstance <IMetadataProvider>(new StandardMetadataProvider());
            #endregion

            #region Command Bus
            container.RegisterInstance <IMessageSender>(Topics.Commands.Path, new TopicSender(infrastructureSetting.ServiceBus, Topics.Commands.Path));

            container.RegisterInstance <ICommandBus>(
                new CommandBus(
                    container.Resolve <IMessageSender>(Topics.Commands.Path),
                    container.Resolve <IMetadataProvider>(),
                    container.Resolve <ITextSerializer>()
                    ));
            #endregion

            #region Context
            container.RegisterType <OAuthDbContext>(
                new InjectionConstructor("MobileOAuth"));
            #endregion

            #region Cache Context
            container.RegisterType <RedisReadClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor(redisCacheConfig));
            container.RegisterType <RedisWriteClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor(redisCacheConfig));
            #endregion

            container.RegisterInstance <IUserClient>(new UserClient());

            container.RegisterType <IApplicationRepository, ApplicationRepository>();
            container.RegisterType <IAdminUserRepository, AdminUserRepository>();

            container.RegisterType <IAppService, ApplicationService>();
            container.RegisterType <IAdminUserService, AdminUserService>();
            container.RegisterType <IDeviceService, RedisDeviceService>();
            container.RegisterType <IRefreshTokenService, RedisRefreshTokenService>();
            container.RegisterType <IUserService, UserService>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
Exemplo n.º 12
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
        }
Exemplo n.º 13
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
        }
Exemplo n.º 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
        }
Exemplo n.º 15
0
        public given_service_bus_config()
        {
            System.Diagnostics.Trace.Listeners.Clear();
            this.settings = InfrastructureSettings.Read("Settings.xml").ServiceBus;
            foreach (var topic in this.settings.Topics)
            {
                topic.Path = topic.Path + Guid.NewGuid().ToString();
            }

            var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(this.settings.TokenIssuer, this.settings.TokenAccessKey);
            var serviceUri    = ServiceBusEnvironment.CreateServiceUri(this.settings.ServiceUriScheme, this.settings.ServiceNamespace, this.settings.ServicePath);

            this.namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));

            this.retryPolicy = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(retryStrategy);

            this.sut = new ServiceBusConfig(this.settings);

            Cleanup();
        }
Exemplo n.º 16
0
        public given_empty_store()
        {
            tableName = "EventStoreFixture" + new Random((int)DateTime.Now.Ticks).Next();
            var settings = InfrastructureSettings.Read("Settings.xml").EventSourcing;

            account = CloudStorageAccount.Parse(settings.ConnectionString);
            sut     = new EventStore(account, tableName);

            sourceId     = Guid.NewGuid().ToString();
            partitionKey = Guid.NewGuid().ToString();
            events       = new[] {
                new EventData {
                    Version = 1, SourceId = sourceId, SourceType = "Source", TypeName = "Test1", Payload = "Payload1", CorrelationId = "correlation1"
                },
                new EventData {
                    Version = 2, SourceId = sourceId, SourceType = "Source", TypeName = "Test2", Payload = "Payload2", CorrelationId = "correlation2"
                },
                new EventData {
                    Version = 3, SourceId = sourceId, SourceType = "Source", TypeName = "Test3", Payload = "Payload3", CorrelationId = "correlation3"
                }
            };
        }
        public void when_reading_eventlog_settings_from_file_then_succeeds()
        {
            var settings = InfrastructureSettings.Read("Settings.Template.xml").MessageLog;

            Assert.NotNull(settings);
        }
Exemplo n.º 18
0
 public given_messaging_settings()
 {
     System.Diagnostics.Trace.Listeners.Clear();
     this.Settings = InfrastructureSettings.Read("Settings.xml").ServiceBus;
 }
Exemplo n.º 19
0
        internal static TopicSender GetTopicSender(string topic)
        {
            var settings = InfrastructureSettings.Read("Settings.xml");

            return(new TopicSender(settings.ServiceBus, "conference/" + topic));
        }
Exemplo n.º 20
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.º 21
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.º 22
0
 public given_messaging_settings()
 {
     Trace.Listeners.Clear();
     Settings = InfrastructureSettings.Read("Settings.xml").ServiceBus;
 }
Exemplo n.º 23
0
        public static IUnityContainer CreateContainer()
        {
            UnityContainer container = new UnityContainer();

            #region Infrastructure

            string serviceBusSetting = AppDomain.CurrentDomain.BaseDirectory + "InfrastructureSetting.xml";
            MobileOAuthSettings infrastructureSetting = InfrastructureSettings.Read <MobileOAuthSettings>(serviceBusSetting);
            ServiceBusConfig    serviceBusConfig      = new ServiceBusConfig(infrastructureSetting.ServiceBus);
            RedisCacheSetting   redisCacheConfig      = infrastructureSetting.RedisCache;
            serviceBusConfig.Initialize();

            container.RegisterInstance <ITextSerializer>(new JsonTextSerializer());
            container.RegisterInstance <IMetadataProvider>(new StandardMetadataProvider());
            #endregion

            #region Command Bus
            // event bus
            container.RegisterInstance <IMessageSender>(Topics.Commands.Path, new TopicSender(infrastructureSetting.ServiceBus, Topics.Commands.Path));
            container.RegisterInstance <ICommandBus>(
                new CommandBus(
                    container.Resolve <IMessageSender>(Topics.Commands.Path),
                    container.Resolve <IMetadataProvider>(),
                    container.Resolve <ITextSerializer>()
                    ));
            #endregion

            #region Event Bus
            container.RegisterInstance <IMessageSender>(Topics.Events.Path, new TopicSender(infrastructureSetting.ServiceBus, Topics.Events.Path));
            container.RegisterInstance <IEventBus>(
                new EventBus(
                    container.Resolve <IMessageSender>(Topics.Events.Path),
                    container.Resolve <IMetadataProvider>(),
                    container.Resolve <ITextSerializer>()));
            #endregion

            #region Cache Context
            container.RegisterType <RedisReadClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor(redisCacheConfig));
            container.RegisterType <RedisWriteClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor(redisCacheConfig));
            #endregion

            #region Context
            container.RegisterType <OAuthDbContext>(
                new InjectionConstructor("MobileOAuth"));
            #endregion

            #region Repository
            container.RegisterType <IUserDeviceRepository, UserDeviceRepository>();
            #endregion

            #region CommandHandler
            container.RegisterType <ICommandHandler, OAuthViewGenerator>("OAuthViewGenerator");

            var oAuthViewGenerator =
                new CommandProcessor(new SessionSubscriptionReceiver(infrastructureSetting.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.OAuthViewGenerator, false, new SessionSubscriptionReceiverInstrumentation(Topics.Commands.Subscriptions.OAuthViewGenerator, false)), container.Resolve <ITextSerializer>());

            oAuthViewGenerator.Register(container.Resolve <ICommandHandler>("OAuthViewGenerator"));

            container.RegisterInstance <IProcessor>("OAuthViewGeneratorProcessor", oAuthViewGenerator);
            #endregion

            container.RegisterEventProcessor <AuthenInfoGenerator>(serviceBusConfig, Topics.Events.Subscriptions.AuthenInfoSync, false);

            return(container);
        }