private void Run() { // If false, don't bother if (!(bool)ServiceVariables["IsRunning"]) { return; } var uri = (Uri)ServiceVariables["HostUri"]; // https://github.com/unosquare/embedio using (_webServer = new EmbedIO.WebServer(uri.AbsoluteUri, EmbedIO.Constants.RoutingStrategy.Regex)) { #if DEBUG //Terminal.Settings.DisplayLoggingMessageType = LogMessageType.Debug; #else Terminal.Settings.DisplayLoggingMessageType = LogMessageType.None; #endif // First, we will configure our web server by adding Modules. // Please note that order DOES matter. // ================================================================================================ // If we want to enable sessions, we simply register the LocalSessionModule // Beware that this is an in-memory session storage mechanism so, avoid storing very large objects. // You can use the server.GetSession() method to get the SessionInfo object and manupulate it. // You could potentially implement a distributed session module using something like Redis _webServer.RegisterModule(new LocalSessionModule()); // Here we setup serving of static files _webServer.RegisterModule(new StaticFilesModule("Content")); // The static files module will cache small files in ram until it detects they have been modified. _webServer.Module <StaticFilesModule>().UseRamCache = true; _webServer.Module <StaticFilesModule>().DefaultExtension = ".html"; // We don't need to add the line below. The default document is always index.html. _webServer.Module <StaticFilesModule>().DefaultDocument = "index.html"; // Enable CORS to enable CRUD operations over http _webServer.EnableCors(); // Register Api module _webServer.RegisterModule(new WebApiModule()); // Register the Service controller //var servicesController = new ServicesController(_serviceContext); _webServer.Module <WebApiModule>().RegisterController <ServicesController>(); // Once we've registered our modules and configured them, we call the RunAsync() method. _webServer.RunAsync(); // _serviceContext.Log.Informational("The WebServer is running on: " + uri.AbsoluteUri); while ((bool)ServiceVariables["IsRunning"]) { Thread.Sleep(1); } } _serviceContext.Log.Informational("NancyWeb host it no longer active"); }
public bool TakePhoto(WebServer server, HttpListenerContext context) { try { if (IsRunningOnMono()) { var process = Process.Start("raspistill", "-o /home/pi/target/ui/" + DateTime.Now.ToString("yyyMMdd-HHmm") + ".jpg"); process.WaitForExit(); } else { var filename = Path.Combine(photodir, DateTime.Now.ToString("yyyMMdd-HHmm") + ".jpg"); (new WebClient()).DownloadFile("http://unosquare.github.io/assets/embedio.png", filename); } var dir = new DirectoryInfo(photodir); var files = dir.GetFiles("*.jpg").Select(x => x.Name).Take(10); return context.JsonResponse(files); } catch (Exception ex) { return HandleError(context, ex); } }
private static void Main(string[] args) { #region Setup buttons Setup.WiringPiSetupGpio(); CoreFunctions.SetPinMode(26, Constants.PinMode.Input); Task.Run(() => { ApiController.ButtonCheck.Add(26, 0); var prev = true; while (true) { var x = CoreFunctions.ReadBit(26); if (x != prev) { ApiController.ButtonCheck[26] += prev ? 1 : 0; prev = x; } System.Threading.Thread.Sleep(5); } }); #endregion var url = "http://*:9696/"; if (args.Length > 0) url = args[0]; // Our web server is disposable. Note that if you don't want to use logging, // there are alternate constructors that allow you to skip specifying an ILog object. using (var server = new WebServer(url, new SimpleConsoleLog())) { server.WithWebApiController<ApiController>(); server.RegisterModule(new CorsModule()); // Here we setup serving of static files server.RegisterModule(new StaticFilesModule(Directory.GetCurrentDirectory())); // The static files module will cache small files in ram until it detects they have been modified. server.Module<StaticFilesModule>().UseRamCache = true; server.Module<StaticFilesModule>().DefaultExtension = ".html"; // We don't need to add the line below. The default document is always index.html. //server.Module<Modules.StaticFilesWebModule>().DefaultDocument = "index.html"; // Once we've registered our modules and configured them, we call the RunAsync() method. // This is a non-blocking method (it return immediately) so in this case we avoid // disposing of the object until a key is pressed. //server.Run(); server.RunAsync(); // Wait for any key to be pressed before disposing of our web server. // In a service we'd manage the lifecycle of of our web server using // something like a BackgroundWorker or a ManualResetEvent. Console.ReadKey(true); } }
public ThemeServer(string themeRoot) { this.ThemeRoot = themeRoot; if (!Directory.Exists(this.ThemeRoot)) { Directory.CreateDirectory(this.ThemeRoot); } var url = "http://localhost:30000/"; this.themeWebServer = new WebServer(url); }
public bool GetIndex(WebServer server, HttpListenerContext context) { try { var buffer = Encoding.UTF8.GetBytes(WebsocketsUpdate("/api/current")); context.Response.ContentType = "text/html"; context.Response.OutputStream.Write(buffer, 0, buffer.Length); return true; } catch (Exception ex) { return HandleError(context, ex); } }
public bool GetService(Unosquare.Labs.EmbedIO.WebServer webServer, HttpListenerContext context, string name) { try { return(false); } catch (Exception ex) { return(HandleError(context, ex, (int)System.Net.HttpStatusCode.InternalServerError)); } }
public bool Delete(WebServer server, HttpListenerContext context) { try { var model = context.ParseJson<Entry>(); // TODO: Complete return true; } catch (Exception ex) { return HandleError(context, ex); } }
public async Task<bool> Io(WebServer server, HttpListenerContext context) { var lastSegment = context.Request.Url.Segments.Last(); var bcmPinNumber = int.Parse(lastSegment); CoreFunctions.SetPinMode(bcmPinNumber, Constants.PinMode.Output); CoreFunctions.WriteBit(bcmPinNumber, true); await Task.Delay(500); CoreFunctions.WriteBit(bcmPinNumber, false); return true; }
public bool GetHosts(WebServer server, HttpListenerContext context) { try { var data = LocalCdn.HostEntries; return context.JsonResponse(data); } catch (Exception ex) { return HandleError(context, ex); } }
public bool GetPhotos(WebServer server, HttpListenerContext context) { try { var dir = new DirectoryInfo(photodir); var files = dir.GetFiles("*.jpg").Select(x => x.Name).Take(10); return context.JsonResponse(files); } catch (Exception ex) { return HandleError(context, ex); } }
private bool EchoThemes(HttpListenerContext context, WebServer server, bool sendBuffer = true) { HashSet<object> themesDirectory = new HashSet<object>(); foreach (string themeInfo in from directory in Directory.GetDirectories(this.ThemeRoot) where File.Exists(Path.Combine(directory, "theme.json")) select File.ReadAllText(Path.Combine(directory, "theme.json"))) { themesDirectory.Add(JsonConvert.DeserializeObject(themeInfo)); } byte[]output = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(themesDirectory)); context.Response.OutputStream.Write(output, 0, output.Length); context.Response.OutputStream.Close(); return true; }
public bool Post(WebServer server, HttpListenerContext context) { try { var model = context.ParseJson<Entry>(); LocalCdn.AddEntry(model.Url); return true; } catch (Exception ex) { return HandleError(context, ex); } }
public bool GetPeople(WebServer server, HttpListenerContext context) { try { var model = context.ParseJson<GridDataRequest>(); return context.JsonResponse(model.CreateGridDataResponse(People.AsQueryable())); } catch (Exception ex) { // here the error handler will respond with a generic 500 HTTP code a JSON-encoded object // with error info. You will need to handle HTTP status codes correctly depending on the situation. // For example, for keys that are not found, ou will need to respond with a 404 status code. return HandleError(context, ex); } }
public void Start(int port) { _server = new WebServer($"http://+:{port}/", new NullLog(), RoutingStrategy.Wildcard); _server.RegisterModule(new WebApiModule()); _server.Module<WebApiModule>().RegisterController<PlayerStatsController>(); var module = new WebSocketsModule(); _server.RegisterModule(module); _currentServer = new PublishDataSocketsServer(@"Current Race Stats Server"); module.RegisterWebSocketsServer("/api/current", _currentServer); try { _server.RunAsync(); } catch (HttpListenerException e) { Logging.Warning(e.Message + $"\nDon’t forget to reserve url using something like “netsh http add urlacl url=\"http://+:{port}/\" user=everyone”."); } catch (Exception e) { Logging.Error(e); } }
static void Main(string[] args) { var url = "http://localhost:9196/"; using (var server = new WebServer(url, new SimpleConsoleLog())) { server.RegisterModule(new LocalSessionModule()); server.RegisterModule(new StaticFilesModule("./")); server.Module<StaticFilesModule>().UseRamCache = true; server.Module<StaticFilesModule>().DefaultExtension = ".html"; server.RunAsync(); var browser = new System.Diagnostics.Process() { StartInfo = new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true } }; browser.Start(); Console.ReadKey(true); } }
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments.</param> private static void Main(string[] args) { var url = "http://localhost:9696/"; if (args.Length > 0) url = args[0]; // Our web server is disposable. Note that if you don't want to use logging, // there are alternate constructors that allow you to skip specifying an ILog object. using (var server = new WebServer(url, new Labs.EmbedIO.Log.SimpleConsoleLog())) { // First, we will configure our web server by adding Modules. server.RegisterModule(new WebApiModule()); server.Module<WebApiModule>().RegisterController<PeopleController>(); // Here we setup serving of static files server.RegisterModule(new StaticFilesModule(HtmlRootPath) { UseRamCache = true, DefaultExtension = ".html" }); // Once we've registered our modules and configured them, we call the RunAsync() method. // This is a non-blocking method (it return immediately) so in this case we avoid // disposing of the object until a key is pressed. server.RunAsync(); // Fire up the browser to show the content if we are debugging! #if DEBUG var browser = new System.Diagnostics.Process() { StartInfo = new System.Diagnostics.ProcessStartInfo(url) {UseShellExecute = true} }; browser.Start(); #endif // Wait for any key to be pressed before disposing of our web server. // In a service we'd manage the lifecycle of of our web server using // something like a BackgroundWorker or a ManualResetEvent. Console.ReadKey(true); } }
public bool Get(WebServer server, HttpListenerContext context) { try { var data = EntryRepository.GetAll(); var lastSegment = context.Request.Url.Segments.Last(); if (lastSegment.EndsWith("/")) return context.JsonResponse(data.Select(x => x.Name)); if (data.Any(p => p.Name == lastSegment)) { return context.JsonResponse(data.FirstOrDefault(p => p.Name == lastSegment)); } throw new KeyNotFoundException("Key Not Found: " + lastSegment); } catch (Exception ex) { return HandleError(context, ex); } }
/// <summary> /// Gets the session. /// </summary> /// <param name="server">The server.</param> /// <param name="context">The context.</param> /// <returns></returns> public static SessionInfo GetSession(this WebServer server, WebSocketContext context) { return(server.SessionModule == null ? null : server.SessionModule.GetSession(context)); }
public async Task<bool> ButtonIo(WebServer server, HttpListenerContext context) { var lastSegment = context.Request.Url.Segments.Last(); var bcmPinNumber = int.Parse(lastSegment); return context.JsonResponse(new { count = ButtonCheck[bcmPinNumber] }); }
/// <summary> /// Deletes the session object associated to the current context. /// </summary> /// <param name="context">The context.</param> /// <param name="server">The server.</param> public static void DeleteSession(this HttpListenerContext context, WebServer server) { server.DeleteSession(context); }
/// <summary> /// Gets the session object associated to the current context. /// Returns null if the LocalSessionWebModule has not been loaded. /// </summary> /// <param name="context">The context.</param> /// <param name="server">The server.</param> /// <returns>A session info for the given websocket context</returns> #if NET47 public static SessionInfo GetSession(this System.Net.WebSockets.WebSocketContext context, WebServer server)
/// <summary> /// Gets the session object associated to the current context. /// Returns null if the LocalSessionWebModule has not been loaded. /// </summary> /// <param name="server">The server.</param> /// <param name="context">The context.</param> /// <returns>A session info for the given server context</returns> public static SessionInfo GetSession(this WebServer server, HttpListenerContext context) { return(server.SessionModule?.GetSession(context)); }
/// <summary> /// Deletes the given session object. /// </summary> /// <param name="server">The server.</param> /// <param name="session">The session info.</param> public static void DeleteSession(this WebServer server, SessionInfo session) { server.SessionModule?.DeleteSession(session); }
/// <summary> /// Gets the session. /// </summary> /// <param name="server">The server.</param> /// <param name="context">The context.</param> /// <returns>A session info for the given websocket context.</returns> public static SessionInfo GetSession(this WebServer server, IWebSocketContext context) => server.SessionModule?.GetSession(context);
private bool HandleGet(HttpListenerContext context, WebServer server, bool sendBuffer = true) { var urlPath = context.Request.Url.LocalPath.Replace('/', Path.DirectorySeparatorChar); // adjust the path to see if we've got a default document if (urlPath.Last() == Path.DirectorySeparatorChar) urlPath = urlPath + DefaultDocument; urlPath = urlPath.TrimStart(new char[] {Path.DirectorySeparatorChar}); var localPath = Path.Combine(FileSystemPath, urlPath); var eTagValid = false; byte[] buffer = null; var fileDate = DateTime.Today; var partialHeader = context.RequestHeader(Constants.HeaderRange); var usingPartial = String.IsNullOrWhiteSpace(partialHeader) == false && partialHeader.StartsWith("bytes="); if (string.IsNullOrWhiteSpace(DefaultExtension) == false && DefaultExtension.StartsWith(".") && File.Exists(localPath) == false) { var newPath = localPath + DefaultExtension; if (File.Exists(newPath)) localPath = newPath; } if (File.Exists(localPath) == false) return false; if (usingPartial == false) { fileDate = File.GetLastWriteTime(localPath); var requestHash = context.RequestHeader(Constants.HeaderIfNotMatch); if (RamCache.ContainsKey(localPath) && RamCache[localPath].LastModified == fileDate) { server.Log.DebugFormat("RAM Cache: {0}", localPath); var currentHash = Extensions.ComputeMd5Hash(RamCache[localPath].Buffer) + '-' + fileDate.Ticks; if (String.IsNullOrWhiteSpace(requestHash) || requestHash != currentHash) { buffer = RamCache[localPath].Buffer; context.Response.AddHeader(Constants.HeaderETag, currentHash); } else { eTagValid = true; } } else { server.Log.DebugFormat("File System: {0}", localPath); if (sendBuffer) { buffer = File.ReadAllBytes(localPath); var currentHash = Extensions.ComputeMd5Hash(buffer) + '-' + fileDate.Ticks; if (String.IsNullOrWhiteSpace(requestHash) || requestHash != currentHash) { if (UseRamCache && buffer.Length <= MaxRamCacheFileSize) { RamCache[localPath] = new RamCacheEntry() {LastModified = fileDate, Buffer = buffer}; } context.Response.AddHeader(Constants.HeaderETag, currentHash); } else { eTagValid = true; } } } } // check to see if the file was modified or etag is the same var utcFileDateString = fileDate.ToUniversalTime() .ToString(Constants.BrowserTimeFormat, CultureInfo.InvariantCulture); if (usingPartial == false && (eTagValid || context.RequestHeader(Constants.HeaderIfModifiedSince).Equals(utcFileDateString))) { context.Response.AddHeader(Constants.HeaderCacheControl, "private"); context.Response.AddHeader(Constants.HeaderPragma, string.Empty); context.Response.AddHeader(Constants.HeaderExpires, string.Empty); context.Response.ContentType = string.Empty; context.Response.StatusCode = 304; } else { var extension = Path.GetExtension(localPath).ToLowerInvariant(); if (MimeTypes.ContainsKey(extension)) context.Response.ContentType = MimeTypes[extension]; context.Response.AddHeader(Constants.HeaderCacheControl, "private"); context.Response.AddHeader(Constants.HeaderPragma, string.Empty); context.Response.AddHeader(Constants.HeaderExpires, string.Empty); context.Response.AddHeader(Constants.HeaderLastModified, utcFileDateString); context.Response.AddHeader(Constants.HeaderAcceptRanges, "bytes"); if (sendBuffer) { var lrange = 0; var urange = 0; var size = (long) 0; var isPartial = false; var fileSize = new FileInfo(localPath).Length; if (usingPartial) { var range = partialHeader.Replace("bytes=", "").Split('-'); if (range.Length == 2 && int.TryParse(range[0], out lrange) && int.TryParse(range[1], out urange)) { isPartial = true; } if ((range.Length == 2 && int.TryParse(range[0], out lrange) && string.IsNullOrWhiteSpace(range[1])) || (range.Length == 1 && int.TryParse(range[0], out lrange))) { urange = (int) fileSize - 1; isPartial = true; } if (range.Length == 2 && string.IsNullOrWhiteSpace(range[0]) && int.TryParse(range[1], out urange)) { lrange = (int) fileSize - urange; urange = (int)fileSize - 1; isPartial = true; } } if (isPartial) { if (urange > fileSize) { context.Response.StatusCode = 416; context.Response.AddHeader(Constants.HeaderContentRanges, string.Format("bytes */{0}", fileSize)); return true; } size = (urange - lrange) + 1; context.Response.AddHeader(Constants.HeaderContentRanges, string.Format("bytes {0}-{1}/{2}", lrange, urange, fileSize)); context.Response.StatusCode = 206; server.Log.DebugFormat("Opening stream {0} bytes {1}-{2} size {3}", localPath, lrange, urange, size); buffer = new byte[size]; // Open FileStream with FileShare using (var fs = new FileStream(localPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (lrange + size > fs.Length) size = fs.Length - lrange; fs.Seek(lrange, SeekOrigin.Begin); fs.Read(buffer, 0, (int) size); fs.Close(); } // Reset lower range lrange = 0; } else { size = buffer.LongLength; // Perform compression if available if (context.RequestHeader(Constants.HeaderAcceptEncoding).Contains("gzip")) { buffer = buffer.Compress(); context.Response.AddHeader(Constants.HeaderContentEncoding, "gzip"); size = buffer.LongLength; lrange = 0; } } context.Response.ContentLength64 = size; try { context.Response.OutputStream.Write(buffer, lrange, (int) size); } catch (HttpListenerException) { // Connection error, nothing else to do } } else { context.Response.ContentLength64 = buffer == null ? new FileInfo(localPath).Length : buffer.LongLength; } } return true; }
public static void RunServer() { try { using (_server = new WebServer("http://*:80/", new SimpleConsoleLog())) { _server.WithWebApiController<ApiController>(); _server.RegisterModule(new CorsModule()); _server.RegisterModule(new StaticFilesModule(TmpFolder)); _server.Module<StaticFilesModule>().UseRamCache = true; _server.Module<StaticFilesModule>().DefaultExtension = ".html"; File.WriteAllText(Path.Combine(TmpFolder, "index.html"), Resources.index); File.WriteAllText(Path.Combine(TmpFolder, "app.js"), Resources.app); File.WriteAllText(Path.Combine(TmpFolder, "app.jsx"), Resources.appjsx); File.WriteAllText(Path.Combine(TmpFolder, "jquery.js"), Resources.jquery_2_1_4_min); File.WriteAllText(Path.Combine(TmpFolder, "JSXTransformer.js"), Resources.JSXTransformer); File.WriteAllText(Path.Combine(TmpFolder, "react.js"), Resources.react_with_addons_min); _server.RunAsync(); while (true) { Console.WriteLine("Type an Url to add or press Enter to stop..."); var result = Console.ReadLine(); if (string.IsNullOrWhiteSpace(result)) break; AddEntry(result); } var currentHost = File.ReadAllText(HostFile); // Restore if (OriginalHostFile != currentHost) File.WriteAllText(HostFile, OriginalHostFile); } } catch (Exception ex) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); } }
/// <summary> /// Gets the session object associated to the current context. /// Returns null if the LocalSessionWebModule has not been loaded. /// </summary> /// <param name="context">The context.</param> /// <param name="server">The server.</param> /// <returns></returns> public static SessionInfo GetSession(this HttpListenerContext context, WebServer server) { return(server.SessionModule == null ? null : server.SessionModule.GetSession(context)); }
public static SessionInfo GetSession(this Unosquare.Net.WebSocketContext context, WebServer server) #endif { return(server.SessionModule?.GetSession(context)); }
public EmbedIOWebApi(Unosquare.Labs.EmbedIO.WebServer server) { this.server = server; }
public static SessionInfo GetSession(this WebServer server, WebSocketContext context) #endif { return(server.SessionModule?.GetSession(context)); }
/// <summary> /// Gets the session object associated to the current context. /// Returns null if the LocalSessionWebModule has not been loaded. /// </summary> /// <param name="context">The context.</param> /// <param name="server">The server.</param> /// <returns>A session object for the given server context</returns> public static SessionInfo GetSession(this HttpListenerContext context, WebServer server) { return(server.GetSession(context)); }
/// <summary> /// Instances a Middleware context /// </summary> /// <param name="httpListenerContext">The HttpListenerContext</param> /// <param name="webserver">The WebServer instance</param> public MiddlewareContext(HttpListenerContext httpListenerContext, WebServer webserver) { HttpContext = httpListenerContext; Handled = false; WebServer = webserver; }
/// <summary> /// Deletes the session object associated to the current context. /// </summary> /// <param name="server">The server.</param> /// <param name="context">The context.</param> public static void DeleteSession(this WebServer server, HttpListenerContext context) { server.SessionModule?.DeleteSession(context); }