public void Configuration(IAppBuilder app) { var settings = new ApplicationSettings(); if (settings.MigrateDatabase) { // Perform the required migrations DoMigrations(); } var kernel = SetupNinject(settings); app.Use(typeof(DetectSchemeHandler)); if (settings.RequireHttps) { app.Use(typeof(RequireHttpsHandler)); } app.UseShowExceptions(); // This needs to run before everything app.Use(typeof(AuthorizationHandler), kernel.Get<IAuthenticationTokenService>()); SetupSignalR(kernel, app); SetupWebApi(kernel, app); SetupMiddleware(settings, app); SetupNancy(kernel, app); SetupErrorHandling(); }
public void Configuration(IAppBuilder app) { var httpConfiguration = new HttpConfiguration(); // Configure Web API Routes: // - Enable Attribute Mapping // - Enable Default routes at /api. httpConfiguration.MapHttpAttributeRoutes(); httpConfiguration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null ); app.Use<SimpleLogger>(); app.Use<AuthenticationCheck>(); app.UseWebApi(httpConfiguration); // Make ./public the default root of the static files in our Web Application. app.UseFileServer(new FileServerOptions { RequestPath = new PathString(string.Empty), FileSystem = new PhysicalFileSystem("./public"), EnableDirectoryBrowsing = true, }); app.UseStageMarker(PipelineStage.MapHandler); }
public void Configuration(IAppBuilder app) { // So that squishit works Directory.SetCurrentDirectory(AppDomain.CurrentDomain.SetupInformation.ApplicationBase); var configuration = new JabbrConfiguration(); if (configuration.MigrateDatabase) { // Perform the required migrations DoMigrations(); } var kernel = SetupNinject(configuration); app.Use(typeof(DetectSchemeHandler)); if (configuration.RequireHttps) { app.Use(typeof(RequireHttpsHandler)); } app.UseErrorPage(); SetupAuth(app, kernel); SetupSignalR(configuration, kernel, app); SetupWebApi(kernel, app); SetupMiddleware(kernel, app); SetupFileUpload(kernel, app); SetupNancy(kernel, app); SetupErrorHandling(); }
/// <summary> /// The Startup configuration sets up a pipeline with three middleware components, the first two displaying diagnostic information /// and the last one responding to events (and also displaying diagnostic information). The PrintCurrentIntegratedPipelineStage /// method displays the integrated pipeline event this middleware is invoked on and a message. /// </summary> public void Configuration(IAppBuilder app) { app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "Middleware 1"); return next.Invoke(); }); app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "2nd MW"); return next.Invoke(); }); // You can mark OMCs to execute at specific stages of the pipeline by using the IAppBuilder UseStageMarker() extension method. // To run a set of middleware components during a particular stage, insert a stage marker right after the last component is the set // during registration. There are rules on which stage of the pipeline you can execute middleware and the order components must run // (The rules are explained later in the tutorial). Add the UseStageMarker method to the Configuration code as shown below: app.UseStageMarker(PipelineStage.Authenticate); app.Run(context => { PrintCurrentIntegratedPipelineStage(context, "3rd MW"); return context.Response.WriteAsync("Hello world"); }); app.UseStageMarker(PipelineStage.ResolveCache); }
public void Configuration(IAppBuilder app) { app.Use<AddBreadCrumbMiddleware>("start-of-the-line"); app.Map("/branch1", app1 => { app1.Use<AddBreadCrumbMiddleware>("took-branch1"); // Nesting paths, e.g. /branch1/branch2 app1.Map("/branch2", app2 => { app2.Use<AddBreadCrumbMiddleware>("took-branch2"); app2.Use<DisplayBreadCrumbs>(); }); MapIfIE(app1); app1.Use<DisplayBreadCrumbs>(); }); // Only full segments are matched, so /branch1 does not match /branch100 app.Map("/branch100", app1 => { app1.Use<AddBreadCrumbMiddleware>("took-branch100"); app1.Use<DisplayBreadCrumbs>(); }); MapIfIE(app); app.Use<AddBreadCrumbMiddleware>("no-branches-taken"); app.Use<DisplayBreadCrumbs>(); }
public void Configuration(IAppBuilder app) { var configuration = new JabbrConfiguration(); if (configuration.MigrateDatabase) { // Perform the required migrations DoMigrations(); } var kernel = SetupNinject(configuration); app.Use(typeof(DetectSchemeHandler)); if (configuration.RequireHttps) { app.Use(typeof(RequireHttpsHandler)); } app.UseErrorPage(); SetupAuth(app, kernel); SetupSignalR(kernel, app); SetupWebApi(kernel, app); SetupMiddleware(kernel, app); SetupNancy(kernel, app); SetupErrorHandling(); }
public void ConfigAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions {}); //[email protected] //Azure680628 app.Use(async (context, next) => { await next.Invoke(); }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // Client Id of Application ClientId = "24e8d712-4765-48f1-9698-9e335da6f780", // The authority provides a discoverable openid service //https://login.windows.net/JohnsonAzureAD.onmicrosoft.com/.well-known/openid-configuration // The keys //https://login.windows.net/common/discovery/keys Authority = "https://login.windows.net/JohnsonAzureAD.onmicrosoft.com", PostLogoutRedirectUri = "http://localhost:53509/" }); app.Use(async (context, next) => { await next.Invoke(); }); }
public void Configuration(IAppBuilder builder) { builder.UseAlpha("a", "b"); builder.UseFunc(app => Alpha.Invoke(app, "a", "b")); builder.UseFunc(Alpha.Invoke, "a", "b"); builder.Use(Beta.Invoke("a", "b")); builder.UseFunc(Beta.Invoke, "a", "b"); builder.UseGamma("a", "b"); builder.Use(typeof(Gamma), "a", "b"); builder.UseType<Gamma>("a", "b"); builder.UseFunc<AppFunc>(app => new Gamma(app, "a", "b").Invoke); builder.Use(typeof(Delta), "a", "b"); builder.UseType<Delta>("a", "b"); builder.UseFunc<AppFunc>(app => new Delta(app, "a", "b").Invoke); builder.Run(this); }
public void MiddlewaresAtDifferentStagesConfiguration(IAppBuilder app) { app.Use((context, next) => { //Create a custom object in the dictionary to push middlewareIds. context.Set<Stack<int>>("stack", new Stack<int>()); return next.Invoke(); }); var stageTuples = new Tuple<RequestNotification, PipelineStage>[] { new Tuple<RequestNotification, PipelineStage>(RequestNotification.AuthenticateRequest, PipelineStage.Authenticate), new Tuple<RequestNotification, PipelineStage>(RequestNotification.AuthenticateRequest, PipelineStage.PostAuthenticate), new Tuple<RequestNotification, PipelineStage>(RequestNotification.AuthorizeRequest, PipelineStage.Authorize), new Tuple<RequestNotification, PipelineStage>(RequestNotification.AuthorizeRequest, PipelineStage.PostAuthorize), new Tuple<RequestNotification, PipelineStage>(RequestNotification.ResolveRequestCache, PipelineStage.ResolveCache), new Tuple<RequestNotification, PipelineStage>(RequestNotification.ResolveRequestCache, PipelineStage.PostResolveCache), new Tuple<RequestNotification, PipelineStage>(RequestNotification.MapRequestHandler, PipelineStage.MapHandler), new Tuple<RequestNotification, PipelineStage>(RequestNotification.MapRequestHandler, PipelineStage.PostMapHandler), new Tuple<RequestNotification, PipelineStage>(RequestNotification.AcquireRequestState, PipelineStage.AcquireState), new Tuple<RequestNotification, PipelineStage>(RequestNotification.AcquireRequestState, PipelineStage.PostAcquireState), new Tuple<RequestNotification, PipelineStage>(RequestNotification.PreExecuteRequestHandler, PipelineStage.PreHandlerExecute), }; for (int middlewareId = 0; middlewareId < stageTuples.Length; middlewareId++) { var stage = stageTuples[middlewareId]; app.Use<IntegratedPipelineMiddleware>(stage.Item1, middlewareId); app.UseStageMarker(stage.Item2); } }
public void Configuration(IAppBuilder app) { if (Debugger.IsAttached) { app.Use(async (_http, _next) => { await _next(); Console.WriteLine($"{_http.Response.StatusCode}: {_http.Request.Uri}"); }); } app.Use((_http, _next) => { if (_http.Request.Headers.ContainsKey("Origin")) { _http.Response.Headers.Set("Access-Control-Allow-Origin", "*"); } return _next(); }); foreach (var _subStartup in _Kernel.GetAll<ISubStartup>()) { app.Map(_subStartup.Path, _subApp => _subStartup.Configuration(_subApp)); } }
// Invoked once at startup to configure your application. public void Configuration(IAppBuilder builder) { builder.Use((context, next) => { context.Response.Headers.Add("MyHeader", new [] { "abc" }); return next(); }); builder.UseStaticFiles("/Client"); //builder.UseFileServer(new FileServerOptions() //{ // RequestPath = new PathString("/Client"), // FileSystem = new PhysicalFileSystem(".\\Client") //}); builder.Use<BasicAuthentication>(); HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute("Default", "api/Customer/{customerID}", new { controller="CustomerWebApi", customerID = RouteParameter.Optional }); var oDataBuilder = new ODataConventionModelBuilder(); oDataBuilder.EntitySet<Customer>("Customer"); config.Routes.MapODataRoute("odata", "odata", oDataBuilder.GetEdmModel()); // Use this if you want XML instead of JSON //config.Formatters.XmlFormatter.UseXmlSerializer = true; //config.Formatters.Remove(config.Formatters.JsonFormatter); config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; //config.Formatters.Remove(config.Formatters.XmlFormatter); builder.UseWebApi(config); }
public void Configuration(IAppBuilder app) { var settings = new ApplicationSettings(); if (settings.MigrateDatabase) { // Perform the required migrations DoMigrations(); } var kernel = SetupNinject(settings); app.Use(typeof(DetectSchemeHandler)); if (settings.RequireHttps) { app.Use(typeof(RequireHttpsHandler)); } app.UseShowExceptions(); SetupAuth(app, kernel); SetupSignalR(kernel, app); SetupWebApi(kernel, app); SetupMiddleware(kernel, app, settings); SetupNancy(kernel, app); SetupErrorHandling(); }
public void Configuration(IAppBuilder app) { // app.UseWelcomePage("/"); //app.Use(new Func<AppFunc, AppFunc>( // next => ( // env => // { // string strText = "åå§ę¹å¼ēOwin"; // var response = env["owin.ResponseBody"] as Stream; // var responseHeaders = env["owin.ResponseHeader"] as Dictionary<string, string[]>; // responseHeaders.Add("content-type", "text-plain"); // return response.WriteAsync(Encoding.UTF8.GetBytes(strText), 0, strText.Length); // } // ))); app.Use<HelloWorldMiddleware>(); app.Use<NonebaseMiddleware>(); app.Use((context, next) => { TextWriter output = context.Get<TextWriter>("host.TraceOutput"); return next().ContinueWith(result => { output.WriteLine("Scheme {0} : Method {1} : Path {2} : MS {3}", context.Request.Scheme, context.Request.Method, context.Request.Path, getTime()); }); }); // ęå ³å¦ä½é ē½®åŗēØēØåŗēčƦē»äæ”ęÆļ¼čÆ·č®æé® http://go.microsoft.com/fwlink/?LinkID=316888 app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync("Hello Owin from selfhost!"); }); }
public void Configuration(IAppBuilder app) { // Show an error page app.UseErrorPage(); // Logging component app.Use<LoggingComponent>(); // Configure web api routing var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Use web api middleware app.UseWebApi(config); // Throw an exception app.Use(async (context, next) => { if (context.Request.Path.ToString() == "/fail") throw new Exception("Doh!"); await next(); }); // Welcome page app.UseWelcomePage("/"); }
public void Configuration(IAppBuilder app) { #if DEBUG app.UseErrorPage(); #endif app.Use( async (context, next) => { // Log all exceptions and incoming requests Console.WriteLine("{0} {1} {2}", context.Request.Method, context.Request.Path, context.Request.QueryString); try { await next(); } catch (Exception exception) { Console.WriteLine(exception.ToString()); throw; } }); var contentFileSystem = new PhysicalFileSystem("Content"); app.UseBabel(new BabelFileOptions() { StaticFileOptions = new StaticFileOptions() { FileSystem = contentFileSystem }}); app.UseFileServer(new FileServerOptions() { FileSystem = contentFileSystem }); app.Use<CommentsMiddleware>(); }
public void Configuration(IAppBuilder app) { //Listando todo o pipeline app.Use(async (environment, next) => { foreach (var pair in environment.Environment) { Console.WriteLine("{0} : {1}", pair.Key, pair.Value); } await next(); }); //Exibindo o que foi requisitado e a resposta app.Use(async (environment, next) => { Console.WriteLine("RequisiĆ§Ć£o: {0}", environment.Request.Path); await next(); Console.WriteLine("Resposta: {0}", environment.Response.StatusCode); }); app.Run(ctx => { return ctx.Response.WriteAsync("Fim!"); }); }
public void CreateLoggerConfiguration(IAppBuilder app) { app.SetLoggerFactory(new LoggerFactory()); app.Use<LoggingMiddleware1>(app); app.Use<LoggingMiddleware2>(app); }
public void Configuration(IAppBuilder builder) { builder.UseAlpha("one", "two"); builder.Use(Beta.Middleware("three", "four")); builder.Use((AppDelegate)Main); }
// The factory designer office that decides what the assembly line should look like // by ordering a set of assembly line constructor machines. private static void Startup(IAppBuilder app) { // Have to explicitly construct the Func<...> since the argument of // Use() is of type object. app.Use(new Func<AppFunc, AppFunc>(BasicAuthenticationMiddleware)); app.Use(new Func<AppFunc, AppFunc>(StartPageMiddleware)); }
public void Configure(IAppBuilder app) { if (!string.IsNullOrWhiteSpace(this.Username) && !string.IsNullOrWhiteSpace(this.Password)) { // if a username and password are supplied, enable basic auth app.Use(BasicAuth); } app.Use(HandleRequest); }
public void Configuration(IAppBuilder app) { app.Use (typeof(HelloWorldOwin.MyFirstMiddleware)); app.Use (typeof(HelloWorldOwin.MySecondMiddleware)); app.Run (context => { return context.Response.WriteAsync("<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>"); }); }
public void Configuration(IAppBuilder builder) { builder.Use(new Func<AppFunc, AppFunc>(OwinDefaultMiddleWare)); builder.Use(typeof(Alpha)); builder.Use(typeof(Beta), "etc"); builder.Use(new Func<AppFunc, AppFunc>(DefaultApplication)); builder.AddSignatureConversion(Conversion1); builder.AddSignatureConversion(Conversion2); }
public void Configure(IAppBuilder app) { app.Use<SerilogMiddleware>(); app.Use<ExceptionHandlerMiddleware>(_container.GetInstance<JsonSerializerSettings>()); app.Use<MagistrateOperatorMiddleware>(_config); _container .GetAllInstances<IController>() .ForEach(controller => controller.Configure(app)); }
public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute("default", "api/{controller}"); //app.Use(typeof(TestMiddleware)); app.Use<HelloWorldComponent>(); app.Use<TestMiddleware>(); app.UseWebApi(config); }
private static void RegisterPipelineMiddleware(HttpOptions options, IEnumerable<ResponseMiddleware> responseMiddlewares, IAppBuilder app) { app.Use<DiscoverCommand>(options.CommandNameResolver, options.CommandFactory); foreach (var middleware in responseMiddlewares) { app.Use(middleware.MiddlewareType, middleware.Arguments); } app.Use<ExecuteCommandPipeline>(options.CommandPipeline); }
public void Configuration(IAppBuilder app) { app.Use(async (ctx, next) => { ctx.Response.ContentType = "text/html"; await ctx.Response.WriteAsync("hello from TGG!<br/>"); await next(); }); app.Use<MyMiddleware>(); }
public void Configuration(IAppBuilder app) { app.Use(typeof(TestOwinMiddleware)); // Claims manager // ClaimsAuthorizationManager // Create a user app.Use(typeof(AuthenticationSimulator)); ConfigureAuth(app); }
public static void Configuration(IAppBuilder app) { // Katana app.Use<DebugMiddleware>((DebugMiddlewareOptions)null); //app.Use<DebugMiddleware>(new DebugMiddlewareOptions(StartWatch, StopWatch)); //app.UseDebugMiddleware(new DebugMiddlewareOptions(StartWatch, StopWatch)); app.Use(async (context, next) => { await context.Response.WriteAsync("<html><head></head><body><b>H</b>ello World</body></html>"); }); }
public void NoStagesSpecified(IAppBuilder app) { app.UseErrorPage(); app.Use<BreadCrumbMiddleware>("a", "PreHandlerExecute"); app.Use<BreadCrumbMiddleware>("b", "PreHandlerExecute"); app.Use<BreadCrumbMiddleware>("c", "PreHandlerExecute"); app.Run(context => { var fullBreadCrumb = context.Get<string>("test.BreadCrumb"); Assert.Equal("abc", fullBreadCrumb); return Task.FromResult(0); }); }
public void Configuration(IAppBuilder appBuilder) { appBuilder.Use(typeof(Middleware1)); appBuilder.Use<Middleware2>(); appBuilder.Use( async (context, next) => { await context.Response.WriteAsync("middleware 3 way in"); await next(); await context.Response.WriteAsync("middleware 3 way back"); }); appBuilder.Map("/siva", this.C); }
public static IAppBuilder UseCustomMiddleware(this IAppBuilder app) { app.Use(typeof(CustomMiddleware)); return(app); }
/// <summary> /// Add identity server token authentication to the pipeline. /// </summary> /// <param name="app">The application.</param> /// <param name="options">The options.</param> /// <returns></returns> public static IAppBuilder UseIdentityServerBearerTokenAuthentication(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } var loggerFactory = app.GetLoggerFactory(); var middlewareOptions = new IdentityServerOAuthBearerAuthenticationOptions(); switch (options.ValidationMode) { case ValidationMode.Local: middlewareOptions.LocalValidationOptions = ConfigureLocalValidation(options, loggerFactory); break; case ValidationMode.ValidationEndpoint: middlewareOptions.EndpointValidationOptions = ConfigureEndpointValidation(options, loggerFactory); break; case ValidationMode.Both: middlewareOptions.LocalValidationOptions = ConfigureLocalValidation(options, loggerFactory); middlewareOptions.EndpointValidationOptions = ConfigureEndpointValidation(options, loggerFactory); break; default: throw new Exception("ValidationMode has invalid value"); } if (!options.DelayLoadMetadata) { // evaluate the lazy members so that they can do their job if (middlewareOptions.LocalValidationOptions != null) { var ignore = middlewareOptions.LocalValidationOptions.Value; } if (middlewareOptions.EndpointValidationOptions != null) { var ignore = middlewareOptions.EndpointValidationOptions.Value; } } if (options.TokenProvider != null) { middlewareOptions.TokenProvider = options.TokenProvider; } app.Use <IdentityServerBearerTokenValidationMiddleware>(app, middlewareOptions, loggerFactory); if (options.RequiredScopes.Any()) { var scopeOptions = new ScopeRequirementOptions { AuthenticationType = options.AuthenticationType, RequiredScopes = options.RequiredScopes }; app.Use <ScopeRequirementMiddleware>(scopeOptions); } if (options.PreserveAccessToken) { app.Use <PreserveAccessTokenMiddleware>(); } app.UseStageMarker(PipelineStage.Authenticate); return(app); }
public static void PreventResponseCaching(this IAppBuilder app) { app.Use(Middleware); }
public static IAppBuilder RequireSsl(this IAppBuilder app, RequireSslOptions options) { app.Use(typeof(RequireSslMiddleware), options); return(app); }
public void Configuration(IAppBuilder app) { var OAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(4), Provider = new SimpleAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { AccessTokenProvider = new CustomAuthenticationTokenProvider() }); app.Use(new Func <AppFunc, AppFunc>(next => (env) => { var ctx = new OwinContext(env); if (ctx.Get <bool>("custom.ExpiredToken")) { ctx.Response.StatusCode = 403; ctx.Response.ReasonPhrase = "Expired Token"; return(Task.FromResult(0)); } else { return(next(env)); } })); // Hangfire initialization var providerName = System.Configuration.ConfigurationManager. ConnectionStrings["toems"].ProviderName; if (providerName.Equals("MySql.Data.MySqlClient")) { //mysql Hangfire.GlobalConfiguration.Configuration.UseStorage( new MySqlStorage(System.Configuration.ConfigurationManager. ConnectionStrings["toems"].ConnectionString)); } else { //sql server Hangfire.GlobalConfiguration.Configuration.UseStorage( new SqlServerStorage(System.Configuration.ConfigurationManager. ConnectionStrings["toems"].ConnectionString)); } app.UseHangfireDashboard(); app.UseHangfireServer(); try { if (ConfigurationManager.AppSettings["ServerRole"].ToLower().Equals("primary")) { RecurringJob.AddOrUpdate("ScheduleRunner-Job", () => new ScheduleRunner().Run(), "*/15 * * * *", TimeZoneInfo.Local); var imagingTimeout = ServiceSetting.GetSettingValue(SettingStrings.ImageTaskTimeoutMinutes); if (!string.IsNullOrEmpty(imagingTimeout)) { if (!imagingTimeout.Equals("0")) { RecurringJob.AddOrUpdate("ImagingTaskTimeout-Job", () => new ServiceActiveImagingTask().CancelTimedOutTasks(), "*/5 * * * *", TimeZoneInfo.Local); } } var groupSchedule = ServiceSetting.GetSettingValue(SettingStrings.DynamicGroupSchedule); var ldapSchedule = ServiceSetting.GetSettingValue(SettingStrings.LdapSyncSchedule); var storageSchedule = ServiceSetting.GetSettingValue(SettingStrings.FolderSyncSchedule); var resetSchedule = ServiceSetting.GetSettingValue(SettingStrings.ResetReportSchedule); var approvalSchedule = ServiceSetting.GetSettingValue(SettingStrings.ApproveReportSchedule); var smartSchedule = ServiceSetting.GetSettingValue(SettingStrings.SmartReportSchedule); var dataCleanupSchedule = ServiceSetting.GetSettingValue(SettingStrings.DataCleanupSchedule); var lowDiskSchedule = ServiceSetting.GetSettingValue(SettingStrings.LowDiskSchedule); RecurringJob.AddOrUpdate("DynamicGroupUpdate-Job", () => new UpdateDynamicMemberships().All(), groupSchedule, TimeZoneInfo.Local); RecurringJob.AddOrUpdate("StorageSync-Job", () => new FolderSync().RunAllServers(), storageSchedule, TimeZoneInfo.Local); RecurringJob.AddOrUpdate("LDAPSync-Job", () => new LdapSync().Run(), ldapSchedule, TimeZoneInfo.Local); if (!string.IsNullOrEmpty(resetSchedule)) { RecurringJob.AddOrUpdate("ResetRequestReport-Job", () => new ServiceResetRequest().SendResetRequestReport(), resetSchedule, TimeZoneInfo.Local); } else { RecurringJob.RemoveIfExists("ResetRequestReport-Job"); } if (!string.IsNullOrEmpty(approvalSchedule)) { RecurringJob.AddOrUpdate("ApprovalRequestReport-Job", () => new ServiceApprovalRequest().SendApprovalRequestReport(), approvalSchedule, TimeZoneInfo.Local); } else { RecurringJob.RemoveIfExists("ApprovalRequestReport-Job"); } if (!string.IsNullOrEmpty(smartSchedule)) { RecurringJob.AddOrUpdate("SmartReport-Job", () => new ServiceReport().SendSmartReport(), smartSchedule, TimeZoneInfo.Local); } else { RecurringJob.RemoveIfExists("SmartReport-Job"); } if (!string.IsNullOrEmpty(lowDiskSchedule)) { RecurringJob.AddOrUpdate("LowDiskReport-Job", () => new ServiceReport().SendLowDiskSpaceReport(), lowDiskSchedule, TimeZoneInfo.Local); } else { RecurringJob.RemoveIfExists("LowDiskReport-Job"); } if (!string.IsNullOrEmpty(dataCleanupSchedule)) { RecurringJob.AddOrUpdate("DataCleanup-Job", () => new DataCleanup().Run(), dataCleanupSchedule, TimeZoneInfo.Local); } else { RecurringJob.RemoveIfExists("DataCleanup-Job"); } } } catch { // ignored } }
public void Configuration(IAppBuilder app) { #if DEBUG app.UseErrorPage(); #endif app.UseWelcomePage("/welcome"); app.Use(async(ctx, next) => { Debug.WriteLine("IN - [{0}] {1}{2}", ctx.Request.Method, ctx.Request.Path, ctx.Request.QueryString); await next(); if (ctx.IsHtmlResponse()) { await ctx.Response.WriteAsync("Added at bottom will be moved into body by good browser"); } Debug.WriteLine("OUT - " + ctx.Response.ContentLength); }); app.UseDebugMiddleware(new DebugMiddlewareOptions { OnIncomingRequest = ctx => { var watch = new Stopwatch(); watch.Start(); ctx.Environment["DebugStopwatch"] = watch; }, OnOutgoingRequest = ctx => { var watch = (Stopwatch)ctx.Environment["DebugStopwatch"]; watch.Stop(); Debug.WriteLine("Request took: " + watch.ElapsedMilliseconds + " ms"); } }); app.Map("/mapped", map => map.Run(ctx => { ctx.Response.ContentType = "text/html"; return(ctx.Response.WriteAsync("<html><body>mapped</body></html>")); })); //app.UseBeanMiddleware(); //app.Use(async (ctx, next) => //{ // if (ctx.Authentication.User != null && // ctx.Authentication.User.Identity != null && // ctx.Authentication.User.Identity.IsAuthenticated) // { // await next(); // } // else // { // ctx.Authentication.Challenge(AuthenticationTypes.Federation); // } //}); app.UseCornifyMiddleware(new CornifyMiddlewareOptions { Autostart = false }); app.UseKonamiCodeMiddleware(new KonamiCodeMiddlewareOptions { Action = "setInterval(function(){ cornify_add(); },500);" }); app.UseServeDirectoryMiddleware(); }
public void Configuration(IAppBuilder app) { var applicationInsightsKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"); if (!string.IsNullOrEmpty(applicationInsightsKey)) { TelemetryConfiguration.Active.InstrumentationKey = applicationInsightsKey; } if (_managerAssembly != null) { AreaRegistration.RegisterAllAreas(); CallChildConfigure(app, _managerAssembly, "VirtoCommerce.Platform.Web.Startup", "Configuration", "~/areas/admin", "admin/"); } UnityWebActivator.Start(); var container = UnityConfig.GetConfiguredContainer(); var locator = new UnityServiceLocator(container); ServiceLocator.SetLocatorProvider(() => locator); //Cure for System.Runtime.Caching.MemoryCache freezing //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol app.SanitizeThreadCulture(); // Caching configuration // Be cautious with SystemWebCacheHandle because it does not work in native threads (Hangfire jobs). var localCache = CacheFactory.FromConfiguration <object>("storefrontCache"); var localCacheManager = new LocalCacheManager(localCache); container.RegisterInstance <ILocalCacheManager>(localCacheManager); //Because CacheManagerOutputCacheProvider used diff cache manager instance need translate clear region by this way //https://github.com/MichaCo/CacheManager/issues/32 localCacheManager.OnClearRegion += (sender, region) => { try { CacheManagerOutputCacheProvider.Cache.ClearRegion(region.Region); } catch { } }; localCacheManager.OnClear += (sender, args) => { try { CacheManagerOutputCacheProvider.Cache.Clear(); } catch { } }; var distributedCache = CacheFactory.Build("distributedCache", settings => { var jsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; var redisCacheEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Storefront:RedisCache:Enabled", false); var memoryHandlePart = settings .WithJsonSerializer(jsonSerializerSettings, jsonSerializerSettings) .WithUpdateMode(CacheUpdateMode.Up) .WithSystemRuntimeCacheHandle("memory") .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1)); if (redisCacheEnabled) { var redisCacheConnectionStringName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Storefront:RedisCache:ConnectionStringName", "RedisCache"); var redisConnectionString = ConfigurationHelper.GetConnectionStringValue(redisCacheConnectionStringName); memoryHandlePart .And .WithRedisConfiguration("redis", redisConnectionString) .WithRetryTimeout(100) .WithMaxRetries(1000) .WithRedisBackplane("redis") .WithRedisCacheHandle("redis", true) .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1)); } }); var distributedCacheManager = new DistributedCacheManager(distributedCache); container.RegisterInstance <IDistributedCacheManager>(distributedCacheManager); var logger = LogManager.GetLogger("default"); container.RegisterInstance <ILogger>(logger); // Create new work context for each request container.RegisterType <WorkContext, WorkContext>(new PerRequestLifetimeManager()); Func <WorkContext> workContextFactory = () => container.Resolve <WorkContext>(); container.RegisterInstance(workContextFactory); // Workaround for old storefront base URL: remove /api/ suffix since it is already included in every resource address in VirtoCommerce.Client library. var baseUrl = ConfigurationHelper.GetConnectionStringValue("VirtoCommerceBaseUrl"); if (baseUrl != null && baseUrl.EndsWith("/api/", StringComparison.OrdinalIgnoreCase)) { var apiPosition = baseUrl.LastIndexOf("/api/", StringComparison.OrdinalIgnoreCase); if (apiPosition >= 0) { baseUrl = baseUrl.Remove(apiPosition); } } var apiAppId = ConfigurationHelper.GetAppSettingsValue("vc-public-ApiAppId"); var apiSecretKey = ConfigurationHelper.GetAppSettingsValue("vc-public-ApiSecretKey"); container.RegisterInstance(new HmacCredentials(apiAppId, apiSecretKey)); container.RegisterType <VirtoCommerceApiRequestHandler>(new PerRequestLifetimeManager()); ServicePointManager.UseNagleAlgorithm = false; container.RegisterType <System.Net.Http.HttpClientHandler>(new InjectionFactory(c => new System.Net.Http.HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })); //Timeout for all API requests. Should be small on production to prevent platform API flood. var apiRequestTimeout = TimeSpan.Parse(ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Storefront:ApiRequest:Timeout", "0:0:30")); var baseUri = new Uri(baseUrl); container.RegisterType <ICacheModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CacheModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <ICartModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CartModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <ICatalogModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CatalogModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IContentModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new ContentModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <ICoreModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CoreModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <ICustomerModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CustomerModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IInventoryModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new InventoryModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IMarketingModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new MarketingModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IOrdersModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new OrdersModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IPlatformModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new PlatformModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IPricingModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new PricingModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IQuoteModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new QuoteModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <ISitemapsModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new SitemapsModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IStoreModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new StoreModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <ISubscriptionModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new SubscriptionModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).DisableRetries().WithTimeout(apiRequestTimeout))); container.RegisterType <IProductRecommendationsModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new ProductRecommendationsModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), c.Resolve <System.Net.Http.HttpClientHandler>()).WithTimeout(apiRequestTimeout))); container.RegisterType <IMarketingService, MarketingServiceImpl>(); container.RegisterType <IPromotionEvaluator, PromotionEvaluator>(); container.RegisterType <ITaxEvaluator, TaxEvaluator>(); container.RegisterType <IPricingService, PricingServiceImpl>(); container.RegisterType <ICustomerService, CustomerServiceImpl>(); container.RegisterType <IMenuLinkListService, MenuLinkListServiceImpl>(); container.RegisterType <ISeoRouteService, SeoRouteService>(); container.RegisterType <IProductAvailabilityService, ProductAvailabilityService>(); container.RegisterType <IInventoryService, InventoryServiceImpl>(); container.RegisterType <ICartBuilder, CartBuilder>(); container.RegisterType <IQuoteRequestBuilder, QuoteRequestBuilder>(); container.RegisterType <ICatalogSearchService, CatalogSearchServiceImpl>(); container.RegisterType <IAuthenticationManager>(new InjectionFactory(context => HttpContext.Current.GetOwinContext().Authentication)); container.RegisterType <IUrlBuilder, UrlBuilder>(); container.RegisterType <IStorefrontUrlBuilder, StorefrontUrlBuilder>(new PerRequestLifetimeManager()); container.RegisterType <IRecommendationsService, CognitiveRecommendationsService>("Cognitive"); container.RegisterType <IRecommendationsService, AssociationRecommendationsService>("Association"); //Register domain events container.RegisterType <IEventPublisher <OrderPlacedEvent>, EventPublisher <OrderPlacedEvent> >(); container.RegisterType <IEventPublisher <UserLoginEvent>, EventPublisher <UserLoginEvent> >(); container.RegisterType <IEventPublisher <QuoteRequestUpdatedEvent>, EventPublisher <QuoteRequestUpdatedEvent> >(); //Register event handlers (observers) container.RegisterType <IAsyncObserver <OrderPlacedEvent>, CustomerServiceImpl>("Invalidate customer cache when user placed new order"); container.RegisterType <IAsyncObserver <QuoteRequestUpdatedEvent>, CustomerServiceImpl>("Invalidate customer cache when quote request was updated"); container.RegisterType <IAsyncObserver <UserLoginEvent>, CartBuilder>("Merge anonymous cart with loggined user cart"); container.RegisterType <IAsyncObserver <UserLoginEvent>, QuoteRequestBuilder>("Merge anonymous quote request with loggined user quote"); var cmsContentConnectionString = BlobConnectionString.Parse(ConfigurationHelper.GetConnectionStringValue("ContentConnectionString")); var themesBasePath = cmsContentConnectionString.RootPath.TrimEnd('/') + "/" + "Themes"; var staticContentBasePath = cmsContentConnectionString.RootPath.TrimEnd('/') + "/" + "Pages"; //Use always file system provider for global theme var globalThemesBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath("~/App_Data/Themes/default")); IContentBlobProvider themesBlobProvider; IStaticContentBlobProvider staticContentBlobProvider; if ("AzureBlobStorage".Equals(cmsContentConnectionString.Provider, StringComparison.OrdinalIgnoreCase)) { themesBlobProvider = new AzureBlobContentProvider(cmsContentConnectionString.ConnectionString, themesBasePath, localCacheManager); staticContentBlobProvider = new AzureBlobContentProvider(cmsContentConnectionString.ConnectionString, staticContentBasePath, localCacheManager); } else { themesBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath(themesBasePath)); staticContentBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath(staticContentBasePath)); } container.RegisterInstance(staticContentBlobProvider); var shopifyLiquidEngine = new ShopifyLiquidThemeEngine(localCacheManager, workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>(), themesBlobProvider, globalThemesBlobProvider, "~/themes/assets", "~/themes/global/assets"); container.RegisterInstance <ILiquidThemeEngine>(shopifyLiquidEngine); //Register liquid engine ViewEngines.Engines.Add(new DotLiquidThemedViewEngine(shopifyLiquidEngine)); // Shopify model binders convert Shopify form fields with bad names to VirtoCommerce model properties. container.RegisterType <IModelBinderProvider, ShopifyModelBinderProvider>("shopify"); //Static content service var staticContentService = new StaticContentServiceImpl(shopifyLiquidEngine, localCacheManager, workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>(), StaticContentItemFactory.GetContentItemFromPath, staticContentBlobProvider); container.RegisterInstance <IStaticContentService>(staticContentService); //Register generate sitemap background job container.RegisterType <GenerateSitemapJob>(new InjectionFactory(c => new GenerateSitemapJob(themesBlobProvider, c.Resolve <ISitemapsModuleApiClient>(), c.Resolve <IStorefrontUrlBuilder>()))); var changesTrackingEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Storefront:ChangesTracking:Enabled", true); var changesTrackingInterval = TimeSpan.Parse(ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Storefront:ChangesTracking:Interval", "0:1:0")); var changesTrackingService = new ChangesTrackingService(changesTrackingEnabled, changesTrackingInterval, container.Resolve <ICacheModuleApiClient>()); container.RegisterInstance <IChangesTrackingService>(changesTrackingService); app.Use <OriginalHostRewriterOwinMiddleware>(container); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, workContextFactory, () => container.Resolve <CommonController>()); RouteConfig.RegisterRoutes(RouteTable.Routes, container.Resolve <ISeoRouteService>(), workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>()); AuthConfig.ConfigureAuth(app, () => container.Resolve <IStorefrontUrlBuilder>()); var bundleConfig = container.Resolve <BundleConfig>(); bundleConfig.Minify = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Storefront:OptimizeStaticContent", false); bundleConfig.RegisterBundles(BundleTable.Bundles); //This special binders need because all these types not contains default ctor and Money with Currency properties ModelBinders.Binders.Add(typeof(Model.Cart.Shipment), new CartModelBinder <Model.Cart.Shipment>(workContextFactory)); ModelBinders.Binders.Add(typeof(Model.Cart.Payment), new CartModelBinder <Model.Cart.Payment>(workContextFactory)); ModelBinders.Binders.Add(typeof(Model.Order.PaymentIn), new OrderModelBinder <Model.Order.PaymentIn>(workContextFactory)); ModelBinders.Binders.Add(typeof(Model.Recommendations.RecommendationEvalContext), new ReccomendationsModelBinder <Model.Recommendations.RecommendationEvalContext>()); app.Use <WorkContextOwinMiddleware>(container); app.UseStageMarker(PipelineStage.PostAuthorize); app.Use <StorefrontUrlRewriterOwinMiddleware>(container); app.UseStageMarker(PipelineStage.PostAuthorize); }
/// <summary> /// Extension method to configure IdentityServer in the hosting application. /// </summary> /// <param name="app">The application.</param> /// <param name="options">The <see cref="IdentityServer3.Core.Configuration.IdentityServerOptions"/>.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// app /// or /// options /// </exception> public static IAppBuilder UseIdentityServer(this IAppBuilder app, IdentityServerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } options.Validate(); // turn off weird claim mappings for JWTs JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary <string, string>(); if (options.RequireSsl) { app.Use <RequireSslMiddleware>(); } if (options.LoggingOptions.EnableKatanaLogging) { app.SetLoggerFactory(new LibLogKatanaLoggerFactory()); } app.UseEmbeddedFileServer(); app.ConfigureRequestId(); app.ConfigureDataProtectionProvider(options); app.ConfigureIdentityServerBaseUrl(options.PublicOrigin); app.ConfigureIdentityServerIssuer(options); // this needs to be earlier than the autofac middleware so anything is disposed and re-initialized // if we send the request back into the pipeline to render the logged out page app.ConfigureRenderLoggedOutPage(); var container = AutofacConfig.Configure(options); app.UseAutofacMiddleware(container); app.UseCors(); app.ConfigureCookieAuthentication(options.AuthenticationOptions.CookieOptions, options.DataProtector); // this needs to be before external middleware app.ConfigureSignOutMessageCookie(); if (options.PluginConfiguration != null) { options.PluginConfiguration(app, options); } if (options.AuthenticationOptions.IdentityProviders != null) { options.AuthenticationOptions.IdentityProviders(app, Constants.ExternalAuthenticationType); } app.ConfigureHttpLogging(options.LoggingOptions); SignatureConversions.AddConversions(app); var httpConfig = WebApiConfig.Configure(options, container); app.UseAutofacWebApi(httpConfig); app.UseWebApi(httpConfig); using (var child = container.CreateScopeWithEmptyOwinContext()) { var eventSvc = child.Resolve <IEventService>(); // TODO -- perhaps use AsyncHelper instead? DoStartupDiagnosticsAsync(options, eventSvc).Wait(); } return(app); }
public void Configuration(IAppBuilder app) { app.Use <HelloWorldComponent>(); }
public static void UseExceptionLogging(this IAppBuilder appBuilder) { appBuilder.Use(typeof(ExceptionMiddleware)); }
public static IAppBuilder UseFederationAuthentication(this IAppBuilder app, FederationAuthenticationOptions options) { app.Use(typeof(FederationAuthenticationMiddleware), options); return(app); }
// This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder app) { try { var httpConfig = new HttpConfiguration(); var env = Environment.GetEnvironmentVariable("ASPNET_ENVIRONMENT") ?? "development"; // standard variable in asp.net core for environment declaration var config = StartupHelper.Configuration; // var funnyQuotesConfig = new FunnyQuotesConfiguration(); // config.GetSection("FunnyQuotes").Bind(funnyQuotesConfig); // -- container registration var builder = new ContainerBuilder(); // build up autofac container builder.RegisterOptions(); // allow injection of strongly typed config builder.RegisterOption <FunnyQuotesConfiguration>(config.GetSection("FunnyQuotes")); builder.RegisterDiscoveryClient(config); // register eureka service discovery builder.RegisterConfiguration(config); builder.RegisterCloudFoundryOptions(config); builder.RegisterMySqlConnection(config); builder.RegisterConsoleLogging(); builder.Register(ctx => // register EF context { var connString = ctx.Resolve <IDbConnection>().ConnectionString; return(new FunnyQuotesCookieDbContext(connString)); }); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // register all controllers to be injectable builder.RegisterWebApiFilterProvider(httpConfig); // register autofac support for webapi filters builder.RegisterType <LoggerExceptionFilterAttribute>() // register global exception handler .AsWebApiExceptionFilterFor <ApiController>() .SingleInstance(); builder.RegisterCloudFoundryActuators(config); var container = builder.Build(); // compile the container // -- configure owin server httpConfig.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); // default to json instead of xml httpConfig.Routes.MapHttpRoute( // setup default routing for WebApi2 "DefaultApi", "api/{controller}/{action}" ); httpConfig.Routes.MapHttpRoute("Health", "{controller}/{action}", new { controller = "health", action = "health" }); // map "/" to basic health endpoint so the default PCF health check for HTTP 200 response is satisfied httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container); // assign autofac to provide dependency injection on controllers var funnyQuotesConfig = container.Resolve <IOptionsMonitor <FunnyQuotesConfiguration> >().CurrentValue; // -- setup app pipeline app.UseAutofacMiddleware(container); // allows injection of dependencies into owin middleware if (funnyQuotesConfig.EnableSecurity) { app.UseCloudFoundryJwtBearerAuthentication(config); // add security integration for PCF SSO } else { app.Use <NoAuthenticationMiddleware>(); // dummy security provider which is necessary if you have secured actions on controllers } app.UseAutofacWebApi(httpConfig); // merges owin pipeline with autofac request lifecycle app.UseWebApi(httpConfig); // standard OWIN WebAPI2 app.UseCors(CorsOptions.AllowAll); container.StartDiscoveryClient(); // ensure that discovery client is started ContainerBuilderExtensions.StartActuators(container); var logger = container.Resolve <ILogger <Startup> >(); container.MigrateDatabase(); logger.LogInformation(">> App Started <<"); } catch (Exception e) { // given that logging is DI controlled it may not be initialized, just write directly to console Console.Error.WriteLine(e); throw; } }
public static IAppBuilder UseExceptionHandler(this IAppBuilder builder) { return(builder.Use <ExceptionHandlerMiddleware>()); }
public void Configure(IAppBuilder app) { // Configure the app app.UseErrorPage(); SharedOptions sharedStaticFileOptions = new SharedOptions() { RequestPath = new PathString("/console"), FileSystem = new EmbeddedResourceFileSystem(typeof(SearchServiceApplication).Assembly, "NuGet.Services.Search.Console") }; app.Use(async(context, next) => { if (String.Equals(context.Request.Path.Value, "/reloadIndex", StringComparison.OrdinalIgnoreCase)) { if (context.Request.User == null || !context.Request.User.IsInRole(Roles.Admin)) { context.Authentication.Challenge(); } else { ReloadIndex(); context.Response.StatusCode = 200; await context.Response.WriteAsync("Reload started."); return; } } await next(); }); // Just a little bit of rewriting. Not the full UseDefaultFiles middleware, just a quick hack app.Use(async(context, next) => { if (String.Equals(context.Request.Path.Value, "/console", StringComparison.OrdinalIgnoreCase)) { // Redirect to trailing slash to maintain relative links context.Response.Redirect(context.Request.PathBase + context.Request.Path + "/"); context.Response.StatusCode = 301; return; } else if (String.Equals(context.Request.Path.Value, "/console/", StringComparison.OrdinalIgnoreCase)) { context.Request.Path = new PathString("/console/Index.html"); } await next(); }); app.UseStaticFiles(new StaticFileOptions(sharedStaticFileOptions)); var thunk = new Func <PackageSearcherManager>(() => _searcherManager); // Public endpoint(s) app.Use(typeof(QueryMiddleware), ServiceName, "/query", thunk); // Admin endpoints app.Use(typeof(DiagMiddleware), ServiceName, "/diag", thunk); app.Use(typeof(FieldsMiddleware), ServiceName, "/fields", thunk); app.Use(typeof(RangeMiddleware), ServiceName, "/range", thunk); app.Use(typeof(SegmentsMiddleware), ServiceName, "/segments", thunk); app.Use(async(context, next) => { // Handle root requests if (!context.Request.Path.HasValue || String.Equals(context.Request.Path.Value, "/")) { JObject response = new JObject(); response.Add("name", ServiceName.ToString()); response.Add("service", ServiceName.Name); JObject resources = new JObject(); response.Add("resources", resources); resources.Add("range", MakeUri(context, "/range")); resources.Add("fields", MakeUri(context, "/fields")); resources.Add("console", MakeUri(context, "/console")); resources.Add("diagnostics", MakeUri(context, "/diag")); resources.Add("segments", MakeUri(context, "/segments")); resources.Add("query", MakeUri(context, "/query")); if (context.Request.User != null && context.Request.User.IsInRole(Roles.Admin)) { resources.Add("reloadIndex", MakeUri(context, "/reloadIndex")); } await SearchMiddleware.WriteResponse(context, response.ToString()); } }); }
public static IAppBuilder UseMirrorSharp([NotNull] this IAppBuilder app, [CanBeNull] MirrorSharpOptions options = null) { Argument.NotNull(nameof(app), app); app.Use(typeof(Middleware), options ?? new MirrorSharpOptions()); return(app); }
public static void UseCustomMiddleware(this IAppBuilder app, IMemoryCache memory) { app.Use <AuthenticationMiddleware>(memory); }
/// <summary> /// Configures the app builder for OWIN operations. /// </summary> /// <param name="app"></param> public void Configure(IAppBuilder app) { var shimMiddleware = new Func <AppFunc, AppFunc>(ShimMiddleware); app.Use(shimMiddleware); }
public static void UseOwinExceptionHandler(this IAppBuilder app) { app.Use <OwinExceptionHandlerMiddleware>(); }
public static void SetupContainer(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper, string virtualRoot, string routePrefix, string modulesPhysicalPath) { container.RegisterInstance(app); var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>(); moduleInitializerOptions.VirtualRoot = virtualRoot; moduleInitializerOptions.RoutePrefix = routePrefix; //Initialize Platform dependencies var connectionString = ConfigurationHelper.GetConnectionStringValue("VirtoCommerce"); var hangfireOptions = new HangfireOptions { StartServer = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.Enabled", true), JobStorageType = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.StorageType", "Memory"), DatabaseConnectionString = connectionString, WorkerCount = ConfigurationHelper.GetNullableAppSettingsValue("VirtoCommerce:Jobs.WorkerCount", (int?)null) }; var hangfireLauncher = new HangfireLauncher(hangfireOptions); InitializePlatform(app, container, pathMapper, connectionString, hangfireLauncher, modulesPhysicalPath); var moduleManager = container.Resolve <IModuleManager>(); var moduleCatalog = container.Resolve <IModuleCatalog>(); var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator(); // Register URL rewriter for platform scripts var scriptsPhysicalPath = pathMapper.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator(); var scriptsRelativePath = MakeRelativePath(applicationBase, scriptsPhysicalPath); var platformUrlRewriterOptions = new UrlRewriterOptions(); platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), ""); app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath) }); // Register URL rewriter before modules initialization if (Directory.Exists(modulesPhysicalPath)) { var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath); var urlRewriterOptions = new UrlRewriterOptions(); foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>()) { var urlRewriteKey = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName); var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath); urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue); moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath); } app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath) }); } container.RegisterInstance(GlobalConfiguration.Configuration); // Ensure all modules are loaded foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.State == ModuleState.NotStarted)) { moduleManager.LoadModule(module.ModuleName); } SwaggerConfig.RegisterRoutes(container); // Post-initialize // Register MVC areas unless running in the Web Platform Installer mode if (IsApplication) { AreaRegistration.RegisterAllAreas(); } // Register other MVC resources GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); if (IsApplication) { RouteConfig.RegisterRoutes(RouteTable.Routes); } BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Security OWIN configuration var authenticationOptions = new Core.Security.AuthenticationOptions { CookiesEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.Enabled", true), CookiesValidateInterval = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)), BearerTokensEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true), BearerTokensExpireTimeSpan = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)), HmacEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.Enabled", true), HmacSignatureValidityPeriod = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)), ApiKeysEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true), ApiKeysHttpHeaderName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"), ApiKeysQueryStringParameterName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"), }; OwinConfig.Configure(app, container, authenticationOptions); hangfireLauncher.ConfigureOwin(app, container); RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *"); var notificationManager = container.Resolve <INotificationManager>(); notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Registration notification", Description = "This notification is sent by email to a client when he finishes registration", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.RegistrationNotificationSubject, Body = PlatformNotificationResource.RegistrationNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Reset password notification", Description = "This notification is sent by email to a client upon reset password request", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.ResetPasswordNotificationSubject, Body = PlatformNotificationResource.ResetPasswordNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new TwoFactorEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Two factor authentication", Description = "This notification contains a security token for two factor authentication", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.TwoFactorNotificationSubject, Body = PlatformNotificationResource.TwoFactorNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new TwoFactorSmsNotification(container.Resolve <ISmsNotificationSendingGateway>()) { DisplayName = "Two factor authentication", Description = "This notification contains a security token for two factor authentication", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.TwoFactorNotificationSubject, Body = PlatformNotificationResource.TwoFactorNotificationBody, Language = "en-US", } }); //Get initialized modules list sorted by dependency order var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules.OfType <ManifestModuleInfo>()) .Where(m => m.ModuleInstance != null && m.State == ModuleState.Initialized) .ToArray(); foreach (var module in postInitializeModules) { moduleManager.PostInitializeModule(module); } var redisConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"]; // Redis if (redisConnectionString != null && !string.IsNullOrEmpty(redisConnectionString.ConnectionString)) { // Cache RedisConfigurations.AddConfiguration(new RedisConfiguration("redisConnectionString", redisConnectionString.ConnectionString)); // SignalR // https://stackoverflow.com/questions/29885470/signalr-scaleout-on-azure-rediscache-connection-issues GlobalHost.DependencyResolver.UseRedis(new RedisScaleoutConfiguration(redisConnectionString.ConnectionString, "VirtoCommerce.Platform.SignalR")); } // SignalR var tempCounterManager = new TempPerformanceCounterManager(); GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager); var hubConfiguration = new HubConfiguration { EnableJavaScriptProxies = false }; app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration); // Initialize InstrumentationKey from EnvironmentVariable var appInsightKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"); if (!string.IsNullOrEmpty(appInsightKey)) { TelemetryConfiguration.Active.InstrumentationKey = appInsightKey; } }
public static IAppBuilder UseJwtAuthentication(this IAppBuilder app, JwtAuthenticationOptions options) { return(app.Use(typeof(JwtAuthnMiddleware), options)); }
public static IAppBuilder UseAudio(this IAppBuilder builder) { return(builder.Use <Middleware.AudioMiddleware>()); }
public static void UseHelloWorld(this IAppBuilder app) { app.Use <HelloWorldComponent>(); }
public void Configuration(IAppBuilder app) { UnityWebActivator.Start(); var container = UnityConfig.GetConfiguredContainer(); //Caching configuration (system runtime memory handle) var cacheManager = CacheFactory.FromConfiguration <object>("storefrontCache"); container.RegisterInstance <ICacheManager <object> >(cacheManager); //Because CacheManagerOutputCacheProvider used diff cache manager instance need translate clear region by this way //https://github.com/MichaCo/CacheManager/issues/32 cacheManager.OnClearRegion += (sender, region) => { CacheManagerOutputCacheProvider.Cache.ClearRegion(region.Region); }; cacheManager.OnClear += (sender, args) => { CacheManagerOutputCacheProvider.Cache.Clear(); }; // Workaround for old storefront base URL: remove /api/ suffix since it is already included in every resource address in VirtoCommerce.Client library. var baseUrl = ConfigurationManager.ConnectionStrings["VirtoCommerceBaseUrl"].ConnectionString; if (baseUrl != null && baseUrl.EndsWith("/api/", StringComparison.OrdinalIgnoreCase)) { var apiPosition = baseUrl.LastIndexOf("/api/", StringComparison.OrdinalIgnoreCase); if (apiPosition >= 0) { baseUrl = baseUrl.Remove(apiPosition); } } var apiClient = new HmacApiClient(baseUrl, ConfigurationManager.AppSettings["vc-public-ApiAppId"], ConfigurationManager.AppSettings["vc-public-ApiSecretKey"]); container.RegisterInstance <ApiClient>(apiClient); container.RegisterType <IStoreModuleApi, StoreModuleApi>(); container.RegisterType <IVirtoCommercePlatformApi, VirtoCommercePlatformApi>(); container.RegisterType <ICustomerManagementModuleApi, CustomerManagementModuleApi>(); container.RegisterType <ICommerceCoreModuleApi, CommerceCoreModuleApi>(); container.RegisterType <ICustomerManagementModuleApi, CustomerManagementModuleApi>(); container.RegisterType <ICatalogModuleApi, CatalogModuleApi>(); container.RegisterType <IPricingModuleApi, PricingModuleApi>(); container.RegisterType <IInventoryModuleApi, InventoryModuleApi>(); container.RegisterType <IShoppingCartModuleApi, ShoppingCartModuleApi>(); container.RegisterType <IOrderModuleApi, OrderModuleApi>(); container.RegisterType <IMarketingModuleApi, MarketingModuleApi>(); container.RegisterType <ICMSContentModuleApi, CMSContentModuleApi>(); container.RegisterType <ISearchModuleApi, SearchModuleApi>(); container.RegisterType <IMarketingService, MarketingServiceImpl>(); container.RegisterType <IPromotionEvaluator, PromotionEvaluator>(); container.RegisterType <ICartBuilder, CartBuilder>(); container.RegisterType <ICatalogSearchService, CatalogSearchServiceImpl>(); container.RegisterType <IAuthenticationManager>(new InjectionFactory((context) => HttpContext.Current.GetOwinContext().Authentication)); container.RegisterType <IStorefrontUrlBuilder, StorefrontUrlBuilder>(new PerRequestLifetimeManager()); if (_managerAssembly != null) { AreaRegistration.RegisterAllAreas(); CallChildConfigure(app, _managerAssembly, "VirtoCommerce.Platform.Web.Startup", "Configuration", "~/areas/admin", "admin/"); } // Create new work context for each request container.RegisterType <WorkContext, WorkContext>(new PerRequestLifetimeManager()); var shopifyLiquidEngine = new ShopifyLiquidThemeEngine(cacheManager, () => container.Resolve <WorkContext>(), () => container.Resolve <IStorefrontUrlBuilder>(), HostingEnvironment.MapPath("~/App_data/themes"), "~/themes/assets", "~/themes/global/assets"); container.RegisterInstance(shopifyLiquidEngine); //Register liquid engine ViewEngines.Engines.Add(new DotLiquidThemedViewEngine(container.Resolve <ShopifyLiquidThemeEngine>())); // Shopify model binders convert Shopify form fields with bad names to VirtoCommerce model properties. container.RegisterType <IModelBinderProvider, ShopifyModelBinderProvider>("shopify"); //Static content service var staticContentService = new StaticContentServiceImpl(HostingEnvironment.MapPath("~/App_data/Pages"), new Markdown(), shopifyLiquidEngine, cacheManager); container.RegisterInstance <IStaticContentService>(staticContentService); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes, () => container.Resolve <WorkContext>(), container.Resolve <ICommerceCoreModuleApi>(), container.Resolve <IStaticContentService>(), cacheManager); AuthConfig.ConfigureAuth(app); app.Use <WorkContextOwinMiddleware>(container); app.UseStageMarker(PipelineStage.ResolveCache); }
public void Configuration(IAppBuilder appBuilder) { appBuilder.Use <SecurityComponent>(); }
/// <summary> /// Inserts a <see cref="HealthCheckMiddleware"/> into the current <see cref="IAppBuilder"/> pipeline /// </summary> /// <param name="appBuilder">The current <see cref="IAppBuilder"/> pipeline</param> /// <param name="config">A <see cref="HealthCheckMiddlewareConfig"/> containing configuration options for the middleware</param> /// <returns>A <see cref="IAppBuilder"/></returns> public static IAppBuilder UseHealthCheck(this IAppBuilder appBuilder, HealthCheckMiddlewareConfig config) => appBuilder.Use <HealthCheckMiddleware>(config);
public void Attach(IAppBuilder appBuilder) { appBuilder.Use(typeof(AddApplicationVersionHeader)); }
public void Configuration(IAppBuilder builder) { builder.Use((context, next) => context.Response.WriteAsync(_myService.GetFoo())); }
public static void UseTestComponentTwo(this IAppBuilder app) { app.Use(Handler); }
/// <summary> /// This actually runs the startup for the OAuth implementation in OWIN /// </summary> /// <param name="app">The OWIN Builder object</param> public void OnStartup(IAppBuilder app) { var settings = GlobalAttributesCache.Value("OAuthSettings").AsDictionary(); int tokenLifespan = settings["OAuthTokenLifespan"].AsIntegerOrNull() ?? 10; // Go ahead and set the .ROCK authentication cookie app.Use(async(context, next) => { await next(); var cookieName = System.Web.Security.FormsAuthentication.FormsCookieName; if (!string.IsNullOrWhiteSpace(context.Authentication?.User?.Identity?.Name) && context.Request.Cookies[cookieName] == null) { try { Rock.Security.Authorization.SetAuthCookie(context.Authentication.User.Identity.Name, false, false); } catch (System.Web.HttpException) { // Just eat this exception. It's thrown when headers have already been sent } } }); //Enable Application Sign In Cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "OAuth", AuthenticationMode = AuthenticationMode.Passive, LoginPath = new PathString("/" + settings["OAuthLoginPath"].Trim('/')), LogoutPath = new PathString("/" + settings["OAuthLogoutPath"].Trim('/')), SlidingExpiration = false, ExpireTimeSpan = new TimeSpan(0, tokenLifespan, 0) }); //Setup Authorization Server app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AuthorizeEndpointPath = new PathString("/" + settings["OAuthAuthorizePath"].Trim('/')), AccessTokenExpireTimeSpan = new TimeSpan(0, tokenLifespan, 0), TokenEndpointPath = new PathString("/" + settings["OAuthTokenPath"].Trim('/')), ApplicationCanDisplayErrors = false, AllowInsecureHttp = AllowInsecureHttp(), //Authorization server provider which controls the lifecycle fo the Authorization Server Provider = new OAuthAuthorizationServerProvider { OnValidateClientRedirectUri = ValidateClientRedirectUri, OnValidateClientAuthentication = ValidateClientAuthentication, OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials, OnGrantClientCredentials = GrantClientCredentials, }, //Authorization code provider who creates and receives authorization code AuthorizationCodeProvider = new AuthenticationTokenProvider { OnCreate = CreateAuthenticationCode, OnReceive = ReceiveAuthenticationCode, }, //Refresh token provider which creates and receives refresh token RefreshTokenProvider = new AuthenticationTokenProvider { OnCreate = CreateRefreshToken, OnReceive = ReceiveRefreshToken } }); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
public virtual void Configure(IAppBuilder owinApp) { owinApp.Use <AspNetCoreAutofacDependencyInjectionMiddleware>(); owinApp.Use <AutofacScopeBasedDependencyResolverMiddleware>(); }