public CometCommandHandlerPipeline(HttpServer server)
        {
            if (server == null)
                throw new Exception("HttpServer cannot be null.");

            Server = server;
        }
Example #2
0
        static void Main(string[] args)
        {
            // Template generators are used to render templates 
            // (convert code + html to pure html).
            TemplateManager mgr = new TemplateManager();
            mgr.Add("haml", new HamlGenerator());

            // The httpserver is quite dumb and will only serve http, nothing else.
            HttpServer server  = new HttpServer();

            // a controller mode implements a MVC pattern
            // You'll add all controllers to the same module.
            ControllerModule mod = new ControllerModule();
            mod.Add(new UserController(mgr));
            server.Add(mod);

            // file module will be handling files
            FileModule fh = new FileModule("/", Environment.CurrentDirectory);
            fh.AddDefaultMimeTypes();
            server.Add(fh);

            // Let's start pure HTTP, we can also start a HTTPS listener.
            server.Start(IPAddress.Any, 8081);

            Console.ReadLine();
        }
Example #3
0
        static void Main(string[] args)
        {
            HttpServer http = new HttpServer();

            http.ProcessRequest = (request, response) =>
            {
                Console.WriteLine(request.Url);

                if (request.Url != "/foo")
                {
                    response.WriteLine("Hello from {0}.", request.Url);
                }
                else
                {
                    response.StatusCode = HttpStatusCode.NotFound;
                }
            };

            http.Start();

            Console.WriteLine("Press enter to stop HTTP server.");
            Console.ReadLine();

            http.Stop();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
 public void GetWithErrorXmlTest()
 {
     using (var server = new HttpServer(new RequestHandler
     {
         EstimatedMethod = "GET",
         EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/tnreservation/1", Helper.AccountId),
         ContentToSend = new StringContent(TestXmlStrings.InvalidReservationResponseXml, Encoding.UTF8, "application/xml")
     }))
     {
         var client = Helper.CreateClient();
         try
         {
             TnReservation.Get(client, "1").Wait();
             if (server.Error != null) throw server.Error;
         }
         catch (AggregateException exc)
         {
             var ex = exc.InnerExceptions[0] as BandwidthIrisException;
             if (ex != null)
             {
                 Assert.AreEqual("Reservation failed: telephone number 9195551212 is not available.", ex.Message);
                 Assert.AreEqual("5041", ex.Code);
                 return;
             }
         }
         Assert.Fail("should throw an error");
     }
 }
Example #5
0
        public void QueryStringKeyWithMultipleValues()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    Assert.That(e.Request.QueryString.AllKeys, Is.EquivalentTo(new[] { "key" }));
                    Assert.That(e.Request.QueryString.GetValues("key"), Is.EquivalentTo(new[] { "first", "second", "third" }));
                    Assert.AreEqual(e.Request.QueryString["key"], "first,second,third");

                    using (var writer = new StreamWriter(e.Response.OutputStream))
                    {
                        writer.Write(ResponseText);
                    }
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/?key=first&key=second&key=third", server.EndPoint)
                );

                Assert.AreEqual(ResponseText, GetResponseFromRequest(request));
            }
        }
Example #6
0
        public static void Main(string[] args)
        {
            _httpsv = new HttpServer(4649);
              //_httpsv.Sweeping = false;
              _httpsv.AddWebSocketService<Echo>("/Echo");
              _httpsv.AddWebSocketService<Chat>("/Chat");

              _httpsv.OnGet += (sender, e) =>
              {
            onGet(e);
              };

              _httpsv.OnError += (sender, e) =>
              {
            Console.WriteLine(e.Message);
              };

              _httpsv.Start();
              Console.WriteLine("HTTP Server listening on port: {0} service path:", _httpsv.Port);
              foreach (var path in _httpsv.ServicePaths)
            Console.WriteLine("  {0}", path);
              Console.WriteLine();

              Console.WriteLine("Press any key to stop server...");
              Console.ReadLine();

              _httpsv.Stop();
        }
		public void Initialize(Func<DocumentDatabase> databaseGetter, Func<InMemoryRavenConfiguration> settingsGetter, Func<string> tenantIdGetter, HttpServer theServer)
		{
			this.server = theServer;
			this.database = databaseGetter;
			this.settings = settingsGetter;
			this.tenantId = tenantIdGetter;
		}
        [InlineData("GET", "http://localhost/Customers(42)/NS.SpecialCustomer/IsSpecialUpgraded()", "IsSpecialUpgraded_42")] // function bound to derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.Routes
                .MapODataRoute("odata", "", model.Model)
                .MapODataRouteAttributes(config);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
Example #9
0
        public KService( int port )
        {
            Log = new UnityLogger();
            WebServer = new HttpServer();
            jsonrpc = new ServerProxy();
            Service = new KRPCService();
            if (!IsMono)
            {
                WebServer.Localhostonly = true;
            }

            jsonrpc.AddHandlers((IKRPCService)Service);
            Service.Service = this;

            WebServer.Port = port;

            WebServer.UriRequested += WebServer_UriRequested;
            WebServer.UriRequested += WebServer_Json;
            WebServer.UriRequested += WebServer_FileServer;
            WebServer.UriRequested += WebServer_FileIndex;
            WebServer.UriRequested += WebServer_FileNotFound;

            pageModels.Add(new KIWebContext(this) { PagePath = "/index.html", Title = "KInstruments Home" });
            pageModels.Add(new KIWebContext(this) { PagePath = "/radalt.html", Title = "Altitude (RADAR)" });
            pageModels.Add(new KIWebContext(this) { PagePath = "/analogalt.html", Title = "Altitude (MSL)" });
            pageModels.Add(new KIWebContext(this) { PagePath = "/navball.html", Title = "Nav Ball" });
            pageModels.Add(new KIWebContext(this) { PagePath = "/hframe_nav_rad.html", Title = "Nav Ball + Radar Alt" });
            pageModels.Add(new KIWebContext(this) { PagePath = "/gear_stage.html", Title = "Gear / Stage" });
        }
Example #10
0
        public void ExceptionOnRequestReceived()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    throw new Exception();
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/", server.EndPoint)
                );

                try
                {
                    GetResponseFromRequest(request);
                }
                catch (WebException ex)
                {
                    var response = (HttpWebResponse)ex.Response;

                    Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode);
                    Assert.AreEqual("Internal Server Error", response.StatusDescription);
                }
            }
        }
Example #11
0
        public void CanDecodeARequestBody()
        {
            using (var server = new HttpServer("http://*:1234/"))
            {
                string requestBody = "There's no business like \u0160ovs \u4F01\u696D";
                server.POST("/")
                      .Subscribe(ctx =>
                      {
                            ctx.Request.GetBody().Subscribe(body =>
                            {
                                try
                                {
                                    Console.WriteLine(body);
                                    body.Should().Be.EqualTo(requestBody);
                                }
                                finally
                                {
                                   ctx.Respond("hi");
                                }
                            });
                      });

                //Browser.ExecutePost("http://posttestserver.com/post.php", requestBody)
                Browser.ExecutePost("http://localhost:1234", requestBody)
                    .ReadAllContent()
                    .Should().Contain("hi");
            }
        }
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            if (request.UriPath.StartsWith(Url))
            {
                string hash = request.QueryString["hash"].Value;

                if (string.IsNullOrEmpty(hash))
                {
                    ThreadServerModule._404(response);
                }
                else
                {

                    if (Program.queued_files.ContainsKey(hash))
                    {
                        FileQueueStateInfo f = Program.queued_files[hash];

                        JsonObject ob = new JsonObject();

                        ob.Add("p", f.Percent().ToString());
                        ob.Add("s", string.Format("{0} / {1}", Program.format_size_string(f.Downloaded), Program.format_size_string(f.Length)));
                        ob.Add("c", f.Status == FileQueueStateInfo.DownloadStatus.Complete);

                        WriteJsonResponse(response, ob.ToString());
                    }
                    else
                    {
                        ThreadServerModule._404(response);
                    }
                }
                return true;
            }

            return false;
        }
 public void GetTest()
 {
     var item = new Subscription
     {
         Id = "1",
         OrderType = "orders",
         OrderId = "100",
         EmailSubscription = new EmailSubscription
         {
             Email = "test@test",
             DigestRequested = "NONE"
         }
     };
     using (var server = new HttpServer(new RequestHandler
     {
         EstimatedMethod = "GET",
         EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/subscriptions/1", Helper.AccountId),
         ContentToSend = Helper.CreateXmlContent(new SubscriptionsResponse { Subscriptions = new []{item} })
     }))
     {
         var client = Helper.CreateClient();
         var result = Subscription.Get(client, "1").Result;
         if (server.Error != null) throw server.Error;
         Helper.AssertObjects(item, result);
     }
 }
Example #14
0
    public static void Main()
    {
        var thdLed = new Thread(HandleLed);
        thdLed.Start();

        var digitalSensor = new DigitalSensor { InputPin = Pins.GPIO_PIN_D12 };
        var analogSensor = new AnalogSensor { InputPin = Pins.GPIO_PIN_A1, MinValue = 0.0, MaxValue = 3.3 };
        var lowPort = new OutputPort(Pins.GPIO_PIN_A0, false);
        var highPort = new OutputPort(Pins.GPIO_PIN_A2, true);

        var ledActuator = new DigitalActuator { OutputPin = Pins.GPIO_PIN_D13 };
        //need to create HTTP PUTs!

        var webServer = new HttpServer
        {
            RelayDomain = "gsiot-bcjp-yj88",
            RelaySecretKey = "HDMvyM11hAu6H6cxIaT50dL9ALWc81MYB8H/UFhV",
            RequestRouting =
            {
                { "GET /hello*", HandleHello }, //This accepts a lot of URLs
                { "GET /on", HandleOn },
                { "GET /off", HandleOff },
                { "POST /on", HandlePostOn },
                { "POST /off", HandlePostOff },
                { "GET /d12", new MeasuredVariable{ FromSensor=digitalSensor.HandleGet}.HandleRequest},
                { "GET /a1", new MeasuredVariable{ FromSensor=analogSensor.HandleGet}.HandleRequest},
                { "PUT /d13", new ManipulatedVariable{ FromHttpRequest=CSharpRepresentation.TryDeserializeBool,ToActuator=ledActuator.HandlePut}.HandleRequest},
            }
        };
        webServer.Run();
    }
Example #15
0
        public void BasicUpload()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    Assert.That(e.Request.Form.AllKeys, Is.EquivalentTo(new[] { "key" }));
                    Assert.AreEqual("value", e.Request.Form["key"]);
                    Assert.AreEqual("multipart/form-data", e.Request.ContentType);
                    Assert.AreEqual("POST", e.Request.HttpMethod);
                    Assert.IsNull(e.Request.InputStream);
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/", server.EndPoint)
                );

                using (var writer = new MultiPartWriter(request))
                {
                    writer.WriteValue("key", "value");
                }

                GetResponseFromRequest(request);
            }
        }
Example #16
0
        public void NotFound()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    e.Response.Status = "404 Not Found";
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/", server.EndPoint)
                );

                try
                {
                    GetResponseFromRequest(request);
                }
                catch (WebException ex)
                {
                    var response = (HttpWebResponse)ex.Response;

                    Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
                    Assert.AreEqual("Not Found", response.StatusDescription);
                }
            }
        }
        public void SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string requestedMethod, string expectedOrigin, string requestedHeaders)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default", "{controller}");
            HttpServer server = new HttpServer(config);
            CorsMessageHandler corsHandler = new CorsMessageHandler(config);
            corsHandler.InnerHandler = server;
            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
            request.SetConfiguration(config);
            request.Headers.Add(CorsConstants.Origin, "http://localhost");
            request.Headers.Add(CorsConstants.AccessControlRequestMethod, requestedMethod);
            request.Headers.Add(CorsConstants.AccessControlRequestHeaders, requestedHeaders);

            HttpResponseMessage response = invoker.SendAsync(request, CancellationToken.None).Result;
            string origin = response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault();
            string allowMethod = response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault();
            string[] allowHeaders = response.Headers.GetValues(CorsConstants.AccessControlAllowHeaders).FirstOrDefault().Split(',');
            string[] requestedHeaderArray = requestedHeaders.Split(',');

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedOrigin, origin);
            Assert.Equal(requestedMethod, allowMethod);
            foreach (string requestedHeader in requestedHeaderArray)
            {
                Assert.Contains(requestedHeader, allowHeaders);
            }
        }
 public void GetWithXmlTest()
 {
     
     using (var server = new HttpServer(new RequestHandler
     {
         EstimatedMethod = "GET",
         EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/sites/1", Helper.AccountId),
         ContentToSend = new StringContent(TestXmlStrings.ValidSiteResponseXml, Encoding.UTF8, "application/xml")
     }))
     {
         var client = Helper.CreateClient();
         var result = Site.Get(client, "1").Result;
         if (server.Error != null) throw server.Error;
         Assert.AreEqual("1", result.Id);
         Assert.AreEqual("Test Site", result.Name);
         Assert.AreEqual("A Site Description", result.Description);
         Assert.AreEqual("900", result.Address.HouseNumber);
         Assert.AreEqual("Main Campus Drive", result.Address.StreetName);
         Assert.AreEqual("Raleigh", result.Address.City);
         Assert.AreEqual("NC", result.Address.StateCode);
         Assert.AreEqual("27615", result.Address.Zip);
         Assert.AreEqual("United States", result.Address.Country);
         Assert.AreEqual("Service", result.Address.AddressType);
     }
 }
 public QueryableLimitationTest()
 {
     _configuration = new HttpConfiguration();
     _configuration.Routes.MapODataRoute("odata", "odata", GetEdmModel());
     HttpServer server = new HttpServer(_configuration);
     _client = new HttpClient(server);
 }
Example #20
0
    static void Main()
    {
        var lowPort = new OutputPort(Parameters.LowPin, false);
        var highPort = new OutputPort(Parameters.HighPin, true);

        var voltageSensor = new AnalogSensor
        {
            InputPin = Parameters.AnalogPin,
            MinValue = 0.0,
            MaxValue = 3.3
        };

        var webServer = new HttpServer
        {
            RelayDomain = Parameters.RelayDomain,
            RelaySecretKey = Parameters.RelaySecretKey,
            RequestRouting =
            {
                {
                    "GET /voltage/actual",
                    new MeasuredVariable
                    {
                        FromSensor = voltageSensor.HandleGet
                    }.HandleRequest
                }
            }
        };

        webServer.Run();
    }
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            if (request.UriPath.StartsWith(Url))
            {

                string board = request.QueryString[UrlParameters.Board].Value;
                string threadIdStr = request.QueryString[UrlParameters.ThreadId].Value;
                int threadId = -1;
                int.TryParse(threadIdStr, out threadId);

                if (!Program.IsBoardLetterValid(board))
                {
                    ThreadServerModule.write_text("Invalid board letter", response);
                    return true;
                }

                if (threadId <= 0)
                {
                    ThreadServerModule.write_text("Invalid thread id", response);
                    return true;
                }

                string notes = request.QueryString[UrlParameters.ThreadNotesText].Value;

                notes = System.Web.HttpUtility.HtmlDecode(notes);

                ThreadStore.GetStorageEngine().setThreadNotes(board, threadId, notes);

                response.Redirect(ThreadServerModule.GetThreadPageLink(board, threadId));

                return true;
            }
            return false;
        }
Example #22
0
        public static void Main(string [] args)
        {
            _httpsv = new HttpServer (4649);
              #if DEBUG
              _httpsv.Log.Level = LogLevel.TRACE;
              #endif
              _httpsv.RootPath = ConfigurationManager.AppSettings ["RootPath"];
              //_httpsv.KeepClean = false;
              _httpsv.AddWebSocketService<Echo> ("/Echo");
              _httpsv.AddWebSocketService<Chat> ("/Chat");

              _httpsv.OnGet += (sender, e) =>
              {
            onGet (e);
              };

              _httpsv.OnError += (sender, e) =>
              {
            Console.WriteLine (e.Message);
              };

              _httpsv.Start ();
              Console.WriteLine ("HTTP Server listening on port: {0} service path:", _httpsv.Port);
              foreach (var path in _httpsv.ServicePaths)
            Console.WriteLine ("  {0}", path);
              Console.WriteLine ();

              Console.WriteLine ("Press enter key to stop the server...");
              Console.ReadLine ();

              _httpsv.Stop ();
        }
 public void GetTest()
 {
     var item = new Site
     {
         Id = "1",
         Name = "Name",
         Address = new Address
         {
             City = "City",
             Country = "County"
         }
     };
     using (var server = new HttpServer(new RequestHandler
     {
         EstimatedMethod = "GET",
         EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/sites/1", Helper.AccountId),
         ContentToSend = Helper.CreateXmlContent(new SiteResponse{Site = item})
     }))
     {
         var client = Helper.CreateClient();
         var result = Site.Get(client, "1").Result;
         if (server.Error != null) throw server.Error;
         Helper.AssertObjects(item, result);
     }
 }
		public void Initialize(Func<IResourceStore> databaseGetter, Func<IRavenHttpConfiguration> settingsGetter, Func<string> tenantIdGetter, HttpServer theServer)
		{
			this.server = theServer;
			this.database = databaseGetter;
			this.settings = settingsGetter;
			this.tenantId = tenantIdGetter;
		}
Example #25
0
        static void Main(string[] args)
        {
            HttpServer httpServer = new HttpServer(8080, Routes.GET);

            Thread thread = new Thread(new ThreadStart(httpServer.Listen));
            thread.Start();
        }
 public Issue14_should_work_with_concurrent_requests()
 {
     var moduleManager = new ModuleManager();
     moduleManager.Add(this);
     _server = new HttpServer(moduleManager);
     _server.Start(IPAddress.Any, 0);
 }
Example #27
0
        public void ExampleCode()
        {
            using (var server = new HttpServer("http://*:1234/"))
            {
                // simple basic usage, all subscriptions will run in a single event-loop
                server.GET("/hello/{Name}")
                      .Subscribe(ctx => ctx.Respond("Hello, " + ctx.Request.UriArguments.Name + "!"));

                Browser.ExecuteGet("http://localhost:1234/hello/George")
                       .ReadAllContent()
                       .Should().Be.EqualTo("Hello, George!");

                // use Rx LINQ operators
                server.POST("/hi/{Name}")
                      .Where(ctx => ctx.Request.UriArguments.Name == "George")
                      .Subscribe(ctx => ctx.Respond("Hi, George!"));

                server.POST("/hi/{Name}")
                      .Where(ctx => ctx.Request.UriArguments.Name == "Pete")
                      .Subscribe(ctx => ctx.Respond("Hi, Pete!"));

                Browser.ExecutePost("http://localhost:1234/hi/George")
                       .ReadAllContent()
                       .Should().Be.EqualTo("Hi, George!");

                Browser.ExecutePost("http://localhost:1234/hi/Pete")
                       .ReadAllContent()
                       .Should().Be.EqualTo("Hi, Pete!");

                // This becomes a problem:
                //Browser.ExecutePost("http://localhost:1234/hi/Fran").StatusCode.Should().Be.EqualTo(404);
            }
        }
Example #28
0
    static void Main()
    {
        var ledActuator = new DigitalActuator
        {
            OutputPin = Parameters.LedPin
        };

        var webServer = new HttpServer
        {
            // RelayDomain = Parameters.RelayDomain,
            // RelaySecretKey = Parameters.RelaySecretKey,
            RequestRouting =
            {
                {
                    "PUT /led/target",
                    new ManipulatedVariable
                    {
                        FromHttpRequest =
                            CSharpRepresentation.TryDeserializeBool,
                        ToActuator = ledActuator.HandlePut
                    }.HandleRequest
                },
                {
                    "GET /led/target.html",
                    HandleLedTargetHtml
                }
            }
        };

        webServer.Run();
    }
Example #29
0
 private void StartHttpServer()
 {
     server = new HttpServer(this.Port, null, this);
 }
        public static void Main()
        {
            IHttpServer server = new HttpServer();

            server.Start();
        }
Example #31
0
 public void Uninstalled(HttpServer server)
 {
 }
Example #32
0
 public void Installed(HttpServer server)
 {
     stopwatch = new Stopwatch();
     stopwatch.Start();
 }
Example #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnbufferedODataBatchHandler"/> class.
 /// </summary>
 /// <param name="httpServer">The <see cref="HttpServer"/> for handling the individual batch requests.</param>
 public UnbufferedODataBatchHandler(HttpServer httpServer)
     : base(httpServer)
 {
 }
Example #34
0
        public HeadlessMain()
        {
            AppDomain.CurrentDomain.UnhandledException += CrashReport.DefaultExceptionHandler;
            ManageConfig();

            EventMaster.On(EventTypes.ConfigChangeEvent, d => {
                var data = (ConfigChangeEventData)d.Data;
                ProgConfig.UpdateProperty(data.Name, data.Value);
                EventMaster.Post("configSaved", data.Name);
                SetConfigVars();
            });

            SetConfigVars();

            var fdFolder  = PacketManager.GetFolderByProduct(NOAAProductID.GOES13_ABI, (int)ScannerSubProduct.INFRARED_FULLDISK);
            var xxFolder  = PacketManager.GetFolderByProduct(NOAAProductID.GOES13_ABI, (int)ScannerSubProduct.INFRARED_AREA_OF_INTEREST);
            var nhFolder  = PacketManager.GetFolderByProduct(NOAAProductID.GOES13_ABI, (int)ScannerSubProduct.INFRARED_NORTHERN);
            var shFolder  = PacketManager.GetFolderByProduct(NOAAProductID.GOES13_ABI, (int)ScannerSubProduct.INFRARED_SOUTHERN);
            var usFolder  = PacketManager.GetFolderByProduct(NOAAProductID.GOES13_ABI, (int)ScannerSubProduct.INFRARED_UNITEDSTATES);
            var fmFolder  = PacketManager.GetFolderByProduct(NOAAProductID.GOES16_ABI, (int)ScannerSubProduct.NONE);
            var unkFolder = PacketManager.GetFolderByProduct(NOAAProductID.GOES13_ABI, (int)ScannerSubProduct.NONE); // Same for any unknown ABI

            FDImageManager  = new ImageManager(fdFolder, "Full Disk");
            XXImageManager  = new ImageManager(xxFolder, "Area of Interest");
            NHImageManager  = new ImageManager(nhFolder, "Northern Hemisphere");
            SHImageManager  = new ImageManager(shFolder, "Southern Hemisphere");
            USImageManager  = new ImageManager(usFolder, "United States");
            FMImageManager  = new ImageManager(fmFolder, "FM1");
            UNKImageManager = new ImageManager(unkFolder, "Unknown");

            FDImageManager.InitMapDrawer();
            XXImageManager.InitMapDrawer();
            NHImageManager.InitMapDrawer();
            SHImageManager.InitMapDrawer();
            USImageManager.InitMapDrawer();
            FMImageManager.InitMapDrawer();
            UNKImageManager.InitMapDrawer();

            directoryHandler = new DirectoryHandler(FileHandler.FinalFileFolder, "/data");

            mtx = new Mutex();
            cn  = new Connector();

            demuxManager = new DemuxManager {
                RecordToFile = ProgConfig.RecordIntermediateFile
            };
            cn.StatisticsAvailable += data => {
                mtx.WaitOne();
                statistics = data;
                mtx.ReleaseMutex();

                if (ProgConfig.SaveStatistics)
                {
                    ThreadPool.QueueUserWorkItem((a) => StatisticsManager.Update(new DBStatistics {
                        SCID                  = data.scid,
                        VCID                  = data.vcid,
                        PacketNumber          = (long)data.packetNumber,
                        VitErrors             = data.vitErrors,
                        FrameBits             = data.frameBits,
                        RSErrors0             = data.rsErrors [0],
                        RSErrors1             = data.rsErrors [1],
                        RSErrors2             = data.rsErrors [2],
                        RSErrors3             = data.rsErrors [3],
                        SignalQuality         = data.signalQuality,
                        SyncCorrelation       = data.syncCorrelation,
                        PhaseCorrection       = data.phaseCorrection,
                        LostPackets           = (long)data.lostPackets,
                        AverageVitCorrections = data.averageVitCorrections,
                        AverageRSCorrections  = data.averageRSCorrections,
                        DroppedPackets        = (long)data.droppedPackets,
                        SyncWord              =
                            $"{data.syncWord[0]:X02}{data.syncWord[1]:X02}{data.syncWord[2]:X02}{data.syncWord[3]:X02}",
                        FrameLock = data.frameLock > 0,
                    }));
                }

                stModel.Refresh(statistics);
                httpsv.WebSocketServices.Broadcast(stModel.toJSON());
            };

            cn.ChannelDataAvailable       += demuxManager.parseBytes;
            cn.ConstellationDataAvailable += data => {
                var cm = new ConstellationModel(data);
                if (httpsv.IsListening)
                {
                    httpsv.WebSocketServices.Broadcast(cm.toJSON());
                }
            };

            statistics = new Statistics_st();
            stModel    = new StatisticsModel(statistics);
            UIConsole.Log("Headless Main Created");
            UIConsole.Log($"HTTP Server at port {ProgConfig.HTTPPort}");
            httpsv = new HttpServer(ProgConfig.HTTPPort)
            {
                RootPath = Path.GetFullPath(Path.Combine(".", "web"))
            };

            httpsv.OnGet += HandleHTTPGet;
            httpsv.AddWebSocketService("/mainws", () => new WSHandler {
                dh = directoryHandler
            });

            UIConsole.MessageAvailable += (data) => {
                var cm = new ConsoleModel(data.Priority.ToString(), data.Message);
                if (httpsv.IsListening)
                {
                    httpsv.WebSocketServices["/mainws"].Sessions.Broadcast(cm.toJSON());
                }

                messageListMutex.WaitOne();
                if (messageList.Count >= MAX_CACHED_MESSAGES)
                {
                    messageList.RemoveAt(0);
                }
                messageList.Add(data);
                messageListMutex.ReleaseMutex();
            };
        }
Example #35
0
        protected override void OnStart(string[] args)
        {
            FileIniDataParser parser = new FileIniDataParser();

            config = parser.ReadFile(AppDomain.CurrentDomain.BaseDirectory + "config.ini", System.Text.Encoding.UTF8);

            int portPointer = 5410;

            http                  = new HttpServer();
            http.EndPoint         = new IPEndPoint(IPAddress.Loopback, portPointer);
            http.RequestReceived += HTTPRequest;
            http.Start();

            foreach (SectionData section in config.Sections)
            {
                portPointer++;
                string ip   = section.SectionName;
                int    port = portPointer;
                if (ProxiesConfig.ContainsKey(ip))
                {
                    continue;
                }

                bool failed = false;
                for (int retry = 0; retry <= 1; retry++)
                {
                    failed = false;

                    try {
                        ProxyServer proxy = new ProxyServer();
                        proxy.AddEndPoint(new ExplicitProxyEndPoint(IPAddress.Loopback, port, false));
                        proxy.UpStreamEndPoint = new IPEndPoint(IPAddress.Parse(ip), 0);
                        proxy.Start();

                        Proxies.Add(ip, proxy);
                        ProxiesConfig.Add(ip, new Dictionary <string, dynamic>());
                    } catch {
                        failed = true;
                        continue;
                    }

                    break;
                }

                if (failed)
                {
                    continue;
                }


                ProxiesConfig[ip].Add("ip", ip);
                ProxiesConfig[ip].Add("port", port);

                foreach (KeyData key in section.Keys)
                {
                    if (ProxiesConfig[ip].ContainsKey(key.KeyName.ToLower()))
                    {
                        continue;
                    }
                    ProxiesConfig[ip].Add(key.KeyName.ToLower(), key.Value);
                }
            }
        }
Example #36
0
 public BuiltinListener(TestContext ctx, HttpServer server)
 {
     TestContext = ctx;
     Server      = server;
 }
Example #37
0
        private void mnuStartServer_Click(object sender, EventArgs e)
        {
            #region 设置处理文件夹路径Tar包存放文件夹路径
            try
            {
                //接收TAR包存放路径
                sRevTarPath = serverini.ReadValue("FolderSet", "RevTarFolder");
                if (!Directory.Exists(sRevTarPath))
                {
                    Directory.CreateDirectory(sRevTarPath);//不存在该路径就创建
                }
                //接收到的Tar包解压存放路径
                sUnTarPath = serverini.ReadValue("FolderSet", "UnTarFolder");
                if (!Directory.Exists(sUnTarPath))
                {
                    Directory.CreateDirectory(sUnTarPath);//不存在该路径就创建
                }
                //生成的需发送的XML文件路径
                sSourcePath = serverini.ReadValue("FolderSet", "XmlBuildFolder");
                if (!Directory.Exists(sSourcePath))
                {
                    Directory.CreateDirectory(sSourcePath);//
                }
                //生成的TAR包,将要被发送的位置
                sSendTarPath = serverini.ReadValue("FolderSet", "SndTarFolder");
                if (!Directory.Exists(sSendTarPath))
                {
                    Directory.CreateDirectory(sSendTarPath);
                }
                sAudioFilesFolder = serverini.ReadValue("FolderSet", "AudioFileFolder");
                if (!Directory.Exists(sAudioFilesFolder))
                {
                    Directory.CreateDirectory(sAudioFilesFolder);
                }
                //预处理文件夹
                strBeUnTarFolder = serverini.ReadValue("FolderSet", "BeUnTarFolder");
                if (!Directory.Exists(strBeUnTarFolder))
                {
                    Directory.CreateDirectory(strBeUnTarFolder);
                }
                strBeSendFileMakeFolder = serverini.ReadValue("FolderSet", "BeXmlFileMakeFolder");
                if (!Directory.Exists(strBeSendFileMakeFolder))
                {
                    Directory.CreateDirectory(strBeSendFileMakeFolder);
                }
                //预处理文件夹
                if (strBeUnTarFolder == "" || strBeSendFileMakeFolder == "")
                {
                    MessageBox.Show("预处理文件夹路径不能为空,请设置好路径!");
                    this.Close();
                }

                if (sRevTarPath == "" || sSendTarPath == "" || sSourcePath == "" || sUnTarPath == "")
                {
                    MessageBox.Show("文件夹路径不能为空,请设置好路径!");
                    this.Close();
                }
            }
            catch (Exception em)
            {
                MessageBox.Show("文件夹设置错误,请重新:" + em.Message);
                this.Close();
            }
            #endregion 文件夹路径设置END

            bDeal = true;//解析开关
            try
            {
                IPAddress[] ipArr;
                ipArr = Dns.GetHostAddresses(Dns.GetHostName());
                if (!ipArr.Contains(iServerIP))
                {
                    MessageBox.Show("IP设置错误,请重新设置后运行服务!");
                    return;
                }
                httpServer = new HttpServer(iServerIP, iServerPort);
            }
            catch (Exception es)
            {
                MessageBox.Show("可能端口已经使用中,请重新分配端口:" + es.Message);
                return;
            }


            if (mnuStartServer.Text == "启动伺服")
            {
                //启动服务
                MessageShowDlg = new MessageShowForm {
                    label1 = { Text = @"启动服务?" }
                };
                MessageShowDlg.ShowDialog();
                if (MessageShowDlg.IsSure)
                {
                    mnuStartServer.Text     = "停止伺服";
                    httpthread              = new Thread(new ThreadStart(httpServer.listen));
                    httpthread.IsBackground = true;
                    httpthread.Name         = "HttpServer服务";
                    httpthread.Start();
                    skinDataGridView_Main.Visible = true;
                    // skinDataGridView_Main.Dock=Dock.f
                }
            }
            else
            {
                //停止服务
                MessageShowDlg = new MessageShowForm {
                    label1 = { Text = @"停止服务?" }
                };
                MessageShowDlg.ShowDialog();
                if (MessageShowDlg.IsSure)
                {
                    mnuStartServer.Text = "启动伺服";
                    if (httpthread != null)
                    {
                        httpthread.Abort();
                        httpthread = null;
                    }
                    httpServer.StopListen();
                    skinDataGridView_Main.Visible = false;
                }
            }
        }
        static void Main()
        {
            HttpServer server = new HttpServer(8081, RouteTable.Routes);

            MvcEngine.Run(server, "IssueTracker.Web");
        }
Example #39
0
        public void AddRoutes(HttpServer webserver, Drone drone)
        {
            webserver.AddAction("GET", BaseRoute, (context) =>
            {
                return(new
                {
                    value = drone.AreMotorsEnabled
                });
            });

            webserver.AddAction("POST", BaseRoute, (context) =>
            {
                drone.EnableMotors();

                return(new
                {
                    message = "Motors enabled"
                });
            });

            webserver.AddAction("DELETE", BaseRoute, (context) =>
            {
                drone.DisableMotors();

                return(new
                {
                    message = "Motors disabled"
                });
            });

            webserver.AddAction("GET", $"{BaseRoute}/throttles", (context) =>
            {
                var throttles = drone.GetMotorThrottles();
                return(new
                {
                    frontLeft = throttles.Item1,
                    frontRight = throttles.Item2,
                    rearLeft = throttles.Item3,
                    rearRight = throttles.Item4
                });
            });

            webserver.AddAction("POST", $"{BaseRoute}/test", (context) =>
            {
                string input;
                using (StreamReader reader = new StreamReader(context.Request.InputStream))
                {
                    input = reader.ReadToEnd();
                }

                float value = JsonConvert.DeserializeObject <RunTestStruct>(input).Value;
                _           = Task.Run(() =>
                {
                    drone.RunTest(value);
                });

                return(new
                {
                    message = "Motor test started"
                });
            });

            webserver.AddAction("POST", $"{BaseRoute}/throttle", (context) =>
            {
                string input;
                using (StreamReader reader = new StreamReader(context.Request.InputStream))
                {
                    input = reader.ReadToEnd();
                }

                float value = JsonConvert.DeserializeObject <RunTestStruct>(input).Value;
                _           = Task.Run(() =>
                {
                    drone.MotorThrottle = value;
                });

                return(new
                {
                    message = "Motor throttle set"
                });
            });
        }
Example #40
0
 public HttpListenerConnection(TestContext ctx, HttpServer server, HttpListenerContext context)
     : base(server, context.Request.RemoteEndPoint)
 {
     TestContext = ctx;
     Context     = context;
 }
Example #41
0
        public void Run()
        {
            // initialize XS1 Configuration
            XS1_Configuration = new XS1Configuration(ConfigurationCacheMinutes);
            MAXMonitoringThread      ELVMax   = null;
            SolarLogMonitoringThread SolarLog = null;

            // Start Sensor-Check Thread
            SensorCheck Sensorcheck       = new SensorCheck(ConsoleOutputLogger);
            Thread      SensorCheckThread = new Thread(new ThreadStart(Sensorcheck.Run));

            SensorCheckThread.Start();

            // Start Actor Re-Switching Thread
            ActorReswitching ActorReSwitch_      = new ActorReswitching(XS1_Configuration, ConsoleOutputLogger, TemporaryBlacklist, OnWaitOffLIst);
            Thread           ActorReswitchThread = new Thread(new ThreadStart(ActorReSwitch_.Run));

            ActorReswitchThread.Start();

            // Start the SolarLog Thread (if enabled)
            // TODO: make it switchable / configurable
            if (Properties.Settings.Default.SolarLogEnabled)
            {
                SolarLog = new SolarLogMonitoringThread(Properties.Settings.Default.SolarLogURLDomain, ConsoleOutputLogger, SolarLog_DataQueue, Properties.Settings.Default.SolarLogUpdateIntervalMsec);
                Thread SolarLogThread = new Thread(new ThreadStart(SolarLog.Run));
                SolarLogThread.Start();
            }

            // Start the ELVMax Thread
            if (Properties.Settings.Default.ELVMAXEnabled)
            {
                ELVMax = new MAXMonitoringThread(Properties.Settings.Default.ELVMAXIP, Properties.Settings.Default.ELVMAXPort, ConsoleOutputLogger, MAX_DataQueue, Properties.Settings.Default.ELVMAXUpdateIntervalMsec);
                Thread ELVMaxThread = new Thread(new ThreadStart(ELVMax.Run));
                ELVMaxThread.Start();
            }

            XS1MonitoringThread XS1 = new XS1MonitoringThread(ServerName, ConsoleOutputLogger, UserName, Password, XS1_DataQueue);
            Thread XS1Thread        = new Thread(new ThreadStart(XS1.Run));

            XS1Thread.Start();

            // Start integrated HTTP Server
            HttpServer httpServer         = new HttpServer(Properties.Settings.Default.HTTPPort, Properties.Settings.Default.HTTPIP, Properties.Settings.Default.HTTPDocumentRoot, sensor_data_store, miataru_data_store, XS1_Configuration, ConsoleOutputLogger, ELVMax, Properties.Settings.Default.HTTPAuthEnabled, Properties.Settings.Default.HTTPAuthUsername, Properties.Settings.Default.HTTPAuthPassword, Properties.Settings.Default.HTTPAuthDisabledAdressStartsWith);
            Thread     http_server_thread = new Thread(new ThreadStart(httpServer.listen));

            http_server_thread.Start();

            // Start Service Monitorng thread
            if (Properties.Settings.Default.NetworkMonitorEnabled)
            {
                NetworkMonitoring monitor       = new NetworkMonitoring(ConsoleOutputLogger, NetworkMonitor_Queue, Properties.Settings.Default.NetworkMonitorUpdateIntervalMsec);
                Thread            monitorThread = new Thread(new ThreadStart(monitor.Run));
                monitorThread.Start();
            }

            // Start Alarming thread
            if (Properties.Settings.Default.AlarmingEnabled)
            {
                AlarmingThread alarmThread     = new AlarmingThread(ConsoleOutputLogger, Alarming_Queue, sensor_data_store, actor_data_store, miataru_data_store);
                Thread         alarming_thread = new Thread(new ThreadStart(alarmThread.Run));
                alarming_thread.Start();
            }

            // Start Miataru Thread
            if (Properties.Settings.Default.MiataruEnabled)
            {
                MiataruThread miataruThread  = new MiataruThread(ConsoleOutputLogger, miataru_data_store, Properties.Settings.Default.MiataruUpdateTime);
                Thread        miataru_Thread = new Thread(new ThreadStart(miataruThread.Run));
                miataru_Thread.Start();
            }

            while (!Shutdown)
            {
                try
                {
                    #region Handle XS1 events
                    XS1_DataObject dataobject = null;
                    if (XS1_DataQueue.TryDequeue(out dataobject))
                    {
                        if (dataobject.Type == ObjectTypes.Actor)
                        {
                            lock (actor_data_store)
                            {
                                actor_data_store.Write(dataobject.Serialize());
                            }

                            lock (KnownActorStates.KnownActorStatuses)
                            {
                                bool usethisactor = true;
                                // check if this actor is on temporary blacklist (like when it was handled)
                                lock (TemporaryBlacklist)
                                {
                                    if (TemporaryBlacklist.Contains(dataobject.Name))
                                    {
                                        usethisactor = false;
                                    }
                                    TemporaryBlacklist.Remove(dataobject.Name);
                                }

                                if (usethisactor)
                                {
                                    // if Alarming is enabled, queue this XS1 Event up for alarming...
                                    if (Properties.Settings.Default.AlarmingEnabled)
                                    {
                                        Alarming_Queue.Enqueue(dataobject);
                                    }

                                    // this actor action did not result in any action hacs made - so we try to make the best out of it
                                    #region Scripting Handling
                                    // check if this sensor is something we should act uppon
                                    foreach (ScriptingActorElement Element in ScriptingActorConfiguration.ScriptingActorActions)
                                    {
                                        if (dataobject.Name == Element.SensorToWatchName)
                                        {
                                            if (dataobject.Value == Element.SensorValue)
                                            {
                                                // obviously there is a ScriptingActorConfiguration entry
                                                // so we execute the actor preset

                                                set_state_actuator.set_state_actuator ssa = new set_state_actuator.set_state_actuator();
                                                ConsoleOutputLogger.WriteLineToScreenOnly("detected actor scripting action on actor " + Element.SensorToWatchName + " - " + Element.ActorToSwitchName + " to " + Element.ActionToRunName);

                                                if (Element.ActionToRunName == actor_status.URL)
                                                {
                                                    ConsoleOutputLogger.WriteLine("Scripting Actor URL");
                                                    // handle URLs -> the ActorToSwitch Name will be the URL to trigger


                                                    try
                                                    {
                                                        WebClient client = new WebClient();
                                                        client.Encoding = System.Text.Encoding.UTF8;
                                                        String JSONInput = client.DownloadString(Element.ActorToSwitchName);

                                                        ConsoleOutputLogger.WriteLine("Doing HTTP GET on: " + Element.ActorToSwitchName);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        ConsoleOutputLogger.WriteLine("Exception on URL Actor Scripting: " + e.Message);
                                                    }
                                                }

                                                // check what action is going to happen now...
                                                if (Element.ActionToRunName == actor_status.On)
                                                {
                                                    ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                }

                                                if (Element.ActionToRunName == actor_status.Off)
                                                {
                                                    ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);

                                                    // remove from OnWaitOffList
                                                    lock (OnWaitOffLIst)
                                                    {
                                                        if (OnWaitOffLIst.Contains(Element.ActorToSwitchName))
                                                        {
                                                            OnWaitOffLIst.Remove(Element.ActorToSwitchName);
                                                        }
                                                    }
                                                }

                                                if (Element.ActionToRunName == actor_status.OnOff)
                                                {
                                                    // look for the current status in the known actors table
                                                    lock (KnownActorStates.KnownActorStatuses)
                                                    {
                                                        if (KnownActorStates.KnownActorStatuses.ContainsKey(Element.ActorToSwitchName))
                                                        {
                                                            current_actor_status Status = KnownActorStates.KnownActorStatuses[Element.ActorToSwitchName];
                                                            if (Status.Status == actor_status.On)
                                                            {
                                                                ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);
                                                            }
                                                            else
                                                            if (Status.Status == actor_status.Off)
                                                            {
                                                                ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                        }
                                                    }
                                                }
                                                if (Element.ActionToRunName == actor_status.OnWaitOff)
                                                {
                                                    lock (OnWaitOffLIst)
                                                    {
                                                        ConsoleOutputLogger.WriteLine("Adding " + Element.ActorToSwitchName + " to ActorReSwitching OnWaitOff List");
                                                        OnWaitOffLIst.Add(Element.ActorToSwitchName);
                                                    }
                                                    ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON_WAIT_OFF", XS1_Configuration);
                                                }
                                            }
                                        }
                                    }
                                    #endregion


                                    if (KnownActorStates.KnownActorStatuses.ContainsKey(dataobject.Name))
                                    {
                                        // is contained
                                        if (dataobject.Value == 100)
                                        {
                                            KnownActorStates.KnownActorStatuses[dataobject.Name] = new current_actor_status(dataobject.Name, actor_status.On);
                                        }
                                        else
                                        {
                                            KnownActorStates.KnownActorStatuses[dataobject.Name] = new current_actor_status(dataobject.Name, actor_status.Off);
                                        }
                                    }
                                    else
                                    {
                                        if (dataobject.Value == 100)
                                        {
                                            KnownActorStates.KnownActorStatuses.Add(dataobject.Name, new current_actor_status(dataobject.Name, actor_status.On));
                                        }
                                        else
                                        {
                                            KnownActorStates.KnownActorStatuses.Add(dataobject.Name, new current_actor_status(dataobject.Name, actor_status.Off));
                                        }
                                    }
                                }
                                else
                                {
                                    ConsoleOutputLogger.WriteLine("Actor " + dataobject.Name + " is on the blacklist (ActorReSwitching) and therefore is ignored this time.");
                                }
                            }
                        }
                        else
                        if (dataobject.Type == ObjectTypes.Sensor)
                        {
                            lock (sensor_data_store)
                            {
                                sensor_data_store.Write(dataobject.Serialize());
                            }
                            // update the sensor in the sensor check
                            Sensorcheck.UpdateSensor(dataobject.Name);

                            // if Alarming is enabled, queue this XS1 Event up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                if (!dataobject.IgnoreForAlarming)                                              // this if for those events which get re-queued as xs1 events despite being for example elvmax events
                                {
                                    Alarming_Queue.Enqueue(dataobject);
                                }
                            }

                            // check if this sensor is something we should act uppon
                            foreach (ScriptingActorElement Element in ScriptingActorConfiguration.ScriptingActorActions)
                            {
                                if (dataobject.Name == Element.SensorToWatchName)
                                {
                                    if (dataobject.Value == Element.SensorValue)
                                    {
                                        // obviously there is a ScriptingActorConfiguration entry
                                        // so we execute the actor preset

                                        set_state_actuator.set_state_actuator ssa = new set_state_actuator.set_state_actuator();
                                        ConsoleOutputLogger.WriteLineToScreenOnly("detected actor scripting action on sensor " + Element.SensorToWatchName + " - " + Element.ActorToSwitchName + " to " + Element.ActionToRunName);

                                        if (Element.ActionToRunName == actor_status.URL)
                                        {
                                            ConsoleOutputLogger.WriteLine("Scripting Actor URL");
                                            // handle URLs -> the ActorToSwitch Name will be the URL to trigger


                                            try
                                            {
                                                WebClient client = new WebClient();
                                                client.Encoding = System.Text.Encoding.UTF8;
                                                String JSONInput = client.DownloadString(Element.ActorToSwitchName);

                                                ConsoleOutputLogger.WriteLine("Doing HTTP GET on: " + Element.ActorToSwitchName);
                                            }
                                            catch (Exception e)
                                            {
                                                ConsoleOutputLogger.WriteLine("Exception on URL Actor Scripting: " + e.Message);
                                            }
                                        }

                                        // check what action is going to happen now...
                                        if (Element.ActionToRunName == actor_status.On)
                                        {
                                            ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                        }

                                        if (Element.ActionToRunName == actor_status.Off)
                                        {
                                            ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);

                                            // remove from OnWaitOffList
                                            lock (OnWaitOffLIst)
                                            {
                                                if (OnWaitOffLIst.Contains(Element.ActorToSwitchName))
                                                {
                                                    OnWaitOffLIst.Remove(Element.ActorToSwitchName);
                                                }
                                            }
                                        }

                                        if (Element.ActionToRunName == actor_status.OnOff)
                                        {
                                            // look for the current status in the known actors table
                                            lock (KnownActorStates.KnownActorStatuses)
                                            {
                                                if (KnownActorStates.KnownActorStatuses.ContainsKey(Element.ActorToSwitchName))
                                                {
                                                    current_actor_status Status = KnownActorStates.KnownActorStatuses[Element.ActorToSwitchName];
                                                    if (Status.Status == actor_status.On)
                                                    {
                                                        ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);
                                                    }
                                                    else
                                                    if (Status.Status == actor_status.Off)
                                                    {
                                                        ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                    }
                                                }
                                                else
                                                {
                                                    ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                }
                                            }
                                        }
                                        if (Element.ActionToRunName == actor_status.OnWaitOff)
                                        {
                                            lock (OnWaitOffLIst)
                                            {
                                                ConsoleOutputLogger.WriteLine("Adding " + Element.ActorToSwitchName + " to ActorReSwitching OnWaitOff List");
                                                OnWaitOffLIst.Add(Element.ActorToSwitchName);
                                            }
                                            ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON_WAIT_OFF", XS1_Configuration);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        if (dataobject.Type == ObjectTypes.Unknown)
                        {
                            unknown_data_store.Write(dataobject.Serialize());
                        }

                        ConsoleOutputLogger.WriteLine(ServerName + " - " + dataobject.OriginalXS1Statement);
                    }
                    #endregion

                    #region Handle MAX events
                    // the strategy for MAX events is quite easy: emulate XS1 events and stuff the XS1 queue with those faked events
                    // that takes care of the storage and the
                    if (Properties.Settings.Default.ELVMAXEnabled)
                    {
                        IDeviceDiffSet max_dataobject = null;

                        if (MAX_DataQueue.TryDequeue(out max_dataobject))
                        {
                            // if Alarming is enabled, queue this ELV MAX up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                Alarming_Queue.Enqueue(max_dataobject);
                            }

                            StringBuilder sb = new StringBuilder();

                            sb.Append("S\t" + max_dataobject.DeviceName + "\t" + max_dataobject.DeviceType);

                            if (max_dataobject.DeviceType == DeviceTypes.HeatingThermostat)
                            {
                                HeatingThermostatDiff _heating = (HeatingThermostatDiff)max_dataobject;

                                // this is what is different on the heating thermostats
                                //ConsoleOutputLogger.WriteLine(_heating.ToString());

                                // first the temperature data
                                XS1_DataObject maxdataobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _heating.RoomName + "-" + _heating.DeviceName, ObjectTypes.Sensor, "heating_thermostat", DateTime.Now, _heating.RoomID, _heating.Temperature, _heating.ToString(), true);
                                SensorCheckIgnoreConfiguration.AddToIgnoreList(maxdataobject.Name);
                                XS1_DataQueue.Enqueue(maxdataobject);

                                // then the low battery if exists
                                if (_heating.LowBattery == BatteryStatus.lowbattery)
                                {
                                    XS1_DataObject lowbatteryobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _heating.RoomName + "-" + _heating.DeviceName, ObjectTypes.Sensor, "low_battery", DateTime.Now, _heating.RoomID, _heating.Temperature, _heating.ToString() + ", LowBattery", true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(lowbatteryobject.Name);
                                    XS1_DataQueue.Enqueue(lowbatteryobject);
                                }

                                if (_heating.Mode == ThermostatModes.boost)
                                {
                                    XS1_DataObject boostmodeobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _heating.RoomName + "-" + _heating.DeviceName, ObjectTypes.Sensor, "boost", DateTime.Now, _heating.RoomID, _heating.Temperature, _heating.ToString() + ", Boost", true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(boostmodeobject.Name);
                                    XS1_DataQueue.Enqueue(boostmodeobject);
                                }
                            }

                            if (max_dataobject.DeviceType == DeviceTypes.ShutterContact)
                            {
                                ShutterContactDiff _shutter = (ShutterContactDiff)max_dataobject;

                                // this is what is different on the ShutterContacts
                                //ConsoleOutputLogger.WriteLine(_shutter.ToString());

                                // first the open/close status
                                if (_shutter.ShutterState == ShutterContactModes.open)
                                {
                                    XS1_DataObject maxdataobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "shutter_contact", DateTime.Now, _shutter.RoomID, 1.0, _shutter.ToString(), true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(maxdataobject.Name);
                                    XS1_DataQueue.Enqueue(maxdataobject);
                                }
                                else
                                {
                                    XS1_DataObject maxdataobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "shutter_contact", DateTime.Now, _shutter.RoomID, 0.0, _shutter.ToString(), true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(maxdataobject.Name);
                                    XS1_DataQueue.Enqueue(maxdataobject);
                                }

                                // then the low battery if exists
                                if (_shutter.LowBattery == BatteryStatus.lowbattery)
                                {
                                    if (_shutter.ShutterState == ShutterContactModes.open)
                                    {
                                        XS1_DataObject lowbatteryobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "low_battery", DateTime.Now, _shutter.RoomID, 1.0, _shutter.ToString() + ",LowBattery", true);
                                        SensorCheckIgnoreConfiguration.AddToIgnoreList(lowbatteryobject.Name);
                                        XS1_DataQueue.Enqueue(lowbatteryobject);
                                    }
                                    else
                                    {
                                        XS1_DataObject lowbatteryobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "low_battery", DateTime.Now, _shutter.RoomID, 0.0, _shutter.ToString() + ",LowBattery", true);
                                        SensorCheckIgnoreConfiguration.AddToIgnoreList(lowbatteryobject.Name);
                                        XS1_DataQueue.Enqueue(lowbatteryobject);
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region Handle SolarLog events
                    if (Properties.Settings.Default.SolarLogEnabled)
                    {
                        SolarLogDataSet solarlog_dataobject = null;

                        if (SolarLog_DataQueue.TryDequeue(out solarlog_dataobject))
                        {
                            // Pac
                            XS1_DataQueue.Enqueue(new XS1_DataObject(Properties.Settings.Default.SolarLogURLDomain, "Pac", ObjectTypes.Sensor, "Pac", solarlog_dataobject.DateAndTime, 1, solarlog_dataobject.Pac, "solarlog," + Properties.Settings.Default.SolarLogURLDomain + ",Pac," + solarlog_dataobject.Pac + "," + solarlog_dataobject.DateAndTime.Ticks, true));
                            // aPdc
                            XS1_DataQueue.Enqueue(new XS1_DataObject(Properties.Settings.Default.SolarLogURLDomain, "aPdc", ObjectTypes.Sensor, "aPdc", solarlog_dataobject.DateAndTime, 1, solarlog_dataobject.aPdc, "solarlog," + Properties.Settings.Default.SolarLogURLDomain + ",aPdc," + solarlog_dataobject.aPdc + "," + solarlog_dataobject.DateAndTime.Ticks, true));

                            // if Alarming is enabled, queue this SolarLog Event up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                Alarming_Queue.Enqueue(solarlog_dataobject);
                            }
                        }
                    }
                    #endregion

                    #region Handle Network Monitor events
                    if (Properties.Settings.Default.NetworkMonitorEnabled)
                    {
                        NetworkMonitoringDataSet networkmonitor_dataobject = null;

                        if (NetworkMonitor_Queue.TryDequeue(out networkmonitor_dataobject))
                        {
                            if (networkmonitor_dataobject.Status == Org.Mentalis.Network.ICMP_Status.Success)
                            {
                                XS1_DataQueue.Enqueue(new XS1_DataObject(networkmonitor_dataobject.Descriptor, networkmonitor_dataobject.HostnameIP, ObjectTypes.Sensor, "Ping", networkmonitor_dataobject.TimeOfMeasurement, 2, 1, "OnlineCheck," + networkmonitor_dataobject.HostnameIP + "," + networkmonitor_dataobject.Descriptor + ",Online", true));
                            }
                            else
                            {
                                XS1_DataQueue.Enqueue(new XS1_DataObject(networkmonitor_dataobject.Descriptor, networkmonitor_dataobject.HostnameIP, ObjectTypes.Sensor, "Ping", networkmonitor_dataobject.TimeOfMeasurement, 2, 0, "OnlineCheck," + networkmonitor_dataobject.HostnameIP + "," + networkmonitor_dataobject.Descriptor + ",Offline", true));
                            }

                            // if Alarming is enabled, queue this Network Monitor Event up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                Alarming_Queue.Enqueue(networkmonitor_dataobject);
                            }
                        }
                    }
                    #endregion
                }
                catch (Exception)
                {
                    AcceptingCommands = false;
                    //Thread.Sleep(1);
                }
                Thread.Sleep(1);
            }
            if (ELVMax != null)
            {
                ELVMax.running = false;
            }
            XS1.running = false;

            Thread.Sleep(200);                  // ... msecs period to wait for new input...
        }
Example #42
0
        public async Task <string> Run()
        {
            Log.Info("Initializing Captcha Bypass WebServer...");

            if (WebConf == null)
            {
                WebConf      = new Configuration();
                WebConf.Port = 80;
                WebConf.AllowDirectoryListing = false;
                WebConf.SourcePaths.Add(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "web"));
            }

            if (HttpServer == null)
            {
                HttpServer = new HttpServer(WebConf);
                HttpServer.RequestReceived    += (sender, args) => Log.Debug("[{0}] - {1}", args.Request.HttpMethod, args.Request.Path);
                HttpServer.UnhandledException += (sender, args) => Log.Exception(args.Exception, args.Exception.Source);
            }

            if (!SetHostsFile())
            {
                return(null);
            }

            try
            {
                Log.Info("Starting WebServer...");
                HttpServer.Start();
            }
            catch (Exception ex)
            {
                Log.Exception(ex, "Failed to start the WebServer. Possible port or permission issue.");
                try
                {
                    var lines     = File.ReadAllLines(HostsFilePath).ToList();
                    var nexonLine = lines.FirstOrDefault(l => l.Contains("nexon.com"));
                    if (!string.IsNullOrWhiteSpace(nexonLine))
                    {
                        lines.Remove(nexonLine);
                        File.WriteAllLines(HostsFilePath, lines);
                        HostFileFailure = false;
                    }

                    lines     = File.ReadAllLines(HostsFilePath).ToList();
                    nexonLine = lines.FirstOrDefault(l => l.Contains("nexon.com"));
                    if (!string.IsNullOrWhiteSpace(nexonLine))
                    {
                        Log.Error("The sanity check for the HOSTS file failed, falling back!");
                        HostFileFailure = true;
                        return(null);
                    }
                }
                catch (Exception ex2)
                {
                    // Should never be called as non admin...
                    Log.Exception(ex2, "Failed to read or edit the HOSTS file. {0}",
                                  App.IsAdministrator() ? "Running as admin." : "NOT running as admin.");
                    HostFileFailure = true;
                    return(null);
                }

                return(null);
            }

            string recaptchaToken = null;

            Completed += s => recaptchaToken = s;

            Log.Info("Starting the browser...");
            RunAsDesktopUser(BrowserHelper.GetDefaultBrowserPath(), "http://nexon.com");

            while (recaptchaToken == null)
            {
                await Task.Delay(100);
            }

            return(recaptchaToken);
        }
Example #43
0
 public BitODataBatchHandler(HttpServer httpServer)
     : base(httpServer)
 {
 }
Example #44
0
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            _webApiConfig = new HttpConfiguration();
            _webApiConfig.SuppressHostPrincipal();

            _webApiConfig.SetTimeZoneInfo(TimeZoneInfo.Utc);

            _webApiConfig.Formatters.Clear();

            _webApiConfig.IncludeErrorDetailPolicy = AppEnvironment.DebugMode ? IncludeErrorDetailPolicy.LocalOnly : IncludeErrorDetailPolicy.Never;

            _webApiConfig.DependencyResolver = WebApiDependencyResolver;

            _webApiConfig.Services.Replace(typeof(IHttpControllerSelector), new DefaultODataHttpControllerSelector(_webApiConfig));

            WebApiConfigurationCustomizers.ToList()
            .ForEach(webApiConfigurationCustomizer =>
            {
                webApiConfigurationCustomizer.CustomizeWebApiConfiguration(_webApiConfig);
            });

            _server = new HttpServer(_webApiConfig);

            _webApiConfig.UseCustomContainerBuilder(() => ContainerBuilder);

            var odataModulesAndAssembliesGroups = ApiAssembliesProvider.GetApiAssemblies()
                                                  .SelectMany(asm =>
            {
                ODataModuleAttribute[] odataModuleAttributes = asm.GetCustomAttributes <ODataModuleAttribute>().ToArray();

                return(odataModuleAttributes.Select(oma => new { ODataModule = oma, Assembly = asm }));
            })
                                                  .GroupBy(odataModuleAndAssembly => odataModuleAndAssembly.ODataModule.ODataRouteName);

            foreach (var odataModuleAndAssemblyGroup in odataModulesAndAssembliesGroups)
            {
                ODataModelBuilder modelBuilder = ODataModelBuilderProvider.GetODataModelBuilder(_webApiConfig, containerName: $"{odataModuleAndAssemblyGroup.Key}Context", @namespace: null);

                foreach (var odataModuleAndAssembly in odataModuleAndAssemblyGroup)
                {
                    ODataModuleConfiguration.ConfigureODataModule(odataModuleAndAssemblyGroup.Key, odataModuleAndAssembly.Assembly, modelBuilder);
                }

                string routeName = $"{odataModuleAndAssemblyGroup.Key}-odata";

                _odataBatchHandler = new DefaultODataBatchHandler(_server);

                _odataBatchHandler.MessageQuotas.MaxOperationsPerChangeset = int.MaxValue;

                _odataBatchHandler.MessageQuotas.MaxPartsPerBatch = int.MaxValue;

                _odataBatchHandler.MessageQuotas.MaxNestingDepth = int.MaxValue;

                _odataBatchHandler.MessageQuotas.MaxReceivedMessageSize = long.MaxValue;

                _odataBatchHandler.ODataRouteName = routeName;

                IEnumerable <IODataRoutingConvention> conventions = ODataRoutingConventions.CreateDefault();

                IEdmModel edmModel = modelBuilder.GetEdmModel();

                _webApiConfig.MapODataServiceRoute(routeName, odataModuleAndAssemblyGroup.Key, builder =>
                {
                    builder.AddService(ServiceLifetime.Singleton, sp => conventions);
                    builder.AddService(ServiceLifetime.Singleton, sp => edmModel);
                    builder.AddService(ServiceLifetime.Singleton, sp => _odataBatchHandler);
                    builder.AddService(ServiceLifetime.Singleton, sp => WebApiDependencyResolver);
                });
            }

            owinApp.UseAutofacWebApi(_webApiConfig);

            WebApiOwinPipelineInjector.UseWebApi(owinApp, _server, _webApiConfig);

            _webApiConfig.EnsureInitialized();
        }
Example #45
0
        public static void Main(string[] args)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            HttpServer server = null;

            try
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;

                int port = 6069;
                if (args != null && args.Length > 0)
                {
                    port = Convert.ToInt32(args[0]);
                }

                Console.WriteLine($"server starting at port:{port}...");
                var webroot = $"{AppDomain.CurrentDomain.BaseDirectory}Port{port}";

                if (!System.IO.Directory.Exists(webroot))
                {
                    System.IO.Directory.CreateDirectory(webroot);
                }

                if (System.IO.File.Exists($"{webroot}/main.html") == false)
                {
                    System.IO.File.WriteAllText($"{webroot}/main.html", "<html><body controller=\"Way.EJServer.MainController\"></body></html>");
                }

                server = new HttpServer(new int[] { port }, webroot);
                Console.WriteLine($"Root:{server.Root}");

                server.RegisterHandler(new DownLoadCodeHandler());
                server.RegisterHandler(new DownLoadSimpleCodeHandler());
                server.RegisterHandler(new DownLoadVerySimpleCodeHandler());
                server.RegisterHandler(new DownloadTableDataHandler());
                server.RegisterHandler(new ImportDataHandler());
                server.RegisterHandler(new ImportCSFileHandler());

                server.UseHttps(new X509Certificate2("./EJServerCert.pfx", "123456"), System.Security.Authentication.SslProtocols.None, true);
                Console.WriteLine($"use ssl EJServerCert.pfx");

                server.SessionTimeout = 60 * 24;


                //copy action table data
                //复制action表
                using (var db = new EJ.DB.easyjob($"Data Source=\"{webroot}/EasyJob.db\"", DatabaseType.Sqlite))
                {
                    //判断是否有__action

                    bool isOldVersion = false;
                    try
                    {
                        db.Database.ExecSqlString("select count(*) from __action");
                        isOldVersion = true;
                    }
                    catch (Exception)
                    {
                    }

                    if (isOldVersion && db.DesignHistory.Count() == 0)
                    {
                        db.BeginTransaction();
                        try
                        {
                            db.Database.ExecuteReader((reader) =>
                            {
                                db.Insert(new DesignHistory()
                                {
                                    ActionId   = Convert.ToInt32(reader["id"]),
                                    Type       = (string)reader["type"],
                                    Content    = (string)reader["content"],
                                    DatabaseId = Convert.ToInt32(reader["databaseid"]),
                                });
                                return(true);
                            }, "select * from __action", null);
                            db.CommitTransaction();
                        }
                        catch (Exception)
                        {
                            db.RollbackTransaction();
                            throw;
                        }
                    }
                }

                server.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            while (true)
            {
                Console.Write("Web>");
                var line = Console.ReadLine();
                if (line == null)
                {
                    //是在后台运行的
                    while (true)
                    {
                        System.Threading.Thread.Sleep(10000000);
                    }
                }
                else if (line == "exit")
                {
                    break;
                }
            }
            server?.Stop();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
Example #46
0
 public httpToSignal()
 {
     server = new HttpServer();
     server.OnHttpRequest += new OnHttpRequestHandler(server_OnHttpRequest);
 }
Example #47
0
        public static void Main(string[] args)
        {
            HttpServer server = new HttpServer(8081, RouteTable.Routes);

            MvcEngine.Run(server, "PizzaForum.App");
        }
        public void Test()
        {
            // hostname to use
            // we need something different than 127.0.0.1 or localhost for the proxy!
            IPHostEntry hostEntry;

            try {
                hostEntry = Dns.GetHostEntry("mylocalhost");
            } catch (Exception) {
                hostEntry = null;
            }
            var host = hostEntry == null ? "127.0.0.1" : "mylocalhost";

            var baseDir = Path.Combine(TestFolder, "http");

            Directory.CreateDirectory(baseDir);

            var gitLabServer = new SimpleGitLabServer(baseDir, "admin");
            var proxyServer  = new SimpleHttpProxyServer("jucai69d", "julien caillon");

            var cts   = new CancellationTokenSource();
            var task1 = HttpServer.ListenAsync(8086, cts.Token, gitLabServer.OnHttpRequest, true);
            var task2 = HttpServer.ListenAsync(8087, cts.Token, proxyServer.OnHttpRequest, true);

            // do
            gitLabServer.Tags = new List <GitLabTag> {
                new GitLabTag {
                    TagName    = "v1.0.1-beta",
                    TagMessage = "rel1",
                    TagSha1    = "1",
                    Release    = new GitLabRelease {
                        TagName     = "",
                        Description = "Description"
                    }
                },
                new GitLabTag {
                    TagName    = "v1.1.0",
                    TagMessage = "rel2",
                    TagSha1    = "2"
                },
                new GitLabTag {
                    TagName    = "v1.2.1-beta",
                    TagMessage = "rel3",
                    TagSha1    = "3"
                },
                new GitLabTag {
                    TagName    = "v3.0.0",
                    TagMessage = "rel5",
                    TagSha1    = "5"
                },
                new GitLabTag {
                    TagName    = "v2.0.0",
                    TagMessage = "rel4",
                    TagSha1    = "4"
                }
            };

            var updater = new GitLabUpdater($"http://{host}:8086");

            updater.UsePrivateToken("admin");
            updater.UseProxy($"http://{host}:8087/", "jucai69d", "julien caillon");
            updater.SetProjectId("test/truc");
            updater.UseMaxNumberOfTagsToFetch(10);

            var tags = updater.FetchNewReleases(UpdaterHelper.StringToVersion("0"));

            Assert.AreEqual(5, tags.Count);
            Assert.AreEqual("rel5", tags[0].TagMessage);

            tags = updater.FetchNewReleases(UpdaterHelper.StringToVersion("3"));
            Assert.AreEqual(0, tags.Count);

            tags = updater.FetchNewReleases(UpdaterHelper.StringToVersion("1.2"));
            Assert.AreEqual(3, tags.Count);
            Assert.AreEqual("rel5", tags[0].TagMessage);

            File.WriteAllText(Path.Combine(baseDir, "testFile"), "cc");
            var countProgress = 0;
            var dlPath        = updater.DownloadToTempFile("testFile", progress => countProgress++);

            Assert.IsTrue(countProgress > 0);
            Assert.IsTrue(File.Exists(dlPath));
            Assert.AreEqual(File.ReadAllText(Path.Combine(baseDir, "testFile")), File.ReadAllText(dlPath));

            File.Delete(dlPath);

            countProgress = 0;
            dlPath        = updater.DownloadRepositoryArchive("mysha1", progress => countProgress++);
            Assert.IsTrue(countProgress > 0);
            Assert.IsTrue(File.Exists(dlPath));
            Assert.AreEqual(new FileInfo(dlPath).Length, 10);

            File.Delete(dlPath);

            if (!host.Equals("127.0.0.1"))
            {
                Assert.IsTrue(proxyServer.NbRequestsHandledOk > 0);
            }

            HttpServer.Stop(cts, task1, task2);
        }
        static void Main(string[] args)
        {
            HttpServer server = new HttpServer(8081, RouteTable.Routes);

            MvcEngine.Run(server);
        }
Example #50
0
 private IFeatureRequestor MakeRequestor(HttpServer server) => MakeRequestor(server.Uri);
 public void AddPassthrough(Func <HttpRequest, bool> condition, HttpServer server)
 {
     ConditionalPassthroughs.Add(condition, server);
 }
        private static string PrettyPrintRequestsFor(HttpServer server)
        {
            var logs = _serverRequests[server];

            return(logs.Select(PrettyPrintRequestLog).JoinWith(Environment.NewLine));
        }
 public RoutingCollection(HttpServer server)
 {
     Server = server;
 }
Example #54
0
        public static void Main(string[] args)
        {
            Logging.LogMsg(Logging.LogLevel.NORMAL, "Startup HTTPServer");
            // Create a new instance of the HttpServer class.
            //
            // If you would like to provide the secure connection, you should
            // create a new instance with the 'secure' parameter set to true,
            // or an https scheme HTTP URL.
            //var httpsv = new HttpServer(4649);
            int port   = 8080;//Convert.ToInt32(Console.ReadLine());
            var httpsv = new HttpServer(IPAddress.Parse("188.64.57.167"), port);

            //var httpsv = new HttpServer("http://188.64.57.167:80");

            //var httpsv = new HttpServer (8080, true);

            //var httpsv = new HttpServer (System.Net.IPAddress.Any, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.Any, 5963, true);

            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Any, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Any, 5963, true);

            //var httpsv = new HttpServer ("http://0.0.0.0:4649");
            //var httpsv = new HttpServer ("https://0.0.0.0:5963");

            //var httpsv = new HttpServer ("http://[::0]:4649");
            //var httpsv = new HttpServer ("https://[::0]:5963");

            //var httpsv = new HttpServer (System.Net.IPAddress.Loopback, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.Loopback, 5963, true);

            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Loopback, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Loopback, 5963, true);

            //var httpsv = new HttpServer ("http://localhost:8080");
            //var httpsv = new HttpServer ("https://localhost:5963");

            //var httpsv = new HttpServer ("http://127.0.0.1:4649");
            //var httpsv = new HttpServer ("https://127.0.0.1:5963");

            //var httpsv = new HttpServer ("http://[::1]:4649");
            //var httpsv = new HttpServer ("https://[::1]:5963");
#if DEBUG
            // To change the logging level.
            httpsv.Log.Level = LogLevel.Trace;

            // To change the wait time for the response to the WebSocket Ping or Close.
            //httpsv.WaitTime = TimeSpan.FromSeconds (2);

            // Not to remove the inactive WebSocket sessions periodically.
            //httpsv.KeepClean = false;
#endif
            // To provide the secure connection.

            /*
             * var cert = ConfigurationManager.AppSettings["ServerCertFile"];
             * var passwd = ConfigurationManager.AppSettings["CertFilePassword"];
             * httpsv.SslConfiguration.ServerCertificate = new X509Certificate2 (cert, passwd);
             */

            // To provide the HTTP Authentication (Basic/Digest).

            /*
             * httpsv.AuthenticationSchemes = AuthenticationSchemes.Basic;
             * httpsv.Realm = "WebSocket Test";
             * httpsv.UserCredentialsFinder = id => {
             * var name = id.Name;
             *
             * // Return user name, password, and roles.
             * return name == "nobita"
             *   ? new NetworkCredential (name, "password", "gunfighter")
             *   : null; // If the user credentials aren't found.
             * };
             */

            // To resolve to wait for socket in TIME_WAIT state.
            //httpsv.ReuseAddress = true;

            // Set the document root path.
            httpsv.RootPath = ConfigurationManager.AppSettings["RootPath"];

            // Set the HTTP GET request event.
            httpsv.OnGet += (sender, e) =>
            {
                var req = e.Request;
                var res = e.Response;

                var path = req.RawUrl;
                if (path == "/")
                {
                    path += "index.html";
                }

                var content = httpsv.GetFile(path);
                if (content == null)
                {
                    res.StatusCode = (int)HttpStatusCode.NotFound;
                    return;
                }

                if (path.EndsWith(".html"))
                {
                    res.ContentType     = "text/html";
                    res.ContentEncoding = Encoding.UTF8;
                }
                else if (path.EndsWith(".js"))
                {
                    res.ContentType     = "application/javascript";
                    res.ContentEncoding = Encoding.UTF8;
                }

                res.WriteContent(content);
            };

            // Add the WebSocket services.
            //httpsv.AddWebSocketService<Echo> ("/Echo");
            //httpsv.AddWebSocketService<Chat> ("/Chat");
            httpsv.AddWebSocketService <Client>("/Game");

            // Add the WebSocket service with initializing.

            /*
             * httpsv.AddWebSocketService<Chat> (
             * "/Chat",
             * () =>
             *  new Chat ("Anon#") {
             *    // To send the Sec-WebSocket-Protocol header that has a subprotocol name.
             *    Protocol = "chat",
             *    // To ignore the Sec-WebSocket-Extensions header.
             *    IgnoreExtensions = true,
             *    // To emit a WebSocket.OnMessage event when receives a ping.
             *    EmitOnPing = true,
             *    // To validate the Origin header.
             *    OriginValidator = val => {
             *        // Check the value of the Origin header, and return true if valid.
             *        Uri origin;
             *        return !val.IsNullOrEmpty ()
             *               && Uri.TryCreate (val, UriKind.Absolute, out origin)
             *               && origin.Host == "localhost";
             *      },
             *    // To validate the cookies.
             *    CookiesValidator = (req, res) => {
             *        // Check the cookies in 'req', and set the cookies to send to
             *        // the client with 'res' if necessary.
             *        foreach (Cookie cookie in req) {
             *          cookie.Expired = true;
             *          res.Add (cookie);
             *        }
             *
             *        return true; // If valid.
             *      }
             *  }
             * );
             */

            httpsv.Start();
            // TÜV
            SessionHandler handler = new SessionHandler();
            handler.StartSession(0, 1);

            // Xyqom
            SessionHandler handler2 = new SessionHandler();
            handler2.StartSession(1, 1);

            // Shared (Auto)
            SessionHandler handler3 = new SessionHandler();
            handler3.StartSession(2, 1);

            if (httpsv.IsListening)
            {
                Logging.LogMsg(Logging.LogLevel.NORMAL, "Listening on port {0}, and providing WebSocket services:",
                               httpsv.Port);
                foreach (var path in httpsv.WebSocketServices.Paths)
                {
                    Logging.LogMsg(Logging.LogLevel.NORMAL, "- {0}", path);
                }
            }
            while (true)
            {
                var entry = Console.ReadLine();
                if (entry != null)
                {
                    string[] cmd = entry.Split(Convert.ToChar(";"));
                    switch (cmd[0])
                    {
                    case "start":
                        handler.SessionEvents.StartGameSession();
                        break;

                    case "test":
                        handler.ActiveSession.GetClient(Client.ClientType.Wrapper)?.WE?.SetupPipes();
                        break;
                    }
                }
            }

            Logging.LogMsg(Logging.LogLevel.NORMAL, "\nPress Enter key to stop the server...");
            Console.ReadLine();
            httpsv.Stop();
        }
 private static string RequestErrorFor(this HttpServer server, string mainError)
 {
     return($"{mainError}. Got requests: {PrettyPrintRequestsFor(server)}");
 }
 public static void ShouldNotHaveReceivedRequestFor(this HttpServer server, string path, HttpMethods method = HttpMethods.Any)
 {
     Assert.IsFalse(server.GetRequestLogsMatching(path, method).Any(),
                    server.RequestErrorFor($"Should have no requests matching path {path} and method {method}."));
 }
 public static IEnumerable <RequestLogItem> GetRequestLogsMatching(this HttpServer server, string path, HttpMethods method)
 {
     return(server.GetRequestLogsMatching(l => l.Path == path && HttpMethodsExtensions.Matches(method, l.Method)));
 }
Example #58
0
 public void StopHttpServer()
 {
     _httpServer?.Dispose();
     _httpServer = null;
 }
        public void CreateWithDefaultClientTest()
        {
            var item = new TnLineOptions
            {
                TelephoneNumber = "5209072451<",
                CallingNameDisplay = "off"
            };

            using (var server = new HttpServer(new[]
            {
                new RequestHandler
                {
                    EstimatedMethod = "POST",
                    EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/lineOptionOrders", Helper.AccountId),
                    EstimatedContent = Helper.ToXmlString(new LineOptionOrderRequest{TnLineOptions = new []{item}}),
                    ContentToSend = new StringContent(TestXmlStrings.LineOption, Encoding.UTF8, "application/xml"),
                }
            }))
            {
                var i = LineOptionOrder.Create(item).Result;
                if (server.Error != null) throw server.Error;
                Assert.AreEqual(1, i.Length);
                Assert.AreEqual("2013223685", i[0]);
            }
        }
Example #60
-1
        public async Task WebHost_Batching_WithSpecialCharactersInUrl()
        {
            // Arrange
            var handler = new SuccessMessageHandler();

            var routeCollection = new HostedHttpRouteCollection(new RouteCollection(), "/");
            routeCollection.Add("default", routeCollection.CreateRoute(
                "values/  space",
                defaults: null,
                constraints: null,
                dataTokens: null,
                handler: handler));

            var configuration = new HttpConfiguration(routeCollection);

            var server = new HttpServer(configuration);

            var batchHandler = new DefaultHttpBatchHandler(server);
            var request = new HttpRequestMessage
            {
                Content = new MultipartContent("mixed")
                {
                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, "http://contoso.com/values/  space"))
                }
            };

            // Arrange
            var response = await batchHandler.ProcessBatchAsync(request, CancellationToken.None);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(handler.IsCalled);
        }