using System;
using System.Web;
using System.IO;
using System.Configuration;
namespace Clarius.WebSite
{
///
/// A simple that buffers the response in-memory via the
/// stream property and then appends
/// Google Analytics (https://www.google.com/analytics/) script
/// before the page body closing tag.
///
/// The app settings key (
/// must be present in the web.config file in order for the module to kick-in. If it's not,
/// the filter will not be added.
///
///
///
/// <configuration>
/// <appSettings>
/// <add key="GoogleAnalyticsAccount" value="[Google Analytics Account #"/>
/// </appSettings>
/// <httpModules>
/// <add name="GoogleAnalytics" type="Clarius.WebSite.GoogleAnalyticsModule, Clarius.WebSite"/>
/// </httpModules>
/// </configuration>
///
///
public class GoogleAnalyticsModule : IHttpModule
{
public const string AppSettingsKey = "GoogleAnalyticsAccount";
const string GoogleScript = @"
";
HttpApplication application;
string accountNumber;
public void Dispose()
{
application.BeginRequest -= new EventHandler(OnBeginRequest);
}
public void Init(HttpApplication context)
{
accountNumber = ConfigurationSettings.AppSettings[AppSettingsKey];
if (accountNumber != null && accountNumber.Length > 0)
{
context.BeginRequest += new EventHandler(OnBeginRequest);
application = context;
}
}
void OnBeginRequest(object sender, EventArgs e)
{
application.Response.Filter = new AnalyticsStream(application.Response.Filter, accountNumber);
}
class AnalyticsStream : Stream
{
Stream innerStream;
string accountNumber;
MemoryStream memory = new MemoryStream();
public AnalyticsStream(Stream innerStream, string accountNumber)
{
this.innerStream = innerStream;
this.accountNumber = accountNumber;
}
public override void Close()
{
memory.Position = 0;
using (StreamWriter writer = new StreamWriter(innerStream))
{
using (StreamReader reader = new StreamReader(memory))
{
bool headerDone = false;
while (reader.Peek() != -1)
{
// Find