public void RegisterRouteTest() { HTTPServer server = new HTTPServer(); bool status = server.RegisterRoute("GET", "/messages", (RequestContext rc, StreamWriter sw) => { }); Assert.AreEqual(status, true); }
public static void SendFile(IHTTPContext context, String filename, String contentType) { if (!File.Exists(filename)) { context.Response.SendErrorResponse(404); return; } String lastModified = File.GetLastWriteTimeUtc(filename).ToString("R"); if (context.RequestHeaders["If-Modified-Since"] == lastModified) { context.Response.SendStatus(304); return; } if (contentType == null) { contentType = HTTPServer.GetMimeTypeForExtension(Path.GetExtension(filename)); } using (FileStream fs = File.OpenRead(filename)) { context.Response.SendStatus(200); if (!String.IsNullOrEmpty(contentType)) { context.Response.SendHeader("Content-Type", contentType); } context.Response.SendHeader("Last-Modified", lastModified); context.Response.WriteResponseData(fs); } }
public WWCP_Net_JSON_IO_Tests() { HTTPAPI = new HTTPServer<RoamingNetworks, RoamingNetwork>( TCPPort: IPPort.Parse(8000), DefaultServerName: "GraphDefined WWCP Unit Tests", DNSClient: new DNSClient(SearchForIPv6DNSServers: false) ); HTTPAPI.AttachTCPPort(IPPort.Parse(8001)); //WWCPAPI = OpenChargingCloudAPI.AttachToHTTPAPI(HTTPAPI); HTTPAPI.Start(); //var RN_1 = WWCPAPI.CreateNewRoamingNetwork(RoamingNetworkId: RoamingNetwork_Id.Parse("TEST_RN1"), // Description: I18NString.Create(Languages.de, "Test Roaming Netz 1"). // Add(Languages.en, "Test roaming network 1")); //var RN_2 = WWCPAPI.CreateNewRoamingNetwork(Hostname: HTTPHostname.Parse("virtualhost"), // RoamingNetworkId: RoamingNetwork_Id.Parse("TEST_RN2"), // Description: I18NString.Create(Languages.de, "Test Roaming Netz 2"). // Add(Languages.en, "Test roaming network 2")); //var CPO_1 = RN_1.CreateNewEVSEOperator(EVSEOperatorId: EVSEOperator_Id.Parse("DE*GEF"), // Name: I18NString.Create(Languages.de, "GraphDefined"), // Description: I18NString.Create(Languages.de, "GraphDefined Test EVSE Operator"), // Configurator: evseoperator => { // evseoperator.DataLicense = DataLicenses.OpenDatabaseLicense; // }); //var Pool_1 = CPO_1.CreateNewChargingPool(ChargingPoolId: ChargingPool_Id.Parse(CPO_1.Id, "1111"), // Configurator: pool => { // pool.Address = new Address(Country.Germany, // "07749", // I18NString.Create(Languages.de, "Jena"), // "Biberweg", "18"); // }); //var Pool_2 = CPO_1.CreateNewChargingPool(ChargingPoolId: ChargingPool_Id.Parse(CPO_1.Id, "2222"), // Configurator: pool => { // pool.Address = new Address(Country.Germany, // "07749", // I18NString.Create(Languages.de, "Jena"), // "Biberweg", "18"); // }); //var Pool_3 = CPO_1.CreateNewChargingPool(ChargingPoolId: ChargingPool_Id.Parse(CPO_1.Id, "3333"), // Configurator: pool => { // pool.Address = new Address(Country.Germany, // "07749", // I18NString.Create(Languages.de, "Jena"), // "Biberweg", "18"); // }); //var Sta1_P1 = Pool_1.CreateNewStation(ChargingStationId: ChargingStation_Id.Parse(CPO_1.Id, "11115678"), // Configurator: station => { // }); }
public void Stop() { TCPServer?.Stop(); UDPServer?.Stop(); HTTPServer?.Stop(); WebSocketServer?.Stop(); }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync( Microsoft.ApplicationInsights.WindowsCollectors.Metadata | Microsoft.ApplicationInsights.WindowsCollectors.Session); this.InitializeComponent(); this.Suspending += OnSuspending; logModel.AppendLog(Log.CreateLog("Local Webserver starting...", Log.LogType.System)); webServer = new HTTPServer(); webServer.Initialise(); logModel.AppendLog(Log.CreateLog("Local Webserver initialized", Log.LogType.System)); Messenger.Default.Register <RefreshDashboardMessage>(this, (mess) => { var frame = Window.Current.Content as Frame; if (frame != null) { Type currentPage = frame.SourcePageType; if (currentPage == typeof(MainPage)) { App.TryShowNewWindow <MainPage>(); } } }); }
public void Main(string[] args) { HTTPServer server = new HTTPServer(); server.Start(); /* SqlConnection cnn; //string connectionString = (@"Data Source=localhost; Initial Catalog=ContosoUniversity1; Integrated Security=True"); string connectionString = "Data Source=(LocalDb)\\v11.0;AttachDBFilename=C:\\Users\\v-honguy\\Documents\\Visual Studio 2015\\Projects\\ContosoUniversity\\ContosoUniversity\\App_Data\\ContosoUniversity1.mdf;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;"; cnn = new SqlConnection(connectionString); try { cnn.Open(); Console.WriteLine("Connection Open ! "); cnn.Close(); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("Can not open connection ! "); Console.ReadLine(); } */ }
/// <summary> /// Initialize the OCPI HTTP server using IPAddress.Any, http port 8080 and maybe start the server. /// </summary> internal GenericAPI(RoamingNetwork RoamingNetwork, HTTPServer HTTPServer, String URIPrefix = "/ext/OCPI", Func <String, Stream> GetRessources = null, String ServiceName = DefaultHTTPServerName, EMailAddress APIEMailAddress = null, PgpPublicKeyRing APIPublicKeyRing = null, PgpSecretKeyRing APISecretKeyRing = null, String APIPassphrase = null, EMailAddressList APIAdminEMail = null, SMTPClient APISMTPClient = null, String LogfileName = DefaultLogfileName) { #region Initial checks if (RoamingNetwork == null) { throw new ArgumentNullException("RoamingNetwork", "The given parameter must not be null!"); } if (HTTPServer == null) { throw new ArgumentNullException("HTTPServer", "The given parameter must not be null!"); } if (URIPrefix.IsNullOrEmpty()) { throw new ArgumentNullException("URIPrefix", "The given parameter must not be null or empty!"); } if (!URIPrefix.StartsWith("/")) { URIPrefix = "/" + URIPrefix; } #endregion #region Init data this._HTTPServer = HTTPServer; this._GetRessources = GetRessources; this._URIPrefix = URIPrefix; this._ServiceName = ServiceName; this._APIEMailAddress = APIEMailAddress; this._APIPublicKeyRing = APIPublicKeyRing; this._APISecretKeyRing = APISecretKeyRing; this._APIPassphrase = APIPassphrase; this._APIAdminEMail = APIAdminEMail; this._APISMTPClient = APISMTPClient; this._DNSClient = HTTPServer.DNSClient; #endregion RegisterURITemplates(); }
static void Main(string[] args) { System.Console.WriteLine("Starting a server..."); HTTPServer server = new HTTPServer(8086); server.Start(); }
[Test] // Test if the function ReadStream gets the right text from the StreamReader public void ReadStreamTest() { //arrange var myStream = new Mock <ITcpClient>(); //create my new StreamReader with my own text string testString = "GET /messages HTTP/1.1"; UTF8Encoding encoding = new UTF8Encoding(); UnicodeEncoding uniEncoding = new UnicodeEncoding(); byte[] testArray = encoding.GetBytes(testString); MemoryStream ms = new MemoryStream(testArray); StreamReader sr = new StreamReader(ms); //mock the GetStreamReader Function to return my selfmade Streamreader myStream .Setup(c => c.GetStreamReader()) .Returns(sr); //act HTTPServer myServer = new HTTPServer(myStream.Object); string actual = myServer.ReadStream(); //assert Assert.AreEqual(testString, actual); }
public void HandleClient_PostNewMessage_ChecksInternalResponse() { // Arrange var memory = new MemoryStream(); var writer = new StreamWriter(memory) { AutoFlush = true }; String requestAllMessagesRead = "POST /messages HTTP/1.1\r\n" + "Host: localhost:10001\r\n" + "User-Agent: curl/7.55.1\r\n" + "Accept: */*\r\n" + "Content-type: application/json\r\n\r\n" + "New Content goes here"; writer.Write(requestAllMessagesRead); memory.Position = 0; var mockClient = new Mock <IMyTcpClient>(); mockClient.Setup(x => x.GetStream()).Returns(memory); // Act var server = new HTTPServer(8080); server.HandleClient(mockClient.Object); // Assert Assert.AreEqual(server.Response.GetStatus(), "200 OK"); Assert.AreEqual(server.Response.GetMimeType(), "text/plain"); Assert.AreEqual(server.Response.GetMessage(), "Successfully posted message: \n\nNew Content goes here"); }
static void Main(string[] args) { HTTPServer server = new HTTPServer((Request request, NetworkStream clientStream) => { lock (dummyobject) { request.Display(ConsoleColor.Yellow); } RequestHandler handler = new RequestHandler(); Response response = handler.HandleRequest(request); response.AddHeader("Content-Type", "text"); response.AddHeader("Server", "my shitty laptop"); response.AddHeader("Date", DateTime.Today.ToString()); lock (dummyobject) { response.Display(ConsoleColor.Green); Console.WriteLine("----------------------------------------------------------------------------------\n"); } response.Send(clientStream); }); server.Start(Config.LISTENINGPORT); }
/// <summary> /// Return the RAW request header. /// </summary> public static void RegisterRAWRequestHandler(this HTTPServer HTTPServer, HTTPHostname Hostname, String URITemplate, HTTPMethod HTTPMethod = null) { HTTPServer.AddMethodCallback(Hostname, HTTPMethod: HTTPMethod ?? HTTPMethod.GET, URITemplate: URITemplate, HTTPDelegate: async Request => { return(new HTTPResponseBuilder(Request) { HTTPStatusCode = HTTPStatusCode.OK, Server = HTTPServer.DefaultServerName, Date = DateTime.Now, CacheControl = "no-cache", Connection = "close", ContentType = HTTPContentType.TEXT_UTF8, Content = ("Incoming http connection from '" + Request.RemoteSocket + "'" + Environment.NewLine + Environment.NewLine + Request.RawHTTPHeader + Environment.NewLine + Environment.NewLine + "Method => " + Request.HTTPMethod + Environment.NewLine + "URL => " + Request.URI + Environment.NewLine + "QueryString => " + Request.QueryString + Environment.NewLine + "Protocol => " + Request.ProtocolName + Environment.NewLine + "Version => " + Request.ProtocolVersion + Environment.NewLine).ToUTF8Bytes() }); }); }
public static void ITEM_EXISTS <TId, TItem>(this HTTPServer HTTPServer, HTTPPath UriTemplate, ParseIdDelegate <TId> ParseIdDelegate, Func <String, String> ParseIdError, TryGetItemDelegate <TId, TItem> TryGetItemDelegate, ItemFilterDelegate <TItem> ItemFilterDelegate, Func <TId, String> TryGetItemError, String HTTPServerName = HTTPServer.DefaultHTTPServerName) { HTTPServer.AddMethodCallback(HTTPHostname.Any, HTTPMethod.EXISTS, UriTemplate, HTTPContentType.JSON_UTF8, HTTPDelegate: async Request => { if (!ParseIdDelegate(Request.ParsedURLParameters[0], out TId Id)) { return new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.BadRequest, Server = HTTPServerName, Date = Timestamp.Now, AccessControlAllowOrigin = "*", AccessControlAllowMethods = "GET, EXISTS, COUNT", AccessControlAllowHeaders = "Content-Type, Accept, Authorization", ETag = "1", ContentType = HTTPContentType.JSON_UTF8, Content = ErrorMessage(ParseIdError(Request.ParsedURLParameters[0])).ToUTF8Bytes(), CacheControl = "no-cache", Connection = "close" } } ; if (!TryGetItemDelegate(Id, out TItem Item) || !ItemFilterDelegate(Item)) { return new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.NotFound, Server = HTTPServerName, Date = Timestamp.Now, ContentType = HTTPContentType.JSON_UTF8, Content = ErrorMessage(TryGetItemError(Id)).ToUTF8Bytes(), CacheControl = "no-cache", Connection = "close" } } ; return(new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.OK, Server = HTTPServerName, Date = Timestamp.Now, ETag = "1", CacheControl = "public", //Expires = "Mon, 25 Jun 2015 21:31:12 GMT", Connection = "close" }); }); }
public string Listen(int port, LuaFunction luaf) { try { return(HTTPServer.Listen(port, (qs, body) => { try { var queryString = Lua.NewTable(); foreach (var key in qs.Keys) { queryString[key] = qs[key]; } var result = luaf.Call(queryString, body); if (result == null || result.Length < 1) { return null; } return result[0].ToString(); } catch (Exception ex) { var err = $"Error running listener function attached to port {port}\nError message: {ex.Message}"; LogOutputCallback(err); return err; } })); } catch (Exception e) { var err = $"Could not start listening on port {port}\n Exception: {e.Message}"; LogOutputCallback(err); return(err); } }
/// <summary> /// Create an instance of the OCPI HTTP API for Charge Point Operators /// using the given HTTP server. /// </summary> public CPOAPI(RoamingNetwork RoamingNetwork, HTTPServer HTTPServer, String URIPrefix = "/ext/OCPI", String ServiceName = DefaultHTTPServerName, EMailAddress APIEMailAddress = null, PgpSecretKeyRing APISecretKeyRing = null, String APIPassphrase = null, EMailAddressList APIAdminEMail = null, SMTPClient APISMTPClient = null) : base(RoamingNetwork, HTTPServer, URIPrefix, ResourceName => typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot." + ResourceName), ServiceName, APIEMailAddress, null, //OpenPGP.ReadPublicKeyRing(typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot.About.robot@offenes-jena_pubring.gpg")), APISecretKeyRing, APIPassphrase, APIAdminEMail, APISMTPClient, LogfileName) { RegisterCPOURITemplates(); }
static void Main(string[] args) { Console.WriteLine("Initializing dapp server"); // either parse the settings from the program args or initialize them manually var settings = ServerSettings.Parse(args); var server = new HTTPServer(settings, ConsoleLogger.Write); Console.WriteLine("Starting Phantasma Dapp samples at port " + settings.Port); server.Get("/", (request) => { return(HTTPResponse.FromString("Hello world!")); }); Console.CancelKeyPress += delegate { server.Stop(); }; // uncomment this line to enable sample connector, comment if you want to use Poltergeist or Phantom new Thread(() => RunConnector()).Start(); server.Run(); }
public RPCServer(NexusAPI api, string endPoint, int port, LoggerCallback logger = null) { if (string.IsNullOrEmpty(endPoint)) { endPoint = "/"; } Port = port; EndPoint = endPoint; API = api; var settings = new ServerSettings() { Environment = ServerEnvironment.Prod, Port = port, MaxPostSizeInBytes = 1024 * 128, Compression = false }; _server = new HTTPServer(settings, logger); var rpc = new RPCPlugin(_server, endPoint); foreach (var entry in api.Methods) { var methodName = char.ToLower(entry.Name[0]) + entry.Name.Substring(1); var apiMethod = entry; rpc.RegisterHandler(methodName, (paramNode) => { var args = new object[apiMethod.Parameters.Count]; for (int i = 0; i < args.Length; i++) { if (i < paramNode.ChildCount) { args[i] = paramNode.GetNodeByIndex(i).Value; } else if (apiMethod.Parameters[i].HasDefaultValue) { args[i] = apiMethod.Parameters[i].DefaultValue; } else { throw new RPCException("missing argument: " + apiMethod.Parameters[i].Name); } } IAPIResult result; try { result = api.Execute(apiMethod.Name, args); } catch (APIException e) { throw new RPCException(e.Message); } CheckForError(result); return(APIUtils.FromAPIResult(result)); }); } }
public ViewsRenderer(HTTPServer server, string viewsPath) { if (server == null) { throw new ArgumentNullException(nameof(server)); } TemplateEngine = new TemplateEngine(server, viewsPath); }
static void Main(string[] args) { HTTPServer server = new HTTPServer(10001); Console.WriteLine("Server running"); Console.WriteLine("Waiting for a connection... "); server.start(); }
private static void Start() { Console.Title = "Akarr's steambot"; Console.ForegroundColor = ConsoleColor.White; Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); config = new Config(); if (!config.LoadConfig()) { Console.WriteLine("Config file (config.cfg) can't be found or is corrupted ! Bot can't start."); Console.ReadKey(); return; } PrintWelcomeMessage(); Updater updater = new Updater(config.DisableAutoUpdate, BUILD_VERSION); LoadModules(); Task.WaitAll(updater.Update()); httpsrv = new HTTPServer(config.WebinterfacePort); httpsrv.Listen(); if (config.DisplayLocation) { SendLocation(); } steambotManager = new Manager(config); threadManager = new Thread(new ThreadStart(steambotManager.Start)); threadManager.CurrentUICulture = new CultureInfo("en-US"); threadManager.Start(); AttemptLoginBot(config.SteamUsername, config.SteamPassword, config.SteamAPIKey); while (steambotManager.OnlineBots.Count < 1) { Thread.Sleep(TimeSpan.FromSeconds(3)); } steambotManager.SelectFirstBot(); string command = ""; do { Console.Write("> "); command = Console.ReadLine(); steambotManager.Command(command); } while(command != "quit"); httpsrv.Stop(); steambotManager.Stop(); }
public static void ITEM_GET <TId, TItem>(this HTTPServer HTTPServer, HTTPPath UriTemplate, ParseIdDelegate <TId> ParseIdDelegate, Func <String, String> ParseIdError, TryGetItemDelegate <TId, TItem> TryGetItemDelegate, ItemFilterDelegate <TItem> ItemFilterDelegate, Func <TId, String> TryGetItemError, ItemToJSONDelegate <TItem> ToJSONDelegate) { HTTPServer.AddMethodCallback(HTTPHostname.Any, HTTPMethod.GET, UriTemplate, HTTPContentType.JSON_UTF8, HTTPDelegate: async Request => { TId Id; TItem Item; if (!ParseIdDelegate(Request.ParsedURLParameters[0], out Id)) { return new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.BadRequest, Server = HTTPServer.DefaultServerName, ContentType = HTTPContentType.JSON_UTF8, Content = ErrorMessage(ParseIdError(Request.ParsedURLParameters[0])).ToUTF8Bytes(), CacheControl = "no-cache", Connection = "close" } } ; if (!TryGetItemDelegate(Id, out Item) || !ItemFilterDelegate(Item)) { return new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.NotFound, Server = HTTPServer.DefaultServerName, ContentType = HTTPContentType.JSON_UTF8, Content = ErrorMessage(TryGetItemError(Id)).ToUTF8Bytes(), CacheControl = "no-cache", Connection = "close" } } ; return(new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.OK, Server = HTTPServer.DefaultServerName, ContentType = HTTPContentType.JSON_UTF8, Content = ToJSONDelegate(Item).ToUTF8Bytes(), ETag = "1", CacheControl = "public", //Expires = "Mon, 25 Jun 2015 21:31:12 GMT", Connection = "close" }); }); }
public static void InitHTTPServer( Dictionary <string, HTTPServer.RequestHandler> routes) { int startingPort = 2871; HttpHandlerSetup.Server = HTTPUtils.SetupServer(startingPort, startingPort + 10, routes, string.Empty); RegistryManager.Instance.PartnerServerPort = HttpHandlerSetup.Server.Port; HttpHandlerSetup.Server.Run(); }
private void RegisterURITemplates() { #region PUT ~/* // curl -X PUT http://127.0.0.1:9901/diagnostics/test.log -T test.log HTTPServer.AddMethodCallback(HTTPHostname.Any, HTTPMethod.PUT, URLPathPrefix + "{file}", HTTPDelegate: async Request => { try { var filepath = Request.Path.ToString().Replace("..", ""); var filename = filepath.Substring(filepath.LastIndexOf("/") + 1); var file = File.Create(filename); var data = Request.HTTPBody; await file.WriteAsync(data, 0, data.Length); DebugX.Log("UploadAPI: Received file '" + filename + "'!"); return new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.Created, Server = DefaultHTTPServerName, Date = Timestamp.Now, AccessControlAllowOrigin = "*", AccessControlAllowMethods = "PUT", Connection = "close" }; } catch (Exception e) { DebugX.Log("UploadAPI: Could not received file: " + e.Message); return new HTTPResponse.Builder(Request) { HTTPStatusCode = HTTPStatusCode.InternalServerError, Server = DefaultHTTPServerName, Date = Timestamp.Now, AccessControlAllowOrigin = "*", AccessControlAllowMethods = "PUT", ContentType = HTTPContentType.TEXT_UTF8, Content = e.Message.ToUTF8Bytes(), Connection = "close" }; } }); #endregion }
private void HTTPServerThread(TelemetryData telemetryData, TimingData timingData, IPAddress ipAddress, int port, string httpServerPath, Dictionary <string, IGame> plugins) { _httpServer = new HTTPServer(httpServerPath, port, telemetryData, timingData, ipAddress, plugins); _httpServer.Start(); while (true) { Thread.Sleep(1); } }
public void AuthorizeDomains(String[] domains) { using (HTTPServer httpserver = new HTTPServer()) { httpserver.Listen(80); HTTPPathSelector httprouter = new HTTPPathSelector(); httpserver.ContentProvider = httprouter; AuthorizeDomains(domains, httprouter); } }
private void CreateServer(int port) { Debug.Assert(_server == null || !_server.IsRunning); _server = new HTTPServer(_factory, port); _server.OnServerStart += new HTTPServer.ServerStarted(_server_OnServerStart); _server.OnServerStop += new HTTPServer.ServerStopped(_server_OnServerStop); _server.OnServerException += new HTTPServer.ServerCaughtException(_server_OnServerException); }
/// <summary> /// Register a MovedTemporarily handler. /// </summary> public static void RegisterMovedTemporarilyHandler(this HTTPServer HTTPServer, HTTPHostname Hostname, String URITemplate, String URITarget) { HTTPServer.AddMethodCallback(Hostname, HTTPMethod.GET, URITemplate, HTTPDelegate: async Request => HTTPTools.MovedTemporarily(Request, URITarget)); }
public ViewsRenderer(HTTPServer server, string viewsPath) { if (server == null) { throw new ArgumentNullException(nameof(server)); } TemplateEngine = new TemplateEngine(server, viewsPath); Console.WriteLine(TemplateEngine.ToString()); Console.WriteLine(server.Settings.Path); }
public static void InitHTTPServer( Dictionary <string, HTTPServer.RequestHandler> routes, string vmName) { int frontendServerPort = RegistryManager.Instance.Guest[vmName].FrontendServerPort; HttpHandlerSetup.Server = HTTPUtils.SetupServer(frontendServerPort, frontendServerPort + 40, routes, string.Empty); HttpHandlerSetup.SetFrontendPortInBootParams(HttpHandlerSetup.Server.Port, vmName); RegistryManager.Instance.Guest[vmName].FrontendServerPort = HttpHandlerSetup.Server.Port; HttpHandlerSetup.Server.Run(); }
public TestApp() { HTTPServer <SessionData> server = new HTTPServer <SessionData>(8080, "../../"); AjaxHandler <SessionData> handler = new AjaxHandler <SessionData>(server); handler.AddClass <TestApp>(); File.Delete("../../ajax.js"); File.WriteAllText("../../ajax.js", handler.GetJavascript()); server.Start(); }
public static void ITEMS_GET <TId, TItem>(this HTTPServer HTTPServer, HTTPPath UriTemplate, Dictionary <TId, TItem> Dictionary, ItemFilterDelegate <TItem> Filter, ItemsToJSONDelegate <TItem> ToJSONDelegate) { GET_ITEMS(HTTPServer, UriTemplate, Dictionary.Select(kvp => kvp.Value), Filter, ToJSONDelegate); }
/// <summary> /// Main. /// </summary> /// <param name="myArgs">The arguments.</param> public static void Main(String[] myArgs) { #region Start the HTTPServer var _HTTPServer = new HTTPServer<ILokiHTML5Service>(IPv4Address.Any, IPPort.HTTP, Autostart: true) { ServerName = "Loki HTML5 Demo" }; Console.WriteLine(_HTTPServer); #endregion var _Random = new Random(); var _CancellationTokenSource = new CancellationTokenSource(); var _EventSource = _HTTPServer.URLMapping.EventSource("GraphEvents"); var _SubmitTask = Task.Factory.StartNew(() => { while (!_CancellationTokenSource.IsCancellationRequested) { _EventSource.Submit("vertexadded", "{\"radius\": " + _Random.Next(5, 50) + ", \"x\": " + _Random.Next(50, 550) + ", \"y\": ", _Random.Next(50, 350) + "}"); Thread.Sleep(1000); } }, _CancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); Console.ReadLine(); _CancellationTokenSource.Cancel(); Console.WriteLine("done!"); }
private static SerialPort UART4 = new SerialPort("COM4", 9600); //Sump #endregion Fields #region Methods public static void Main() { Debug.EnableGCMessages(false); Debug.Print(""); Debug.Print(""); Debug.Print(constAppName + " : Startup..."); Debug.Print("Free mem : " + Debug.GC(false).ToString()); // set system time SetSystemTime(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); // initialize and mount SD card MountSDCard(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); // load appSettings appSettings = new AppSettings(); LoadAppSettings(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); // initialize fezConnect fezConnect = new FEZConnect(); InitializeFezConnect(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); // initialize network if (fezConnect.DeviceStatus == FEZConnect.DevStatus.Ready) { InitializeNetwork(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); } // set clock from NTP server if (fezConnect.NetworkStatus == FEZConnect.NetStatus.Ready && appSettings.NTPEnabled) { SetClockFromNTPTime(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); } // start http server if (fezConnect.NetworkStatus == FEZConnect.NetStatus.Ready && appSettings.HTTPEnabled) { httpServer = new HTTPServer(); httpServer.HttpStatusChanged += new HTTPServer.HttpStatusChangedHandler(httpServer_HttpStatusChanged); RegisterHTTPEventHandlers(); Debug.GC(true); Debug.Print("Free mem : " + Debug.GC(false).ToString()); StartHTTPServer(); Debug.GC(true); } // run application //readOWbus(); Thread Timer = new Thread(CheckTime); Timer.Start(); Debug.GC(true); Thread Temps = new Thread(Temp); Temps.Start(); Debug.GC(true); // this is the main program loop rebootTime = DateTime.MaxValue; while (true) { // check for reboot if (DateTime.Now >= rebootTime) { rebootTime = DateTime.MaxValue; ; RebootDevice(); Debug.GC(true); } // your application code goes here // sleep 1 sec Thread.Sleep(1000); } }
private static void FileWasChanged(HTTPServer source, String HTTPSSE_EventIdentification, String ChangeType, String FileName) { source. GetEventSource(HTTPSSE_EventIdentification). SubmitSubEvent(ChangeType, @"{ ""timestamp"": """ + DateTime.Now.ToIso8601() + @""", ""filename"": """ + FileName + @""" }"); }
private static void TankSettingsPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } if (e.HttpRequest.HttpMethod.ToLower() == "post") { if (e.PostParams.Contains("rTemp")) { rTemp = !rTemp; Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } if (e.PostParams.Contains("rPH")) { rPH = !rPH; Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } if (e.PostParams.Contains("rTimer")) { rTimer = !rTimer; Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } if (e.PostParams.Contains("test")) { rTimer = false; Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("mPump")) { if (UART3.IsOpen == true) { UART3.Close(); mPump = true; } else { UART3.Open(); mPump = false; } Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } if (e.PostParams.Contains("sPump")) { if (UART4.IsOpen == true) { UART4.Close(); sPump = true; } else { UART4.Open(); sPump = false; } Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } if (e.PostParams.Contains("fPump")) { if (UART2.IsOpen == true) { UART2.Close(); fPump = true; } else { UART2.Open(); fPump = false; } // this is how it should work with any pin, but the voltage doesn't go high enough for it to work //if (UART2.Read() == true) //{ // UART2.Write(false); // fPump = true; //} //else //{ // UART2.Write(true); // fPump = false; //} Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } } // return page Hashtable tokens = new Hashtable() { {"appName", constAppName}, {"rTemp", rTemp ? "On" : "Off"}, {"rPH", rPH ? "On" : "Off"}, {"rTimer", rTimer ? "On" : "Off"}, {"mPump", mPump ? "On" : "Off"}, {"sPump", sPump ? "On" : "Off"}, {"fPump", fPump ? "On" : "Off"}, }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constTankSettingsPageFileName, tokens); Debug.GC(true); }
private static void httpServer_HttpStatusChanged(HTTPServer.HTTPStatus httpStatus, string message) { Debug.Print(constAppName + " : Http status : " + httpServer.StatusName + (message.Length > 0 ? " : " + message : "")); Debug.Print("Free mem : " + Debug.GC(false).ToString()); }
private static void DevicePageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } Hashtable tokens = new Hashtable() { {"appName", constAppName}, {"software", "Version " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()}, {"firmware", "Version " + SystemInfo.Version}, {"dateTime", DateTime.Now.ToString()}, {"lastReboot", lastRebootTime.ToString() + " (" + (fezConnect.LastResetCause == GHIElectronics.NETMF.Hardware.LowLevel.Watchdog.ResetCause.WatchdogReset ? "Watchdog" : "Power Up") + ")"}, {"availMemory", Debug.GC(false).ToString("n0") + " bytes"}, {"boardNow", temp3.ToString("F3")}, {"voltage", ((float)Battery.ReadVoltage()/1000).ToString("f") + " volts"}, {"rtcOK", (rtcIsWorking ? "" : "Not ") + "Working"}, {"sdCard", (SDCard.IsMounted ? "Mounted" : "Not Mounted")}, {"host", appSettings.HostName}, {"mac", appSettings.MACAddress}, {"ip", NetUtils.IPBytesToString(NetworkInterface.IPAddress)}, {"mask", NetUtils.IPBytesToString(NetworkInterface.SubnetMask)}, {"gateway", NetUtils.IPBytesToString(NetworkInterface.GatewayAddress)}, {"dns", NetUtils.IPBytesToString(NetworkInterface.DnsServer)}, {"restarts", httpServer.HttpRestarts.ToString()}, {"requests", httpServer.HttpRequests.ToString()}, {"404Hits", httpServer.Http404Hits.ToString()} }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constDevicePageFileName, tokens); Debug.GC(true); }
private static void TankStatusPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } if (e.HttpRequest.HttpMethod.ToLower() == "post") { if (e.PostParams.Contains("feed")) { Thread Food = new Thread(Feed); Food.Start(); Debug.GC(true); e.ResponseRedirectTo = constTankStatusPageFileName; return; } if (e.PostParams.Contains("resetT")) { highProbe1 = 1; highProbe2 = 1; lowProbe1 = 30; lowProbe2 = 30; Debug.GC(true); e.ResponseRedirectTo = constTankStatusPageFileName; return; } if (e.PostParams.Contains("resetPH")) { highPH = 3; lowPH = 10; Debug.GC(true); e.ResponseRedirectTo = constTankStatusPageFileName; return; } } Hashtable tokens = new Hashtable() { {"appName", constAppName}, {"dateTime", DateTime.Now.ToString("T")}, {"tankNow", temp1.ToString("F3")}, {"sumpNow", temp2.ToString("F3")}, {"phNow", "NA"}, {"tankHighT", highProbe1.ToString("F3")}, {"tankLowT", lowProbe1.ToString("F3")}, {"sumpHighT", highProbe2.ToString("F3")}, {"sumpLowT", lowProbe2.ToString("F3")}, {"highPH", "NA"}, {"lowPH", "NA"}, }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constTankStatusPageFileName, tokens); Debug.GC(true); }
/// <summary> /// Initialize the OCPI HTTP server using IPAddress.Any, http port 8080 and maybe start the server. /// </summary> internal GenericAPI(RoamingNetwork RoamingNetwork, HTTPServer HTTPServer, String URIPrefix = "/ext/OCPI", Func<String, Stream> GetRessources = null, String ServiceName = DefaultHTTPServerName, EMailAddress APIEMailAddress = null, PgpPublicKeyRing APIPublicKeyRing = null, PgpSecretKeyRing APISecretKeyRing = null, String APIPassphrase = null, EMailAddressList APIAdminEMail = null, SMTPClient APISMTPClient = null, String LogfileName = DefaultLogfileName) { #region Initial checks if (RoamingNetwork == null) throw new ArgumentNullException("RoamingNetwork", "The given parameter must not be null!"); if (HTTPServer == null) throw new ArgumentNullException("HTTPServer", "The given parameter must not be null!"); if (URIPrefix.IsNullOrEmpty()) throw new ArgumentNullException("URIPrefix", "The given parameter must not be null or empty!"); if (!URIPrefix.StartsWith("/")) URIPrefix = "/" + URIPrefix; #endregion #region Init data this._HTTPServer = HTTPServer; this._GetRessources = GetRessources; this._URIPrefix = URIPrefix; this._ServiceName = ServiceName; this._APIEMailAddress = APIEMailAddress; this._APIPublicKeyRing = APIPublicKeyRing; this._APISecretKeyRing = APISecretKeyRing; this._APIPassphrase = APIPassphrase; this._APIAdminEMail = APIAdminEMail; this._APISMTPClient = APISMTPClient; this._DNSClient = HTTPServer.DNSClient; #endregion RegisterURITemplates(); }
/// <summary> /// Create a new HTTP API logger using the default logging delegates. /// </summary> /// <param name="HTTPAPI">A HTTP API.</param> /// <param name="Context">A context of this API.</param> public HTTPLogger(HTTPServer HTTPAPI, String Context = "") : this(HTTPAPI, Context, null, null, null, null) { }
private static void SettingsPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } // save appSettings string msg = ""; if (e.HttpRequest.HttpMethod.ToLower() == "post" && e.PostParams != null) { if (e.PostParams.Contains("pwd") && (string)e.PostParams["pwd"] == appSettings.Password) { if (e.PostParams.Contains("save")) { // save appSettings bool saved = false; try { appSettings.HostName = (string)e.PostParams["host"]; appSettings.MACAddress = (string)e.PostParams["mac"]; appSettings.DHCPEnabled = (e.PostParams.Contains("dhcpEnabled") ? true : false); appSettings.IPAddress = (string)e.PostParams["ip"]; appSettings.IPMask = (string)e.PostParams["mask"]; appSettings.IPGateway = (string)e.PostParams["gateway"]; appSettings.DNSAddress = (string)e.PostParams["dns"]; appSettings.NTPEnabled = (e.PostParams.Contains("ntpEnabled") ? true : false); appSettings.NTPServer = (string)e.PostParams["ntpServer"]; appSettings.NTPOffset = (string)e.PostParams["ntpOffset"]; appSettings.HTTPEnabled = (e.PostParams.Contains("httpEnabled") ? true : false); appSettings.HTTPPort = (string)e.PostParams["httpPort"]; if (((string)e.PostParams["npwd"]).Length > 0) { appSettings.Password = (string)e.PostParams["npwd"]; } if (appSettings.SaveToFlash()) { saved = true; } else { msg = "Error saving settings : " + appSettings.LastErrorMsg; } } catch (Exception ex) { msg = "Error saving settings : " + ex.Message; } Debug.GC(true); // enable restart if (saved) { lock (threadLockObject) { rebootTime = DateTime.Now.AddSeconds(30); } // redirect to restarting page e.ResponseRedirectTo = constRestartPageFileName; return; } } } else { // invalid password msg = "Invalid password. Please try again."; } } // return page Hashtable tokens = new Hashtable() { {"appName", constAppName}, {"host", appSettings.HostName}, {"mac", appSettings.MACAddress}, {"dhcpEnabled", (appSettings.DHCPEnabled ? "checked" : "")}, {"ip", appSettings.IPAddress}, {"mask", appSettings.IPMask}, {"gateway", appSettings.IPGateway}, {"dns", appSettings.DNSAddress}, {"ntpEnabled", (appSettings.NTPEnabled ? "checked" : "")}, {"ntpServer", appSettings.NTPServer}, {"ntpOffset", appSettings.NTPOffset.ToString()}, {"httpEnabled", (appSettings.HTTPEnabled ? "checked" : "")}, {"httpPort", appSettings.HTTPPort.ToString()}, {"pwd", ""}, {"npwd", ""}, {"msg", msg} }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constSettingsPageFileName, tokens); Debug.GC(true); }
/// <summary> /// Create an instance of the OCPI HTTP API for Charge Point Operators /// using the given HTTP server. /// </summary> public CPOAPI(RoamingNetwork RoamingNetwork, HTTPServer HTTPServer, String URIPrefix = "/ext/OCPI", String ServiceName = DefaultHTTPServerName, EMailAddress APIEMailAddress = null, PgpSecretKeyRing APISecretKeyRing = null, String APIPassphrase = null, EMailAddressList APIAdminEMail = null, SMTPClient APISMTPClient = null) : base(RoamingNetwork, HTTPServer, URIPrefix, ResourceName => typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot." + ResourceName), ServiceName, APIEMailAddress, null, //OpenPGP.ReadPublicKeyRing(typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot.About.robot@offenes-jena_pubring.gpg")), APISecretKeyRing, APIPassphrase, APIAdminEMail, APISMTPClient, LogfileName) { RegisterCPOURITemplates(); }
/// <summary> /// Main. /// </summary> /// <param name="myArgs">The arguments.</param> public static void Main(String[] myArgs) { #region Start TCPServers //var _TCPServer1 = new TCPServer(new IPv4Address(new Byte[] { 192, 168, 178, 31 }), new IPPort(2001), NewConnection => // { // NewConnection.WriteToResponseStream("Hello world!" + Environment.NewLine + Environment.NewLine); // NewConnection.Close(); // }, true); //Console.WriteLine(_TCPServer1); // The first line of the repose will be served from the CustomTCPConnection handler. var _TCPServer2 = new TCPServer<CustomTCPConnection>(IPv4Address.Any, new IPPort(2002), NewConnection => { NewConnection.WriteToResponseStream("...world!" + Environment.NewLine + Environment.NewLine); NewConnection.Close(); }, true); Console.WriteLine(_TCPServer2); #endregion #region Start HTTPServers // Although the socket listens on IPv4Address.Any the service is // configured to serve clients only on http://localhost:8181 // More details within DefaultHTTPService.cs var _HTTPServer1 = new HTTPServer(IPv4Address.Any, new IPPort(8181), Autostart: true) { ServerName = "Default Hermod Demo" }; Console.WriteLine(_HTTPServer1); // This service uses a custom HTTPService defined within IRESTService.cs var _HTTPServer2 = new HTTPServer<IRESTService>(IPv4Address.Any, IPPort.HTTP, Autostart: true) { ServerName = "Customized Hermod Demo" }; Console.WriteLine(_HTTPServer2); #endregion #region UDP Servers var _UDPServer1 = new UDPServer(new IPPort(5555), NewPacket => { //NewPacket.Data = new Byte[10]; // NewPacket.Close(); }, true); #endregion var _client1 = new HTTPClient(IPv4Address.Localhost, IPPort.HTTP); var _request0 = _client1.GET("/HelloWorld"). SetHost("localhorst"). AddAccept(HTTPContentType.TEXT_UTF8, 1); var _request1 = _client1.GET("/HelloWorld"). SetHost("localhorst"). AddAccept(HTTPContentType.HTML_UTF8, 1); //WriteRequest(_request0.EntireRequestHeader); //_client1.Execute(_request0, response => WriteResponse(response.Content.ToUTF8String())). // ContinueWith(HTTPClient => { WriteRequest(_request1.EntireRequestHeader); return HTTPClient.Result; }). // ContinueWith(HTTPClient => HTTPClient.Result.Execute(_request1, response => WriteResponse(response.Content.ToUTF8String()))). // Wait(); var _client2 = new HTTPClient(IPv4Address.Parse("188.40.47.229"), IPPort.HTTP); var _requestA = _client2.GET("/"). SetProtocolVersion(HTTPVersion.HTTP_1_1). SetHost("www.ahzf.de"). SetUserAgent("Hermod HTTP Client v0.1"). SetConnection("keep-alive"). AddAccept(HTTPContentType.HTML_UTF8, 1); var _requestB = _client2.GET("/nfgj"). SetProtocolVersion(HTTPVersion.HTTP_1_1). SetHost("www.ahzf.de"). SetUserAgent("Hermod HTTP Client v0.1"). SetConnection("keep-alive"). AddAccept(HTTPContentType.HTML_UTF8, 1); WriteRequest(_requestA); _client2.Execute(_requestA, response => WriteResponse(response)). ContinueWith(Client => Client.Result.Execute(_requestB, response => WriteResponse(response))); var _req23a = new HTTPRequestBuilder(). SetHTTPMethod (HTTPMethod.GET). SetProtocolName ("µHTTP"). SetProtocolVersion (new HTTPVersion(2, 0)). SetHost ("localhorst"). SetUserAgent ("Hermod µHTTP Client"). SetContent ("This the HTTP content..."); _req23a.QueryString.Add("name", "alice"). Add("friend", "bob"). Add("friend", "carol"); var _req23b = new HTTPRequestBuilder() { HTTPMethod = HTTPMethod.GET, ProtocolName = "µHTTP", ProtocolVersion = new HTTPVersion(2, 0), Host = "localhorst", UserAgent = "Hermod µHTTP Client", Content = "This the HTTP content...".ToUTF8Bytes() }; // var Response = new TCPClientRequest("localhost", 80).Send("GETTT / HTTP/1.1").FinishCurrentRequest().Response; Console.ReadLine(); Console.WriteLine("done!"); }
private static void ColorBalancePageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } if (e.HttpRequest.HttpMethod.ToLower() == "post") { if (e.PostParams.Contains("w+1")) { int wLast = wNow; wNow = System.Math.Min(wNow + 1, 100); Ramp(wLast, wNow, up, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w+5")) { int wLast = wNow; wNow = System.Math.Min(wNow + 5, 100); Ramp(wLast, wNow, up, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w+10")) { int wLast = wNow; wNow = System.Math.Min(wNow + 10, 100); Ramp(wLast, wNow, up, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w+25")) { int wLast = wNow; wNow = System.Math.Min(wNow + 25, 100); Ramp(wLast, wNow, up, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w-1")) { int wLast = wNow; wNow = System.Math.Max(wNow - 1, 0); Ramp(wLast, wNow, down, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w-5")) { int wLast = wNow; wNow = System.Math.Max(wNow - 5, 0); Ramp(wLast, wNow, down, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w-10")) { int wLast = wNow; wNow = System.Math.Max(wNow - 10, 0); Ramp(wLast, wNow, down, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("w-25")) { int wLast = wNow; wNow = System.Math.Max(wNow - 25, 0); Ramp(wLast, wNow, down, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b+1")) { int bLast = bNow; bNow = System.Math.Min(bNow + 1, 100); Ramp(bLast, bNow, up, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b+5")) { int bLast = bNow; bNow = System.Math.Min(bNow + 5, 100); Ramp(bLast, bNow, up, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b+10")) { int bLast = bNow; bNow = System.Math.Min(bNow + 10, 100); Ramp(bLast, bNow, up, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b+25")) { int bLast = bNow; bNow = System.Math.Min(bNow + 25, 100); Ramp(bLast, bNow, up, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b-1")) { int bLast = bNow; bNow = System.Math.Max(bNow - 1, 0); Ramp(bLast, bNow, down, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b-5")) { int bLast = bNow; bNow = System.Math.Max(bNow - 5, 0); Ramp(bLast, bNow, down, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b-10")) { int bLast = bNow; bNow = System.Math.Max(bNow - 10, 0); Ramp(bLast, bNow, down, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("b-25")) { int bLast = bNow; bNow = System.Math.Max(bNow - 25, 0); Ramp(bLast, bNow, down, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v+1")) { int vLast = vNow; vNow = System.Math.Min(vNow + 1, 100); Ramp(vLast, vNow, up, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v+5")) { int vLast = vNow; vNow = System.Math.Min(vNow + 5, 100); Ramp(vLast, vNow, up, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v+10")) { int vLast = vNow; vNow = System.Math.Min(vNow + 10, 100); Ramp(vLast, vNow, up, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v+25")) { int vLast = vNow; vNow = System.Math.Min(vNow + 25, 100); Ramp(vLast, vNow, up, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v-1")) { int vLast = vNow; vNow = System.Math.Max(vNow - 1, 0); Ramp(vLast, vNow, down, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v-5")) { int vLast = vNow; vNow = System.Math.Max(vNow - 5, 0); Ramp(vLast, vNow, down, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v-10")) { int vLast = vNow; vNow = System.Math.Max(vNow - 10, 0); Ramp(vLast, vNow, down, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("v-25")) { int vLast = vNow; vNow = System.Math.Max(vNow - 25, 0); Ramp(vLast, vNow, down, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("resetWhite")) { int wLast = wNow; wNow = 0; Ramp(wLast, wNow, down, 0, white); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("resetBlue")) { int bLast = bNow; bNow = 0; Ramp(bLast, bNow, down, 0, blue); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("resetViolet")) { int vLast = vNow; vNow = 0; Ramp(vLast, vNow, down, 0, violet); Debug.GC(true); e.ResponseRedirectTo = constColorBalancePageFileName; return; } if (e.PostParams.Contains("exit")) { Ramp(0, 0, down, 0, white); Ramp(0, 0, down, 0, blue); Ramp(0, 0, down, 0, violet); wNow = 0; bNow = 0; vNow = 0; rTimer = true; Debug.GC(true); e.ResponseRedirectTo = constTankSettingsPageFileName; return; } } // return page Hashtable tokens = new Hashtable() { {"appName", constAppName}, {"whiteNow", wNow.ToString()}, {"blueNow", bNow.ToString()}, {"violetNow", vNow.ToString()}, }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constColorBalancePageFileName, tokens); Debug.GC(true); }
/// <summary> /// Create a new HTTP API logger using the given logging delegates. /// </summary> /// <param name="HTTPAPI">A HTTP API.</param> /// <param name="Context">A context of this API.</param> /// /// <param name="LogHTTPRequest_toConsole">A delegate to log incoming HTTP requests to console.</param> /// <param name="LogHTTPResponse_toConsole">A delegate to log HTTP requests/responses to console.</param> /// <param name="LogHTTPRequest_toDisc">A delegate to log incoming HTTP requests to disc.</param> /// <param name="LogHTTPResponse_toDisc">A delegate to log HTTP requests/responses to disc.</param> /// /// <param name="LogHTTPRequest_toNetwork">A delegate to log incoming HTTP requests to a network target.</param> /// <param name="LogHTTPResponse_toNetwork">A delegate to log HTTP requests/responses to a network target.</param> /// <param name="LogHTTPRequest_toHTTPSSE">A delegate to log incoming HTTP requests to a HTTP server sent events source.</param> /// <param name="LogHTTPResponse_toHTTPSSE">A delegate to log HTTP requests/responses to a HTTP server sent events source.</param> /// /// <param name="LogHTTPError_toConsole">A delegate to log HTTP errors to console.</param> /// <param name="LogHTTPError_toDisc">A delegate to log HTTP errors to disc.</param> /// <param name="LogHTTPError_toNetwork">A delegate to log HTTP errors to a network target.</param> /// <param name="LogHTTPError_toHTTPSSE">A delegate to log HTTP errors to a HTTP server sent events source.</param> /// /// <param name="LogFileCreator">A delegate to create a log file from the given context and log file name.</param> public HTTPLogger(HTTPServer HTTPAPI, String Context, HTTPRequestLoggerDelegate LogHTTPRequest_toConsole, HTTPResponseLoggerDelegate LogHTTPResponse_toConsole, HTTPRequestLoggerDelegate LogHTTPRequest_toDisc, HTTPResponseLoggerDelegate LogHTTPResponse_toDisc, HTTPRequestLoggerDelegate LogHTTPRequest_toNetwork = null, HTTPResponseLoggerDelegate LogHTTPResponse_toNetwork = null, HTTPRequestLoggerDelegate LogHTTPRequest_toHTTPSSE = null, HTTPResponseLoggerDelegate LogHTTPResponse_toHTTPSSE = null, HTTPResponseLoggerDelegate LogHTTPError_toConsole = null, HTTPResponseLoggerDelegate LogHTTPError_toDisc = null, HTTPResponseLoggerDelegate LogHTTPError_toNetwork = null, HTTPResponseLoggerDelegate LogHTTPError_toHTTPSSE = null, Func<String, String, String> LogFileCreator = null) : this(Context, LogHTTPRequest_toConsole, LogHTTPResponse_toConsole, LogHTTPRequest_toDisc, LogHTTPResponse_toDisc, LogHTTPRequest_toNetwork, LogHTTPResponse_toNetwork, LogHTTPRequest_toHTTPSSE, LogHTTPResponse_toHTTPSSE, LogHTTPError_toConsole, LogHTTPError_toDisc, LogHTTPError_toNetwork, LogHTTPError_toHTTPSSE, LogFileCreator) { #region Initial checks if (HTTPAPI == null) throw new ArgumentNullException(nameof(HTTPAPI), "The given HTTP API must not be null!"); this._HTTPAPI = HTTPAPI; #endregion //ToDo: Evaluate Logging targets! HTTPAPI.ErrorLog += (Timestamp, HTTPServer, HTTPRequest, HTTPResponse, Error, LastException) => { DebugX.Log(Timestamp + " - " + HTTPRequest.RemoteSocket.IPAddress + ":" + HTTPRequest.RemoteSocket.Port + " " + HTTPRequest.HTTPMethod + " " + HTTPRequest.URI + " " + HTTPRequest.ProtocolVersion + " => " + HTTPResponse.HTTPStatusCode + " - " + Error); }; }
private static void RestartPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } Hashtable tokens = new Hashtable() { {"appName", constAppName} }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constRestartPageFileName, tokens); Debug.GC(true); }
public void Init_HTTPServer() { _HTTPServer = new HTTPServer();// (IPv4Address.Any, new IPPort(81), Autostart: true); }
private static void TankTimersPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } // save appSettings string msg = ""; if (e.HttpRequest.HttpMethod.ToLower() == "post" && e.PostParams != null) { if (e.PostParams.Contains("pwd") && (string)e.PostParams["pwd"] == appSettings.Password) { if (e.PostParams.Contains("save")) { // save appSettings bool saved = false; try { appSettings.wStartH = (string)e.PostParams["wStartH"]; appSettings.wStartM = (string)e.PostParams["wStartM"]; appSettings.wEndH = (string)e.PostParams["wEndH"]; appSettings.wEndM = (string)e.PostParams["wEndM"]; appSettings.wMax = (string)e.PostParams["wMax"]; appSettings.wRamp = (string)e.PostParams["wRamp"]; appSettings.bStartH = (string)e.PostParams["bStartH"]; appSettings.bStartM = (string)e.PostParams["bStartM"]; appSettings.bEndH = (string)e.PostParams["bEndH"]; appSettings.bEndM = (string)e.PostParams["bEndM"]; appSettings.bMax1 = (string)e.PostParams["bMax1"]; appSettings.bMax2 = (string)e.PostParams["bMax2"]; appSettings.bRamp = (string)e.PostParams["bRamp"]; appSettings.rStartH = (string)e.PostParams["rStartH"]; appSettings.rStartM = (string)e.PostParams["rStartM"]; appSettings.rEndH = (string)e.PostParams["rEndH"]; appSettings.rEndM = (string)e.PostParams["rEndM"]; if (appSettings.SaveToFlash()) { saved = true; } else { msg = "Error saving settings : " + appSettings.LastErrorMsg; } } catch (Exception ex) { msg = "Error saving settings : " + ex.Message; } Debug.GC(true); if (saved) { restartTimer = true; e.ResponseRedirectTo = constTankStatusPageFileName; return; } } } } // return page Hashtable tokens = new Hashtable() { {"appName", constAppName}, {"wStartH", appSettings.wStartH}, {"wStartM", appSettings.wStartM}, {"wEndH", appSettings.wEndH}, {"wEndM", appSettings.wEndM}, {"wMax", appSettings.wMax}, {"wRamp", appSettings.wRamp}, {"bStartH", appSettings.bStartH}, {"bStartM", appSettings.bStartM}, {"bEndH", appSettings.bEndH}, {"bEndM", appSettings.bEndM}, {"bMax1", appSettings.bMax1}, {"bMax2", appSettings.bMax2}, {"bRamp", appSettings.bRamp}, {"rStartH", appSettings.rStartH}, {"rStartM", appSettings.rStartM}, {"rEndH", appSettings.rEndH}, {"rEndM", appSettings.rEndM}, {"pwd", ""}, {"msg", msg} }; e.ResponseHtml = new HtmlFileReader(SDCard.RootDirectory + "\\" + constTankTimersPageFileName, tokens); Debug.GC(true); }
private static void DefaultPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e) { if (SDCard.IsMounted == false && SDCard.MountSD() == false) { e.ResponseText = GetSDCardErrorResponse(); return; } e.ResponseRedirectTo = constTankStatusPageFileName; }