Beispiel #1
0
        private static void Main(string[] args)
        {
            #region Setup buttons

            Setup.WiringPiSetupGpio();
            CoreFunctions.SetPinMode(26, Constants.PinMode.Input);

            Task.Run(() =>
            {
                ApiController.ButtonCheck.Add(26, 0);
                var prev = true;

                while (true)
                {
                    var x = CoreFunctions.ReadBit(26);

                    if (x != prev)
                    {
                        ApiController.ButtonCheck[26] += prev ? 1 : 0;
                        prev = x;
                    }

                    System.Threading.Thread.Sleep(5);
                }
            });

            #endregion

            var url = "http://*:9696/";
            if (args.Length > 0)
                url = args[0];

            // Our web server is disposable. Note that if you don't want to use logging,
            // there are alternate constructors that allow you to skip specifying an ILog object.
            using (var server = new WebServer(url, new SimpleConsoleLog()))
            {
                server.WithWebApiController<ApiController>();
                server.RegisterModule(new CorsModule());

                // Here we setup serving of static files
                server.RegisterModule(new StaticFilesModule(Directory.GetCurrentDirectory()));

                // The static files module will cache small files in ram until it detects they have been modified.
                server.Module<StaticFilesModule>().UseRamCache = true;
                server.Module<StaticFilesModule>().DefaultExtension = ".html";
                // We don't need to add the line below. The default document is always index.html.
                //server.Module<Modules.StaticFilesWebModule>().DefaultDocument = "index.html";

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                // This is a non-blocking method (it return immediately) so in this case we avoid
                // disposing of the object until a key is pressed.
                //server.Run();
                server.RunAsync();

                // Wait for any key to be pressed before disposing of our web server.
                // In a service we'd manage the lifecycle of of our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }
        }
Beispiel #2
0
        private void Run()
        {
            // If false, don't bother
            if (!(bool)ServiceVariables["IsRunning"])
            {
                return;
            }

            var uri = (Uri)ServiceVariables["HostUri"];

            // https://github.com/unosquare/embedio
            using (_webServer = new EmbedIO.WebServer(uri.AbsoluteUri, EmbedIO.Constants.RoutingStrategy.Regex))
            {
#if DEBUG
                //Terminal.Settings.DisplayLoggingMessageType = LogMessageType.Debug;
#else
                Terminal.Settings.DisplayLoggingMessageType = LogMessageType.None;
#endif

                // First, we will configure our web server by adding Modules.
                // Please note that order DOES matter.
                // ================================================================================================
                // If we want to enable sessions, we simply register the LocalSessionModule
                // Beware that this is an in-memory session storage mechanism so, avoid storing very large objects.
                // You can use the server.GetSession() method to get the SessionInfo object and manupulate it.
                // You could potentially implement a distributed session module using something like Redis
                _webServer.RegisterModule(new LocalSessionModule());

                // Here we setup serving of static files
                _webServer.RegisterModule(new StaticFilesModule("Content"));
                // The static files module will cache small files in ram until it detects they have been modified.
                _webServer.Module <StaticFilesModule>().UseRamCache      = true;
                _webServer.Module <StaticFilesModule>().DefaultExtension = ".html";
                // We don't need to add the line below. The default document is always index.html.
                _webServer.Module <StaticFilesModule>().DefaultDocument = "index.html";

                // Enable CORS to enable CRUD operations over http
                _webServer.EnableCors();

                // Register Api module
                _webServer.RegisterModule(new WebApiModule());

                // Register the Service controller
                //var servicesController = new ServicesController(_serviceContext);
                _webServer.Module <WebApiModule>().RegisterController <ServicesController>();

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                _webServer.RunAsync();

                //
                _serviceContext.Log.Informational("The WebServer is running on: " + uri.AbsoluteUri);

                while ((bool)ServiceVariables["IsRunning"])
                {
                    Thread.Sleep(1);
                }
            }

            _serviceContext.Log.Informational("NancyWeb host it no longer active");
        }
Beispiel #3
0
        /// <summary>
        /// Add WebApi Controller to WebServer
        /// </summary>
        /// <param name="webserver">The webserver instance.</param>
        /// <returns>The webserver instance.</returns>
        public static WebServer WithWebApiController <T>(this WebServer webserver) where T : WebApiController, new()
        {
            if (webserver == null)
            {
                throw new ArgumentException(Constants.ArgumentNullExceptionMessage, nameof(webserver));
            }

            if (webserver.Module <WebApiModule>() == null)
            {
                webserver = webserver.WithWebApi();
            }
            webserver.Module <WebApiModule>().RegisterController <T>();

            return(webserver);
        }
Beispiel #4
0
        /// <summary>
        /// Add WebApi Controller to WebServer
        /// </summary>
        /// <param name="webserver">The webserver instance.</param>
        /// <returns>The webserver instance.</returns>
        public static WebServer WithWebApiController <T>(this WebServer webserver) where T : WebApiController, new()
        {
            if (webserver == null)
            {
                throw new ArgumentException("Argument cannot be null.", "webserver");
            }

            if (webserver.Module <WebApiModule>() == null)
            {
                webserver = webserver.WithWebApi();
            }
            webserver.Module <WebApiModule>().RegisterController <T>();

            return(webserver);
        }
Beispiel #5
0
        /// <summary>
        /// Add WebApi Controller to WebServer.
        /// </summary>
        /// <typeparam name="T">The type of Web API Controller.</typeparam>
        /// <param name="webserver">The webserver instance.</param>
        /// <returns>An instance of webserver.</returns>
        /// <exception cref="ArgumentNullException">webserver.</exception>
        public static WebServer WithWebApiController <T>(this WebServer webserver)
            where T : WebApiController
        {
            if (webserver == null)
            {
                throw new ArgumentNullException(nameof(webserver));
            }

            if (webserver.Module <WebApiModule>() == null)
            {
                webserver.RegisterModule(new WebApiModule());
            }

            webserver.Module <WebApiModule>().RegisterController <T>();

            return(webserver);
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            var url = "http://localhost:9196/";
            using (var server = new WebServer(url, new SimpleConsoleLog()))
            {
                server.RegisterModule(new LocalSessionModule());
                server.RegisterModule(new StaticFilesModule("./"));
                server.Module<StaticFilesModule>().UseRamCache = true;
                server.Module<StaticFilesModule>().DefaultExtension = ".html";
                server.RunAsync();

                var browser = new System.Diagnostics.Process()
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }
                };
                browser.Start();
                Console.ReadKey(true);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Load all the WebSockets in an assembly
        /// </summary>
        /// <param name="webserver">The webserver instance.</param>
        /// <param name="assembly">The assembly to load WebSocketsServer types from. Leave null to load from the currently executing assembly.</param>
        /// <returns>An instance of webserver</returns>
        /// <exception cref="System.ArgumentNullException">webserver</exception>
        public static WebServer LoadWebSockets(this WebServer webserver, Assembly assembly = null)
        {
            if (webserver == null)
            {
                throw new ArgumentNullException(nameof(webserver));
            }

            var types = (assembly ?? Assembly.GetEntryAssembly()).GetTypes();

            foreach (var socketServer in types.Where(x => x.GetTypeInfo().BaseType == typeof(WebSocketsServer)))
            {
                if (webserver.Module <WebSocketsModule>() == null)
                {
                    webserver = webserver.WithWebSocket();
                }

                webserver.Module <WebSocketsModule>().RegisterWebSocketsServer(socketServer);
                $"Registering WebSocket Server '{socketServer.Name}'".Info();
            }

            return(webserver);
        }
        public void Start(int port) {
            _server = new WebServer($"http://+:{port}/", new NullLog(), RoutingStrategy.Wildcard);
            _server.RegisterModule(new WebApiModule());
            _server.Module<WebApiModule>().RegisterController<PlayerStatsController>();

            var module = new WebSocketsModule();
            _server.RegisterModule(module);
            _currentServer = new PublishDataSocketsServer(@"Current Race Stats Server");
            module.RegisterWebSocketsServer("/api/current", _currentServer);

            try {
                _server.RunAsync();
            } catch (HttpListenerException e) {
                Logging.Warning(e.Message + $"\nDon’t forget to reserve url using something like “netsh http add urlacl url=\"http://+:{port}/\" user=everyone”.");
            } catch (Exception e) {
                Logging.Error(e);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static void Main(string[] args)
        {
            var url = "http://localhost:9696/";

            if (args.Length > 0)
                url = args[0];

            // Our web server is disposable. Note that if you don't want to use logging,
            // there are alternate constructors that allow you to skip specifying an ILog object.
            using (var server = new WebServer(url, new Labs.EmbedIO.Log.SimpleConsoleLog()))
            {
                // First, we will configure our web server by adding Modules.

                server.RegisterModule(new WebApiModule());
                server.Module<WebApiModule>().RegisterController<PeopleController>();

                // Here we setup serving of static files
                server.RegisterModule(new StaticFilesModule(HtmlRootPath)
                {
                    UseRamCache = true,
                    DefaultExtension = ".html"
                });

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                // This is a non-blocking method (it return immediately) so in this case we avoid
                // disposing of the object until a key is pressed.
                server.RunAsync();

                // Fire up the browser to show the content if we are debugging!
            #if DEBUG
                var browser = new System.Diagnostics.Process()
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo(url) {UseShellExecute = true}
                };
                browser.Start();
            #endif
                // Wait for any key to be pressed before disposing of our web server.
                // In a service we'd manage the lifecycle of of our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }
        }
Beispiel #10
0
        public static void RunServer()
        {
            try
            {
                using (_server = new WebServer("http://*:80/", new SimpleConsoleLog()))
                {
                    _server.WithWebApiController<ApiController>();
                    _server.RegisterModule(new CorsModule());
                    _server.RegisterModule(new StaticFilesModule(TmpFolder));

                    _server.Module<StaticFilesModule>().UseRamCache = true;
                    _server.Module<StaticFilesModule>().DefaultExtension = ".html";

                    File.WriteAllText(Path.Combine(TmpFolder, "index.html"), Resources.index);
                    File.WriteAllText(Path.Combine(TmpFolder, "app.js"), Resources.app);
                    File.WriteAllText(Path.Combine(TmpFolder, "app.jsx"), Resources.appjsx);
                    File.WriteAllText(Path.Combine(TmpFolder, "jquery.js"), Resources.jquery_2_1_4_min);
                    File.WriteAllText(Path.Combine(TmpFolder, "JSXTransformer.js"), Resources.JSXTransformer);
                    File.WriteAllText(Path.Combine(TmpFolder, "react.js"),
                        Resources.react_with_addons_min);

                    _server.RunAsync();

                    while (true)
                    {
                        Console.WriteLine("Type an Url to add or press Enter to stop...");
                        var result = Console.ReadLine();

                        if (string.IsNullOrWhiteSpace(result)) break;

                        AddEntry(result);
                    }

                    var currentHost = File.ReadAllText(HostFile);

                    // Restore
                    if (OriginalHostFile != currentHost) File.WriteAllText(HostFile, OriginalHostFile);
                }
            }
            catch (Exception ex)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
            }
        }