Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            using (var server = new RestServer())
            {
                server.LogToConsole();
                server.PublicFolder = new PublicFolder(@"C:\source\github\gv-gh-pages")
                {
                    Prefix = "Grapevine"
                };

                server.OnBeforeStart = () => Console.WriteLine("---------------> Starting Server");
                server.OnAfterStart  = () => Console.WriteLine($"<--------------- Server Started");

                server.OnBeforeStop = () => Console.WriteLine("---------------> Stopping Server");
                server.OnAfterStop  = () =>
                {
                    Console.WriteLine("<--------------- Server Stopped");
                    Console.ReadLine();
                };

                server.Start();
                Console.ReadLine();
                server.Stop();
            }
        }
Ejemplo n.º 2
0
            public void AfterStoppingThrowsAggregateException()
            {
                var listener = Substitute.For <IHttpListener>();

                listener.IsListening.Returns(true);
                var order = new List <int>();

                using (var server = new RestServer(listener))
                {
                    server.BeforeStopping += restServer => { order.Add(1); listener.IsListening.Returns(false); };
                    server.AfterStopping  += restServer => { order.Add(2); throw new Exception("blah"); };
                    server.AfterStopping  += restServer => { order.Add(3); };

                    try
                    {
                        server.Stop();
                    }
                    catch (Exception e)
                    {
                        e.InnerException.ShouldNotBeNull();
                        e.InnerException?.GetType().ShouldBe(typeof(AggregateException));
                    }

                    listener.IsListening.Returns(false);
                }

                order.Count.ShouldBe(3);
            }
Ejemplo n.º 3
0
        public void StartServer(string hostname, string port)
        {
            try
            {
                if ( _server == null )
                {
                    LOG.Info($"Starting API server: {hostname}:{port}");
                    _server = new RestServer
                    {
                        Host = hostname,
                        Port = port
                    };

                    var apiRoute = new Route(API);
                    _server.Router.Register(apiRoute);

                    _server.Start();
                    LOG.Info("API server started");
                }
            }
            catch ( Exception ex )
            {
                LOG.Error("Failed to start API server", ex);
            }
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            RestServer server = new RestServer();

            try
            {
                server.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "Unable to start REST server.\n" +
                    "Make sure the application is running with Administrator privilegies." +
                    "Exception details:\n\n" +
                    ex.ToString());
            }

            Console.WriteLine(
                "This is an example of using Radish for documenting your REST API methods.\n\n" +
                "Open your favorite web browser and type the following\n" +
                "in the address bar to see the auto-generated documentation:\n\n" +
                "http://localhost:8040/api/help/simple    -- simple template set\n" +
                "http://localhost:8040/api/help/bootstrap -- Bootstrap-based template set\n");

            exitSignal.WaitOne();
            server.Stop();
        }
Ejemplo n.º 5
0
 public FormStarter()
 {
     InitializeComponent();
     this.RestServer             = RestServer.GetInstance();
     this.cmbBoxOk.SelectedIndex = 0;
     actualizeForm();
 }
Ejemplo n.º 6
0
 static void Main(string[] args)
 {
     //RSAParameters rsaParams = MetaMit.Cryptography.Asymmetric.Generation.GenRSAParams(2048);
     //Console.WriteLine(MetaMit.Cryptography.Asymmetric.Collection.GetPublicKey(rsaParams));
     //Console.WriteLine(MetaMit.Cryptography.Asymmetric.Collection.GetPrivateKey(rsaParams));
     using (RestServer server = new RestServer()) { Utils.Server.StartRestServer(server); }
 }
Ejemplo n.º 7
0
    /* Description: Start grapevine HTTP(S) server
     *
     */
    public static void StartGrapevineServer()
    {
        Console.WriteLine("StartGrapevineServer() started");
        try
        {
            using (var server = new RestServer())
            {
                if (Misc.UseHTTPS)
                {
                    server.UseHttps = true;
                }

                server.Port = ConfigurationManager.AppSettings.Get("HttpPort");
                server.LogToConsole().Start();
                while (true)
                {
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("StartGrapevineServer(): {0}", e);
            Console.ReadLine();
            System.Environment.Exit(1);
        }
    }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Debug.WriteLine("Started!");
            ServerSettings settings = new ServerSettings();

            settings.Host = "ec2-35-164-218-97.us-west-2.compute.amazonaws.com";                //93.82.35.63
            //settings.Host = "localhost";    //78.104.199.75
            settings.Port = "8080";
            insertInitialData();
            try
            {
                using (var server = new RestServer(settings))
                {
                    server.LogToConsole().Start();
                    //New Thread needs to be started, which calculates the market prizes and handles the orders.
                    Thread myThread = new Thread(new ThreadStart(orderBookOperations));
                    myThread.Start();
                    Console.ReadLine();
                    server.Stop();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
                Console.ReadLine();
            }
        }
Ejemplo n.º 9
0
        public void StartServer(string hostname, string port)
        {
            try
            {
                LOG.Info("Checking if ACL URL is reserved");
                if (!IsAclUrlReserved(hostname, port))
                {
                    LOG.Info("ACL URL not reserved. Attempting to reserve.");
                    ReserveAclUrl(hostname, port);
                }

                if (_server == null)
                {
                    LOG.Info($"Starting API server: {hostname}:{port}");
                    _server = new RestServer
                    {
                        Host = hostname,
                        Port = port
                    };

                    var apiRoute = new Route(API);
                    _server.Router.Register(apiRoute);

                    _server.Start();
                    LOG.Info("API server started");
                }
            }
            catch (Exception ex)
            {
                LOG.Error("Failed to start API server", ex);
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            RestServer <HttpListener> server = RestServerUtil.CreateFromHttpListener("http://127.0.0.1:9000/");

            // Add a session to a listener context if the request contains a cookie
            server.ServerContext.NeedsSession = rlContext => rlContext.Request.Cookies != null && rlContext.Request.Cookies.Count > 0;

            // The session key is the first cookie
            server.ServerContext.GetSessionKey = rlContext => rlContext.Request.Cookies[1];

            // Set the session lifetime to 15 minutes
            server.ServerContext.GetValidUntil = creationDate => creationDate.AddMinutes(15.0);


            server.Get["", writeAsLine : true] = _ => "Hello world";

            server.Get["/", writeAsLine : true] = _ => {
                Console.WriteLine("Get[/]");
                return("Hello World");
            };

            server.Get["/index/", writeAsLine : true] = _ => {
                //Console.WriteLine("Get[/index/]");
                return("Hello World from server##########################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################");
            };

            Console.WriteLine("Starting server");
            server.Start().GetAwaiter().GetResult();

            Console.ReadLine();
        }
Ejemplo n.º 11
0
            public void Sends500WhenRouteThrowsException()
            {
                var logger = new InMemoryLogger();

                logger.Logs.Count.ShouldBe(0);

                var exception = new Exception("Generic excpetion occured");

                using (var server = new RestServer(Substitute.For <IHttpListener>())
                {
                    Logger = logger
                })
                {
                    Func <IHttpContext, IHttpContext> func = ctx =>
                    {
                        throw exception;
                    };

                    server.Router.Register(func);

                    var context = Mocks.HttpContext();
                    context.Server.Returns(server);

                    server.TestRouteContext(context);

                    context.Response.Received().SendResponse(HttpStatusCode.InternalServerError, exception);
                }

                var logs = logger.Logs.FirstOrDefault(l => l.Level == LogLevel.Error);

                logs.ShouldNotBeNull();
                logs.Exception.ShouldBe(exception);
            }
Ejemplo n.º 12
0
            public void ThrowsExceptionWhenRouteThrowsException()
            {
                var logger = new InMemoryLogger();

                logger.Logs.Count.ShouldBe(0);

                var exception = new Exception("Generic excpetion occured");

                using (var server = new RestServer(Substitute.For <IHttpListener>())
                {
                    Logger = logger
                })
                {
                    Func <IHttpContext, IHttpContext> func = ctx =>
                    {
                        throw exception;
                    };

                    server.Router.Register(func);
                    server.EnableThrowingExceptions = true;

                    var context = Mocks.HttpContext();
                    context.Server.Returns(server);

                    Should.Throw <Exception>(() => server.TestRouteContext(context));
                }

                var logs = logger.Logs.FirstOrDefault(l => l.Level == LogLevel.Error);

                logs.ShouldNotBeNull();
                logs.Exception.ShouldBe(exception);
            }
Ejemplo n.º 13
0
        public static void NestedClosures()
        {
            var server = RestServer.For(s =>
            {
                s.Router = Router.For(r =>
                {
                    r.Register(Route.For(HttpMethod.GET).Use(ctx =>
                    {
                        ctx.Dynamic.Token = "some_token";
                        return(ctx);
                    }));

                    r.Register(Route.For(HttpMethod.GET).To("/api/.*").Use(ctx =>
                    {
                        ctx.Response.AppendCookie(new Cookie {
                            Name = "Token", Value = ctx.Dynamic.Token
                        });
                        var response = ctx.Request.Headers.Get("SomeKey");
                        ctx.Response.SendResponse(response);
                        return(ctx);
                    }));
                });
            });

            server.Start();

            System.Console.Write("Running Nested Closures Instance...");
            System.Console.ReadLine();

            server.Stop();
            System.Console.WriteLine("done");
        }
Ejemplo n.º 14
0
            public void Sends501WhenRouteNotImplemented()
            {
                var logger = new InMemoryLogger();

                logger.Logs.Count.ShouldBe(0);

                using (var server = new RestServer(Substitute.For <IHttpListener>())
                {
                    Logger = logger
                })
                {
                    Func <IHttpContext, IHttpContext> func = ctx =>
                    {
                        throw new NotImplementedException();
                    };

                    server.Router.Register(func);

                    var context = Mocks.HttpContext();
                    context.Server.Returns(server);

                    server.TestRouteContext(context);

                    context.Response.Received().SendResponse(HttpStatusCode.NotImplemented);
                }

                var logs = logger.Logs.FirstOrDefault(l => l.Level == LogLevel.Error);

                logs.ShouldNotBeNull();
                logs.Exception.GetType().ShouldBe(typeof(NotImplementedException));
            }
Ejemplo n.º 15
0
        internal static bool GetIsStarting(this RestServer server)
        {
            var memberInfo = server.GetType();
            var field      = memberInfo?.GetField("IsStarting", BindingFlags.Instance | BindingFlags.NonPublic);

            return((bool)field?.GetValue(server));
        }
Ejemplo n.º 16
0
 public void ForGenericType()
 {
     using (var server = RestServer.For <CustomSettings>())
     {
         server.Port.ShouldBe("5555");
     }
 }
Ejemplo n.º 17
0
            public void ThrowsExceptionWhenRouteNotImplemented()
            {
                var logger = new InMemoryLogger();

                logger.Logs.Count.ShouldBe(0);

                using (var server = new RestServer(Substitute.For <IHttpListener>())
                {
                    Logger = logger
                })
                {
                    Func <IHttpContext, IHttpContext> func = ctx =>
                    {
                        throw new NotImplementedException();
                    };

                    server.Router.Register(func);
                    server.EnableThrowingExceptions = true;

                    var context = Mocks.HttpContext();
                    context.Server.Returns(server);

                    Should.Throw <NotImplementedException>(() => server.TestRouteContext(context));
                }

                var logs = logger.Logs.FirstOrDefault(l => l.Level == LogLevel.Error);

                logs.ShouldNotBeNull();
                logs.Exception.GetType().ShouldBe(typeof(NotImplementedException));
            }
Ejemplo n.º 18
0
            public void DoesNotCallCloseOnListenerWhenListenerIsNull()
            {
                IHttpListener listener = null;
                var           server   = new RestServer(listener);

                Should.NotThrow(() => server.Dispose());
            }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            var config = new RestServerConfiguration
            {
                Host    = "+",
                WebRoot = string.Format("..{0}..{0}server{0}files{0}", Path.DirectorySeparatorChar)
            };

            SetLoggingEvents();

            RestServer server    = new RestServer(config);
            MyResource resources = new MyResource();

            server.AddResource(resources.FooRoute, resources.WriteMore);
            server.AddResource(resources.NotFoundRoute, resources.WriteNotFound);
            server.AddResource(resources.ExceptionRoute, (c) => { throw new Exception("exception happend"); });
            server.AddResource(resources.HtmlWithCssRoute, resources.WriteHtmlWithCss);
//            server.AddResource(route.MatchEverythingRoute, route.WriteRawUrl);
            server.Start();

            while (server.IsListening)
            {
                Thread.Sleep(300);
            }
        }
Ejemplo n.º 20
0
        public static void StartRestServer(RestServer server)
        {
            bool inputValid = false;
            char input;

            while (!inputValid)
            {
                Console.WriteLine("Release or Debug? (R||D)");
                input = Console.ReadKey().KeyChar;
                if (input == 'R' || input == 'r')
                {
                    server.Host = "+";
                    inputValid  = true;
                    Console.WriteLine("");
                }
                if (input == 'D' || input == 'd')
                {
                    server.Host = "localhost";
                    inputValid  = true;
                    Console.WriteLine("");
                }
            }
            server.Port = "5000";
            server.LogToConsole().Start();
            Console.ReadLine();
            server.Stop();
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            IIdService   idService           = new UniqueIdService();
            IDataService inMemoryDataService = new InMemoryDataService(idService);

            inMemoryDataService.SetupData(null);

            IDataService dataService = new ElasticDataService(inMemoryDataService);

            dataService.SetupData(null);

            IJsonService jsonService = new NewtonJsonService();

            using (var server = new RestServer())
            {
                var genreRoute  = new GenreRoute(dataService, jsonService);
                var authorRoute = new AuthorRoute(dataService, jsonService);
                var bookRoute   = new BookRoute(dataService, jsonService);

                server.Host = "127.0.0.1";
                server.Port = "8444";
                server.Router.Register(genreRoute.Handler, "/genres");
                server.Router.Register(authorRoute.Handler, "/authors");
                server.Router.Register(bookRoute.Handler, "/books");

                server.Start();
                Console.ReadLine();
                server.Stop();
            }
        }
Ejemplo n.º 22
0
        internal static void SetIsStarting(this RestServer server, bool val)
        {
            var memberInfo = server.GetType();
            var field      = memberInfo?.GetField("IsStarting", BindingFlags.Instance | BindingFlags.NonPublic);

            field?.SetValue(server, val);
        }
Ejemplo n.º 23
0
        public void runServer(bool state)
        {
            try
            {
                if (state)
                {
                    Rest      = new RestServer();
                    Rest.Port = Settings.Default.Port;
                    Rest.Host = Settings.Default.HostIP;

                    if (Authentication.Enabled)
                    {
                        Rest.Advanced.AuthenticationSchemes = AuthenticationSchemes.Basic;
                    }
                    Rest.UseHttps = Settings.Default.HTTPS;

                    Rest.Start();
                    setRunningStatus();
                }
                else
                {
                    Rest.Stop();
                    Rest.Dispose();
                    setStoppedStatus();
                }
            }
            catch (Exception error)
            {
                DialogResult result = MessageBox.Show(error.ToString(), "Unexpected error.", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                if (result == DialogResult.OK)
                {
                    Application.Exit();
                }
            }
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            RestServer server = new RestServer(IPAddress.Parse("224.0.0.224"), 53186);

            server.RequestReceived     += new EventHandler <RequestEventArgs <HttpRequest, HttpResponse> >(server_RequestReceived);
            server.HttpRequestReceived += new EventHandler <HttpServerEventArgs>(server_HttpRequestReceived);
            server.StartUdp();
            Console.WriteLine("Server Started");
            //HttpRequest request = new HttpRequest("http://224.0.0.224:53186/Lucene/");
            //request.Protocol = TransportProtocol.UDP;
            //request.GetResponse(false);
            //Thread.Sleep(1000);
            //request = new HttpRequest("http://224.0.0.224:53186/Lucene/");
            //request.Protocol = TransportProtocol.UDP;
            //request.GetResponse(false);
            //Thread.Sleep(10000);
            //request = new HttpRequest("http://224.0.0.224:53186/Lucene/");
            //request.Protocol = TransportProtocol.UDP;
            //request.GetResponse(false);
            //Thread.Sleep(30000);
            //request = new HttpRequest("http://224.0.0.224:53186/Lucene/");
            //request.Protocol = TransportProtocol.UDP;
            //request.GetResponse(false);
            Console.Read();
            server.Stop();
            Console.WriteLine("Server Stopped");
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            for (var i = 0; i < args.Length; i++)
            {
                if (args[i] == "--debug")
                {
                    IsDebug = true;
                }

                if (args[i] == "--default")
                {
                    ForceDefaultMapping = true;
                }

                if (args[i] == "--skip-ui")
                {
                    ShouldOpenUI = false;
                }

                if (args[i] == "--mapping")
                {
                    InitialMappingName = args[i + 1];
                    i++;
                }

                if (args[i] == "--start-disabled")
                {
                    ShouldStartDisabled = true;
                }
            }

            RestServerInstance        = new RestServer();
            KeyboardMapperInstance    = new KeyboardMapper();
            ControllerManagerInstance = new ControllerManager();

            KeyboardMapperInstance.OnParse += (s, e) => {
                if (ControllerManagerInstance.IsRunning)
                {
                    ControllerManagerInstance.Stop();
                    ControllerManagerInstance.Start();
                }
            };

            RestServerInstance.Start();

            if (!ShouldStartDisabled)
            {
                KeyboardMapperInstance.Start();
                ControllerManagerInstance.Start();
            }

            // See https://github.com/gmamaladze/globalmousekeyhook/issues/3#issuecomment-230909645
            System.Windows.Forms.ApplicationContext msgLoop = new System.Windows.Forms.ApplicationContext();

            ConsoleCtrlHandlerRef += new ConsoleCtrlHandler(HandleConsoleExit);
            SetConsoleCtrlHandler(ConsoleCtrlHandlerRef, true);

            System.Windows.Forms.Application.Run(msgLoop);
        }
Ejemplo n.º 26
0
 public void ThrowsExceptionWhenStopping()
 {
     using (var server = new RestServer())
     {
         server.SetIsStopping(true);
         Should.Throw <UnableToStartHostException>(() => server.Start());
     }
 }
Ejemplo n.º 27
0
 ConfigServer()
 {
     _httpServer = new RestServer(
         new IPEndPoint(IPAddress.Parse(GetLocalIp()), DependencyConfiguration.DefaultPort),
         null,
         System.Reflection.Assembly.GetExecutingAssembly());
     _httpServer.RegisterRouteHandler(new RestServerServiceFileRouteHandler(DependencyConfiguration.DefaultBasePath));
 }
Ejemplo n.º 28
0
 public void ListenerPrefixBeginsWithHttpsWhenFalse()
 {
     using (var server = new RestServer())
     {
         server.UseHttps.ShouldBeFalse();
         server.ListenerPrefix.StartsWith("http").ShouldBeTrue();
         server.ListenerPrefix.StartsWith("https").ShouldBeFalse();
     }
 }
Ejemplo n.º 29
0
            public void ReturnsFalseWhenListenerIsNull()
            {
                IHttpListener listener = null;

                using (var server = new RestServer(listener))
                {
                    server.IsListening.ShouldBeFalse();
                }
            }
Ejemplo n.º 30
0
            public void TestingMode()
            {
                var listener = Substitute.For <IHttpListener>();

                using (var server = new RestServer(listener))
                {
                    server.TestingMode.ShouldBeTrue();
                }
            }