public WeatherForecastViewModel(AppSecrets appSecrets, Location location) { OpenWeather = new OpenWeather(appSecrets.ApiKey); // use the Logger event LocationSearch = new LocationSearch(OpenWeather); Location = location; InitCommands(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(x => x.LoginPath = new PathString("/Account/Login")); services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.Configure <AppSettings>(Configuration.GetSection("appSettings")); services.Configure <AppSecrets>(Configuration.GetSection("appSecrets")); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "Tower API Documentation", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); AppSettings appSettings = Configuration.GetSection(nameof(AppSettings)).Get <AppSettings>(); AppSecrets appSecrets = Configuration.GetSection(nameof(AppSecrets)).Get <AppSecrets>(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.Debug() .CreateLogger(); services.AddScoped <UnitOfWork>(); services.AddScoped <LogicService>(); services.AddSingleton(x => new SteamApiClient(appSecrets.SteamApiKey)); services.AddSingleton <MemoryCacheService>(); }
public ImageryService(ILogger <ImageryService> logger) { _logger = logger; _meshService = null; appSecrets = null; options = null; cache = null; }
public SearchController( LeakContext context, ISearchService searchService, IOptions <AppSecrets> appSecrets, IHashService hashService) { _appSecrets = appSecrets.Value; _cx = context; _searchService = searchService; this.hashService = hashService; }
public StoresController(IStoresService storesService, ICompaniesService companiesService, IOptions <AppSecrets> optionsAccessor) { _storesService = storesService; _companiesService = companiesService; if (optionsAccessor == null) { throw new ArgumentNullException(nameof(optionsAccessor)); } _appConfig = optionsAccessor.Value; }
private void Application_Startup(object sender, StartupEventArgs e) { SetAppSecrets(); SetUserConfig(); AppSecrets secrets = _appConfig.GetSection("AppSecrets").Get <AppSecrets>(); Location location = _userConfig.GetSection("location").Get <Location>(); var window = new MainWindow(secrets, location); window.Show(); }
public ImageryService(IMeshService meshService, IOptions <AppSecrets> appSecrets, IOptions <DEMNetOptions> options, IMemoryCache cache, ILogger <ImageryService> logger = null) { _logger = logger; _meshService = meshService; this.appSecrets = appSecrets?.Value; this.options = options?.Value; this.cache = cache; }
public static AppSecrets MapAppSecretsToEnvVariables(this AppSecrets _secrets) { if (_secrets == null) { throw new ArgumentNullException(nameof(_secrets)); } _secrets.Authentication = new Authentication { Facebook = new SocialDetails { AppID = Environment.GetEnvironmentVariable("FACEBOOK_APPID"), AppSecret = Environment.GetEnvironmentVariable("FACEBOOK_APPSECRET") }, LinkedIn = new SocialDetails { AppID = Environment.GetEnvironmentVariable("LINKEDIN_APPID "), AppSecret = Environment.GetEnvironmentVariable("LINKEDIN_APPSECRET ") }, Twitter = new SocialDetails { AppID = Environment.GetEnvironmentVariable("TWITTER_APPID "), AppSecret = Environment.GetEnvironmentVariable("TWITTER_APPSECRET ") } }; _secrets.Authorisation = new Authorisation { Roles = new List <string> { Environment.GetEnvironmentVariable("SUPER_USER_ROLE") }, SuperUser = new SuperUser { Email = Environment.GetEnvironmentVariable("SUPER_USER_EMAIL"), Password = Environment.GetEnvironmentVariable("SUPER_USER_PASSWORD ") } }; _secrets.SendGridApiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY"); return(_secrets); }
public override async Task StartAsync(CancellationToken cancellationToken) { _log.LogInformation(nameof(MessageBusService) + " background service is starting..."); AppSecrets secrets = _config.Get <AppSecrets>(); bool success = false; while (!success) { bool result = false; try { result = await Utils.CheckTcpConnectionAsync(secrets.MessageBusHost, General.MessageBusServiceHealthPort); } catch (Exception e) { _log.LogError(nameof(MessageBusService) + " background service check has failed: {Exception}", e); } if (result) { success = true; _messageBusServiceHealthCheck.MessageBusStartupTaskCompleted = true; _log.LogInformation(nameof(MessageBusService) + " background service check succeeded."); } else { await Task.Delay(General.StartupServiceCheckRetryIntervalMs, cancellationToken); } } _busControl.ConnectSendAuditObservers(_auditStore, c => c.Exclude(typeof(IServiceTemplateTestRequestV1), typeof(IServiceTemplateTestResponseV1))); _busControl.ConnectConsumeAuditObserver(_auditStore, c => c.Exclude(typeof(IServiceTemplateTestRequestV1), typeof(IServiceTemplateTestResponseV1))); await _busControl.StartAsync(cancellationToken); _log.LogInformation(nameof(MessageBusService) + " background service has started."); }
/// <summary> /// Создаёт экземпляры всех настроек и получает значения, чтобы провести процесс валидации при старте приложения. /// </summary> public static IServiceCollection AddOptionsAndSecretsValidationOnStartup(this IServiceCollection services) { ////перместить валидацию в общий процесс прогрева https://andrewlock.net/reducing-latency-by-pre-building-singletons-in-asp-net-core/ try { HostOptions hostOptions = services.BuildServiceProvider().GetService <IOptions <HostOptions> >().Value; AwsOptions awsOptions = services.BuildServiceProvider().GetService <IOptions <AwsOptions> >().Value; ApplicationOptions applicationOptions = services.BuildServiceProvider().GetService <IOptions <ApplicationOptions> >().Value; GeneralOptions generalOptions = services.BuildServiceProvider().GetService <IOptions <GeneralOptions> >().Value; IdempotencyOptions idempotencyOptions = services.BuildServiceProvider().GetService <IOptions <IdempotencyOptions> >().Value; AppSecrets appSecrets = services.BuildServiceProvider().GetService <IOptions <AppSecrets> >().Value; } catch (OptionsValidationException ex) { Console.WriteLine($"Error validating {ex.OptionsType.FullName}: {string.Join(", ", ex.Failures)}"); throw; } return(services); }
public HomeController(AppSecrets appSecrets, IHostingEnvironment hostingEnvironment, IConfiguration configuration) { EnvironmentName = hostingEnvironment.EnvironmentName; ConnectionString = appSecrets.Decrypt(configuration["ConnectionString"]); }
/// <summary> /// Configures the services to add to the ASP.NET Core Injection of Control (IoC) container. This method gets called by the ASP.NET runtime. See /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx /// </summary> public void ConfigureServices(IServiceCollection services) { services .AddCustomOptions(_config) .AddOptionsAndSecretsValidationOnStartup(); AppSecrets secrets = _config.GetSection(nameof(AppSecrets)).Get <AppSecrets>(); GeneralOptions generalOptions = _config.GetSection(nameof(ApplicationOptions.General)).Get <GeneralOptions>(); IdempotencyOptions idempotencyOptions = _config .GetSection(nameof(ApplicationOptions.IdempotencyControl)).Get <IdempotencyOptions>(); AWSOptions awsOptions = _config.GetAWSOptions(); services.AddDefaultAWSOptions(awsOptions); if (!string.IsNullOrEmpty(secrets.AppInsightsInstrumentationKey)) { ApplicationInsightsServiceOptions options = new ApplicationInsightsServiceOptions { DeveloperMode = _webHostEnvironment.IsDevelopment(), InstrumentationKey = secrets.AppInsightsInstrumentationKey }; services.AddApplicationInsightsTelemetry(options); } services .AddCorrelationIdFluent(generalOptions) .AddCustomCaching() .AddCustomCors() .AddCustomRouting() .AddResponseCaching() .AddCustomResponseCompression(_config) .AddCustomHealthChecks() .AddCustomSwagger(idempotencyOptions) .AddFluentValidationRulesToSwagger() .AddHttpContextAccessor() .AddSingleton <IActionContextAccessor, ActionContextAccessor>() .AddCustomApiVersioning(); services.AddIdempotencyContextLogging(options => { options.IdempotencyLogAttribute = "IdempotencyKey"; }); services.AddHttpContextLogging(options => { options.LogRequestBody = true; options.LogResponseBody = true; options.MaxBodyLength = generalOptions.MaxLogFieldLength; options.SkipPaths = new List <PathString> { "/metrics" }; }); services .AddControllers() .AddCustomJsonOptions(_webHostEnvironment) .AddCustomMvcOptions(_config) .AddCustomModelValidation(); services.AddIdempotencyControl(options => { options.Enabled = idempotencyOptions.IdempotencyFilterEnabled ?? false; options.HeaderRequired = true; options.IdempotencyHeader = idempotencyOptions.IdempotencyHeader; }); services.AddHttpClient(); services.AddMediatR(GetType().Assembly); services .AddProjectActionHandlers() .AddProjectMappers() .AddProjectRepositories() .AddProjectServices(); services.AddCustomMessageBus(secrets); }
public HashService(IOptions <AppSecrets> appSecrets) { _appSecrets = appSecrets.Value; }
/// <summary> /// Добавляет шину данных МассТранзит. /// </summary> public static IServiceCollection AddCustomMessageBus(this IServiceCollection services, AppSecrets secrets) { services.AddSingleton <IMessageAuditStore, MessageAuditStore>(); services.AddMassTransit(options => { options.UsingRabbitMq((context, cfg) => { cfg.Host(secrets.MessageBusHost, secrets.MessageBusVHost, h => { h.Username(secrets.MessageBusLogin); h.Password(secrets.MessageBusPassword); }); IMessageAuditStore auditStore = context.GetRequiredService <IMessageAuditStore>(); cfg.ConnectSendAuditObservers(auditStore, c => c.Exclude(typeof(IServiceTemplateTestRequestV1), typeof(IServiceTemplateTestResponseV1))); cfg.ConnectConsumeAuditObserver(auditStore, c => c.Exclude(typeof(IServiceTemplateTestRequestV1), typeof(IServiceTemplateTestResponseV1))); cfg.UseSerilogMessagePropertiesEnricher(); cfg.UsePrometheusMetrics(); cfg.ReceiveEndpoint(MbQueueNames.PrivateServiceQueueName, e => { e.PrefetchCount = 16; e.UseMessageRetry(x => x.Interval(2, 500)); e.AutoDelete = true; e.Durable = false; e.ExchangeType = "fanout"; e.Exclusive = true; e.ExclusiveConsumer = true; e.ConfigureConsumer <TestRequestConsumer>(context); }); cfg.ReceiveEndpoint("ya.servicetemplate.receiveendpoint", e => { e.PrefetchCount = 16; e.UseMessageRetry(x => x.Interval(2, 100)); e.UseMbContextFilter(); e.ConfigureConsumer <SomethingHappenedConsumer>(context); }); }); options.AddConsumers(Assembly.GetExecutingAssembly()); }); services.AddMassTransitHostedService(); services.AddSingleton <IPublishEndpoint>(provider => provider.GetRequiredService <IBusControl>()); services.AddSingleton <ISendEndpointProvider>(provider => provider.GetRequiredService <IBusControl>()); services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>()); return(services); }
public EarthdataLoginConnector(IOptions <AppSecrets> secretOptions, ILogger <EarthdataLoginConnector> logger) { this.logger = logger; this.secretOptions = secretOptions.Value; }
public MainWindow(AppSecrets appSecrets, Location location) { InitializeComponent(); DataContext = new WeatherForecastViewModel(appSecrets, location); }
/// <summary> /// Startup method /// </summary> /// <param name="configuration"></param> public Startup(IConfiguration configuration) { Configuration = configuration; _secrets = new AppSecrets(); _settings = new AppSettings(); }
/// <summary> /// Configure services method /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.Configure <AppSettings>(Configuration); _settings = Configuration.Get <AppSettings>(); if (_settings.UseEnviromentalVariables) { _secrets.MapAppSecretsToEnvVariables(); } else { services.Configure <AppSecrets>(Configuration); _secrets = Configuration.Get <AppSecrets>(); } if (_settings.UseInMemDB) { services.AddDbContext <PlinxHubContext>(options => options.UseInMemoryDatabase(databaseName: "Identity")); services.AddDbContext <ApplicationDbContext>(options => options.UseInMemoryDatabase(databaseName: "PlinxHubDB")); } else { services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext <PlinxHubContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); } services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddRoles <IdentityRole>() .AddEntityFrameworkStores <PlinxHubContext>(); services.AddControllersWithViews(); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential // cookies is needed for a given request. options.CheckConsentNeeded = context => true; // requires using Microsoft.AspNetCore.Http; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddRazorPages(); if (_settings.EnableSocialLogins) { services.AddAuthentication().AddGoogle(googleOptions => { googleOptions.ClientId = _secrets.Authentication.Google.AppID; googleOptions.ClientSecret = _secrets.Authentication.Google.AppSecret; }) .AddFacebook(facebookOptions => { facebookOptions.AppId = _secrets.Authentication.Facebook.AppID; facebookOptions.AppSecret = _secrets.Authentication.Facebook.AppSecret; }).AddTwitter(o => { o.ConsumerKey = _secrets.Authentication.Twitter.AppID; o.ConsumerSecret = _secrets.Authentication.Twitter.AppSecret; }).AddLinkedIn(o => { o.ClientId = _secrets.Authentication.LinkedIn.AppID; o.ClientSecret = _secrets.Authentication.LinkedIn.AppID; }); } services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Plinx Orders", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); // requires // using Microsoft.AspNetCore.Identity.UI.Services; // using WebPWrecover.Services; services.AddScoped <IEmailSender, EmailSender>(); services.AddScoped <IEmailRepository, EmailRepository>(); services.AddScoped <IEmailService, EmailService>(); services.AddScoped <IOrderRepository, OrderRepository>(); services.AddScoped <IOrderService, OrderService>(); services.AddScoped <IApiKeyGen, ApiKeyGen>(); MapperConfiguration config = MapperConfig.Get(); services.AddSingleton <IMapper>(new Mapper(config)); }
public ImageryService(IMeshService meshService, IOptions <AppSecrets> options, ILogger <ImageryService> logger = null) { _logger = logger; _meshService = meshService; this.options = options.Value; }
public GitApisController(IOptions <GitHostingApis> hostingApis, IOptions <AppSecrets> secrets) { _gitApis = hostingApis.Value; _secrets = secrets.Value; }