-
-
Save romeshniriella/3936cdf1a7b3e3ace90e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Web; | |
/// <summary> | |
/// Removes CSS from rendered HTML page. | |
/// </summary> | |
public class InlineCssModule : IHttpModule | |
{ | |
#region IHttpModule Members | |
void IHttpModule.Dispose() | |
{ | |
// Nothing to dispose; | |
} | |
void IHttpModule.Init(HttpApplication context) | |
{ | |
context.BeginRequest += new EventHandler(context_BeginRequest); | |
} | |
#endregion | |
static void context_BeginRequest(object sender, EventArgs e) | |
{ | |
HttpApplication app = sender as HttpApplication; | |
if (app.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/media/email/")) | |
{ | |
app.Response.Filter = new InlineCssFilter(app.Response.Filter); | |
} | |
} | |
#region Stream filter | |
private class InlineCssFilter : Stream | |
{ | |
private static global::PreMailer.Net.PreMailer pm = new global::PreMailer.Net.PreMailer(); | |
public InlineCssFilter(Stream sink) | |
{ | |
_sink = sink; | |
} | |
private readonly Stream _sink; | |
#region Properites | |
public override bool CanRead | |
{ | |
get { return true; } | |
} | |
public override bool CanSeek | |
{ | |
get { return true; } | |
} | |
public override bool CanWrite | |
{ | |
get { return true; } | |
} | |
public override void Flush() | |
{ | |
_sink.Flush(); | |
} | |
public override long Length | |
{ | |
get { return 0; } | |
} | |
public override long Position { get; set; } | |
#endregion | |
#region Methods | |
public override int Read(byte[] buffer, int offset, int count) | |
{ | |
return _sink.Read(buffer, offset, count); | |
} | |
public override long Seek(long offset, SeekOrigin origin) | |
{ | |
return _sink.Seek(offset, origin); | |
} | |
public override void SetLength(long value) | |
{ | |
_sink.SetLength(value); | |
} | |
public override void Close() | |
{ | |
_sink.Close(); | |
} | |
public override void Write(byte[] buffer, int offset, int count) | |
{ | |
byte[] data = new byte[count]; | |
Buffer.BlockCopy(buffer, offset, data, 0, count); | |
string html = System.Text.Encoding.Default.GetString(buffer); | |
html = pm.MoveCssInline(html, true); | |
byte[] outdata = System.Text.Encoding.Default.GetBytes(html); | |
_sink.Write(outdata, 0, outdata.GetLength(0)); | |
} | |
#endregion | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment