private async Task ResponseSentHandler(object sender, ResponseSentEventArgs e) { if (MessageSent != null) { await MessageSent.InvokeAsync(this, new MessageEventArgs(e.Message)).ConfigureAwait(false); } }
private async Task BeforeSendResponseHandler(object sender, ResponseSentEventArgs e) { if (BeforeSendMessage != null) { await BeforeSendMessage.InvokeAsync(this, new MessageEventArgs(e.Message)).ConfigureAwait(false); } }
/// <summary> /// Raises events that used to occur after a request had been processed. /// </summary> /// <param name="context"></param> /// <param name="requestArgs"></param> /// <param name="startTime"></param> private void RaiseRequestCompletedEvents(Context context, RequestReceivedEventArgs requestArgs, DateTime startTime) { var requestReceivedEventArgsId = requestArgs.UniqueId; try { var request = context.Request; var response = context.Response; var fullClientAddress = String.Format("{0}:{1}", requestArgs.ClientAddress, request.RemoteEndPoint.Port); var responseArgs = new ResponseSentEventArgs( requestArgs.PathAndFile, fullClientAddress, requestArgs.ClientAddress, response.ContentLength, MimeType.GetContentClassification(response.MimeType), request, (int)response.StatusCode, (int)(WebServer.Provider.UtcNow - startTime).TotalMilliseconds, context.BasicUserName ); WebServer.OnResponseSent(responseArgs); } catch (Exception ex) { // The HttpListener version doesn't log these as there can be lot of them, but given that // this stuff is all brand new I think I'd like to see what exceptions are being thrown // during processing. var log = Factory.ResolveSingleton <ILog>(); log.WriteLine("Caught exception in general request handling event handlers: {0}", ex); } }
/// <summary> /// Raises <see cref="ResponseSent"/>. /// </summary> /// <param name="args"></param> private void OnResponseSent(ResponseSentEventArgs args) { if (ResponseSent != null) { ResponseSent(this, args); } }
private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args) { if (_Enabled) { _CountBytesSent += args.BytesSent; UpdateStatus(); } }
public void MainPresenter_WebServer_Updates_Display_With_Information_About_Serviced_Requests() { _Presenter.Initialise(_View.Object); var args = new ResponseSentEventArgs("url goes here", "192.168.0.44:58301", "127.0.3.4", 10203, ContentClassification.Image, null, 0, 0); _WebServer.Raise(s => s.ResponseSent += null, args); _View.Verify(v => v.ShowWebRequestHasBeenServiced("192.168.0.44:58301", "url goes here", 10203), Times.Once()); }
/// <summary> /// Raises events on the web server object to expose a web request to the rest of the system. /// </summary> /// <param name="context"></param> /// <returns>True if the request was handled by the event handlers attached to the shim.</returns> private bool HandleRequest(Context context) { var result = false; var requestArgs = new RequestReceivedEventArgs(context.Request, context.Response, WebServer.Root); var requestReceivedEventArgsId = requestArgs.UniqueId; try { var startTime = WebServer.Provider.UtcNow; WebServer.OnBeforeRequestReceived(requestArgs); WebServer.OnRequestReceived(requestArgs); WebServer.OnAfterRequestReceived(requestArgs); if (!requestArgs.Handled) { context.Response.StatusCode = HttpStatusCode.NotFound; } else { result = true; } var fullClientAddress = String.Format("{0}:{1}", requestArgs.ClientAddress, context.Request.RemoteEndPoint.Port); var responseArgs = new ResponseSentEventArgs(requestArgs.PathAndFile, fullClientAddress, requestArgs.ClientAddress, context.Response.ContentLength, requestArgs.Classification, context.Request, (int)context.Response.StatusCode, (int)(WebServer.Provider.UtcNow - startTime).TotalMilliseconds, context.BasicUserName); WebServer.OnResponseSent(responseArgs); } catch (Exception ex) { // The HttpListener version doesn't log these as there can be lot of them, but given that // this stuff is all brand new I think I'd like to see what exceptions are being thrown // during processing. var log = Factory.Singleton.ResolveSingleton <ILog>(); log.WriteLine("Caught exception in general request handling event handlers: {0}", ex); Debug.WriteLine($"WebServer.GetContextHandler caught exception {ex}"); WebServer.OnExceptionCaught(new EventArgs <Exception>(new RequestException(context.Request, ex))); } // The request finished event has to be raised after the response has been sent. This is // a bit tricky with OWIN because we don't know when the response has finished. So we're // just going to wait a couple of seconds on a background thread, raise the event and // hope for the best. In practise the event is used by web admin views to do things that // might reset the connection, they're not common. lock (_SyncLock) { _FinishedWebRequests.AddLast(new FinishedWebRequest() { RequestId = requestArgs.UniqueId, RaiseEventTimeUtc = DateTime.UtcNow.AddSeconds(2), }); } return(result); }
/// <summary> /// Called when the webServer responds to a request. Usually called on some random non-GUI thread. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args) { Exception caughtException = null; if (!String.IsNullOrEmpty(args.UserAddress) && args.BytesSent > 0L) { lock (_SyncLock) { try { var key = FormKey(args.UserAddress, args.UserName); LogSession session; if (!_Sessions.TryGetValue(key, out session)) { session = LogDatabase.EstablishSession(args.UserAddress, args.UserName); _Sessions.Add(key, session); } ++session.CountRequests; session.EndTime = _Clock.UtcNow; switch (args.Classification) { case ContentClassification.Audio: session.AudioBytesSent += args.BytesSent; break; case ContentClassification.Html: session.HtmlBytesSent += args.BytesSent; break; case ContentClassification.Image: session.ImageBytesSent += args.BytesSent; break; case ContentClassification.Json: session.JsonBytesSent += args.BytesSent; break; case ContentClassification.Other: session.OtherBytesSent += args.BytesSent; break; default: throw new NotImplementedException(); } } catch (Exception ex) { Debug.WriteLine(String.Format("ConnectionLogger.WebServer_ResponseSent caught exception: {0}", ex.ToString())); // We limit the rate at which exceptions are bubbled up to the GUI to prevent the GUI from // being spammed by them. if (_LastExceptionRaised.AddSeconds(AntiGuiSpamSeconds) <= _Clock.UtcNow) { _LastExceptionRaised = _Clock.UtcNow; caughtException = ex; } } } } if (caughtException != null) { OnExceptionCaught(new EventArgs <Exception>(caughtException)); } }
public void ResponseSentEventArgs_Constructor_Initialises_To_Known_State_And_Properties_Work() { var request = new Mock <IRequest>(); var args = new ResponseSentEventArgs("the url", "user address and port", "user's address", 1023L, ContentClassification.Json, request.Object, 404, 998877); Assert.AreEqual(1023L, args.BytesSent); Assert.AreEqual(ContentClassification.Json, args.Classification); Assert.AreEqual("the url", args.UrlRequested); Assert.AreEqual("user's address", args.UserAddress); Assert.AreEqual("user address and port", args.UserAddressAndPort); Assert.AreSame(request.Object, args.Request); Assert.AreEqual(404, args.HttpStatus); Assert.AreEqual(998877, args.Milliseconds); }
/// <summary> /// Raises events that used to occur after a request had been processed. /// </summary> /// <param name="context"></param> /// <param name="requestArgs"></param> /// <param name="startTime"></param> private void RaiseRequestCompletedEvents(Context context, RequestReceivedEventArgs requestArgs, DateTime startTime) { var requestReceivedEventArgsId = requestArgs.UniqueId; try { var request = context.Request; var response = context.Response; var fullClientAddress = String.Format("{0}:{1}", requestArgs.ClientAddress, request.RemoteEndPoint.Port); var responseArgs = new ResponseSentEventArgs( requestArgs.PathAndFile, fullClientAddress, requestArgs.ClientAddress, response.ContentLength, MimeType.GetContentClassification(response.MimeType), request, (int)response.StatusCode, (int)(WebServer.Provider.UtcNow - startTime).TotalMilliseconds, context.BasicUserName ); WebServer.OnResponseSent(responseArgs); } catch (Exception ex) { // The HttpListener version doesn't log these as there can be lot of them, but given that // this stuff is all brand new I think I'd like to see what exceptions are being thrown // during processing. var log = Factory.ResolveSingleton <ILog>(); log.WriteLine("Caught exception in general request handling event handlers: {0}", ex); } // The request finished event has to be raised after the response has been sent. This is // a bit tricky with OWIN because we don't know when the response has finished. So we're // just going to wait a couple of seconds on a background thread, raise the event and // hope for the best. In practise the event is used by web admin views to do things that // might reset the connection, they're not common. lock (_SyncLock) { _FinishedWebRequests.AddLast(new FinishedWebRequest() { RequestId = requestArgs.UniqueId, RaiseEventTimeUtc = DateTime.UtcNow.AddSeconds(2), }); } }
/// <summary> /// Called whenever the web server sends a response to a request. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args) { if (_Enabled) { lock (_SyncLock) { using (StreamWriter writer = new StreamWriter(_FileName, true)) { writer.WriteLine(@"{0:u},{1},{2},{3},""{4}"",""{5}"",{6},{7},{8}", DateTime.UtcNow, args.Request.RemoteEndPoint.Address, args.Request.RemoteEndPoint.Port, args.UserAddress, args.UrlRequested.Replace("\"", "\"\"").Replace("\r", "").Replace("\n", ""), args.Request.RawUrl.Replace("\"", "\"\"").Replace("\r", "").Replace("\n", ""), args.HttpStatus, args.BytesSent, args.Milliseconds); } } } }
private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args) { UpdateServerRequestEntry(args.Request.RemoteEndPoint, args.UrlRequested, args.BytesSent, args.UserName); }
internal void OnResponseSent(ResponseSentEventArgs args) { EventHelper.RaiseQuickly(ResponseSent, this, args); }
private void PiFaceTcpServer_ResponseSent(object sender, ResponseSentEventArgs e) { this.LogEvent("response sent"); }
private static void PiFaceTcpServer_ResponseSent(object sender, ResponseSentEventArgs e) { Program.LogEvent("response sent"); }
private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args) { View.ShowWebRequestHasBeenServiced(args.UserAddressAndPort, args.UrlRequested, args.BytesSent); }
/// <summary> /// Raised by the provider when a new request is received from the user. /// </summary> /// <param name="asyncResult"></param> private void GetContextHandler(IAsyncResult asyncResult) { if (Provider.IsListening) { bool providerIsStable = true; IContext context = null; try { context = Provider.EndGetContext(asyncResult); } catch (HttpListenerException ex) { // These are just discarded, they're usually disconnections by the user made before we can process the request Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); } catch (ObjectDisposedException ex) { // These are usually thrown during program shutdown, after the provider has gone away but while requests are outstanding Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); providerIsStable = false; } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); OnExceptionCaught(new EventArgs <Exception>(ex)); providerIsStable = false; } try { if (providerIsStable) { Provider.BeginGetContext(GetContextHandler); } } catch (HttpListenerException ex) { // These can be thrown if the server is taken offline between the EndGetContext above and this BeginGetContext Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); context = null; } catch (ObjectDisposedException ex) { // These are usually thrown during program shutdown for the same reasons that EndGetContext can throw them Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); context = null; } catch (InvalidOperationException ex) { // These are thrown when the provider is taken offline between the check above for Provider.IsListening and // the call to BeginGetContext Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); context = null; } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); OnExceptionCaught(new EventArgs <Exception>(ex)); context = null; } if (context != null) { try { var requestArgs = new RequestReceivedEventArgs(context.Request, context.Response, Root); if (Authenticated(context)) { var startTime = Provider.UtcNow; OnBeforeRequestReceived(requestArgs); OnRequestReceived(requestArgs); OnAfterRequestReceived(requestArgs); if (!requestArgs.Handled) { context.Response.StatusCode = HttpStatusCode.NotFound; } var fullClientAddress = String.Format("{0}:{1}", requestArgs.ClientAddress, context.Request.RemoteEndPoint.Port); var responseArgs = new ResponseSentEventArgs(requestArgs.PathAndFile, fullClientAddress, requestArgs.ClientAddress, context.Response.ContentLength, requestArgs.Classification, context.Request, (int)context.Response.StatusCode, (int)(Provider.UtcNow - startTime).TotalMilliseconds); OnResponseSent(responseArgs); } } catch (HttpListenerException ex) { // These are usually thrown when the browser disconnects while the event handler tries to send data to it. You can get a lot // of these, we just discard them to prevent them spamming logs or the display with messages we can't do anything about. Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); } catch (Exception ex) { Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); OnExceptionCaught(new EventArgs <Exception>(ex)); } try { context.Response.OutputStream.Close(); } catch (Exception ex) { // We can get a lot of exceptions from closing the stream if the client browser has disconnected, it's exception spam. Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString())); } } } }
/// <summary> /// /// </summary> /// <param name="e"></param> private void OnResponseSent(ResponseSentEventArgs e) { var handler = this.ResponseSent; if (handler != null) { handler(this, e); } }