private void ProcessRequests() { while (!this.cts.IsCancellationRequested) { try { var context = TaskHelper.RunAsync <HttpListenerContext>(() => { return(this.httpListener.GetContext()); }, null).Result; try { using (timer.NewContext()) { TaskHelper.RunWithWait(() => { ProcessRequest(context); context.Response.Close(); }, null); } } catch (Exception ex) { errors.Mark(); context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server Error"; context.Response.Close(); MetricsErrorHandler.Handle(ex, "Error processing HTTP request"); } } catch (Exception ex) { errors.Mark(); HttpListenerException httpException = ex as HttpListenerException; if (httpException == null || httpException.ErrorCode != 995)// IO operation aborted { MetricsErrorHandler.Handle(ex, "Error processing HTTP request"); } } } }
//public List<ItemMovement> ItemMovements(string CompanySlug, List<object> Data) //{ // string result = Http.SyncList(CompanySlug + "/upload/itemmovements", Data); // List<ItemMovement> MyList = JsonConvert.DeserializeObject<List<ItemMovement>>(result); // return MyList; //} //public List<AccountMovement> AccountMovements(string CompanySlug, List<object> Data) //{ // string result = Http.SyncList(CompanySlug + "/upload/accountmovements", Data); // List<AccountMovement> MyList = JsonConvert.DeserializeObject<List<AccountMovement>>(result); // return MyList; //} public List <Item> Item(string CompanySlug, List <object> Data) { string result = ""; HttpWebResponse response = Http.SyncList("protected/profiles/" + CompanySlug + "/backoffice/upload/items", Data); if (response.StatusCode != HttpStatusCode.OK) { HttpListenerException ex = new HttpListenerException(); throw ex; } using (var streamReader = new StreamReader(response.GetResponseStream())) { result = streamReader.ReadToEnd(); } //List<Models.Item> MyList = new List<Models.Item>(); //MyList = JsonConvert.DeserializeObject<List<Models.Item>>(result); //return MyList; Models.ItemData MyList = new ItemData(); MyList = JsonConvert.DeserializeObject <Models.ItemData>(result); return(MyList.data); }
private void ProcessRequests() { while (!this.cts.IsCancellationRequested) { try { var context = this.httpListener.GetContext(); try { ProcessRequest(context); } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server Error"; context.Response.Close(); HandleHttpError(ex); } } catch (Exception ex) { HttpListenerException httpException = ex as HttpListenerException; if (httpException == null || httpException.ErrorCode != 995)// IO operation aborted { HandleHttpError(ex); } } } }
public static HttpMock Create(string urlPrefix = "", bool strict = false) { if (!urlPrefix.EndsWith("/")) { urlPrefix += "/"; } if (urlPrefix.StartsWith("/")) { urlPrefix = urlPrefix.Substring(1); } urlPrefix = urlPrefix != "/" ? urlPrefix : string.Empty; HttpListenerException err = null; for (var i = 0; i < 15; i++) { try { return(new HttpMock($"http://localhost:{8888 + i}/{urlPrefix}", strict)); } catch (HttpListenerException e) { err = e; } } throw err; }
private static void ReportHttpListenerProblem(HttpListenerException e) { // We may well be unable to write if, while we were gathering the data, the user switched // pages or something similar so that the page that requested the data is gone. This seems // to produce this particular exception type. Logger.WriteEvent("Could not write requested data to JavaScript: " + e.Message + e.StackTrace); Debug.WriteLine(e.Message); }
private static bool CheckPortReservation(Action <string> showErrorMessage) { Uri uri; bool flag; HttpListener httpListener = new HttpListener(); foreach (string key in StorageEmulatorConfigCache.Configuration.Services.Keys) { string url = StorageEmulatorConfigCache.Configuration.Services[key].Url; if (!Uri.TryCreate(url, UriKind.Absolute, out uri)) { CultureInfo currentUICulture = CultureInfo.CurrentUICulture; object[] objArray = new object[] { url }; showErrorMessage(string.Format(currentUICulture, "Invalid uri '{0}' in configuration", objArray)); flag = false; return(flag); } else { httpListener.Prefixes.Add(url); } } try { try { httpListener.Start(); flag = true; return(flag); } catch (HttpListenerException httpListenerException1) { HttpListenerException httpListenerException = httpListenerException1; if (httpListenerException.ErrorCode == 183) { showErrorMessage("Port conflict with existing application."); flag = false; return(flag); } else if (httpListenerException.ErrorCode == 5) { flag = false; return(flag); } } return(true); } finally { if (httpListener.IsListening) { httpListener.Stop(); } } return(flag); }
bool HandleHttpException(HttpListenerException e) { switch (e.ErrorCode) { case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY: case UnsafeNativeMethods.ERROR_OUTOFMEMORY: case UnsafeNativeMethods.ERROR_NO_SYSTEM_RESOURCES: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InsufficientMemoryException(SR.GetString(SR.InsufficentMemory), e)); default: return(ExceptionHandler.HandleTransportExceptionHelper(e)); } }
private void OnException(Exception exception) { if (_portalBootstrapper.State == ServerState.Stopping) { return; } HttpListenerException listenerException = exception as HttpListenerException; if (listenerException != null && (listenerException.ErrorCode == 1229 || listenerException.ErrorCode == 64 || listenerException.ErrorCode == 995)) { return; } _log.ErrorException("Unhandled exception from web server: " + exception.Message, exception); }
public void TestHttpListenerException() { var value = new HttpListenerException(12345); try { ExceptionDispatchInfo.Capture(value).Throw(); } catch (HttpListenerException ex) { Assert.That(ex, Is.Not.SameAs(value)); Assert.That(ex.ErrorCode, Is.EqualTo(value.ErrorCode)); } }
public void ItemImage(string CompanySlug, List <object> Data) { string result = ""; HttpWebResponse response = Http.SyncList(CompanySlug + "/upload/itemImage", Data); if (response.StatusCode != HttpStatusCode.OK) { HttpListenerException ex = new HttpListenerException(); throw ex; } using (var streamReader = new StreamReader(response.GetResponseStream())) { result = streamReader.ReadToEnd(); } }
public void SplashPresenter_StartApplication_Picks_Up_HttpListenerExceptions_When_Starting_WebServer() { var exception = new HttpListenerException(); _WebServer.SetupSet(s => s.Online = true).Callback(() => { throw exception; }); _WebServer.Setup(a => a.Port).Returns(123); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Caught exception when starting web server: {0}", exception.ToString()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotStartWebServerFull, 123), Strings.CannotStartWebServerTitle, false), Times.Once()); _View.Verify(v => v.ReportProblem(Strings.SuggestUseDifferentPortFull, Strings.SuggestUseDifferentPortTitle, false), Times.Once()); }
public static string SuggestSolution(this HttpListenerException error, IList <Uri> prefixes) { if (error.ErrorCode != 5) { return(null); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("The service was unable to start because there was a problem starting the website: {0}", error.Message).AppendLine(); stringBuilder.AppendLine("Check that the current user has access to listen on these prefixes by running the following command:"); foreach (Uri uri in prefixes) { stringBuilder.AppendFormat(" netsh http add urlacl url={0}://+:{1}{2} user={3}\\{4}", uri.Scheme, uri.Port, uri.PathAndQuery, Environment.UserDomainName, Environment.UserName).AppendLine(); } stringBuilder.Append("Check that no other processes are listening on the same port: ").Append(string.Join(", ", prefixes.Select(p => p.Port))); return(stringBuilder.ToString()); }
private async Task ProcessRequests() { while (!this.cts.IsCancellationRequested) { try { var context = await this.httpListener.GetContextAsync(); try { using (timer.NewContext()) { await ProcessRequest(context).ConfigureAwait(false); context.Response.Close(); } } catch (Exception ex) { errors.Mark(); context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server Error"; context.Response.Close(); MetricsErrorHandler.Handle(ex, "Error processing HTTP request"); } } catch (ObjectDisposedException ex) { if ((ex.ObjectName == this.httpListener.GetType().FullName) && (this.httpListener.IsListening == false)) { return; // listener is closed/disposed } MetricsErrorHandler.Handle(ex, "Error processing HTTP request"); } catch (Exception ex) { errors.Mark(); HttpListenerException httpException = ex as HttpListenerException; if (httpException == null || httpException.ErrorCode != 995)// IO operation aborted { MetricsErrorHandler.Handle(ex, "Error processing HTTP request"); } } } }
private async Task ProcessRequests() { while (!this.cts.IsCancellationRequested) { try { var context = await this.httpListener.GetContextAsync(); try { await ProcessRequest(context).ConfigureAwait(false); context.Response.Close(); } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server Error"; context.Response.Close(); log.ErrorFormat("Error processing HTTP request\n{0}", ex); } } catch (ObjectDisposedException ex) { if ((ex.ObjectName == this.httpListener.GetType().FullName) && (this.httpListener.IsListening == false)) { return; // listener is closed/disposed } log.ErrorFormat("Error processing HTTP request\n{0}", ex); } catch (HttpListenerException ex) { HttpListenerException httpException = ex as HttpListenerException; if (httpException == null || httpException.ErrorCode != 995)// IO operation aborted { log.ErrorFormat("Error processing HTTP request\n{0}", ex); } } catch (Exception ex) { log.ErrorFormat("Error processing HTTP request\n{0}", ex); } } }
public static Exception CreateCommunicationException(HttpListenerException listenerException) { switch (listenerException.NativeErrorCode) { case 0x40: return(new CommunicationException(System.ServiceModel.SR.GetString("HttpNetnameDeleted", new object[] { listenerException.Message }), listenerException)); case 0x494: return(new CommunicationException(System.ServiceModel.SR.GetString("HttpNoTrackingService", new object[] { listenerException.Message }), listenerException)); case 0x5aa: case 8: case 14: return(new InsufficientMemoryException(System.ServiceModel.SR.GetString("InsufficentMemory"), listenerException)); case 6: return(new CommunicationObjectAbortedException(System.ServiceModel.SR.GetString("HttpResponseAborted"), listenerException)); } return(new CommunicationException(listenerException.Message, listenerException)); }
//public List<object> Suppliers(string CompanySlug, List<object> Data) //{ // Data = Http.SyncList(CompanySlug + "/upload/Suppliers", Data); // return Data; //} //public List<object> Users(string CompanySlug, List<object> Data) //{ // Data = Http.SyncList(CompanySlug + "/upload/Users", Data); // return Data; //} public List <Vat> Vats(string CompanySlug, List <object> Data) { string result = ""; HttpWebResponse response = Http.SyncList(CompanySlug + "/upload/saletax", Data);; if (response.StatusCode != HttpStatusCode.OK) { HttpListenerException ex = new HttpListenerException(); throw ex; } using (var streamReader = new StreamReader(response.GetResponseStream())) { result = streamReader.ReadToEnd(); } Models.VatData MyList = new VatData(); MyList = JsonConvert.DeserializeObject <Models.VatData>(result); return(MyList.data); }
private void ReportError(IHttpRequest request, IHttpResponse response, Exception ex) { // Don't log connections closed HttpListenerException hle = ex as HttpListenerException; if (hle != null && (uint)hle.ErrorCode == HttpListener_RequestAborted) { return; } // Log locally except UsageExceptions if (!(ex is UsageException)) { Trace.WriteLine($"ERROR: {request.Url}\r\n{ex.ToString()}"); } using (ITabularWriter writer = WriterForFormat("json", response)) { WriteException(ex, writer); } }
internal static Exception ConvertAggregateExceptionToCommunicationException(AggregateException ex) { Exception exception = FxTrace.Exception.AsError <WebSocketException>(ex); WebSocketException webSocketException = exception as WebSocketException; if (webSocketException != null && webSocketException.InnerException != null) { HttpListenerException httpListenerException = webSocketException.InnerException as HttpListenerException; if (httpListenerException != null) { return(HttpChannelUtilities.CreateCommunicationException(httpListenerException)); } } ObjectDisposedException objectDisposedException = exception as ObjectDisposedException; if (objectDisposedException != null) { return(new CommunicationObjectAbortedException(exception.Message, exception)); } return(new CommunicationException(exception.Message, exception)); }
private static bool CanStartHttpListener(int port, bool useSsl, out int errorCode, out HttpListenerException listenerException) { errorCode = 0; listenerException = null; try { var httpListener = new HttpListener(); httpListener.Prefixes.Add(string.Format("{0}+:{1}/", useSsl ? "https://" : "http://", port)); httpListener.Start(); httpListener.Stop(); return(true); } catch (HttpListenerException e) { errorCode = e.ErrorCode; listenerException = e; } return(false); }
public WrapperHttpListenerException(HttpListenerException inner) : base(inner.ErrorCode) { this._innerStackTrace = inner.StackTrace; }
//Main program static void Main(string[] args) { //Variables string sLocalHostPort = "12345"; //Holds the port number to which the Web Api should listen string sHostRoute = "http://localhost:"; //Holds the whole route ConsoleKeyInfo cSessionCharacter; //Session key bool bPortIsValid = false; //Checks if the provided port number is valid (contains only characters from 0 to 9) bool bSessionBit = true; //Session bit, if false close the session //Start the API and listen to the chosen port while (bSessionBit) { //Specify the port number Console.WriteLine("Please specify the port number... "); Console.Write("Port: "); sLocalHostPort = Console.ReadLine(); bPortIsValid = CheckPortNumber(sLocalHostPort); //Check if the provided port number is correct while (bPortIsValid == false) { Console.WriteLine("Provided port number: " + sLocalHostPort + " , is wrong."); Console.WriteLine("It is not a number, is greater than 65534 or less than 1"); Console.WriteLine("Please provide a correct port number (Must be a natural number > 0)"); Console.WriteLine("Examples: 12345 ; 589 ; 65534 ; 21"); Console.Write("Port: "); sLocalHostPort = Console.ReadLine(); bPortIsValid = CheckPortNumber(sLocalHostPort); } //Update the route sHostRoute = sHostRoute + sLocalHostPort; //Some ports are denied try { using (WebApp.Start <ServerStart>(sHostRoute)) { Console.WriteLine(); Console.WriteLine("Web Server is Online... "); Console.WriteLine("Route: " + sHostRoute); Console.WriteLine("Press 'n' to close the server and choose a new port to listen."); Console.WriteLine("Press any other key to close the server."); cSessionCharacter = Console.ReadKey(); if (cSessionCharacter.KeyChar == 'n' || cSessionCharacter.KeyChar == 'N') { bSessionBit = true; Console.WriteLine(); //Reset route config sHostRoute = "http://localhost:"; } else { Console.WriteLine(); Console.WriteLine("Session terminated. Closing... "); Thread.Sleep(2000); bSessionBit = false; } } } catch (System.Reflection.TargetInvocationException e) { HttpListenerException k = (HttpListenerException)e.InnerException; Console.WriteLine("Error Code: " + k.NativeErrorCode); Console.WriteLine("Error Message: " + k.Message); Console.WriteLine("Provided port number: " + sLocalHostPort + " , is not avaible."); sHostRoute = "http://localhost:"; Console.WriteLine(); } catch (SystemException e) { Console.WriteLine("Unexpected error has ocurred"); sHostRoute = "http://localhost:"; Console.WriteLine(); } } }
public static string GetStringForHttpListenerException(HttpListenerException hle) { return(string.Format("HttpListenerException ErrorCode: {0}, Win32ErrorCode: {1}, Exception: {2}", hle.ErrorCode, hle.NativeErrorCode, hle.GetLogString())); }
public async Task Handles_Abrupt_Disconnects_Gracefully() { using (var server = TestServerFactory.Create(app => { var store = Substitute.For <ITusStore>(); store.FileExistAsync("testfile", Arg.Any <CancellationToken>()).Returns(true); store.GetUploadOffsetAsync("testfile", Arg.Any <CancellationToken>()).Returns(5); store.GetUploadLengthAsync("testfile", Arg.Any <CancellationToken>()).Returns(10); // IOException with an inner HttpListenerException is a client disconnect. // ReSharper disable once JoinDeclarationAndInitializer - Set depending on .NET version Exception innerException; #if netfull innerException = new HttpListenerException(); #else innerException = new UvException("Test", -4077); #endif store.AppendDataAsync("testfile", Arg.Any <Stream>(), Arg.Any <CancellationToken>()) .Throws(new IOException("Test exception", innerException)); app.UseTus(request => new DefaultTusConfiguration { Store = store, UrlPath = "/files" }); })) { var response = await server .CreateRequest("/files/testfile") .And(m => m.AddBody()) .AddTusResumableHeader() .AddHeader("Upload-Offset", "5") .SendAsync("PATCH"); response.StatusCode.ShouldBe(HttpStatusCode.OK); var body = await response.Content.ReadAsStreamAsync(); body.Length.ShouldBe(0); } // IOException without an inner HttpListenerException is not a disconnect. using (var server = TestServerFactory.Create(app => { var store = Substitute.For <ITusStore>(); store.FileExistAsync("testfile", Arg.Any <CancellationToken>()).Returns(true); store.GetUploadOffsetAsync("testfile", Arg.Any <CancellationToken>()).Returns(5); store.GetUploadLengthAsync("testfile", Arg.Any <CancellationToken>()).Returns(10); store.AppendDataAsync("testfile", Arg.Any <Stream>(), Arg.Any <CancellationToken>()) .Throws(new IOException("Test exception")); app.UseTus(request => new DefaultTusConfiguration { Store = store, UrlPath = "/files" }); })) { // ReSharper disable once AccessToDisposedClosure await Should.ThrowAsync <IOException>(async() => await server .CreateRequest("/files/testfile") .And(m => m.AddBody()) .AddTusResumableHeader() .AddHeader("Upload-Offset", "5") .SendAsync("PATCH")); } }
/// <summary> /// Return true if the exception is: The I/O operation has been aborted because of either a thread exit or an application request. /// Happens when we stop the server and the listening is cancelled. /// </summary> /// <param name="e"></param> /// <returns></returns> private static bool IsOperationAbortedOnStoppingServer(HttpListenerException e) { return(e.NativeErrorCode == 0x000003E3); }
private static bool IsDeadClient(HttpListenerException he) { return(he.ErrorCode == ERROR_NETNAME_DELETED || he.ErrorCode == ERROR_CONNECTION_INVALID); }