Example #1
0
        private static void ConfigureStaticContent(IAppBuilder app)
        {
            // TODO: When Owin.Compression reaches a more mature state, use that for compression

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/css"),
                FileSystem = new PhysicalFileSystem("Public/Styles")
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/js"),
                FileSystem = new PhysicalFileSystem("Public/Scripts")
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/fonts"),
                FileSystem = new PhysicalFileSystem("Public/Fonts")
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/avatars"),
                FileSystem = new PhysicalFileSystem("Public/Images/Avatars")
            });
        }
Example #2
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {

            appBuilder.UseFileServer(new FileServerOptions()
            {
                RequestPath = PathString.Empty,
                FileSystem = new PhysicalFileSystem(@".\")
            });

            appBuilder.UseStaticFiles("/Views");
            appBuilder.UseStaticFiles("/Scripts");
            appBuilder.UseStaticFiles("/js");
            appBuilder.UseStaticFiles("/Content");

            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();

            //  Enable attribute based routing
            //  http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
            config.MapHttpAttributeRoutes();

            // Remove the XML formatter
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Routes.MapHttpRoute(
                name: "AfterglowAPI",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            appBuilder.UseWebApi(config);
        } 
Example #3
0
 public void Configuration(IAppBuilder app)
 {
     string strUseRedis = CloudConfigurationManager.GetSetting("UseRedis") ?? "false";
     bool useRedis = bool.Parse(strUseRedis);
     var dependencyResolver = new UnityDependencyResolver();
     UnityWireupConfiguration.WireUp(dependencyResolver);
     GlobalHost.DependencyResolver = dependencyResolver;
     var options = new CookieAuthenticationOptions()
     {
         AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
         LoginPath = new PathString("/"),
         LogoutPath = new PathString("/")
     };
     app.UseCookieAuthentication(options);
     app.Use(async (context, next) =>
     {
         if (context.Request.Path.Value.Equals("/") ||
         context.Request.Path.Value.StartsWith("/public", StringComparison.CurrentCultureIgnoreCase))
         {
             await next();
         }
         else if (context.Request.User == null || !context.Request.User.Identity.IsAuthenticated)
         {
             context.Response.StatusCode = 401;
         }
         else
         {
             await next();
         }
     });
     HttpConfiguration webApiConfiguration = new HttpConfiguration();
     webApiConfiguration.DependencyResolver = dependencyResolver;
     webApiConfiguration.MapHttpAttributeRoutes();
     app.UseWebApi(webApiConfiguration);
     RedisConfiguration redisConfiguration = dependencyResolver.Resolve<RedisConfiguration>();
     if (redisConfiguration.UseRedis)
     {
         GlobalHost.DependencyResolver.UseRedis(redisConfiguration.HostName, redisConfiguration.Port, redisConfiguration.Password, redisConfiguration.EventKey);
     }
     app.MapSignalR();
     var sharedOptions = new SharedOptions()
     {
         RequestPath = new PathString(string.Empty),
         FileSystem =
             new PhysicalFileSystem(".//public//content")
     };
     app.UseDefaultFiles(new Microsoft.Owin.StaticFiles.DefaultFilesOptions(sharedOptions)
     {
         DefaultFileNames = new List<string>() { "index.html" }
     });
     app.UseStaticFiles("/public");
     app.UseStaticFiles("/content");
     app.UseStaticFiles("/scripts");
     app.UseStaticFiles("/styles");
     app.UseStaticFiles(new StaticFileOptions(sharedOptions));
 }
Example #4
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/")
            });

            SetupContainer();

            var applicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath;

            // use DotVVM
            DotvvmConfiguration dotvvmConfiguration = app.UseDotVVM(applicationPhysicalPath, true);
            dotvvmConfiguration.ServiceLocator.RegisterSingleton<IViewModelLoader>(() => new WindsorViewModelLoader(container));

            RegisterResources(dotvvmConfiguration);

            AddRoutes(dotvvmConfiguration);

            RegisterMappings();

            RegisterJsCompilables();

            // use static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(applicationPhysicalPath)
            });
        }
Example #5
0
        public void Configuration(IAppBuilder app)
        {
            app.UseFalcor("/model.json",
                routerFactory: config => new NetflixRouter(new FakeRatingService(), new RecommendationService.RecommendationService(), userId: 1));

            app.UseStaticFiles();
        }
        public void Configuration(IAppBuilder app)
        {
            var instrumentationKey = System.Configuration.ConfigurationManager.AppSettings.Get("Telemetry.InstrumentationKey");
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                // set it as early as possible to avoid losing telemetry
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;
            }

            _searcherManager = CreateSearcherManager();

            //test console
            app.Use(async (context, next) =>
            {
                if (string.Equals(context.Request.Path.Value, "/console", StringComparison.OrdinalIgnoreCase))
                {
                    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(new SharedOptions
            {
                RequestPath = new PathString("/console"),
                FileSystem = new EmbeddedResourceFileSystem(typeof(QueryMiddleware).Assembly, "NuGet.Services.Search.Console")
            }));

            app.Run(Invoke);
        }
Example #7
0
        public void Configuration(IAppBuilder app)
        {
            app.Use<RedwoodApp>(HostingEnvironment.ApplicationPhysicalPath);
            app.UseStaticFiles();

            RedwoodConfiguration.Default.RouteTable.MapPageRoute<TaskListPresenter>("");
        }
Example #8
0
 public void Configuration(IAppBuilder app)
 {
     
     app.UseStaticFiles("/Sample/Web");
     
     app.UseXSockets(true);
 }
Example #9
0
 public void DefaultStaticFiles(IAppBuilder app)
 {
     app.Use((context, next) => { context.Response.Headers["PassedThroughOWIN"] = "True"; return next(); });
     app.UseStaticFiles();
     app.Run(context => { context.Response.StatusCode = 402; return context.Response.WriteAsync("Fell Through"); });
     app.UseStageMarker(PipelineStage.MapHandler);
 }
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            // Static file support.
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new PhysicalFileSystem(root: baseDir),
                ServeUnknownFileTypes = false
            });

            // ASP.NET Web API support.
            var config = new HttpConfiguration();
            
            // Fix: CORS support of WebAPI doesn't work on mono. http://stackoverflow.com/questions/31590869/web-api-2-post-request-not-working-on-mono
            if (Type.GetType("Mono.Runtime") != null) config.MessageHandlers.Add(new MonoPatchingDelegatingHandler());

            config.EnableCors();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            app.UseWebApi(config);

            // NancyFx support.
            app.UseNancy();
        }
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            app.UseErrorPage();
#endif
            // Remap '/' to '.\defaults\'.
            // Turns on static files and default files.
            app.UseFileServer(new FileServerOptions()
            {
                RequestPath = PathString.Empty,
                FileSystem = new PhysicalFileSystem(@".\defaults"),
            });

            // Only serve files requested by name.
            app.UseStaticFiles("/files");

            // Turns on static files, directory browsing, and default files.
            app.UseFileServer(new FileServerOptions()
            {
                RequestPath = new PathString("/public"),
                EnableDirectoryBrowsing = true,
            });

            // Browse the root of your application (but do not serve the files).
            // NOTE: Avoid serving static files from the root of your application or bin folder,
            // it allows people to download your application binaries, config files, etc..
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                RequestPath = new PathString("/src"),
                FileSystem = new PhysicalFileSystem(@""),
            });

            // Anything not handled will land at the welcome page.
            app.UseWelcomePage();
        }
Example #12
0
        public void Configuration(IAppBuilder app)
        {
            app.Use((ctx, next) =>
            {
                var output = ctx.Get<TextWriter>("host.TraceOutput");
                output.WriteLine("{0} {1}: {2}", ctx.Request.Scheme, ctx.Request.Method, ctx.Request.Path);
                return next();
            });
            GlobalHost.DependencyResolver.Register(typeof(VoteHub),
                () => new VoteHub(new QuestionRepository()));

            app.UseStaticFiles();
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            //app.MapSignalR();
            app.Map("/signalr", map => map.UseCors(CorsOptions.Value)
                 .RunSignalR(new HubConfiguration
                 {
                     EnableJSONP = true
                 }));

            app.UseNancy(options =>
                    options.PerformPassThrough = context =>
                        context.Response.StatusCode == HttpStatusCode.NotFound);
            
            app.Run(context =>
            {
                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync("Hello World!");
            });
        }
Example #13
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.Trace()
               .CreateLogger();

            app.UseAesDataProtectorProvider();
            app.Map("/admin", adminApp =>
                {
                    var factory = new IdentityManagerServiceFactory();
                   
                    factory.ConfigureSimpleIdentityManagerService("AspId");
                    //factory.ConfigureCustomIdentityManagerServiceWithIntKeys("AspId_CustomPK");

                    var adminOptions = new IdentityManagerOptions(){
                        Factory = factory
                    };
                    adminOptions.SecurityConfiguration.RequireSsl = false;
                    adminApp.UseIdentityManager(adminOptions);
                });

            var idSvrFactory = Factory.Configure();
            idSvrFactory.ConfigureUserService("AspId");

            var viewOptions = new ViewServiceOptions
            {
                TemplatePath = this.basePath.TrimEnd(new char[] { '/' })
            };
            idSvrFactory.ViewService = new IdentityServer3.Core.Configuration.Registration<IViewService>(new ViewService(viewOptions));

            var options = new IdentityServerOptions
            {
                SiteName = "IdentityServer3 - ViewSerive-AspNetIdentity",
                SigningCertificate = Certificate.Get(),
                Factory = idSvrFactory,
                RequireSsl = false,
                AuthenticationOptions = new AuthenticationOptions
                {
                    IdentityProviders = ConfigureAdditionalIdentityProviders,
                }
            };

            app.Map("/core", core =>
            {
                core.UseIdentityServer(options);
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/Content"),
                FileSystem = new PhysicalFileSystem(Path.Combine(this.basePath, "Content")) 
            });

            var config = new HttpConfiguration();
          //  config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("API", "api/{controller}/{action}", new { controller = "Home", action = "Get" });
            app.UseWebApi(config);
        }
Example #14
0
        // 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);
		}
Example #15
0
        public void Configuration(IAppBuilder app)
        {
            /* // Note: Enable only for debugging. This slows down the perf tests.
            app.Use((context, next) =>
            {
                var req = context.Request;
                context.TraceOutput.WriteLine("{0} {1}{2} {3}", req.Method, req.PathBase, req.Path, req.QueryString);
                return next();
            });*/

            app.UseErrorPage(new ErrorPageOptions { SourceCodeLineCount = 20 });
            // app.Use(typeof(AutoTuneMiddleware), app.Properties["Microsoft.Owin.Host.HttpListener.OwinHttpListener"]);
            app.UseSendFileFallback();
            app.Use<CanonicalRequestPatterns>();

            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath = new PathString("/static"),
                FileSystem = new PhysicalFileSystem("public")
            });
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                RequestPath = new PathString("/static"),
                FileSystem = new PhysicalFileSystem("public")
            });
            app.UseStageMarker(PipelineStage.MapHandler);

            FileServerOptions options = new FileServerOptions();
            options.EnableDirectoryBrowsing = true;
            options.StaticFileOptions.ServeUnknownFileTypes = true;

            app.UseWelcomePage("/Welcome");
        }
Example #16
0
 public static void Configuration(IAppBuilder app)
 {
     app.UseStaticFiles();
     app.Use(async (ctx, next) => {
         await ctx.Response.WriteAsync("Hello World");
     });
 }
Example #17
0
 public void Configuration(IAppBuilder app)
 {
     //app.UseStaticFiles(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"Assets"));
     app.UseStaticFiles("/Assets");
     app.Use(typeof(RadMvcMiddleware));
     //app.UseWelcomePage();
 }
Example #18
0
        public void Configuration(IAppBuilder app)
        {
            app.UseFalcor("/model.json", config =>
                new NetflixFalcorRouter(new FakeRatingService(),
                    new FakeRecommendationService(), 1));

            app.UseStaticFiles();
        }
 public void Configuration(IAppBuilder app)
 {
     var config = new HubConfiguration { EnableCrossDomain = true };
     app.MapHubs(config);
     string exeFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
     string webFolder = Path.Combine(exeFolder, "Web");
     app.UseStaticFiles(webFolder);
 }
Example #20
0
        private static void SetupMiddleware(IApplicationSettings settings, IAppBuilder app)
        {
            if (settings.ProxyImages)
            {
                app.MapPath("/proxy", subApp => subApp.Use(typeof(ImageProxyHandler), settings));
            }

            app.UseStaticFiles();
        }
Example #21
0
 public void Configuration(IAppBuilder app)
 {
     app.UseWebApi(Models.Config.GetHttpConfiguration());
     app.UseErrorPage();
     // the next line is needed for handling the UriPathExtensionMapping...
     app.UseStageMarker(PipelineStage.MapHandler);
     app.UseStaticFiles();
     app.UseFileServer(true);
 }
Example #22
0
        public void Configuration(IAppBuilder builder)
        {
            builder.Use(typeof(CustomTracer));
               // builder.Map("/resources", sw => sw.UseSimpleWeb());
            //builder.UseNancy();
            builder.UseStaticFiles("/Web", "Web");
            builder.UseStaticFiles("/Scripts", "Scripts");
            builder.UseStaticFiles("/Content", "Content");
            builder.UseStaticFiles("/partials", "partials");

            //var config = new HttpConfiguration();
            //config.Routes.MapHttpRoute( "DefaultApi","api/{controller}/");
            //builder.UseWebApi(config);

            IWindsorContainer container = new WindsorContainer().Install(FromAssembly.This());
            var controllerFactory = new WindsorControllerFactory(container.Kernel);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);
        }
Example #23
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new StaticFilesConfiguration("htdocs");
            configuration.AddIgnoredExtension(".ts");

            app.UseStaticFiles(configuration);

            app.UseStageMarker(PipelineStage.MapHandler);
        }
Example #24
0
 public void Configuration(IAppBuilder app)
 {
     //app.Run(context => context.Response.WriteAsync("YO"));
     app
         .UseStaticFiles(new StaticFileOptions { FileSystem = new PhysicalFileSystem(Path.Combine(AssemblyDirectory, "static")), RequestPath = new PathString("/static") })
         .Use(MyMiddleware.DoIt())
         .UseNancy()
         ;
 }
 private void SetUpStaticFileHosting(IAppBuilder appBuilder)
 {
     var options = new FileServerOptions
     {
         RequestPath = new PathString("/wwwroot"),
         EnableDirectoryBrowsing = true
     };
     appBuilder.UseFileServer(options);
     appBuilder.UseStaticFiles();
 }
        public void CustomDefaultFileConfiguration(IAppBuilder app)
        {
            var options = new DefaultFilesOptions() { DefaultFileNames = new string[] { "TextFile1.txt" }, FileSystem = new PhysicalFileSystem(@"RequirementFiles\Dir1") };
            app.UseDefaultFiles(options);

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(@"RequirementFiles\Dir1")
            });
        }
Example #27
0
 public void Configuration(IAppBuilder app)
 {
     // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
     #if DEBUG
     app.UseErrorPage();
     #endif
     app.UseWelcomePage("/");
     app.UseStaticFiles();
     //app.UseWebPages();
 }
Example #28
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            appBuilder.UseWebApi(config);
            appBuilder.UseStaticFiles();
        }
Example #29
0
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            app.UseErrorPage();
#endif
            var configuration = new StaticFilesConfiguration("htdocs");
            configuration.AddIgnoredExtension(".ts");

            app.UseStaticFiles(configuration);
        }
Example #30
0
        // ReSharper disable once UnusedMember.Global
        public void Configuration(IAppBuilder app)
        {
            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new PhysicalFileSystem(@".\dist")
            });

            RemoveTransports(GlobalHost.DependencyResolver);

            app.MapSignalR();
        }
Example #31
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public static void ConfigureApp(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            appBuilder.UseWebApi(config);
            appBuilder.UseStaticFiles(
                new StaticFileOptions()
            {
                FileSystem            = new PhysicalFileSystem(@".\wwwroot"),
                ServeUnknownFileTypes = true
            });
        }
Example #32
0
        public void Configuration(IAppBuilder app)
        {
            app.UseErrorPage();

            var dataSetsService  = new FileSystemDataSets(DataSetsRootDirectory);
            var templatesService = new FileSystemTemplates(TemplatesRootDirectory);

            app.Use((context, next) =>
            {
                context.Set(typeof(IDataSetsService).ToString(), dataSetsService);
                context.Set(typeof(ITemplatesService).ToString(), templatesService);
                return(next.Invoke());
            });
            app.UseDesigner(config => config.UseFileStore(ResourcesRootDirectory));

            app.UseReporting(config => config.UseFileStore(ResourcesRootDirectory));

            app.UseStaticFiles(new StaticFileOptions {
                FileSystem = new PhysicalFileSystem(String.Format(@"{0}.\wwwroot\", HttpRuntime.AppDomainAppPath))
            });
        }
Example #33
0
        public void Configuration(IAppBuilder app)
        {
            var applicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath;

            // use DotVVM
            var dotvvmConfiguration = app.UseDotVVM <DotvvmStartup>(applicationPhysicalPath, options: options =>
            {
                options.AddDefaultTempStorages("temp");
                options.AddUploadedFileStorage("App_Data/Temp");
            });

#if !DEBUG
            dotvvmConfiguration.Debug = false;
#endif

            // use static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(applicationPhysicalPath)
            });
        }
Example #34
0
        public void Configuration(IAppBuilder app)
        {
            //For serving up static files
            foreach (var staticDirectory in Constants.StaticDirectories)
            {
                app.UseStaticFiles(staticDirectory);
            }

            app.Map("/signalr", map =>
            {
                var config = new HubConfiguration();

                // Turns cors support on allowing everything
                // In real applications, the origins should be locked down
                map.UseCors(CorsOptions.AllowAll).RunSignalR(config);
            });

            app.Use(SupportReponseTypeByContentType);
            app.UseNancy(a => { a.Bootstrapper = _nancyBootstrapper; });
            app.UseErrorPage();
        }
        public void Configuration(IAppBuilder appBuilder)
        {
            /*appBuilder.Use(async (env, next) =>
             * {
             *  Console.WriteLine(string.Concat("Http method: ", env.Request.Method, ", path: ", env.Request.Path));
             *  await next();
             *  Console.WriteLine(string.Concat("Response code: ", env.Response.StatusCode));
             * });*/

            // Is request a signal?
            RunWebApiConfiguration(appBuilder);

            // Or is it a static file request?
            appBuilder.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(@"..\Web")
            });

            // Or simply / ?
            appBuilder.UseIndexPage();
        }
Example #36
0
        public void Configuration(IAppBuilder app)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            var issuer   = "https://" + ConfigurationManager.AppSettings["auth0:Domain"] + "/";
            var audience = ConfigurationManager.AppSettings["auth0:ClientId"];
            var secret   = TextEncodings.Base64.Encode(TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"]));

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { ConfigurationManager.AppSettings["auth0:ClientId"] },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });


            // serve static content from client folder under api-authentication
            string contentPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\client");

            app.UseStaticFiles(new Microsoft.Owin.StaticFiles.StaticFileOptions()
            {
                RequestPath = new PathString(string.Empty),
                FileSystem  = new PhysicalFileSystem(contentPath)
            });

            // serve the api
            app.UseWebApi(config);
        }
Example #37
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            //  Enable attribute based routing
            //  http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
            config.MapHttpAttributeRoutes();

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            //appBuilder.UseStaticFiles("/static");

            //const string rootFolder = ".";
            //System.Reflection.Assembly ass = ;
            var fileSystem = new EmbeddedResourceFileSystem(Assembly.GetAssembly(typeof(StaticClass)), "TypeScriptHTMLApp");
            var options    = new StaticFileOptions
            {
                FileSystem = fileSystem
            };

            //appBuilder.UseFileServer(options);
            //appBuilder.UseDirectoryBrowser();
            appBuilder.UseStaticFiles(options);
            var defOptions = new DefaultFilesOptions
            {
                DefaultFileNames = { "index.html" },
                FileSystem       = fileSystem
            };

            appBuilder.UseDefaultFiles(defOptions);
            appBuilder.UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}",
                defaults: new { id = RouteParameter.Optional }
                );

            var    relativePath = string.Format(@"..{0}..{0}..{0}", Path.DirectorySeparatorChar);
            string contentPath  = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), relativePath);

            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath = new PathString("/audio"),
                FileSystem  = new PhysicalFileSystem(Path.Combine(contentPath, @"audio"))
            });

            app.UseWebApi(config);
        }
Example #39
0
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            app.UseErrorPage();
#endif
            // Remap '/' to '.\www\'.
            // Turns on static files and default files.
            app.UseFileServer(new FileServerOptions()
            {
                RequestPath             = PathString.Empty,
                FileSystem              = new PhysicalFileSystem(@".\www"),
                EnableDefaultFiles      = true,
                EnableDirectoryBrowsing = false
            });

            // Only serve files requested by name in www.
            app.UseStaticFiles("/www");

            HttpConfiguration config = new HttpConfiguration();
            config.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());

            //  Enable attribute based routing
            //  http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
            config.MapHttpAttributeRoutes();

            // Web API
            config.Routes.MapHttpRoute(
                name: "api",
                routeTemplate: "api/{controller}/{sha1}",
                defaults: new { sha1 = RouteParameter.Optional }
                );
            app.UseWebApi(config);

            // Anything not handled will land at the welcome page.
            //app.UseWelcomePage();

            // signalR
            app.MapSignalR();
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseErrorPage();

            //  search test console

            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(new SharedOptions
            {
                RequestPath = new PathString("/console"),
                FileSystem  = new EmbeddedResourceFileSystem(typeof(Startup).Assembly, "NuGet.Services.BasicSearch.Console")
            }));

            //  start the service running - the Lucene index needs to be reopened regularly on a background thread

            _searcherManager = CreateSearcherManager();

            _searcherManager.Open();

            _gate  = 0;
            _timer = new Timer(new TimerCallback(ReopenCallback), 0, 0, 180 * 1000);

            app.Run(Invoke);
        }
Example #41
0
        public void Configuration(IAppBuilder builder)
        {
            builder.UseDefaultFiles(new DefaultFilesOptions()
            {
                RequestPath      = new PathString(),
                DefaultFileNames = new List <string>()
                {
                    "index.html"
                },
                FileSystem = new PhysicalFileSystem(@".\app")
            });

            builder.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath = new PathString(),
                FileSystem  = new PhysicalFileSystem(@".\app")
            });

            HttpConfiguration httpConfiguration = new HttpConfiguration();
            UnityContainer    container         = new UnityContainer();

            container.RegisterType <IToolManager, ToolManager>();
            container.RegisterType <ICategoryManager, CategoryManager>();
            container.RegisterType <IOSManager, OSManager>();
            httpConfiguration.DependencyResolver = new UnityDependencyResolver(container);

            Mapper.CreateMap <Tool, ToolModel>();
            Mapper.CreateMap <Category, CategoryModel>();
            Mapper.CreateMap <Entities.OperatingSystem, OSModel>();

            httpConfiguration.Filters.Add(new TLErrorAttribute());

            httpConfiguration
            .EnableSwagger(c => c.SingleApiVersion("v1", "ToolList API"))
            .EnableSwaggerUi();

            httpConfiguration.MapHttpAttributeRoutes();
            builder.UseWebApi(httpConfiguration);
        }
Example #42
0
        public void Configuration(IAppBuilder app)
        {
            app.Use <SwitchMiddleware>(
                new List <SwitchMiddlewareCase> {
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/Auth"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/Auth/Login"),
                    AuthenticationType = "ApplicationCookie",
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ComplexSamples/SPARedirect"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    LoginPath          = new PathString("/ComplexSamples/SPARedirect/login"),
                    AuthenticationType = "ApplicationCookie",
                    Provider           = new CookieAuthenticationProvider {
                        OnApplyRedirect = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.OwinContext, c.RedirectUri)
                    }
                })
                    ),
                new SwitchMiddlewareCase(
                    c => c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/AuthenticatedView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/RoleView") ||
                    c.Request.Uri.PathAndQuery.StartsWith("/ControlSamples/ClaimView"), next =>
                    new CookieAuthenticationMiddleware(next, app, new CookieAuthenticationOptions {
                    AuthenticationType = "ApplicationCookie"
                })
                    )
            }
                );
            var config = app.UseDotVVM <DotvvmStartup>(GetApplicationPath());

            config.RouteTable.Add("AuthorizedPresenter", "ComplexSamples/Auth/AuthorizedPresenter", provider => new AuthorizedPresenter());
            app.UseStaticFiles();
        }
Example #43
0
        public void Configuration(IAppBuilder app)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate
            {
                return(true);
            };
            app.Use(typeof(CustomMiddleware));
            app.UseStaticFiles();
            app.UseStageMarker(PipelineStage.MapHandler);

            HttpConfiguration config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            ConfigureAuth(app);

            app.UseWebApi(config);

            var physicalFileSystem = new PhysicalFileSystem(@"./www");
            var options            = new FileServerOptions
            {
                EnableDefaultFiles = true,
                FileSystem         = physicalFileSystem
            };

            options.StaticFileOptions.FileSystem            = physicalFileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            options.DefaultFilesOptions.DefaultFileNames    = new[]
            {
                "index.html"
            };

            app.UseFileServer(options);
        }
Example #44
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            var path = Path.Combine(
                Path.GetDirectoryName("..\\..\\"), "content");

            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new PhysicalFileSystem(path)
            });
            app.MapSignalR();
            app.Map("", appBuilder => appBuilder.Run(context =>
            {
                context.Response.StatusCode = 302;
                context.Response.Headers.Add("Location", new[]
                {
                    "/index.html"
                });
                return(context.Response.WriteAsync(""));
            }));
        }
Example #45
0
        public void Configuration(IAppBuilder config)
        {
            Bundle.RegisterStylePreprocessor(new SassPreprocessor());
            var httpConfig = ConfigureWebApi();

            config.Use <ExceptionMiddleware>();
            config.Use <CultureMiddleware>();
            #if (!DEBUG)
            config.Use <RedirectToHttpsMiddleware>();
            #endif
            config.UseAutofacMiddleware(ConfigureAutofac(httpConfig));

            config.UseStaticFiles("/Client");

            config.UseCors(CorsOptions.AllowAll);
            config.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                CookiePath     = "/admin/hangfire",
                ExpireTimeSpan = TimeSpan.FromMinutes(15)
            });
            config.UseOAuthAuthorizationServer(ConfigureOAuthServer());
            config.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            JobStartup jobStartup = null;
            config.UseHangfire(hangfireConfig =>
            {
                var module = ConfigureHangfire(hangfireConfig);
                jobStartup = module.Resolve <JobStartup>();
            });
            config.UseWebApi(httpConfig);
            config.UseAutofacWebApi(httpConfig);

            config.Use(Handler);

            _logger.Info("Application is started!");

            jobStartup.Start();
        }
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            if (UseServerWorkaround)
            {
                app.Use(async(context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 101)
                    {
                        // this forces ClientWebSocket to believe their is content
                        // to process thus it keeps the socket alive for processing??
                        context.Response.Headers.Set("Content-Length", "1");
                    }
                });
            }

            app.UseStaticFiles();
            app.UseWebApi(config);
        }
Example #47
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "Swagger",
                routeTemplate: "api/swagger/{*path}",
                defaults: new { controller = "Swagger" }
                );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{*path}",
                defaults: new { controller = "Sheet" }
                );


            app.UseWebApi(config);

            app.UseStaticFiles(new Microsoft.Owin.StaticFiles.StaticFileOptions()
            {
                FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem("www")
            });
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseStaticFiles();

            app.UseSwagger(typeof(Startup).Assembly, settings =>
            {
                // configure settings here
                // settings.GeneratorSettings.*: Generator settings and extension points
                // settings.*: Routing and UI settings

                settings.PostProcess = (process) =>
                {
                    process.Info.Title = "WebAPI";
                };
            });

            app.UseSwaggerUi3(typeof(Startup).Assembly, settings =>
            {
                settings.TagsSorter = "alpha";

                // sets the docs on default path /swagger
            });

            app.UseSwaggerUi3(typeof(Startup).Assembly, settings =>
            {
                settings.TagsSorter = "alpha";

                // overrides default documentation with project template. Browse to /help
                settings.Path = "/help";
            });

            app.UseSwaggerReDoc(typeof(Startup).Assembly, settings =>
            {
                // Provides a documentation site with redoc open source documentation template at /redoc
                settings.Path = "/redoc";
            });
        }
Example #49
0
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            app.UseErrorPage();

            PhysicalFileSystem defaultFS = new PhysicalFileSystem(@".\defaults");
#endif
            // Remap '/' to '.\defaults\'.
            // Turns on static files and default files.
            app.UseFileServer(new FileServerOptions()
            {
                RequestPath = PathString.Empty,
                FileSystem  = defaultFS,
            });

            // Only serve files requested by name.
            app.UseStaticFiles("/files");

            // Turns on static files, directory browsing, and default files.
            app.UseFileServer(new FileServerOptions()
            {
                RequestPath             = new PathString("/public"),
                EnableDirectoryBrowsing = true,
            });

            // Browse the root of your application (but do not serve the files).
            // NOTE: Avoid serving static files from the root of your application or bin folder,
            // it allows people to download your application binaries, config files, etc..
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                RequestPath = new PathString("/src"),
                FileSystem  = new PhysicalFileSystem(@""),
            });

            // Anything not handled will land at the welcome page.
            app.UseWelcomePage();
        }
Example #50
0
        public void Configuration(IAppBuilder app)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                //routeTemplate: "{controller}"
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;

            const string rootFolder = ".";
            var          fileSystem = new PhysicalFileSystem(rootFolder);
            var          options    = new FileServerOptions
            {
                EnableDefaultFiles      = true,
                FileSystem              = fileSystem,
                EnableDirectoryBrowsing = true
            };

            app.UseFileServer(options);

            string contentPath = Path.Combine(Environment.CurrentDirectory, @"..\..");

            app.UseStaticFiles(new Microsoft.Owin.StaticFiles.StaticFileOptions()
                                           {
                             RequestPath = new PathString(),
                             FileSystem  = new PhysicalFileSystem(contentPath)
                                                   
            });

            app.UseWebApi(config);
        }
Example #51
0
        public void Configuration(IAppBuilder app)
        {
            var instrumentationKey = System.Configuration.ConfigurationManager.AppSettings.Get("Telemetry.InstrumentationKey");

            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                // set it as early as possible to avoid losing telemetry
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;
            }

            _searcherManager = CreateSearcherManager();

            //test console
            app.Use(async(context, next) =>
            {
                if (string.Equals(context.Request.Path.Value, "/console", StringComparison.OrdinalIgnoreCase))
                {
                    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(new SharedOptions
            {
                RequestPath = new PathString("/console"),
                FileSystem  = new EmbeddedResourceFileSystem(typeof(QueryMiddleware).Assembly, "NuGet.Services.Search.Console")
            }));

            app.Run(Invoke);
        }
Example #52
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.DependencyResolver = new UnityDependencyResolver(SetupContainer());

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "Api",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new PhysicalFileSystem(@"./www"),
            }
                               );

            app.Use <RedirectRootMiddleware>();

            app.UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            var dir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "webdir");

            var staticFilesOptions = new StaticFileOptions
            {
                RequestPath = new PathString(""),
                FileSystem  = new PhysicalFileSystem(dir)
            };

            app.UseStaticFiles(staticFilesOptions);

            var config = new HttpConfiguration();

            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            app.UseWebApi(config);
        }
Example #54
0
        public void Configuration(IAppBuilder app)
        {
            /* // Note: Enable only for debugging. This slows down the perf tests.
             * app.Use((context, next) =>
             * {
             *  var req = context.Request;
             *  context.TraceOutput.WriteLine("{0} {1}{2} {3}", req.Method, req.PathBase, req.Path, req.QueryString);
             *  return next();
             * });*/

            app.UseErrorPage(new ErrorPageOptions {
                SourceCodeLineCount = 20
            });
            // app.Use(typeof(AutoTuneMiddleware), app.Properties["Microsoft.Owin.Host.HttpListener.OwinHttpListener"]);
            app.UseSendFileFallback();
            app.Use <CanonicalRequestPatterns>();

            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath = new PathString("/static"),
                FileSystem  = new PhysicalFileSystem("public")
            });
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                RequestPath = new PathString("/static"),
                FileSystem  = new PhysicalFileSystem("public")
            });
            app.UseStageMarker(PipelineStage.MapHandler);

            FileServerOptions options = new FileServerOptions();

            options.EnableDirectoryBrowsing = true;
            options.StaticFileOptions.ServeUnknownFileTypes = true;

            app.UseWelcomePage("/Welcome");
        }
Example #55
0
        public void Configuration(IAppBuilder app)
        {
            var applicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath;

            // use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/"),
            });

            // use DotVVM
            var dotvvmConfiguration = app.UseDotVVM <DotvvmStartup>(applicationPhysicalPath);

#if DEBUG
            dotvvmConfiguration.Debug = true;
#endif

            // use static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(applicationPhysicalPath)
            });
        }
Example #56
0
        /// <summary>
        /// The method name is defined by convention
        /// </summary>
        public void Configuration(IAppBuilder app)
        {
            string staticFilePath;

            if (ConfigurationManager.AppSettings.AllKeys.Contains(ConfigurationKeys.StaticFilePath))
            {
                staticFilePath = ConfigurationManager.AppSettings[ConfigurationKeys.StaticFilePath];
            }
            else
            {
                throw new InvalidOperationException("Could not find a Static Files Path AppSettings entry for " + ConfigurationKeys.StaticFilePath);
            }

            app.UseStaticFiles(staticFilePath);

            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            app.UseWebApi(config);
        }
Example #57
0
        public void Configuration(IAppBuilder app)
        {
            var applicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath;

            ConfigureAuth(app);
            // use DotVVM
            var dotvvmConfiguration = app.UseDotVVM <DotvvmStartup>(applicationPhysicalPath, debug: IsInDebugMode(), options: options =>
            {
                options.AddDefaultTempStorages("temp");
                options.AddUploadedFileStorage("App_Data/Temp");
            });


            // use static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(applicationPhysicalPath)
            });
            //app.Run(context =>
            //{
            //    context.Response.Redirect("/");
            //    return Task.FromResult(0);
            //});
        }
Example #58
0
 private static void SetupMiddleware(IKernel kernel, IAppBuilder app)
 {
     app.UseStaticFiles();
 }
Example #59
0
        public void Configuration(IAppBuilder app, string virtualRoot, string routPrefix)
        {
            VirtualRoot = virtualRoot;

            _assembliesPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Modules");
            var platformPath        = HostingEnvironment.MapPath(VirtualRoot).EnsureEndSeparator();
            var modulesVirtualPath  = VirtualRoot + "/Modules";
            var modulesPhysicalPath = HostingEnvironment.MapPath(modulesVirtualPath).EnsureEndSeparator();

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            //Modules initialization
            var bootstrapper = new VirtoCommercePlatformWebBootstrapper(modulesVirtualPath, modulesPhysicalPath, _assembliesPath, platformPath);

            bootstrapper.Run();

            var container = bootstrapper.Container;

            container.RegisterInstance(app);

            var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>();

            moduleInitializerOptions.VirtualRoot = virtualRoot;
            moduleInitializerOptions.RoutPrefix  = routPrefix;

            //Initialize Platform dependencies
            const string connectionStringName = "VirtoCommerce";

            InitializePlatform(app, container, connectionStringName);

            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        = HostingEnvironment.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)
                });
            }

            // Ensure all modules are loaded
            foreach (var module in moduleCatalog.Modules.Where(x => x.State == ModuleState.NotStarted))
            {
                moduleManager.LoadModule(module.ModuleName);
            }

            // Post-initialize

            // Platform MVC configuration
            if (IsApplication)
            {
                AreaRegistration.RegisterAllAreas();
            }

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Security OWIN configuration
            var authenticationOptions = new Core.Security.AuthenticationOptions
            {
                CookiesEnabled             = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.Enabled", true),
                CookiesValidateInterval    = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)),
                BearerTokensEnabled        = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true),
                BearerTokensExpireTimeSpan = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)),
                HmacEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.Enabled", true),
                HmacSignatureValidityPeriod = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)),
                ApiKeysEnabled                  = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true),
                ApiKeysHttpHeaderName           = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"),
                ApiKeysQueryStringParameterName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"),
            };

            OwinConfig.Configure(app, container, connectionStringName, authenticationOptions);

            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 sends by email to client when he finish registration",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = PlatformNotificationResource.RegistrationNotificationBody,
                    Subject  = PlatformNotificationResource.RegistrationNotificationSubject,
                    Language = "en-US"
                }
            });

            notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Reset password notification",
                Description          = "This notification sends by email to client when he want to reset his password",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = PlatformNotificationResource.ResetPasswordNotificationBody,
                    Subject  = PlatformNotificationResource.ResetPasswordNotificationSubject,
                    Language = "en-US"
                }
            });

            var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules)
                                        .Where(m => m.ModuleInstance != null)
                                        .ToArray();

            foreach (var module in postInitializeModules)
            {
                moduleManager.PostInitializeModule(module);
            }

            // SignalR
            var tempCounterManager = new TempPerformanceCounterManager();

            GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager);
            var hubConfiguration = new HubConfiguration {
                EnableJavaScriptProxies = false
            };

            app.MapSignalR("/" + moduleInitializerOptions.RoutPrefix + "signalr", hubConfiguration);

            //Start background sample data installation if in config set concrete zip path (need for demo)
            var settingManager = container.Resolve <ISettingsManager>();

            if (!settingManager.GetValue("VirtoCommerce:SampleDataInstalled", false))
            {
                var sampleDataUrl = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:SampleDataUrl", string.Empty);
                if (!string.IsNullOrEmpty(sampleDataUrl) && sampleDataUrl.EndsWith(".zip"))
                {
                    var exportImportController = container.Resolve <PlatformExportImportController>();
                    exportImportController.TryToImportSampleData(sampleDataUrl);
                }
            }
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseErrorPage();

            //  search test console

            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(new SharedOptions
            {
                RequestPath = new PathString("/console"),
                FileSystem  = new EmbeddedResourceFileSystem(typeof(Startup).Assembly, "NuGet.Services.Metadata.Console")
            }));

            //  AAD integration - adding this middleware gives us the claims

            string audience    = _configurationService.Get("ida.Audience");
            string tenant      = _configurationService.Get("ida.Tenant");
            string aadInstance = _configurationService.Get("ida.AADInstance");

            string metadataAddress = string.Format(aadInstance, tenant) + "/federationmetadata/2007-06/federationmetadata.xml";

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience   = audience,
                    ValidateIssuer  = true,
                    IssuerValidator = (string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters) => issuer
                },
                Tenant          = tenant,
                MetadataAddress = metadataAddress
            });

            //  start the service running - the Lucene index needs to be reopened regularly on a background thread

            string searchIndexRefresh = _configurationService.Get("Search.IndexRefresh") ?? "15";
            int    seconds;

            if (!int.TryParse(searchIndexRefresh, out seconds))
            {
                seconds = 60;
            }

            _searcherManager = null;

            _gate  = 0;
            _timer = new Timer(ReopenCallback, 0, 10, seconds * 1000);

            app.Run(Invoke);
        }