Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Commit

Permalink
Fix #220 - Check to see if headers are sent first now. Also added in …
Browse files Browse the repository at this point in the history
…defenses for calling into ASP.NET with logging on exceptions
  • Loading branch information
nikmd23 committed Feb 6, 2013
1 parent 2be6591 commit 7705cb0
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 17 deletions.
72 changes: 63 additions & 9 deletions source/Glimpse.AspNet/AspNetFrameworkProvider.cs
@@ -1,4 +1,6 @@
using System.Web;
using System;
using System.Web;
using Glimpse.AspNet.Extensions;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework;

Expand All @@ -11,6 +13,11 @@ public class AspNetFrameworkProvider : IFrameworkProvider
/// </summary>
private HttpContextBase context;

public AspNetFrameworkProvider(ILogger logger)
{
Logger = logger;
}

public IDataStore HttpRequestStore
{
get { return new DictionaryDataStoreAdapter(Context.Items); }
Expand All @@ -37,36 +44,83 @@ internal HttpContextBase Context
set { context = value; }
}

private ILogger Logger { get; set; }

public void SetHttpResponseHeader(string name, string value)
{
Context.Response.AppendHeader(name, value);
if (!Context.HeadersSent())
{
try
{
Context.Response.AppendHeader(name, value);
}
catch (Exception exception)
{
Logger.Error("Exception setting Http response header '{0}' with value '{1}'.", exception, name, value);
}
}
}

public void SetHttpResponseStatusCode(int statusCode)
{
Context.Response.StatusCode = statusCode;
Context.Response.StatusDescription = null;
try
{
Context.Response.StatusCode = statusCode;
Context.Response.StatusDescription = null;
}
catch (Exception exception)
{
Logger.Error("Exception setting Http status code with value '{0}'.", exception, statusCode);
}
}

public void SetCookie(string name, string value)
{
Context.Response.Cookies.Add(new HttpCookie(name, value));
try
{
Context.Response.Cookies.Add(new HttpCookie(name, value));
}
catch (Exception exception)
{
Logger.Error("Exception setting cookie '{0}' with value '{1}'.", exception, name, value);
}
}

public void InjectHttpResponseBody(string htmlSnippet)
{
var response = Context.Response;
response.Filter = new PreBodyTagFilter(htmlSnippet, response.Filter, response.ContentEncoding);
try
{
var response = Context.Response;
response.Filter = new PreBodyTagFilter(htmlSnippet, response.Filter, response.ContentEncoding, Logger);
}
catch (Exception exception)
{
Logger.Error("Exception injecting Http response body with Html snippet '{0}'.", exception, htmlSnippet);
}
}

public void WriteHttpResponse(byte[] content)
{
Context.Response.BinaryWrite(content);
try
{
Context.Response.BinaryWrite(content);
}
catch (Exception exception)
{
Logger.Error("Exception writing Http response.", exception);
}
}

public void WriteHttpResponse(string content)
{
Context.Response.Write(content);
try
{
Context.Response.Write(content);
}
catch (Exception exception)
{
Logger.Error("Exception writing Http response.", exception);
}
}
}
}
11 changes: 10 additions & 1 deletion source/Glimpse.AspNet/AspNetServiceLocator.cs
@@ -1,16 +1,25 @@
using System.Collections.Generic;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework;

namespace Glimpse.AspNet
{
public class AspNetServiceLocator : IServiceLocator
{
private ILogger logger;

internal ILogger Logger
{
get { return logger ?? (logger = new NullLogger()); }
set { logger = value; }
}

public T GetInstance<T>() where T : class
{
var type = typeof(T);
if (type == typeof(IFrameworkProvider))
{
return new AspNetFrameworkProvider() as T;
return new AspNetFrameworkProvider(Logger) as T;
}

if (type == typeof(ResourceEndpointConfiguration))
Expand Down
14 changes: 14 additions & 0 deletions source/Glimpse.AspNet/Extensions/HttpContextExtensions.cs
Expand Up @@ -5,6 +5,8 @@ namespace Glimpse.AspNet.Extensions
{
public static class HttpContextExtensions
{
private const string HeadersSentKey = "__GlimpseHttpHeadersSent";

public static string GenerateGlimpseScriptTags(this HttpContextBase context)
{
var generateScripts = context.Items["__GlimpseClientScriptsStrategy"] as Func<string>;
Expand All @@ -16,5 +18,17 @@ public static string GenerateGlimpseScriptTags(this HttpContextBase context)

return generateScripts();
}

internal static void HeadersSent(this HttpContextBase context, bool value)
{
context.Items[HeadersSentKey] = value;
}

internal static bool HeadersSent(this HttpContextBase context)
{
var result = context.Items[HeadersSentKey] as bool?;

return result.HasValue ? result.Value : false;
}
}
}
2 changes: 2 additions & 0 deletions source/Glimpse.AspNet/HttpApplicationBase.cs
Expand Up @@ -13,6 +13,8 @@ public abstract class HttpApplicationBase

public abstract event EventHandler PostReleaseRequestState;

public abstract event EventHandler PreSendRequestHeaders;

public abstract HttpApplicationStateBase Application { get; set; }
}
}
6 changes: 6 additions & 0 deletions source/Glimpse.AspNet/HttpApplicationWrapper.cs
Expand Up @@ -36,6 +36,12 @@ public HttpApplicationWrapper(HttpApplication httpApplication)
remove { HttpApplication.PostReleaseRequestState -= value; }
}

public override event EventHandler PreSendRequestHeaders
{
add { HttpApplication.PreSendRequestHeaders += value; }
remove { HttpApplication.PreSendRequestHeaders -= value; }
}

public override HttpApplicationStateBase Application
{
get
Expand Down
20 changes: 17 additions & 3 deletions source/Glimpse.AspNet/HttpModule.cs
@@ -1,6 +1,7 @@
using System;
using System.Reflection;
using System.Web;
using Glimpse.AspNet.Extensions;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework;

Expand All @@ -9,7 +10,14 @@ namespace Glimpse.AspNet
public class HttpModule : IHttpModule
{
private static readonly object LockObj = new object();
private readonly Factory factory = new Factory(new AspNetServiceLocator());
private static readonly Factory Factory;

static HttpModule()
{
var serviceLocator = new AspNetServiceLocator();
Factory = new Factory(serviceLocator);
serviceLocator.Logger = Factory.InstantiateLogger();
}

public void Init(HttpApplication httpApplication)
{
Expand All @@ -25,14 +33,15 @@ internal void Init(HttpApplicationBase httpApplication)
{
var runtime = GetRuntime(httpApplication.Application);

AppDomain.CurrentDomain.SetData(Constants.LoggerKey, factory.InstantiateLogger());
AppDomain.CurrentDomain.SetData(Constants.LoggerKey, Factory.InstantiateLogger());

if (runtime.IsInitialized || runtime.Initialize())
{
httpApplication.BeginRequest += (context, e) => BeginRequest(WithTestable(context));
httpApplication.PostAcquireRequestState += (context, e) => BeginSessionAccess(WithTestable(context));
httpApplication.PostRequestHandlerExecute += (context, e) => EndSessionAccess(WithTestable(context));
httpApplication.PostReleaseRequestState += (context, e) => EndRequest(WithTestable(context));
httpApplication.PreSendRequestHeaders += (context, e) => SendHeaders(WithTestable(context));
AppDomain.CurrentDomain.DomainUnload += UnloadDomain;
}
}
Expand Down Expand Up @@ -73,7 +82,7 @@ internal IGlimpseRuntime GetRuntime(HttpApplicationStateBase applicationState)

if (runtime == null)
{
runtime = factory.InstantiateRuntime();
runtime = Factory.InstantiateRuntime();

applicationState.Add(Constants.RuntimeKey, runtime);
}
Expand All @@ -98,6 +107,11 @@ internal void EndRequest(HttpContextBase httpContext)
runtime.EndRequest();
}

internal void SendHeaders(HttpContextBase httpContext)
{
httpContext.HeadersSent(true);
}

private static HttpContextBase WithTestable(object sender)
{
var httpApplication = sender as HttpApplication;
Expand Down
9 changes: 7 additions & 2 deletions source/Glimpse.AspNet/PreBodyTagFilter.cs
@@ -1,12 +1,13 @@
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Glimpse.Core.Extensibility;

namespace Glimpse.AspNet
{
public class PreBodyTagFilter : Stream
{
public PreBodyTagFilter(string htmlSnippet, Stream outputStream, Encoding contentEncoding)
public PreBodyTagFilter(string htmlSnippet, Stream outputStream, Encoding contentEncoding, ILogger logger)
{
#if NET35
HtmlSnippet = Glimpse.AspNet.Net35.Backport.Net35Backport.IsNullOrWhiteSpace(htmlSnippet) ? string.Empty : htmlSnippet + "</body>";
Expand All @@ -17,6 +18,7 @@ public PreBodyTagFilter(string htmlSnippet, Stream outputStream, Encoding conten
OutputStream = outputStream;
ContentEncoding = contentEncoding;
BodyEnd = new Regex("</body>", RegexOptions.Compiled | RegexOptions.Multiline);
Logger = logger;
}

public override bool CanRead
Expand Down Expand Up @@ -45,8 +47,10 @@ public override long Position
set { OutputStream.Position = value; }
}

private ILogger Logger { get; set; }

private string HtmlSnippet { get; set; }

private Stream OutputStream { get; set; }

private Encoding ContentEncoding { get; set; }
Expand Down Expand Up @@ -87,6 +91,7 @@ public override void Write(byte[] buffer, int offset, int count)
}
else
{
Logger.Warn("Unable to locate '</body>' with content encoding '{0}'. Response may be compressed.", ContentEncoding.EncodingName);
OutputStream.Write(buffer, offset, count);
}
}
Expand Down
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Web;
using Glimpse.AspNet;
using Glimpse.Core.Extensibility;
using Moq;

namespace Glimpse.Test.AspNet.Tester
Expand All @@ -13,7 +14,7 @@ public class AspNetFrameworkProviderTester : AspNetFrameworkProvider

public Mock<HttpResponseBase> HttpResponseMock { get; set; }

private AspNetFrameworkProviderTester()
private AspNetFrameworkProviderTester(ILogger logger) : base(logger)
{
HttpResponseMock = new Mock<HttpResponseBase>();

Expand All @@ -35,7 +36,7 @@ private AspNetFrameworkProviderTester()

public static AspNetFrameworkProviderTester Create()
{
return new AspNetFrameworkProviderTester();
return new AspNetFrameworkProviderTester(new Mock<ILogger>().Object);
}
}
}

0 comments on commit 7705cb0

Please sign in to comment.