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(); }
partial void OnCreating() { azureSettings = InfrastructureSettings.Read("Settings.xml"); busConfig = new ServiceBusConfig(azureSettings.ServiceBus); busConfig.Initialize(); }
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); } }
static void Main(string[] args) { try { Console.Title = ServiceName; _config = Config.Build(); var serviceBusSettings = new ServiceBusSettings(); var serviceBusQueuesSettings = new ServiceBusQueuesSettings(); var connectionStringSettings = new ConnectionStringSettings(); var blobSettings = new BlobStorageSettings(); _config.GetSection("ServiceBus").Bind(serviceBusSettings); _config.GetSection("ServiceBusQueues").Bind(serviceBusQueuesSettings); _config.GetSection("ConnectionStrings").Bind(connectionStringSettings); _config.GetSection("BlobStorage").Bind(blobSettings); _infrastructureSettings = InfrastructureSettings.Create(connectionStringSettings, serviceBusQueuesSettings, serviceBusSettings, blobSettings); DisplayConfiguration(); ProductServiceBus.Instance.GetProductServiceBus(); Console.ReadLine(); ProductServiceBus.Instance.StopProductServiceBus(); } catch (Exception e) { Console.WriteLine(e); Console.ReadLine(); } }
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); }
partial void OnCreating() { this.azureSettings = InfrastructureSettings.Read("Settings.xml"); this.busConfig = new ServiceBusConfig(this.azureSettings.ServiceBus); busConfig.Initialize(); }
private void RegisterRepositories(IServiceCollection services, InfrastructureSettings azureSettings, ILoggerFactory loggerFactory) { var eventSourcingAccount = CloudStorageAccount.Parse(azureSettings.EventSourcing.ConnectionString); var eventLogger = loggerFactory.CreateLogger <EventStore>(); var eventStore = new EventStore(eventSourcingAccount, azureSettings.EventSourcing.OrdersTableName, eventLogger); var anchorsAvailabilityEventStore = new EventStore(eventSourcingAccount, azureSettings.EventSourcing.AnchorsAvailabilityTableName, eventLogger); services.AddSingleton <IEventStore>(eventStore); services.AddSingleton <IPendingEventsQueue>(eventStore); services.AddSingleton <IEventStore>(anchorsAvailabilityEventStore); services.AddSingleton <IPendingEventsQueue>(anchorsAvailabilityEventStore); services.AddSingleton <IEventStoreBusPublisher, EventStoreBusPublisher>( provider => new EventStoreBusPublisher( provider.GetServices <IMessageSender>().ToList()[1], provider.GetServices <IPendingEventsQueue>().First(), loggerFactory.CreateLogger <EventStoreBusPublisher>())); services.AddSingleton <IEventStoreBusPublisher, EventStoreBusPublisher>( provider => new EventStoreBusPublisher( provider.GetServices <IMessageSender>().Last(), provider.GetServices <IPendingEventsQueue>().Last(), loggerFactory.CreateLogger <EventStoreBusPublisher>())); //TODO: fix repos for each eventStores services.AddSingleton <IEventSourcedRepository <Order>, AzureEventSourcedRepository <Order> >( provider => new AzureEventSourcedRepository <Order>( provider.GetServices <IEventStore>().First(), //"orders" provider.GetServices <IEventStoreBusPublisher>().First(), //"orders" provider.GetService <ITextSerializer>(), provider.GetService <IMetadataProvider>(), provider.GetService <IMemoryCache>())); services.AddSingleton <IEventSourcedRepository <AnchorAssignments>, AzureEventSourcedRepository <AnchorAssignments> >( provider => new AzureEventSourcedRepository <AnchorAssignments>( provider.GetServices <IEventStore>().First(), //"orders" provider.GetServices <IEventStoreBusPublisher>().First(), //"orders" provider.GetService <ITextSerializer>(), provider.GetService <IMetadataProvider>(), provider.GetService <IMemoryCache>())); services.AddSingleton <IEventSourcedRepository <AnchorsAvailability>, AzureEventSourcedRepository <AnchorsAvailability> >( provider => new AzureEventSourcedRepository <AnchorsAvailability>( provider.GetServices <IEventStore>().Last(), //"anchorsavailability" provider.GetServices <IEventStoreBusPublisher>().Last(), //"anchorsavailability" provider.GetService <ITextSerializer>(), provider.GetService <IMetadataProvider>(), provider.GetService <IMemoryCache>())); services.AddSingleton <IProcessor>( //"OrdersEventStoreBusPublisher", provider => new PublisherProcessorAdapter(provider.GetServices <IEventStoreBusPublisher>().First() /*"orders"*/, cancellationTokenSource.Token)); services.AddSingleton <IProcessor>( //"SeatsAvailabilityEventStoreBusPublisher", provider => new PublisherProcessorAdapter(provider.GetServices <IEventStoreBusPublisher>().Last() /*"anchorsavailability"*/, cancellationTokenSource.Token)); }
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); }
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); }
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); }
public void GetElasticIPsTest(string settingsResturn, int count, string first) { var settingsProvider = new Mock <IProvideSettings>(); settingsProvider.Setup(m => m.GetSetting("ElasticServerUrls")).Returns(settingsResturn); var infrastructureSettings = new InfrastructureSettings(settingsProvider.Object); var urls = infrastructureSettings.GetElasticIPs("ElasticServerUrls"); Assert.NotNull(urls); Assert.AreEqual(count, urls.Count()); Assert.AreEqual(first, urls.First().AbsoluteUri); }
public static InfrastructureSettings Create(ConnectionStringSettings connectionStringSettings, ServiceBusQueuesSettings serviceBusQueuesSettings, ServiceBusSettings serviceBusSettings) { var infrastructureSettings = new InfrastructureSettings { ConnectionStringSettings = connectionStringSettings, ServiceBusQueuesSettings = serviceBusQueuesSettings, ServiceBusSettings = serviceBusSettings, }; return(infrastructureSettings); }
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)); }
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(); } }
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); }
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); }
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 }
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 }
/// <summary> /// Custom configuration for Settings. /// </summary> /// <param name="services"></param> /// <param name="config"></param> /// <returns></returns> public static InfrastructureSettings ConfigureSettings(this IServiceCollection services, IConfiguration config) { if (config == null) { throw new ArgumentNullException(nameof(config)); } InfrastructureSettings infrastructureSettings = config .GetSection(nameof(InfrastructureSettings)) .Get <InfrastructureSettings>(); services.Configure <InfrastructureSettings>(config .GetSection(nameof(InfrastructureSettings))); services.AddHttpClient() .AddSingleton <HttpProxy, HttpProxy>(); return(infrastructureSettings); }
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(); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> /// <returns></returns> public IServiceProvider ConfigureServices(IServiceCollection services) { InfrastructureSettings infrastructureSettings = services.ConfigureSettings(Configuration); IdentityModelEventSource.ShowPII = true; services.AddControllers(); services.RegisterDataBaseContext(Configuration); services.AddCovid19Authorization(); services.AddCovid19Authentication(Configuration, infrastructureSettings, Configuration, Log.Logger); services.ConfigureMvc(); services.ConfigureResponses(); services.ConfigureSwagger(Environment, infrastructureSettings); services.ConfigureHostedServices(Configuration); // Custom services.ConfigureAppInsights(Configuration); //custom return(services.ConfigureAutofac(Environment, Configuration, infrastructureSettings.LogicalRemove)); }
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 }
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(); }
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" } }; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var applicationSettings = new ApplicationSettings(); Configuration.Bind(applicationSettings); services.AddSingleton <ApplicationSettings>(applicationSettings); // init infrastructure InfrastructureSettings infrastructureSettings = new InfrastructureSettings { KosConnectionString = applicationSettings.ConnectionStrings.KOS, MunicipalitiesGeoJsonUrl = applicationSettings.ExternalUrls.MunicipalitiesGeoJson, DataSetToLayerMap = applicationSettings.DataSetToLayerMap, DataAgeDataSetToLayerMap = applicationSettings.DataAgeDataSetToLayerMap, DataQualityDataSetToLayerMap = applicationSettings.DataQualityDataSetToLayerMap, WmsUrlBase = applicationSettings.Wms.UrlBase, WmsVersion = applicationSettings.Wms.Version }; Infrastructure.StartupInitializer.Initialize(services, infrastructureSettings); // init core Core.StartupInitializer.InitializeDependencies(services); Core.StartupInitializer.LocalPathThematicGeoJson = applicationSettings.LocalPathThematicGeoJson; // init web services.AddTransient <IContextViewModelHelper, ContextViewModelHelper>(); // Add the localization services to the services container services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddControllersWithViews() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); services.AddDbContext <KosContext>(item => item.UseSqlServer(Configuration.GetConnectionString("KOS"))); ConfigureProxy(applicationSettings); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { using (var scope = app.ApplicationServices.CreateScope()) { // TODO: Cambiar a un IStartupFilter app.ConfigureMigration(HostingContext, scope.ServiceProvider, env); } InfrastructureSettings settings = Configuration.GetSettings <InfrastructureSettings>(); app.UseDeveloperExceptionPage(); // configuramos swagger si esta permitido var configSectionSwagger = HostingContext.Configuration.GetSection("Swagger"); bool swaggerEnable = configSectionSwagger.GetValue <bool>("Enable"); if (swaggerEnable) { app.UseSwaggerPipeline(settings); } app.UseHttpsRedirection(); app.UseResponseCompression(); app.UseStaticFiles(); app.UseSerilogRequestLogging(); app.UseRouting(); if (settings.Authentication.Enabled) { app.UseAuthentication(); // TODO: Enriquecer el log con el usuario autenticado. app.UseAuthorization(); app.UseFillUserInfoMiddleware(); } // TODO: Mover a ConfigureServices // permitimos localizacion var supportedCultures = new[] { new CultureInfo("es"), new CultureInfo("en"), }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("es"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures }); AllowedLanguages.Instance.Languages = new List <CultureInfo>(supportedCultures); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public TransactionDataSldProvider(InfrastructureSettings settings, IWmsUrlProvider wmsUrlProvider) : base(_ServiceName, wmsUrlProvider) { _dataSetToLayerMap = settings.DataSetToLayerMap; }
internal static TopicSender GetTopicSender(string topic) { var settings = InfrastructureSettings.Read("Settings.xml"); return(new TopicSender(settings.ServiceBus, "conference/" + topic)); }
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))); }
/// <summary> /// Configura el pipeline de swagger. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseSwaggerPipeline(this IApplicationBuilder app, InfrastructureSettings settings) { SwaggerOptions swaggerClient = settings.Authentication.AzureADSwaggerClient; if (swaggerClient.Enabled) { app.UseSwagger(c => c.RouteTemplate = "docs/{documentName}/swagger.json") .UseSwaggerUI(c => { c.SwaggerEndpoint("/docs/v1/swagger.json", "Acciona Covid-19 WebApi"); if (settings.Authentication.Enabled) { c.OAuthClientId(swaggerClient.ClientId); c.OAuthClientSecret(swaggerClient.ClientSecret); c.OAuthAdditionalQueryStringParams(new Dictionary<string, string> { { "resource", settings.Authentication.AzureADApiAuthentication.Backend.ClientId } }); } }); } return app; }
/// <summary> /// Custom configuration for Swagger /// </summary> /// <param name="services"></param> /// <param name="settings"></param> /// <returns></returns> public static IServiceCollection ConfigureSwagger(this IServiceCollection services, IWebHostEnvironment environment, InfrastructureSettings infrastructureSettings) { SwaggerOptions identityServerSwaggerClient = infrastructureSettings.Authentication.IdentityServerSwaggerClient; SwaggerOptions azureADSwaggerClient = infrastructureSettings.Authentication.AzureADSwaggerClient; if (identityServerSwaggerClient.Enabled) { services.AddSwaggerGen(c => { var dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); foreach (var fi in dir.EnumerateFiles("*.xml")) { c.IncludeXmlComments(fi.FullName); } c.SwaggerDoc("v1", new OpenApiInfo { Title = "Acciona Covid-19", Version = $"v1.{environment.EnvironmentName}", Description = "WEB API" }); c.OperationFilter <ResponseTypeOperationFilter>(); c.DocumentFilter <SwaggerAddEnumDescriptions>(); if (infrastructureSettings.Authentication.Enabled) { //************************************************************************************************* //************** AUTENTICACION SWAGGER ************************************************************ //https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md //https://joonasw.net/view/testing-azure-ad-protected-apis-part-1-swagger-ui c.AddSecurityDefinition("oauth2_IdentityServer", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri(identityServerSwaggerClient.AuthorizationUrl), TokenUrl = new Uri(identityServerSwaggerClient.TokenUrl), Scopes = identityServerSwaggerClient.Scopes } } }); c.AddSecurityDefinition("oauth2_AzureAD", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri($"https://foo-login.bar/{infrastructureSettings.Authentication.AzureADApiAuthentication.Tenant}/oauth2/authorize", UriKind.Absolute), Scopes = azureADSwaggerClient.Scopes, }, }, }); c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme() { Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Name = "X-Api-Key", }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2_IdentityServer" } }, identityServerSwaggerClient.Scopes.Keys.ToArray() }, { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2_AzureAD" } }, azureADSwaggerClient.Scopes.Keys.ToArray() }, { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" } }, new string[] { } } }); } }); } return(services); }
public given_messaging_settings() { Trace.Listeners.Clear(); Settings = InfrastructureSettings.Read("Settings.xml").ServiceBus; }