示例#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();
            }
        }
示例#2
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);
            }
        }
示例#3
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();
        }
示例#4
0
            public void AfterStartingThrowsAggregateException()
            {
                var listener = Substitute.For <IHttpListener>();
                var order    = new List <int>();

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

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

                    listener.IsListening.Returns(false);
                }

                order.Count.ShouldBe(3);
            }
示例#5
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);
            }
        }
示例#6
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();
            }
        }
示例#7
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();
                }
            }
        }
示例#8
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();
        }
示例#9
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);
            }
        }
示例#10
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);
        }
示例#11
0
 public void ThrowsExceptionWhenStopping()
 {
     using (var server = new RestServer())
     {
         server.SetIsStopping(true);
         Should.Throw <UnableToStartHostException>(() => server.Start());
     }
 }
        public void StartServer()
        {
            MockRefDataRepository.Reset();

            RestServer = new RestServer();
            RestServer.Start(ServerName, Port, Config);

            OnServerStarted();
        }
示例#13
0
        static void Main(string[] args)
        {
            {
                var v           = "v0.1.0.0";
                var nameService = "Load Balancer Service";
                Console.Title = nameService + " " + v;
                Console.WriteLine("     L O A D   B A L A N C E R   S E R V I C E    " + v);
                var serverStandar = new RestServer();

                var input = "";
                while ((input = Console.ReadLine()) != "q")
                {
                    switch (input)
                    {
                    case "start":
                        Console.WriteLine("Starting service...");
                        serverStandar.Port = "5010";
                        serverStandar.Host = "*";
                        serverStandar.Start();
                        Console.Title = "[ON]  " + nameService + " " + v;

                        break;


                    case "start --log":
                        Console.WriteLine("Starting service...");

                        using (var server = new RestServer())
                        {
                            server.Port = "5010";
                            server.Host = "*";
                            server.LogToConsole().Start();
                            Console.Title = "[ON]  " + nameService + " " + v;
                            Console.ReadLine();
                            server.Stop();
                        }

                        break;

                    case "stop":
                        Console.WriteLine("Stopping service...");
                        serverStandar.Stop();
                        Console.Title = nameService + " " + v;
                        break;

                    case "--version":
                        Console.WriteLine(v);

                        break;

                    default:
                        Console.WriteLine(String.Format("Unknown command: {0}", input));
                        break;
                    }
                }
            }
        }
示例#14
0
        static void Main(string[] args)
        {
            CreateLoadConfig();

            using (var server = new RestServer(LoadSettings()))
            {
                server.Start();
            }
        }
示例#15
0
            public void AbortsWhenAlreadyStarting()
            {
                var listener = Substitute.For <IHttpListener>();

                using (var server = new RestServer(listener))
                {
                    server.SetIsStarting(true);
                    server.Start();
                    listener.DidNotReceive().Start();
                    listener.IsListening.Returns(false);
                }
            }
示例#16
0
            public void ThrowsExceptionWhenExceptionOccursWhileStarting()
            {
                var listener = Substitute.For <IHttpListener>();

                listener.When(_ => _.Start()).Do(_ => { throw new Exception(); });

                using (var server = new RestServer(listener))
                {
                    Should.Throw <UnableToStartHostException>(() => server.Start());
                    server.GetIsStarting().ShouldBeFalse();
                }
            }
示例#17
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (!server.IsListening)
     {
         server.Start();
         this.button1.Text = "Stop Server";
     }
     else
     {
         server.Stop();
         this.button1.Text = "Start Server";
     }
 }
示例#18
0
        private void button1_Click(object sender, EventArgs e)
        {
            ServerSettings settings = new ServerSettings()
            {
                Port         = maskedTextBox1.Text,
                PublicFolder = new PublicFolder("web")
            };

            server = new RestServer(settings);
            server.Start();

            button1.Enabled = false;
            button2.Enabled = true;
        }
示例#19
0
        private void StartNetworkService()
        {
            CountdownLatch latch = new CountdownLatch(1);

            this.Network = new ChatServer(this, protocolProvider, latch);
            _            = this.Network.Bind(new IPEndPoint(ServerSettings.SERVER_HOST, ServerSettings.SERVER_PORT));

            RestAPI = new RestServer();
            RestAPI.Start(ServerSettings.WEBSERVER_HOST, ServerSettings.WEBSERVER_PORT, latch);

            latch.Wait();

            new ConsoleManager();
        }
示例#20
0
            public void OnAfterStartNotExecutedWhenNotListening()
            {
                var invoked  = false;
                var listener = Substitute.For <IHttpListener>();

                using (var server = new RestServer(listener)
                {
                    OnAfterStart = () => { invoked = true; }
                })
                {
                    server.Start();
                    invoked.ShouldBeFalse();
                }
            }
示例#21
0
    public static void WebStart(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
    {
        SignumServer.Start(app, env, typeof(Startup).Assembly);

        AuthServer.Start(app, () => Starter.Configuration.Value.AuthTokens, "IMPORTANT SECRET FROM Southwind. CHANGE THIS STRING!!!");
        CacheServer.Start(app);
        FilesServer.Start(app);
        UserQueryServer.Start(app);
        DashboardServer.Start(app);
        WordServer.Start(app);
        ExcelServer.Start(app);
        ChartServer.Start(app);
        MapServer.Start(app);
        ToolbarServer.Start(app);
        TranslationServer.Start(app,
                                new AlreadyTranslatedTranslator(),
                                new AzureTranslator(
                                    () => Starter.Configuration.Value.Translation.AzureCognitiveServicesAPIKey,
                                    () => Starter.Configuration.Value.Translation.AzureCognitiveServicesRegion),
                                new DeepLTranslator(() => Starter.Configuration.Value.Translation.DeepLAPIKey)
                                ); //TranslationServer
        SchedulerServer.Start(app, lifetime);
        ProcessServer.Start(app);
        MailingServer.Start(app);
        ProfilerServer.Start(app);
        DiffLogServer.Start(app);
        RestServer.Start(app);
        RestLogServer.Start(app);
        PredictorServer.Start(app);
        WorkflowServer.Start(app);
        AlertsServer.Start(app);
        DynamicServer.Start(app);

        OmniboxServer.Start(app,
                            new EntityOmniboxResultGenenerator(),
                            new DynamicQueryOmniboxResultGenerator(),
                            new ChartOmniboxResultGenerator(),
                            new DashboardOmniboxResultGenerator(DashboardLogic.Autocomplete),
                            new UserQueryOmniboxResultGenerator(UserQueryLogic.Autocomplete),
                            new UserChartOmniboxResultGenerator(UserChartLogic.Autocomplete),
                            new MapOmniboxResultGenerator(type => OperationLogic.TypeOperations(type).Any()),
                            new ReactSpecialOmniboxGenerator()
                               //new HelpModuleOmniboxResultGenerator(),
                            ); //Omnibox

        ReflectionServer.RegisterLike(typeof(RegisterUserModel), () => true);

        SignumCultureSelectorFilter.GetCurrentCulture = (ctx) => GetCulture(ctx);
    }
示例#22
0
        public bool Start()
        {
            bool res = false;

            try
            {
                _restServer.Start();
                res = true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Cannot start!");
            }

            Logger.Info($"WebServer on {Port}");
            return(res);
        }
示例#23
0
            public void OnBeforeStartExecuted()
            {
                var invoked  = false;
                var listener = Substitute.For <IHttpListener>();

                listener.When(l => l.Start()).Do(info => listener.IsListening.Returns(invoked));

                using (var server = new RestServer(listener)
                {
                    OnBeforeStart = () => { invoked = true; }
                })
                {
                    server.Start();
                    invoked.ShouldBeTrue();
                    listener.IsListening.Returns(false);
                }
            }
示例#24
0
        public void StartServer(string hostname, string port)
        {
            try
            {
                if (_server == null)
                {
                    _server = new RestServer
                    {
                        Host = hostname,
                        Port = port
                    };

                    _server.Start();
                }
            }
            catch (Exception) {
            }
        }
示例#25
0
        public static void Main(string[] args)
        {
            using (var server = new RestServer())
            {
                server.LogToConsole();

                server.OnBeforeStart         = () => server.Logger.Trace("Starting Server");
                server.OnAfterStart          = () => server.Logger.Trace("Server Started");
                server.OnBeforeStop          = () => server.Logger.Trace("Stopping Server");
                server.OnAfterStop           = () => server.Logger.Trace("Server Stopped");
                server.Router.BeforeRouting += ctx => server.Logger.Debug("Before Routing!!");
                server.Router.BeforeRouting += ctx => server.Logger.Debug("After Routing!!");

                server.Start();
                Console.ReadLine();
                server.Stop();
            }
        }
        public static void Start(
            AdminShellPackageEnv package, string host, string port, GrapevineLoggerSuper logger = null)
        {
            // if running, stop old server
            Stop();

            var helper = new AasxHttpContextHelper();

            helper.Package      = package;
            TestResource.helper = helper;

            var serverSettings = new ServerSettings();

            serverSettings.Host = host;
            serverSettings.Port = port;

            if (logger != null)
            {
                logger.Warn(
                    "Please notice: the API and REST routes implemented in this version " +
                    "of the source code are not specified and standardised by the" +
                    "specification Details of the Administration Shell. " +
                    "The hereby stated approach is solely the opinion of its author(s).");
            }

            startedRestServer = new RestServer(serverSettings);
            {
                if (logger != null)
                {
                    startedRestServer.Logger = logger;
                }
                startedRestServer.Start();
            }

            // tail of the messages, again
            if (logger != null)
            {
                logger.Warn(
                    "Please notice: the API and REST routes implemented in this version " +
                    "of the source code are not specified and standardised by the" +
                    "specification Details of the Administration Shell. " +
                    "The hereby stated approach is solely the opinion of its author(s).");
            }
        }
示例#27
0
        internal void Run()
        {
            // Set up to scan this assembly only.
            ServerSettings restServerSettings = new ServerSettings();

            restServerSettings.Router.Register(Assembly.GetExecutingAssembly());
            using (var server = new RestServer(restServerSettings))
            {
                server.Host = "+";
                server.Port = Config.RestService.Port.ToString();
                //server.LogToConsole();
                server.Start();
                Printer.PrintMessage($"Rest server started, bound to port #b#{server.Port}##.");
                while (true)
                {
                    System.Threading.Thread.Sleep(5000);
                }
            }
        }
        public void Start()
        {
            // do not start if not enabled
            if (!_config.Enabled)
            {
                return;
            }

            if (_isRunning)
            {
                Logger.Warn("Ignoring start(). REST server already running");
                return;
            }

            try
            {
                // create server instance
                _restServer = new RestServer
                {
                    Host = _config.Host,
                    Port = _config.Port.ToString()
                };

                // bind all registered routes to router (see constructor for bindings)
                IRouter router = new Router();
                foreach (var route in _routers)
                {
                    route.Register(router);
                }
                _restServer.Router = router;

                // start the server
                _restServer.Start();
                _isRunning = true;
                Logger.Info("REST server running on {0}:{1}", _config.Host, _config.Port);
            }
            catch (Exception e)
            {
                var msg = $"Could not start rest server on {_config.Host}:{_config.Port}, cause: {e.Message}";
                throw new ApplicationException(msg, e);
            }
        }
        public void StopsServer()
        {
            var stopped = new ManualResetEvent(false);
            var port    = PortFinder.FindNextLocalOpenPort(1234);

            using (var server = new RestServer {
                Port = port
            })
            {
                server.OnAfterStop += () => { stopped.Set(); };

                server.Start();
                server.IsListening.ShouldBeTrue();
                server.ListenerPrefix.ShouldBe($"http://localhost:{port}/");

                server.ThreadSafeStop();
                stopped.WaitOne(300, false);

                server.IsListening.ShouldBeFalse();
            }
        }
示例#30
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;
                }
            }

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

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

            RestServerInstance.Start();
            KeyboardMapperInstance.Start();
            ControllerManagerInstance.Start();

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