Ejemplo n.º 1
0
        public static void WriteStartupErrorMessage(string message, string stackTrace = null, string source = null)
        {
            string headerLine = new string('-', Helpers.AppHeader.Length);

            Console.WriteLine(headerLine);
            Console.WriteLine(Helpers.AppHeader);
            Console.WriteLine(headerLine);

            ColorConsole.WriteWarning("\r\nSomething went wrong during server startup!");
            Console.WriteLine();

            Console.WriteLine("The Live Reload Server has run into a problem and has stopped working.\r\n");
            ColorConsole.WriteError(message);

            if (!string.IsNullOrEmpty(stackTrace))
            {
                Console.WriteLine("----- Error Info -----");
                Console.WriteLine(stackTrace);
                Console.WriteLine(source);
                Console.WriteLine("----------------------");
            }
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            if (Environment.CommandLine.Contains("LiveReloadWebServer", StringComparison.InvariantCultureIgnoreCase))
            {
                Helpers.ExeName = "LiveReloadWebServer";
            }

            try
            {
                var version = Assembly.GetExecutingAssembly().GetName().Version;
                var ver     = version.Major + "." + version.Minor +
                              (version.Build > 0 ? "." + version.Build : string.Empty);
                Helpers.AppHeader = $"Live Reload Web Server v{ver}";


                if (args.Contains("--help", StringComparer.InvariantCultureIgnoreCase) ||
                    args.Contains("/h") || args.Contains("-h"))
                {
                    ShowHelp();
                    return;
                }

                var builder = CreateHostBuilder(args);
                if (builder == null)
                {
                    return;
                }

                WebHost = builder.Build();

                WebHost.Run();
            }
            catch (IOException ex)
            {
                ColorConsole.WriteWarning("\r\nUnable to start the Web Server.");
                Console.WriteLine("------------------------------");
                ColorConsole.WriteWrappedHeader("\r\nUnable to start the Web Server.", headerColor: ConsoleColor.DarkYellow);

                Console.WriteLine("Most likely the server port is already in use by another application.");
                Console.WriteLine("Please try and choose another port with the `--port` switch. And try again.");
                Console.WriteLine("\r\n\r\n");
                ColorConsole.WriteError(ex.Message);
                Console.WriteLine("---------------------------------------------------------------------------");
            }
            catch (SocketException ex)
            {
                ColorConsole.WriteError("\r\nUnable to start the Web Server.");
                Console.WriteLine("------------------------------");

                Console.WriteLine("The server Host IP address is invalid.");
                Console.WriteLine("Please try and choose another host IP address with the `--host` switch. And try again.");
                Console.WriteLine("\r\n\r\n");
                ColorConsole.WriteError(ex.Message);
                Console.WriteLine("---------------------------------------------------------------------------");
            }
            catch (Exception ex)
            {
                // can't catch internal type
                if (ex.StackTrace.Contains("ThrowOperationCanceledException"))
                {
                    return;
                }

                WriteStartupErrorMessage(ex.Message, ex.StackTrace, ex.Source);
            }
        }
Ejemplo 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 (ServerConfig.DetailedErrors)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

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

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

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

            // 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 || !string.IsNullOrEmpty(ServerConfig.FolderNotFoundFallbackPath))
            {
                app.UseRouting();
            }

#if USE_RAZORPAGES
            if (ServerConfig.UseRazor)
            {
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapRazorPages();
                });
            }
#endif
            if (ServerConfig.UseMarkdown)
            {
                app.UseEndpoints(endpoints =>
                {
                    // We need MVC Routing for Markdown to work
                    endpoints.MapDefaultControllerRoute();
                });
            }

            //if (!string.IsNullOrEmpty(ServerConfig.FolderNotFoundFallbackPath))
            //{
            //    app.UseEndpoints(endpoints =>
            //    {
            //        endpoints.MapFallbackToFile("/index.html");
            //    });
            //}
            //app.Use(FallbackMiddlewareHandler);


            string headerLine = new string('-', Helpers.AppHeader.Length);
            Console.WriteLine(headerLine);
            ColorConsole.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]";
            }

            ColorConsole.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.Write($"Open Browser : {ServerConfig.OpenBrowser}");

            Console.WriteLine($"Default Pages: {ServerConfig.DefaultFiles}");
            Console.WriteLine($"Detail Errors: {ServerConfig.DetailedErrors}");
            ColorConsole.WriteEmbeddedColorLine($"Environment  : [darkgreen]{env.EnvironmentName}[/darkgreen]  {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}");

            Console.WriteLine();
            ColorConsole.Write(Helpers.ExeName + " --help", ConsoleColor.DarkCyan);
            Console.WriteLine(" for start options...");
            Console.WriteLine();
            ColorConsole.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);
                ColorConsole.WriteEmbeddedColorLine("Additional Assembly: [darkgreen]" + fname + "[/darkgreen]");
            }

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

            Console.ForegroundColor = oldColor;

            if (ServerConfig.OpenBrowser)
            {
                Helpers.OpenUrl(ServerConfig.GetHttpUrl());
            }

            if (ServerConfig.OpenEditor)
            {
                string cmdLine = null;
                try
                {
                    cmdLine = ServerConfig.EditorLaunchCommand.Replace("%1", ServerConfig.WebRoot);
                    Westwind.Utilities.ShellUtils.ExecuteCommandLine(cmdLine);
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteError("Failed to launch editor with: " + cmdLine);
                    ColorConsole.WriteError("-- " + ex.Message);
                }
            }
        }