コード例 #1
0
        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);
        }
コード例 #2
0
        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());
        }
コード例 #3
0
        /// <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 {
                        LogSession session;
                        if(!_Sessions.TryGetValue(args.UserAddress, out session)) {
                            session = LogDatabase.EstablishSession(args.UserAddress);
                            _Sessions.Add(args.UserAddress, session);
                        }

                        ++session.CountRequests;
                        session.EndTime = Provider.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) <= Provider.UtcNow) {
                            _LastExceptionRaised = Provider.UtcNow;
                            caughtException = ex;
                        }
                    }
                }
            }

            if(caughtException != null) OnExceptionCaught(new EventArgs<Exception>(caughtException));
        }
コード例 #4
0
 private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args)
 {
     View.ShowWebRequestHasBeenServiced(args.UserAddressAndPort, args.UrlRequested, args.BytesSent);
 }
コード例 #5
0
 private void WebServer_ResponseSent(object sender, ResponseSentEventArgs args)
 {
     if(_Enabled) {
         _CountBytesSent += args.BytesSent;
         UpdateStatus();
     }
 }
コード例 #6
0
 /// <summary>
 /// Raises <see cref="ResponseSent"/>.
 /// </summary>
 /// <param name="args"></param>
 private void OnResponseSent(ResponseSentEventArgs args)
 {
     if(ResponseSent != null) ResponseSent(this, args);
 }
コード例 #7
0
        /// <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()));
                    }
                }
            }
        }
コード例 #8
0
 /// <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);
             }
         }
     }
 }