// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { if (HostingEnvironment.IsDevelopment()) { services.AddEntityFrameworkNpgsql() .AddDbContext <BarbellHeroDbContext>(options => options.UseNpgsql(Configuration["Data:DbContext:ConnectionString"])); } else { var host = Environment.GetEnvironmentVariable("DB_HOST"); var database = Environment.GetEnvironmentVariable("DB_NAME"); var user = Environment.GetEnvironmentVariable("DB_USER"); var port = Environment.GetEnvironmentVariable("DB_PORT"); var password = Environment.GetEnvironmentVariable("DB_PASSWORD"); services.AddEntityFrameworkNpgsql() .AddDbContext <BarbellHeroDbContext>(options => options.UseNpgsql($"User ID={user};Password={password};Server={host};Port={port};Database={database};")); } services.AddMvc(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddTransient <IMovementRepository, MovementRepository>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); // Add JavaScriptEngineSwitcher services to the services container. services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName ) .AddChakraCore() .AddMsie(options => { options.EngineMode = JsEngineMode.ChakraIeJsRt; }) .AddNiL() .AddVroom() ; // Add framework services. services.AddMvc(options => { options.CacheProfiles.Add("CacheCompressedContent5Minutes", new CacheProfile { NoStore = HostingEnvironment.IsDevelopment(), Duration = 300, Location = ResponseCacheLocation.Client, VaryByHeader = "Accept-Encoding" } ); }); // Add JavaScriptEngineSwitcher sample services to the services container. services.AddSingleton <JsEvaluationService>(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // As seen on: https://sethreid.co.nz/delivering-single-page-apps-aspnet-core/ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { context.Request.Path = "/index.html"; } }); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (HostingEnvironment.IsDevelopment()) { app.UseCors("AllowDevelopment"); } app.UseMvc(); app.UseDefaultFiles(options); app.UseStaticFiles(); }
private void SetupAuthorization(IServiceCollection services, ServiceProvider serviceProvider) { if (HostingEnvironment.IsDevelopment() == false) { var azureActiveDirectoryConfiguration = serviceProvider.GetService <IOptions <AzureActiveDirectoryConfiguration> >(); services.AddAuthorization(o => { o.AddPolicy("default", policy => { policy.RequireAuthenticatedUser(); }); }); services.AddAuthentication(auth => { auth.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(auth => { auth.Authority = $"https://login.microsoftonline.com/{azureActiveDirectoryConfiguration.Value.Tenant}"; auth.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidAudiences = new List <string> { azureActiveDirectoryConfiguration.Value.Identifier, azureActiveDirectoryConfiguration.Value.Id } }; }); services.AddSingleton <IClaimsTransformation, AzureAdScopeClaimTransformation>(); } }
protected override void ConfigureInternal(IApplicationBuilder app) { app.UseIdentityServer(); app.SeedIdentityServer( clients: DbSeed.GetSeedClients(ServiceConfiguration), apiRessources: DbSeed.GetSeedApiResources(ServiceConfiguration), identityRessources: DbSeed.GetSeedIdentityRessources()); app.SeedApplicationUser(DbSeed.GetSeedUsers()); if (!HostingEnvironment.IsDevelopment()) { //app.UseHsts(); //app.UseHttpsRedirection(); } app.UseExceptionHandler("/Home/Error"); app.UseAuthentication(); app.UseStaticFiles(); app.UseSwagger(ServiceConfiguration); app.UseMvcWithDefaultRoute(); }
public Startup(IHostingEnvironment env, ILoggerFactory logger) { this.HostingEnvironment = env; this.LoggerFactory = logger; string projectName = env.ApplicationName; int projLength = projectName.Length; string path = env.ContentRootPath; int index = path.IndexOf(projectName); int last = index + projLength; string basePath = path.Remove(last); var builder = new ConfigurationBuilder() .SetBasePath(basePath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); if (HostingEnvironment.IsDevelopment()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } Configuration = builder.Build(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { if (HostingEnvironment.IsDevelopment()) { services.AddNodeServices(options => { options.LaunchWithDebugging = true; options.DebuggingPort = 9229; }); } services.AddOptions(); services.AddResponseCompression(); services.AddMemoryCache(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot/dist"; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "AspNetCoreSpa", Version = "v1" }); }); services.AddMvc(); }
public override void ConfigureServices(IServiceCollection services) { services .AddAuthentication(sharedOptions => { sharedOptions.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme; sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddGoogle( options => { options.ClientId = Configuration["OcelotConfigEditor:Authentication:Google:ClientId"]; options.ClientSecret = Configuration["OcelotConfigEditor:Authentication:Google:ClientSecret"]; options.CallbackPath = GetCallbackPath("OcelotConfigEditor:Authentication:Google:CallbackPath", CallbackPath); options.SaveTokens = true; options.Events = new OAuthEvents { OnRemoteFailure = context => { context.HandleResponse(); context.Response.StatusCode = 500; context.Response.ContentType = "text/plain"; return(context.Response.WriteAsync(HostingEnvironment.IsDevelopment() ? context.Failure.ToString() : "An error occurred processing your authentication.")); } }; }); }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Register the IConfiguration instance which Info binds against. if (HostingEnvironment.IsDevelopment()) { services.AddCors(options => options.AddPolicy("AllowDevelopment", p => p.WithOrigins("http://localhost:3000") .AllowAnyMethod() .AllowAnyHeader())); } // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); services.AddSwaggerGen(c => { var assembly = Assembly.GetAssembly(typeof(Startup)); var assemblyName = assembly.GetName(); var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); var fullSemVersion = assemblyName.Version.ToString(); if (fileVersionInfo.ProductVersion.Contains("+")) { fullSemVersion = fileVersionInfo.ProductVersion.Split("+".ToCharArray())[0]; } c.SwaggerDoc($"v{fullSemVersion}", new Info { Title = $"{assembly.GetName().Name}", Version = $"v{fullSemVersion}" }); c.IncludeXmlComments(Path.ChangeExtension(Assembly.GetEntryAssembly().Location, "xml")); }); services.AddSingleton <IGameBoardListContainer, GameBoardListContainer>(); }
protected UserAgentInfo GetUserAgentInfo() { var ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); #if DEBUG if (HostingEnvironment.IsDevelopment() && !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("DEBUG_CUSTOM_IP"))) { if (System.Net.IPAddress.TryParse(Environment.GetEnvironmentVariable("DEBUG_CUSTOM_IP"), out System.Net.IPAddress customIp)) { ip = customIp.MapToIPv4().ToString(); } } #endif // ip object var ipObj = System.Net.IPAddress.Parse(ip); // agent var agent = "Unknown"; if (HttpContext.Request.Headers.TryGetValue("User-Agent", out var agentParsed)) { agent = agentParsed.ToString(); } return(new UserAgentInfo() { Ip = ip, IpObject = ipObj, Agent = agent, }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services .AddSwaggerGen(c => { c.SwaggerDoc("1.0.0", new Info { Version = "1.0.0", Title = "Number Theory", Description = "Number Theory Calculation Service (ASP.NET Core 2.1)", Contact = new Contact() { Name = "Stefan Ilic", Email = "*****@*****.**" }, }); }); if (HostingEnvironment.IsDevelopment()) { services.AddSingleton <IDataAccessLayer>(s => new DevDal(Configuration.GetConnectionString("StefansLocalSqlite"))); } else { } }
private void RegisterDependencies(IApplicationBuilder app) { _container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); // Singletons _container.RegisterSingleton <ILogger>(_logger); _container.RegisterSingleton(app.ApplicationServices.GetService <ILoggerFactory>()); _container.RegisterSingleton(_s3Client); _container.RegisterSingleton <IMemoryCache>(new MemoryCache(new MemoryCacheOptions())); _container.RegisterSingleton <IMarkdownClient>(new MarkdownAwsSdkClient(_lambdaClient, _settings.LambdaFunctionName)); _container.RegisterSingleton(_settings); _container.RegisterSingleton(_fileUploadSettings); _container.RegisterSingleton <ICommonSettings>(_settings); _container.RegisterSingleton <IS3Settings>(_settings); _container.RegisterSingleton <ISqlSettings>(_settings); _container.RegisterSingleton <ICloudWatchSettings>(_settings); // Scoped _container.Register <IMarkdownSqlContext, MarkdownSqlContext>(Lifestyle.Scoped); _container.Register <IDbConnectionProvider, DbConnectionProvider>(Lifestyle.Scoped); _container.RegisterSingleton(app.ApplicationServices.GetService <IHttpContextAccessor>()); _container.RegisterOrganisationDataProvider(HostingEnvironment.IsDevelopment()); // MVC _container.RegisterMvcControllers(app); _container.RegisterMvcViewComponents(app); // The following registers a Func<T> delegate that can be injected as singleton, and on invocation resolves a MVC IViewBufferScope service for that request. // _container.RegisterSingleton<Func<IViewBufferScope>>(app.GetRequestService<IViewBufferScope>); Service.Startup.RegisterDependanciesWeb(_container); _container.Verify(); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="loggerFactory"></param> /// <param name="provider"></param> public void Configure( IApplicationBuilder app, ILoggerFactory loggerFactory, IApiVersionDescriptionProvider provider) { if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); Logger.LogWarning($@" IsDevelopment" + HostingEnvironment.ContentRootPath); } else { app.UseHsts(); } // app.UseHttpsRedirection(); app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI( options => { SwaggerDefaultValues.SwaggerOptionUi(provider, options); }); }
// This method gets called by the runtime. Use this method to add services to the container. public virtual void ConfigureServices(IServiceCollection services) { services.ConfigurePartyDetailsOptions(Configuration, HostingEnvironment); services.AddSigning(); MvcCoreBuilder = services.AddMvcCore(o => { if (!HostingEnvironment.IsDevelopment()) { var genericErrorMessage = "Invalid value."; o.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => genericErrorMessage); o.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) => genericErrorMessage); o.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => genericErrorMessage); o.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) => genericErrorMessage); } }) .AddApiExplorer() //see https://github.com/domaindrivendev/Swashbuckle.AspNetCore#swashbuckle--apiexplorer .AddJsonFormatters() .AddAuthorization() .AddDataAnnotations() .AddJsonOptions(options => { options.SerializerSettings.Converters.Add(new TrimmingConverter()); }) ; services.AddJwtAuthentication(HostingEnvironment, Configuration); services.AddSwagger(SwaggerName, HostingEnvironment, ApiVersion, DocumentingAssemblies); services.AddJsonSchema(); services.AddFileProvider(HostingEnvironment); services.AddApplicationInsights(ApplicationInsightsName, HostingEnvironment); services.AddTransient <HideLiveApiMethodAttribute>(); services.AddTransient <HideProductionMethodAttribute>(); services.AddTransient <ClientIdCheckFilter>(); }
// Configure your AppHost with the necessary configuration and dependencies your App needs public override void Configure(Container container) { Plugins.Add(new SharpPagesFeature()); // enable server-side rendering, see: https://sharpscript.net/docs/sharp-pages LogManager.LogFactory = new NLogFactory() { }; SetConfig(new HostConfig { UseSameSiteCookies = true, AddRedirectParamsToQueryString = true, DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), HostingEnvironment.IsDevelopment()), }); SetupLogging(); SetupDatabase(container); SetupErrorHandling(); Seed(); JsConfig.TextCase = TextCase.PascalCase; JsConfig.DateHandler = DateHandler.UnixTimeMs; container.Register(c => new UnBoy()); container.Register(c => new FundayBoy()); container.Register(c => new SearchBoy()); var SB = HostContext.Resolve <SearchBoy>(); var AB = HostContext.Resolve <UnBoy>(); var FB = HostContext.Resolve <FundayBoy>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc(); if (HostingEnvironment.IsDevelopment()) { services.AddNodeServices(options => { options.LaunchWithDebugging = true; options.DebuggingPort = 9229; }); } services.AddOptions(); services.AddResponseCompression(); services.AddMemoryCache(); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); }
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { HostingEnvironment = hostingContext.HostingEnvironment; Configuration = config.Build(); }) .ConfigureServices(services => { services.AddMvc(); }) .Configure(app => { if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } // Configuration is available during startup. Examples: // Configuration["key"] // Configuration["subsection:suboption1"] app.UseMvcWithDefaultRoute(); app.UseStaticFiles(); }) .Build();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { HostingEnvironment = hostingContext.HostingEnvironment; Configuration = config.Build(); }) .ConfigureServices(services => { services.AddMvc(); }) .Configure(app => { var loggerFactory = app.ApplicationServices .GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger <Program>(); logger.LogInformation("Logged in Configure"); if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } // Configuration is available during startup. Examples: // Configuration["key"] // Configuration["subsection:suboption1"] app.UseMvcWithDefaultRoute(); app.UseStaticFiles(); });
/// <summary> /// Configures MVC. /// </summary> /// <param name="options">The <see cref="MvcOptions"/> to configure.</param> private void ConfigureMvc(MvcOptions options) { if (!HostingEnvironment.IsDevelopment()) { //options.Filters.Add(new RequireHttpsAttribute()); } }
private void ConfigureJwt(IServiceCollection services) { var signingConfigurations = new SigningConfigurations("key.pem"); services.AddSingleton(signingConfigurations); var tokenConfigurations = new TokenConfigurations() { // Audience = "ExampleAudience", // Issuer = "ExampleIssuer", Seconds = HostingEnvironment.IsDevelopment() ? (int)TimeSpan.FromDays(834).TotalSeconds : (int)TimeSpan.FromHours(2).TotalSeconds, }; services.AddSingleton(tokenConfigurations); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = tokenConfigurations.Issuer == null ? false : true, ValidateAudience = tokenConfigurations.Audience == null ? false : true, ValidIssuer = tokenConfigurations.Issuer, ValidAudience = tokenConfigurations.Audience, ValidateLifetime = true, ValidateIssuerSigningKey = signingConfigurations.Key == null ? false : true, ClockSkew = TimeSpan.FromSeconds(10), IssuerSigningKey = signingConfigurations.Key, }; }); }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Information); loggerFactory.AddDebug(minLevel: LogLevel.Trace); if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseCookieAuthentication(new CookieAuthenticationOptions() { LoginPath = new PathString("/signin") }); app.UseGitHubAuthentication(options => { options.ClientId = Configuration["GitHubClientId"]; options.ClientSecret = Configuration["GitHubClientSecret"]; options.Scope.Add("repo"); options.SaveTokens = true; options.AutomaticChallenge = true; }); app.UseSession(); app.UseMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(c => { c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod()); }); if (HostingEnvironment.IsDevelopment()) { Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.Development.json", optional: true) .AddEnvironmentVariables() .Build(); } services.AddDbContext <OxiyopalDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("OxiyopalDbContext"))); services.AddScoped(typeof(IRepository <,>), typeof(Repository <,>)); services.AddTransient <ICilindroService, CilindroService>(); services.AddTransient <ICarteraService, CarteraService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString("/dist"), FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")) }); var assetServer = Configuration.GetValue <string>("REVIEWER_ASSET_SERVER", null); var globalToken = Configuration.GetSection("GitLab").GetValue <string>("globalToken"); app.UseAuthentication(); app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/hooks"), sub => sub.ChallengeAllUnauthenticatedCalls()); app.Use(async(ctx, next) => { using (MappedDiagnosticsLogicalContext.SetScoped("context", new Dictionary <string, object>())) { await next(); } }); app.UseOwin(owin => { owin.UseNancy(opt => opt.Bootstrapper = new Bootstraper(assetServer, _container, globalToken)); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { //Authentication app.UseAuthentication(); //Returns homepage with Angular's app: index.html in wwwroot. //(UseDefaultFiles must be called before UseStaticFiles to serve the default file) app.UseDefaultFiles(); //Serves static files, such as HTML, CSS, images, and Javascript //directly from project's web root directory (<content_root>/wwwroot by default): app.UseStaticFiles(); //Creates artificial delay in Development if (HostingEnvironment.IsDevelopment()) { app.Use(async(context, next) => { Random r = new Random(); System.Threading.Tasks.Task.Delay(r.Next(500, 2000)).Wait(); await next.Invoke(); }); } //Using attribute routing with Http[Verb] attributes app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) // (note: 'env.EnvironmentName' above can also be used in "Configure{0}") { //logBuilder.AddConsole(); //? {ILoggerFactory}.AddConsole(Configuration.GetSection("Logging")) //logBuilder.AddDebug(); if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } //! var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>(); //! app.UseRequestLocalization(locOptions.Value); //! (example usage: http://localhost:5000/api/About?culture=en-US) app.UseCoreXTDemosWithDefaultRouting(HostingEnvironment); app.Run(async(context) => { await context.Response.WriteAsync("Error: There is no content at this address (URL). Please go back and try again.\r\n URL path was '" + context.Request.Path + "'."); }); }
public async Task <IActionResult> Post([FromBody] TripViewModel tripViewModel) { try { if (ModelState.IsValid) { var trip = Mapper.Map <Trip>(tripViewModel); trip.UserName = User.Identity.Name; TravelRepository.AddTrip(trip); if (await TravelRepository.SaveChangesAsync()) { // Use map in case database modified the trip in any way. var value = Mapper.Map <TripViewModel>(trip); // todo|jdevl32: contant(s)... return(Created($"/api/trip/{value.Name}", value)); } // if } // if else if (HostingEnvironment.IsDevelopment()) { return(BadRequest(ModelState)); } // if } // try catch (Exception ex) { Logger.LogError($"Error adding trip ({tripViewModel}): {ex}"); } // catch return(BadRequest()); }
// Configure your AppHost with the necessary configuration and dependencies your App needs public override void Configure(Container container) { //Register logger LogManager.LogFactory = new NLogFactory(); Plugins.Add(new SharpPagesFeature()); // enable server-side rendering, see: https://sharpscript.net/docs/sharp-pages SetConfig(new HostConfig { UseSameSiteCookies = true, AddRedirectParamsToQueryString = true, DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), HostingEnvironment.IsDevelopment()), }); var conFactory = new OrmLiteConnectionFactory(AppSettings.GetString("connectionString"), PostgreSqlDialect.Provider); container.Register <IDbConnectionFactory>(conFactory); Plugins.Add(new AutoQueryFeature { MaxLimit = 100, StripUpperInLike = false, EnableAutoQueryViewer = true }); Plugins.Add(new AdminFeature()); SeedDatabase.Seed(); }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); if (HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, ReactHotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); }
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); HostingEnvironment.ConfigureNLog($"nlog.{HostingEnvironment.EnvironmentName}.config"); if (HostingEnvironment.IsDevelopment() || HostingEnvironment.IsStaging()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(s => s.SwaggerEndpoint("/swagger/v1/swagger.json", "Streetwood API")); } else { app.UseHsts(); } app.UseCors(s => { s.AllowAnyOrigin(); s.AllowAnyHeader(); s.AllowAnyMethod(); }); // app.UseHttpsRedirection(); app.UseAuthentication(); app.UseStaticFiles(); app.UseMiddleware <ExceptionHandlerMiddleware>(); app.UseMvc(); applicationLifetime.ApplicationStopped.Register(() => Container.Dispose()); }
private async Task HandleCommandAsync(SocketMessage messageParam) { var message = (SocketUserMessage)messageParam; if (message == null) { return; } int argPos = 0; if (!(message.HasCharPrefix(_settings.Prefix, ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)) || message.Author.IsBot) { return; } var context = new SocketCommandContext(_client, message); var result = await Commands.ExecuteAsync( context, argPos, _Provider); if (_environment.IsDevelopment() && !result.IsSuccess) { await context.Channel.SendMessageAsync(result.ErrorReason); } }