private void ActivateServers() { AddLog("Trying to activate servers..."); fEchoServer = new EchoServer(); try { fEchoServer.Open(); AddLog("EchoServer is active."); } catch (Exception ex) { AddLog("Can't activate EchoServer. An exception occured: " + ex.Message); } fHttpServer = new SimpleHttpServer(); fHttpServer.Port = Convert.ToInt32(nudPort.Value); fHttpServer.RootPath = txtRoot.Text; fHttpServer.ServerName = txtServerName.Text; if (this.fHttpServer.BindingV4 != null) { this.fHttpServer.BindingV4.ListenerThreadCount = Convert.ToInt32(this.nudCount.Value); } fHttpServer.HttpRequest += OnHttpRequest; fHttpServer.Open(); AddLog(String.Format("SimpleHttpServer is active on {0} port.", fHttpServer.Port)); SetEnable(false); AddLog("Servers activated."); btnAction.Text = "Deactivate Servers"; }
/// <summary> /// This method creates a stub server (<code>server</code>). /// It will then create the proxy (<code>proxy</code>). /// Finally it issues a web request to the proxy. /// </summary> /// <param name="serverOptions">The options for the running HTTP server.</param> /// <param name="proxyOptions">The options for the running proxy server.</param> /// <param name="serverAssertion">The configuration/assertion code to run in the context of the server.</param> /// <param name="clientAssertion">The configuration/assertion code to run in the context of the client.</param> private static void ExecuteTestInContext( SimpleHttpServerOptions serverOptions, SimpleHttpServerOptions proxyOptions, Action <HttpListenerContext> serverAssertion, Action <NtlmProxy> clientAssertion) { // Unfortunately I'm not familiar enough with await/async to correct the following: #pragma warning disable 1998 using (var server = new SimpleHttpServer(async context => #pragma warning restore 1998 { var response = new HttpResponseMessage { Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(ExpectedResultText))) }; if (serverAssertion != null) { serverAssertion(context); } return(response); }, serverOptions)) { var serverUri = new Uri(string.Format("http://localhost:{0}/", server.Port)); using (var proxy = new NtlmProxy(serverUri, proxyOptions)) { clientAssertion(proxy); } } }
public void SimpleHttpServer_SanityChecks_TooBigPortNumberThrowsException() { var mockedServiceEndpoint = new Mock <BaseHttpServiceEndpoint>(); SimpleHttpServer server = new SimpleHttpServer(mockedServiceEndpoint.Object, 65536); Assert.Fail("Constructor should throw an exception."); }
/// <summary> /// This method creates a stub server (<code>server</code>). /// It will then create the proxy (<code>proxy</code>). /// Finally it issues a web request to the proxy. /// </summary> /// <param name="serverOptions">The options for the running HTTP server.</param> /// <param name="proxyOptions">The options for the running proxy server.</param> /// <param name="serverAssertion">The configuration/assertion code to run in the context of the server.</param> /// <param name="clientAssertion">The configuration/assertion code to run in the context of the client.</param> private static void ExecuteTestInContext( SimpleHttpServerOptions serverOptions, SimpleHttpServerOptions proxyOptions, Action <HttpListenerContext> serverAssertion, Action <NtlmProxy> clientAssertion) { using (var server = new SimpleHttpServer(context => { return(new Task <HttpResponseMessage>(() => { var response = new HttpResponseMessage { Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(ExpectedResultText))) }; if (serverAssertion != null) { serverAssertion(context); } return response; })); }, serverOptions)) { var serverUri = new Uri(string.Format("http://localhost:{0}/", server.Port)); using (var proxy = new NtlmProxy(serverUri, proxyOptions)) { clientAssertion(proxy); } } }
public void SimpleHttpServer_CreateAnInstance_InstanceIsCreatedWithoutAnyErrors() { var mockedServiceEndpoint = new Mock <BaseHttpServiceEndpoint>(); SimpleHttpServer server = new SimpleHttpServer(mockedServiceEndpoint.Object, 12345); Assert.IsNotNull(server); }
private void SetText(bool reloadReferences) { if (_currentDevice == null) { return; } UpdateEditorLanguage(_currentCodeType.CodeType, reloadReferences); if (!String.IsNullOrWhiteSpace(_currentCodeType.EditFilePath)) { var filePathData = Encoding.UTF8.GetBytes(_currentCodeType.EditFilePath); var fileContentsDataString = SimpleHttpServer.SendPostRequest(_currentDevice.DeviceAddress, filePathData, "GetFileContents"); _currentWrapText = ""; CodeEditor.Document.SetText(fileContentsDataString); CodeEditor.Document.SetHeaderAndFooterText("", ""); CodeEditor.Document.FileName = Path.GetFileName(_currentCodeType.EditFilePath); } else { var isPixate = _currentDevice.PixateCssPaths != null; _currentWrapText = EditorHelpers.GetWrapText(_currentCodeType.CodeType, _currentDevice.DeviceType, isPixate ? new List <string> { "using PixateLib;" } : null); CodeEditor.Document.SetText(EditorHelpers.GetDefaultCode(_currentCodeType.CodeType, _currentDevice.DeviceType)); CodeEditor.Document.SetHeaderAndFooterText(WrapHeader, WrapFooter); CodeEditor.Document.FileName = "ProtoPad.cs"; } }
public void Dispose() { Try.Do(() => { _httpServer?.StopAsync().Wait(); _httpServer = null; }, false); }
/// <summary> /// Start the internal HTTP-Server /// </summary> public void StartHttpServer() { _httpServer = new SimpleHttpServer(80, AuthType.Implicit); _httpServer.OnAuth += HttpServerOnOnAuth; _httpThread = new Thread(_httpServer.Listen); _httpThread.Start(); }
/// <summary> /// Start the internal HTTP-Server /// </summary> public void StartHttpServer(int port = 80) { _httpServer = new SimpleHttpServer(port, AuthType.Implicit); _httpServer.OnAuth += HttpServerOnOnAuth; _httpThread = new Thread(_httpServer.Listen); _httpThread.Start(); }
/// <summary> /// Start the internal HTTP-Server /// </summary> public void StartHttpServer(int port = 80) { _httpServer = new SimpleHttpServer(port, AuthType.Authorization); _httpServer.OnAuth += HttpServerOnOnAuth; _httpThread = new Thread(_httpServer.Listen); _httpThread.Start(); }
void IService.OnStart(string[] args) { _httpServer = new SimpleHttpServer(); WebFolder = _httpServer.WebFolder; OnBinding(_httpServer); WebFolder = _httpServer.WebFolder; _httpServer.StartAsync(Port); }
public void SimpleHttpServer_SanityChecks_WellKnownPortNumbersAreMappedToDefault() { var mockedServiceEndpoint = new Mock <BaseHttpServiceEndpoint>(); Random portRandomizer = new Random(); SimpleHttpServer server = new SimpleHttpServer(mockedServiceEndpoint.Object, portRandomizer.Next(1023)); Assert.AreEqual(server.ListeningPort, 80); }
/// <summary> /// Start the internal HTTP-Server /// </summary> public void StartHttpServer(int port = 80) { _httpServer = new SimpleHttpServer(port, AuthType.Implicit); _httpServer.OnAuth += HttpServerOnOnAuth; _httpThread = new Thread(_httpServer.Listen); _httpThread.Start(); isServerActive = true; }
private void ConnectToApp(DeviceItem deviceItem) { _currentDevice = deviceItem; var isLocal = _currentDevice.DeviceType == DeviceTypes.Local; ClearSimulatorWindowButton.IsEnabled = !isLocal; if (isLocal) { LogToResultsWindow("Running locally (regular .Net)"); } else { _currentDevice.MainXamarinAssemblyName = SimpleHttpServer.SendCustomCommand(_currentDevice.DeviceAddress, "GetMainXamarinAssembly"); if (_currentDevice.DeviceType == DeviceTypes.iOS) { var cssFilesJson = SimpleHttpServer.SendCustomCommand(_currentDevice.DeviceAddress, "GetPixateCssFiles"); _currentDevice.PixateCssPaths = UtilityMethods.JsonDecode <string[]>(cssFilesJson); } LogToResultsWindow("Connected to device '{0}' on [{1}]", _currentDevice.DeviceName, _currentDevice.DeviceAddress); } UpdateCodeTypesComboBox(); Title = String.Format("ProtoPad - {0}", _currentDevice.DeviceName); SetText(true); SendCodeButton.IsEnabled = true; LoadAssemblyButton.IsEnabled = true; StatusLabel.Content = ""; if (_currentDevice.DeviceType != DeviceTypes.iOS) { return; // todo: locate and provide Android Emulator file path if applicable } var wrapText = EditorHelpers.GetWrapText(CodeTypes.Expression, _currentDevice.DeviceType, null); var getFolderCode = wrapText.Replace("__STATEMENTSHERE__", "Environment.GetFolderPath(Environment.SpecialFolder.Personal)"); var result = SendCode(_currentDevice.DeviceAddress, false, getFolderCode); if (result == null || result.Results == null) { return; } var folder = result.Results.FirstOrDefault(); if (folder == null) { return; } StatusLabel.Content = folder.ResultValue.PrimitiveValue.ToString(); }
private ProtoPadServer(UIApplicationDelegate appDelegate, UIWindow window, int?overrideListeningPort = null, string overrideBroadcastedAppName = null) { _appDelegate = appDelegate; _window = window; BroadcastedAppName = overrideBroadcastedAppName ?? String.Format("ProtoPad Service on iOS Device {0}", UIDevice.CurrentDevice.Name); ListeningPort = overrideListeningPort ?? 8080; LocalIPAddress = Helpers.GetCurrentIPAddress(); var mainMonotouchAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.ToLower() == "monotouch"); var requestHandlers = new Dictionary <string, Func <byte[], string> > { { "GetMainXamarinAssembly", requestData => mainMonotouchAssembly.FullName }, { "WhoAreYou", requestData => "iOS" }, { "GetPixateCssFiles", requestData => JsonEncode(_pixateCssPaths.ToArray()) }, { "ExecuteAssembly", requestData => { var response = "{}"; var remoteCommandDoneEvent = new AutoResetEvent(false); _appDelegate.InvokeOnMainThread(() => ExecuteAssemblyAndCreateResponse(requestData, remoteCommandDoneEvent, ref response)); remoteCommandDoneEvent.WaitOne(); return(response); } }, { "UpdatePixateCSS", requestData => { var response = "{}"; var remoteCommandDoneEvent = new AutoResetEvent(false); var filePathDataLength = requestData[1] + (requestData[0] << 8); var filePathData = new byte[filePathDataLength]; Array.Copy(requestData, 2, filePathData, 0, filePathDataLength); var filePath = Encoding.UTF8.GetString(filePathData); var cssFileDataLength = requestData.Length - (2 + filePathDataLength); var cssFileData = new byte[cssFileDataLength]; Array.Copy(requestData, 2 + filePathDataLength, cssFileData, 0, cssFileDataLength); _appDelegate.InvokeOnMainThread(() => UpdatePixateCssFile(filePath, cssFileData, remoteCommandDoneEvent, ref response)); remoteCommandDoneEvent.WaitOne(); return(response); } }, { "GetFileContents", requestData => { var response = ""; var filePath = Encoding.UTF8.GetString(requestData); var remoteCommandDoneEvent = new AutoResetEvent(false); _appDelegate.InvokeOnMainThread(() => GetFileContents(filePath, remoteCommandDoneEvent, ref response)); remoteCommandDoneEvent.WaitOne(); return(response); } } }; _httpServer = new SimpleHttpServer(ListeningPort, requestHandlers); _udpServer = new UdpDiscoveryServer(BroadcastedAppName, String.Format("http://{0}:{1}/", LocalIPAddress, ListeningPort)); }
static void Main(string[] args) { var server = new SimpleHttpServer(1234, Host, DatabaseName, DatabaseUrl, new GraphQlDefaultHandler()); using (var client = new HttpClient()) { var result1 = client.GetStringAsync("http://localhost:1234/index.html").Result; var result2 = client.GetStringAsync("http://localhost:1234/index.html?_sw-precache=3b0574e5bb73113c46c0ebba65ab959b").Result; } }
private void InitializeHttpServer() { var executingDir = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); if (executingDir == null) { throw new Exception("Unable to discover path to executing directory"); } var pathToTodoMvc = Path.Combine(executingDir, "todomvc"); _simpleHttpServer = new SimpleHttpServer(pathToTodoMvc); }
public HttpTransportServer() { _httpServer = new SimpleHttpServer(); _httpServer.BeginRequest += HttpServer_BeginRequest; Serializer = new JsonTextSerializer(); Core.Status.Attach(collection => { collection.Add(nameof(Name), Name); collection.Add(nameof(Port), Port); collection.Add(nameof(EnableGetDescriptors), EnableGetDescriptors); Core.Status.AttachChild(_httpServer, this); Core.Status.AttachChild(Serializer, this); }); }
static async Task MainAsync(params string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel(); }; string sourceDir = @"http\"; TestController controller = new TestController(); var getRoutes = new Dictionary <string, RouteInfo>(); getRoutes.Add("/hello", new RouteInfo { ActionName = "Hello", ControllerType = typeof(Program) }); getRoutes.Add("/account", new RouteInfo { ActionName = "Account", ControllerInstance = controller }); var postRoutes = new Dictionary <string, RouteInfo>(); postRoutes.Add("/", new RouteInfo { ActionName = "Post", ControllerType = typeof(Program) }); using (SimpleHttpServer httpServer = new SimpleHttpServer("127.0.0.1", "8080", (8 * 1024), 3000, sourceDir, cts.Token) { GetRoutes = getRoutes, PostRoutes = postRoutes }) { Console.WriteLine("Simple HTTP Server Running..."); Console.WriteLine("============================="); Helper.OpenBrowser($"http://{httpServer.Ip}:{httpServer.PortNumber}"); Helper.OpenBrowser($"http://{httpServer.Ip}:{httpServer.PortNumber}/hello"); Helper.OpenBrowser($"http://{httpServer.Ip}:{httpServer.PortNumber}/account/Kenan/33"); await httpServer.RequestReceivedAsync(async httpRequest => { await Console.Out.WriteLineAsync(httpRequest.ToString()); }); } }
private void SendCssButton_Click(object sender, RoutedEventArgs e) { var cssText = CodeEditor.Document.CurrentSnapshot.Text; var cssData = Encoding.UTF8.GetBytes(cssText); var cssFilePathData = Encoding.UTF8.GetBytes(_currentCodeType.EditFilePath); var requestLength = 2 + cssFilePathData.Length + cssData.Length; var requestData = new byte[requestLength]; var cssFilePathDataLength = (ushort)(cssFilePathData.Length); requestData[0] = (byte)(cssFilePathDataLength >> 8); requestData[1] = (byte)cssFilePathDataLength; Array.Copy(cssFilePathData, 0, requestData, 2, cssFilePathDataLength); Array.Copy(cssData, 0, requestData, 2 + cssFilePathDataLength, cssData.Length); SimpleHttpServer.SendPostRequest(_currentDevice.DeviceAddress, requestData, "UpdatePixateCSS"); }
public HttpTransportServer() { _httpServer = new SimpleHttpServer(); _httpServer.OnBeginRequest += HttpServer_OnBeginRequest; Serializer = new JsonTextSerializer(); Core.Status.Attach(collection => { collection.Add(nameof(Name), Name); collection.Add(nameof(Port), Port); collection.Add(nameof(EnableGetDescriptors), EnableGetDescriptors); collection.Add("Bytes Sent", Counters.BytesSent, true); collection.Add("Bytes Received", Counters.BytesReceived, true); Core.Status.AttachChild(_httpServer, this); Core.Status.AttachChild(Serializer, this); }); }
private ProtoPadServer(Activity activity, int?overrideListeningPort = null, string overrideBroadcastedAppName = null) { _contextActivity = activity; BroadcastedAppName = overrideBroadcastedAppName ?? String.Format("ProtoPad Service on ANDROID Device {0}", Android.OS.Build.Model); ListeningPort = overrideListeningPort ?? 8080; LocalIPAddress = Helpers.GetCurrentIPAddress(); var mainMonodroidAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.ToLower() == "mono.android"); var requestHandlers = new Dictionary <string, Func <byte[], string> > { { "GetMainXamarinAssembly", data => mainMonodroidAssembly.FullName }, { "WhoAreYou", data => "Android" }, { "ExecuteAssembly", data => { var response = "{}"; var remoteCommandDoneEvent = new AutoResetEvent(false); _contextActivity.RunOnUiThread(() => Response(data, remoteCommandDoneEvent, ref response)); remoteCommandDoneEvent.WaitOne(); return(response); } } }; _httpServer = new SimpleHttpServer(ListeningPort, requestHandlers); IPAddress broadCastAddress; using (var wifi = _contextActivity.GetSystemService(Android.Content.Context.WifiService) as WifiManager) { try { _mcLock = wifi.CreateMulticastLock("ProtoPadLock"); _mcLock.Acquire(); } catch (Java.Lang.SecurityException e) { Debug.WriteLine("Could not optain Multicast lock: {0}. Did you enable CHANGE_WIFI_MULTICAST_STATE permission in your app manifest?", e.Message); } broadCastAddress = GetBroadcastAddress(wifi); } var inEmulator = Build.Brand.Equals("generic", StringComparison.InvariantCultureIgnoreCase); _udpServer = new UdpDiscoveryServer(BroadcastedAppName, String.Format("http://{0}:{1}/", inEmulator ? "localhost" : LocalIPAddress.ToString(), inEmulator ? "?" : ListeningPort.ToString()), broadCastAddress); }
protected override void OnHandler(ParameterHandlerInfo info) { Core.Log.Warning("Starting HTTP TEST"); info.Service = new TaskService(async token => { var server = new SimpleHttpServer() .AddGetHandler("/", context => { context.Response.WriteLine("Hola Mundo"); }) .AddHttpControllerRoutes <MyController>(); await server.StartAsync(8085).ConfigureAwait(false); Core.Log.InfoBasic("Listening to port 8085"); await Task.Run(() => token.WaitHandle.WaitOne(), token).ConfigureAwait(false); await server.StopAsync().ConfigureAwait(false); }); info.ShouldEndExecution = false; }
private static MainWindow.DeviceTypes?QuickConnect(string endpoint) { var appIdentifier = SimpleHttpServer.SendCustomCommand(endpoint, "WhoAreYou"); if (String.IsNullOrWhiteSpace(appIdentifier)) { return(null); } if (appIdentifier.Contains("Android")) { return(MainWindow.DeviceTypes.Android); } if (appIdentifier.Contains("iOS")) { return(MainWindow.DeviceTypes.iOS); } return(null); }
private void LoadAssemblyButton_Click(object sender, RoutedEventArgs e) { if (_currentDevice == null) { MessageBox.Show("Please connect to an app first!"); return; } var dlg = new Microsoft.Win32.OpenFileDialog { DefaultExt = ".dll" }; var frameworkReferenceAssembliesDirectory = Path.GetDirectoryName(_referencedAssemblies.First()); switch (_currentDevice.DeviceType) { case DeviceTypes.Android: dlg.Filter = "Xamarin.Android-compatible assembly (.dll)|*.dll"; dlg.InitialDirectory = Path.Combine(frameworkReferenceAssembliesDirectory, "MonoAndroid"); break; case DeviceTypes.iOS: dlg.Filter = "Xamarin.iOS-compatible assembly (.dll)|*.dll"; dlg.InitialDirectory = Path.Combine(frameworkReferenceAssembliesDirectory, @"MonoTouch\v4.0"); break; case DeviceTypes.Local: dlg.Filter = ".Net assembly (.dll)|*.dll"; dlg.InitialDirectory = Path.Combine(frameworkReferenceAssembliesDirectory, @".NETFramework"); break; } var result = dlg.ShowDialog(); if (!result.Value) { return; } var assemblyPath = dlg.FileName; _projectAssembly.AssemblyReferences.AddFrom(assemblyPath); _referencedAssemblies.Add(assemblyPath); SimpleHttpServer.SendPostRequest(_currentDevice.DeviceAddress, File.ReadAllBytes(assemblyPath), "ExecuteAssembly"); }
public static void Start(int port) { try { _logger.InfoFormat("Start MyHttpServer:{0}", port); if (webserver != null) { try { webserver.Stop(); } catch (Exception e) { _logger.InfoFormat("Stop MyHttpServer:{0}", e); } } webserver = new SimpleHttpServer("/non-existing-folder", port); webserver.AddPageHandler("/ObjectPool", new ObjectAllocatorPageHandler()); webserver.AddPageHandler("/EntityMap", new EntityMapComparePageHandler()); webserver.AddPageHandler("/Network", new ENetNetworkHandler()); webserver.AddPageHandler("/BandWidthMonitor", new BandWidthMonitorHandler()); webserver.AddPageHandler("/SanpShotData", new SnapSHotHandler()); webserver.AddPageHandler("/fps", new FpsHandler()); webserver.AddPageHandler("/debug", new DebugHandler()); webserver.AddPageHandler("/rigidbody", new RigidbodyInfoHandler()); webserver.AddPageHandler("/res", new LoadResHandler(true)); webserver.AddPageHandler("/resall", new LoadResHandler(false)); webserver.AddPageHandler("/all", new AllPageHandler()); webserver.AddPageHandler("/freelog-var", new FreeDebugDataHandler(1)); webserver.AddPageHandler("/freelog-message", new FreeDebugDataHandler(2)); webserver.AddPageHandler("/freelog-func", new FreeDebugDataHandler(3)); webserver.AddPageHandler("/threads", new ThreadDebugHandler()); webserver.AddPageHandler("/server", new ServerInfoHandler()); webserver.AddPageHandler("/mapobj", new MapObjectInfoHandler()); } catch (Exception e) { _logger.ErrorFormat("Start Http server failed: {0}", e); } }
private ExecuteResponse SendCode(string url, bool wrapWithDefaultCode = true, string specialNonEditorCode = null) { var assemblyPath = CompileSource(wrapWithDefaultCode, specialNonEditorCode); if (String.IsNullOrWhiteSpace(assemblyPath)) { return(null); } if (_currentDevice.DeviceType == DeviceTypes.Local) { var executeResponse = EditorHelpers.ExecuteLoadedAssemblyString(File.ReadAllBytes(assemblyPath)); var dumpValues = executeResponse.GetDumpValues(); if (dumpValues != null) { executeResponse.Results = dumpValues.Select(v => new ResultPair(v.Description, Dumper.ObjectToDumpValue(v.Value, v.Level, executeResponse.GetMaxEnumerableItemCount()))).ToList(); } return(executeResponse); } var responseString = SimpleHttpServer.SendPostRequest(url, File.ReadAllBytes(assemblyPath), "ExecuteAssembly").Trim(); return(String.IsNullOrWhiteSpace(responseString) ? null : UtilityMethods.JsonDecode <ExecuteResponse>(responseString)); }
/// <summary> /// This will stop the internal HTTP-Server (Should be called after you got the Token) /// </summary> public void StopHttpServer() { _httpServer.Dispose(); _httpServer = null; isServerActive = false; }
/// <summary> /// Start the internal HTTP-Server /// </summary> public void StartHttpServer() { _httpServer = new SimpleHttpServer(80, AuthType.Authorization); _httpServer.OnAuth += HttpServerOnOnAuth; _httpThread = new Thread(_httpServer.Listen); _httpThread.Start(); }
/// <summary> /// This will stop the internal HTTP-Server (Should be called after you got the Token) /// </summary> public void StopHttpServer() { _httpServer.Dispose(); _httpServer = null; }
/// <summary> /// This will stop the internal HTTP-Server (Should be called after you got the Token) /// </summary> public void StopHttpServer() { _httpServer = null; }
public HttpStatusTransport(int port = 80) { var htmlPage = this.GetAssembly().GetResourceString("Status.htm"); var xmlSerializer = new XmlTextSerializer(); var jsonSerializer = new JsonTextSerializer() { UseCamelCase = true }; _httpServer = new SimpleHttpServer(); _httpServer.AddGetHandler("/", ctx => { ctx.Response.Write(htmlPage); }); _httpServer.AddGetHandler("/xml", ctx => { if (OnFetchStatus == null) { return; } var statuses = OnFetchStatus.Invoke(); ctx.Response.ContentType = SerializerMimeTypes.Xml; xmlSerializer.Serialize(statuses, ctx.Response.OutputStream); }); _httpServer.AddGetHandler("/json", ctx => { if (OnFetchStatus == null) { return; } var statuses = OnFetchStatus.Invoke(); ctx.Response.ContentType = SerializerMimeTypes.Json; jsonSerializer.Serialize(statuses, ctx.Response.OutputStream); }); _httpServer.AddGetHandler("/gccollect", ctx => { GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); GC.WaitForPendingFinalizers(); ctx.Response.ContentType = SerializerMimeTypes.Json; ctx.Response.Write("true"); }); _httpServer.AddGetHandler("/discovery", ctx => { var services = DiscoveryService.GetRegisteredServices(); var statusServices = services.Where(s => s.Category == DiscoveryService.FrameworkCategory && s.Name == "STATUS.HTTP").ToArray(); ctx.Response.WriteLine("<html><head><title>Discovered Status Services</title></head><body style='padding:30px;'><h1 style='text-align:center;'>Discovered status services</h1>"); foreach (var g in statusServices.GroupBy(s => new { s.EnvironmentName, s.MachineName }).OrderBy(s => s.Key.EnvironmentName)) { ctx.Response.WriteLine($"<h3>Environment: {g.Key.EnvironmentName} - Machine: {g.Key.MachineName}</h3>"); ctx.Response.WriteLine("<ul>"); foreach (var ss in g) { var dct = (Dictionary <string, object>)ss.Data.GetValue(); ctx.Response.WriteLine("<li style='list-style-type: none;'>"); foreach (var ssAddress in ss.Addresses) { ctx.Response.WriteLine($"<a href='http://{ssAddress.ToString()}:{dct["Port"]}/' target='_blank' style='text-decoration: none;color: blue;'>{ssAddress.ToString()}</a> /"); } ctx.Response.WriteLine($" {ss.ApplicationName}</li>"); } ctx.Response.WriteLine("</ul>"); } ctx.Response.WriteLine("</body></html>"); }); StartListening(port).WaitAsync(); Core.Status.DeAttachObject(_httpServer); }