// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            bool useSsl      = Helpers.GetLogicalSetting("useSsl", Configuration, false);
            bool showUrls    = Helpers.GetLogicalSetting("ShowUrls", Configuration, true);
            bool openBrowser = Helpers.GetLogicalSetting("OpenBrowser", Configuration, true);

            string defaultFiles = Configuration["DefaultFiles"];

            if (string.IsNullOrEmpty(defaultFiles))
            {
                defaultFiles = "index.html,default.htm,default.html";
            }

            var strPort = Configuration["Port"];

            if (!int.TryParse(strPort, out Port))
            {
                Port = 5200;
            }

            if (UseLiveReload)
            {
                app.UseLiveReload();
            }

            ////if (env.IsDevelopment())
            ////    app.UseDeveloperExceptionPage();
            ////else
            app.UseExceptionHandler("/Error");

            if (showUrls)
            {
                var socketUrl = Configuration["LiveReload:WebSocketUrl"];

                app.Use(async(context, next) =>
                {
                    var originalPath = context.Request.Path.Value;

                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    await next();

                    // ignore Web socket requests
                    if (context.Request.Path.Value == socketUrl)
                    {
                        return;
                    }

                    // need to ensure this happens all at once otherwise multiple threads
                    // write intermixed console output on simultaneous requests
                    lock (consoleLock)
                    {
                        WriteConsoleLogDisplay(context, sw, originalPath);
                    }
                });
            }

            if (UseMarkdown)
            {
                app.UseMarkdown();
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider     = new PhysicalFileProvider(WebRoot),
                DefaultFileNames = new List <string>(defaultFiles.Split(',', ';'))
            });

            // add static files to WebRoot and our templates folder which provides markdown templates
            // and potentially other library resources in the future

            var wrProvider = new PhysicalFileProvider(WebRoot);
            var tpProvider = new PhysicalFileProvider(Path.Combine(Startup.StartupPath, "templates"));

            var extensionProvider = new FileExtensionContentTypeProvider();

            extensionProvider.Mappings.Add(".dll", "application/octet-stream");
            if (LiveReloadConfiguration.Current.AdditionalMimeMappings != null)
            {
                foreach (var map in LiveReloadConfiguration.Current.AdditionalMimeMappings)
                {
                    extensionProvider.Mappings[map.Key] = map.Value;
                }
            }

            var compositeProvider = new CompositeFileProvider(wrProvider, tpProvider);

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider          = compositeProvider, //new PhysicalFileProvider(WebRoot),
                RequestPath           = new PathString(""),
                ContentTypeProvider   = extensionProvider,
                ServeUnknownFileTypes = true
            });

            if (UseRazor || UseMarkdown)
            {
                app.UseRouting();
            }

#if USE_RAZORPAGES
            if (UseRazor)
            {
                app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
            }
#endif
            if (UseMarkdown)
            {
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapDefaultControllerRoute();
                });
            }

            // 404  - fall through middleware
            if (!string.IsNullOrEmpty(LiveReloadConfiguration.Current.FolderNotFoundFallbackPath))
            {
                app.Use(async(context, next) =>
                {
                    var path = context.Request.Path;
                    if (string.IsNullOrEmpty(Path.GetExtension(path)))
                    {
                        var fi = new FileInfo(Path.Combine(WebRoot, LiveReloadConfiguration.Current.FolderNotFoundFallbackPath.Trim('/', '\\')));
                        await context.Response.SendFileAsync(new PhysicalFileInfo(fi));
                        await context.Response.CompleteAsync();
                    }
                });
            }

            var url        = $"http{(useSsl ? "s" : "")}://localhost:{Port}";
            var extensions = Configuration["Extensions"];

            string headerLine = new string('-', Helpers.AppHeader.Length);
            Console.WriteLine(headerLine);
            ConsoleHelper.WriteLine(Helpers.AppHeader, ConsoleColor.Yellow);
            Console.WriteLine(headerLine);
            Console.WriteLine($"(c) West Wind Technologies, 2019-{DateTime.Now.Year}\r\n");

            Console.Write($"Site Url     : ");
            ConsoleHelper.WriteLine(url, ConsoleColor.DarkCyan);
            Console.WriteLine($"Web Root     : {WebRoot}");
            Console.WriteLine($"Executable   : {Assembly.GetExecutingAssembly().Location}");
            Console.WriteLine(
                $"Extensions   : {(string.IsNullOrEmpty(extensions) ? $"{(UseRazor ? ".cshtml," : "")}.css,.js,.htm,.html,.ts" : extensions)}");
            Console.WriteLine($"Live Reload  : {UseLiveReload}");

#if USE_RAZORPAGES
            Console.WriteLine($"Use Razor    : {UseRazor}");
#endif

            Console.WriteLine($"Use Markdown : {UseMarkdown}");
            if (UseMarkdown)
            {
                Console.WriteLine($"  Resources  : {CopyMarkdownResources}");
                Console.WriteLine($"  Template   : {MarkdownTemplate}");
                Console.WriteLine($"  Theme      : {MarkdownTheme}");
                Console.WriteLine($"  SyntaxTheme: {MarkdownSyntaxTheme}");
            }
            Console.WriteLine($"Show Urls    : {showUrls}");
            Console.WriteLine($"Open Browser : {openBrowser}");
            Console.WriteLine($"Default Pages: {defaultFiles}");
            Console.WriteLine($"Environment  : {env.EnvironmentName}");

            Console.WriteLine();
            ConsoleHelper.Write(Helpers.ExeName + "--help", ConsoleColor.DarkCyan);
            Console.WriteLine(" for start options...");
            Console.WriteLine();
            ConsoleHelper.WriteLine("Ctrl-C or Ctrl-Break to exit...", ConsoleColor.Yellow);

            Console.WriteLine("----------------------------------------------");

            var oldColor = Console.ForegroundColor;
            foreach (var assmbly in LoadedPrivateAssemblies)
            {
                var fname = Path.GetFileName(assmbly);
                ConsoleHelper.WriteLine("Additional Assembly: " + fname, ConsoleColor.DarkGreen);
            }

            foreach (var assmbly in FailedPrivateAssemblies)
            {
                var fname = Path.GetFileName(assmbly);
                ConsoleHelper.WriteLine("Failed Additional Assembly: " + fname, ConsoleColor.DarkGreen);
            }

            Console.ForegroundColor = oldColor;

            if (openBrowser)
            {
                Helpers.OpenUrl(url);
            }
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            bool useSsl      = Helpers.GetLogicalSetting("useSsl", Configuration);
            bool showUrls    = Helpers.GetLogicalSetting("ShowUrls", Configuration);
            bool openBrowser = Helpers.GetLogicalSetting("OpenBrowser", Configuration);

            string defaultFiles = Configuration["DefaultFiles"];

            if (string.IsNullOrEmpty(defaultFiles))
            {
                defaultFiles = "index.html,default.htm,default.html";
            }

            var strPort = Configuration["Port"];

            if (!int.TryParse(strPort, out Port))
            {
                Port = 5000;
            }

            if (UseLiveReload)
            {
                app.UseLiveReload();
            }

            ////if (env.IsDevelopment())
            ////    app.UseDeveloperExceptionPage();
            ////else
            app.UseExceptionHandler("/Error");

            if (showUrls)
            {
                app.Use(async(context, next) =>
                {
                    var url =
                        $"{context.Request.Method}  {context.Request.Scheme}://{context.Request.Host}  {context.Request.Path}{context.Request.QueryString}";
                    Console.WriteLine(url);
                    await next();
                });
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider     = new PhysicalFileProvider(WebRoot),
                DefaultFileNames = new List <string>(defaultFiles.Split(',', ';'))
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(WebRoot), RequestPath = new PathString("")
            });

#if USE_RAZORPAGES
            if (UseRazor)
            {
                app.UseRouting();
                app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
            }
#endif
            var url        = $"http{(useSsl ? "s" : "")}://localhost:{Port}";
            var extensions = Configuration["Extensions"];

            string headerLine = new string('-', Helpers.AppHeader.Length);
            Console.WriteLine(headerLine);
            Console.WriteLine(Helpers.AppHeader);
            Console.WriteLine(headerLine);
            Console.WriteLine($"(c) West Wind Technologies, 2018-{DateTime.Now.Year}\r\n");
            Console.Write($"Site Url     : ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(url);
            Console.ResetColor();
            Console.WriteLine($"Web Root     : {WebRoot}");
            Console.WriteLine(
                $"Extensions   : {(string.IsNullOrEmpty(extensions) ? $"{(UseRazor ? ".cshtml," : "")}.css,.js,.htm,.html,.ts" : extensions)}");
            Console.WriteLine($"Live Reload  : {UseLiveReload}");

#if USE_RAZORPAGES
            Console.WriteLine($"Use Razor    : {UseRazor}");
#endif
            Console.WriteLine($"Show Urls    : {showUrls}");
            Console.WriteLine($"Open Browser : {openBrowser}");
            Console.WriteLine($"Default Pages: {defaultFiles}");
            Console.WriteLine($"Environment  : {env.EnvironmentName}");

            Console.WriteLine();
            Console.WriteLine($"'{Helpers.ExeName} --help' for start options...");
            Console.WriteLine();
            Console.WriteLine("Ctrl-C or Ctrl-Break to exit...");

            Console.WriteLine("----------------------------------------------");

            var oldColor = Console.ForegroundColor;
            foreach (var assmbly in LoadedPrivateAssemblies)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Additional Assembly: " + assmbly);
            }

            foreach (var assmbly in FailedPrivateAssemblies)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed Additional Assembly: " + assmbly);
            }

            Console.ForegroundColor = oldColor;

            if (openBrowser)
            {
                Helpers.OpenUrl(url);
            }
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (ServerConfig.UseLiveReload)
            {
                app.UseLiveReload();
            }

            ////if (env.IsDevelopment())
            ////    app.UseDeveloperExceptionPage();
            ////else

            app.UseExceptionHandler("/Error");

            if (ServerConfig.ShowUrls)
            {
                app.Use(DisplayRequestInfoMiddlewareHandler);
            }

            if (ServerConfig.UseMarkdown)
            {
                app.UseMarkdown();
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider     = new PhysicalFileProvider(ServerConfig.WebRoot),
                DefaultFileNames = new List <string>(ServerConfig.DefaultFiles.Split(',', ';'))
            });

            // add static files to WebRoot and our templates folder which provides markdown templates
            // and potentially other library resources in the future

            var wrProvider = new PhysicalFileProvider(ServerConfig.WebRoot);
            var tpProvider = new PhysicalFileProvider(Path.Combine(Startup.StartupPath, "templates"));

            var extensionProvider = new FileExtensionContentTypeProvider();

            extensionProvider.Mappings.Add(".dll", "application/octet-stream");
            if (ServerConfig.AdditionalMimeMappings != null)
            {
                foreach (var map in ServerConfig.AdditionalMimeMappings)
                {
                    extensionProvider.Mappings[map.Key] = map.Value;
                }
            }

            var compositeProvider = new CompositeFileProvider(wrProvider, tpProvider);
            var staticFileOptions = new StaticFileOptions
            {
                //FileProvider = compositeProvider, //new PhysicalFileProvider(WebRoot),

                FileProvider        = new PhysicalFileProvider(ServerConfig.WebRoot),
                RequestPath         = new PathString(""),
                ContentTypeProvider = extensionProvider,
                DefaultContentType  = "application/octet-stream"
            };

            app.UseStaticFiles(staticFileOptions);


            if (ServerConfig.UseRazor || ServerConfig.UseMarkdown)
            {
                app.UseRouting();
            }

#if USE_RAZORPAGES
            if (ServerConfig.UseRazor)
            {
                app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
            }
#endif
            if (ServerConfig.UseMarkdown)
            {
                app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); });
            }

            app.Use(FallbackMiddlewareHandler);


            string headerLine = new string('-', Helpers.AppHeader.Length);
            Console.WriteLine(headerLine);
            ConsoleHelper.WriteLine(Helpers.AppHeader, ConsoleColor.Yellow);
            Console.WriteLine(headerLine);
            Console.WriteLine($"(c) West Wind Technologies, 2019-{DateTime.Now.Year}\r\n");

            string displayUrl = ServerConfig.GetHttpUrl();
            string hostUrl    = ServerConfig.GetHttpUrl(true);
            if (hostUrl == displayUrl || hostUrl.Contains("127.0.0.1"))
            {
                hostUrl = null;
            }
            else
            {
                hostUrl = $"  [darkgray](binding: {hostUrl})[/darkgray]";
            }

            ConsoleHelper.WriteEmbeddedColorLine($"Site Url     : [darkcyan]{ServerConfig.GetHttpUrl()}[/darkcyan] {hostUrl}");
            //ConsoleHelper.WriteLine(, ConsoleColor.DarkCyan);
            Console.WriteLine($"Web Root     : {ServerConfig.WebRoot}");
            Console.WriteLine($"Executable   : {Assembly.GetExecutingAssembly().Location}");
            Console.WriteLine($"Live Reload  : {ServerConfig.UseLiveReload}");
            if (ServerConfig.UseLiveReload)
            {
                Console.WriteLine(
                    $"  Extensions : {(string.IsNullOrEmpty(ServerConfig.Extensions) ? $"{(ServerConfig.UseRazor ? ".cshtml," : "")}.css,.js,.htm,.html,.ts" : ServerConfig.Extensions)}");
            }


#if USE_RAZORPAGES
            Console.WriteLine($"Use Razor    : {ServerConfig.UseRazor}");
#endif

            Console.WriteLine($"Use Markdown : {ServerConfig.UseMarkdown}");
            if (ServerConfig.UseMarkdown)
            {
                Console.WriteLine($"  Resources  : {ServerConfig.CopyMarkdownResources}");
                Console.WriteLine($"  Template   : {ServerConfig.MarkdownTemplate}");
                Console.WriteLine($"  Theme      : {ServerConfig.MarkdownTheme}");
                Console.WriteLine($"  SyntaxTheme: {ServerConfig.MarkdownSyntaxTheme}");
            }

            Console.WriteLine($"Show Urls    : {ServerConfig.ShowUrls}");
            Console.WriteLine($"Open Browser : {ServerConfig.OpenBrowser}");
            Console.WriteLine($"Default Pages: {ServerConfig.DefaultFiles}");
            Console.WriteLine($"Environment  : {env.EnvironmentName}");

            Console.WriteLine();
            ConsoleHelper.Write(Helpers.ExeName + " --help", ConsoleColor.DarkCyan);
            Console.WriteLine(" for start options...");
            Console.WriteLine();
            ConsoleHelper.WriteLine("Ctrl-C or Ctrl-Break to exit...", ConsoleColor.Yellow);

            Console.WriteLine("----------------------------------------------");

            var oldColor = Console.ForegroundColor;
            foreach (var assmbly in LoadedPrivateAssemblies)
            {
                var fname = Path.GetFileName(assmbly);
                ConsoleHelper.WriteEmbeddedColorLine("Additional Assembly: [green]" + fname + "[/green]");
            }

            foreach (var assmbly in FailedPrivateAssemblies)
            {
                var fname = Path.GetFileName(assmbly);
                ConsoleHelper.WriteLine("Failed Additional Assembly: " + fname, ConsoleColor.DarkGreen);
            }

            Console.ForegroundColor = oldColor;

            if (ServerConfig.OpenBrowser)
            {
                Helpers.OpenUrl(ServerConfig.GetHttpUrl());
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            bool useSsl      = Helpers.GetLogicalSetting("useSsl", Configuration, false);
            bool showUrls    = Helpers.GetLogicalSetting("ShowUrls", Configuration, true);
            bool openBrowser = Helpers.GetLogicalSetting("OpenBrowser", Configuration, true);

            string defaultFiles = Configuration["DefaultFiles"];

            if (string.IsNullOrEmpty(defaultFiles))
            {
                defaultFiles = "index.html,default.htm,default.html";
            }

            var strPort = Configuration["Port"];

            if (!int.TryParse(strPort, out Port))
            {
                Port = 5200;
            }

            if (UseLiveReload)
            {
                app.UseLiveReload();
            }

            ////if (env.IsDevelopment())
            ////    app.UseDeveloperExceptionPage();
            ////else
            app.UseExceptionHandler("/Error");

            if (showUrls)
            {
                var socketUrl = Configuration["LiveReload:WebSocketUrl"];

                app.Use(async(context, next) =>
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    await next();

                    // ignore Web socket requests
                    if (context.Request.Path.Value == socketUrl)
                    {
                        return;
                    }

                    lock (consoleLock)
                    {
                        var url =
                            $"{context.Request.Method}  {context.Request.Scheme}://{context.Request.Host}  {context.Request.Path}{context.Request.QueryString}";

                        url = url.PadRight(80, ' ');

                        var ct         = context.Response.ContentType;
                        bool isPrimary = ct != null &&
                                         (ct.StartsWith("text/html") ||
                                          ct.StartsWith("text/plain") ||
                                          ct.StartsWith("application/json") ||
                                          ct.StartsWith("text/xml"));

                        if (ct == null) // no response
                        {
                            ConsoleHelper.Write(url + " ", ConsoleColor.Red);
                            isPrimary = true;
                        }
                        else if (isPrimary)
                        {
                            ConsoleHelper.Write(url + " ", ConsoleColor.Gray);
                        }
                        else
                        {
                            ConsoleHelper.Write(url + " ", ConsoleColor.DarkGray);
                        }

                        var status = context.Response.StatusCode;
                        if (status >= 200 && status < 400)
                        {
                            ConsoleHelper.Write(status.ToString(),
                                                isPrimary ? ConsoleColor.Green : ConsoleColor.DarkGreen);
                        }
                        else if (status == 401)
                        {
                            ConsoleHelper.Write(status.ToString(),
                                                isPrimary ? ConsoleColor.Yellow : ConsoleColor.DarkYellow);
                        }
                        else if (status >= 400)
                        {
                            ConsoleHelper.Write(status.ToString(), isPrimary ? ConsoleColor.Red : ConsoleColor.DarkRed);
                        }

                        sw.Stop();
                        ConsoleHelper.WriteLine($" {sw.ElapsedMilliseconds:n0}ms".PadLeft(8), ConsoleColor.DarkGray);
                    }
                });
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider     = new PhysicalFileProvider(WebRoot),
                DefaultFileNames = new List <string>(defaultFiles.Split(',', ';'))
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(WebRoot), RequestPath = new PathString("")
            });

#if USE_RAZORPAGES
            if (UseRazor)
            {
                app.UseRouting();
                app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
            }
#endif
            var url        = $"http{(useSsl ? "s" : "")}://localhost:{Port}";
            var extensions = Configuration["Extensions"];

            string headerLine = new string('-', Helpers.AppHeader.Length);
            Console.WriteLine(headerLine);
            ConsoleHelper.WriteLine(Helpers.AppHeader, ConsoleColor.Yellow);
            Console.WriteLine(headerLine);
            Console.WriteLine($"(c) West Wind Technologies, 2019-{DateTime.Now.Year}\r\n");

            Console.Write($"Site Url     : ");
            ConsoleHelper.WriteLine(url, ConsoleColor.DarkCyan);
            Console.WriteLine($"Web Root     : {WebRoot}");
            Console.WriteLine($"Executable   : {Assembly.GetExecutingAssembly().Location}");
            Console.WriteLine(
                $"Extensions   : {(string.IsNullOrEmpty(extensions) ? $"{(UseRazor ? ".cshtml," : "")}.css,.js,.htm,.html,.ts" : extensions)}");
            Console.WriteLine($"Live Reload  : {UseLiveReload}");

#if USE_RAZORPAGES
            Console.WriteLine($"Use Razor    : {UseRazor}");
#endif
            Console.WriteLine($"Show Urls    : {showUrls}");
            Console.WriteLine($"Open Browser : {openBrowser}");
            Console.WriteLine($"Default Pages: {defaultFiles}");
            Console.WriteLine($"Environment  : {env.EnvironmentName}");

            Console.WriteLine();
            ConsoleHelper.Write(Helpers.ExeName + "--help", ConsoleColor.DarkCyan);
            Console.WriteLine(" for start options...");
            Console.WriteLine();
            ConsoleHelper.WriteLine("Ctrl-C or Ctrl-Break to exit...", ConsoleColor.Yellow);

            Console.WriteLine("----------------------------------------------");

            var oldColor = Console.ForegroundColor;
            foreach (var assmbly in LoadedPrivateAssemblies)
            {
                var fname = Path.GetFileName(assmbly);
                ConsoleHelper.WriteLine("Additional Assembly: " + fname, ConsoleColor.DarkGreen);
            }

            foreach (var assmbly in FailedPrivateAssemblies)
            {
                var fname = Path.GetFileName(assmbly);
                ConsoleHelper.WriteLine("Failed Additional Assembly: " + fname, ConsoleColor.DarkGreen);
            }

            Console.ForegroundColor = oldColor;

            if (openBrowser)
            {
                Helpers.OpenUrl(url);
            }
        }