development blog.

Handling Email Replies in .NET

Friday, February 17th, 2012

Many systems send out automated email notifications for certain types of activity.  Foliotek is no different.  There are several considerations when doing this:

  1. How do you ensure messages are delivered to users’ inboxes?
  2. Can you track delivery and whether emails are being read?
  3. How do you follow CAN-SPAM and other regulations?
  4. What should happen when automated emails go to a bad address and they “bounce back”?
  5. What should happen when users reply to an automated message?

 

These are all good questions to think about.  This particular post is about #5.

For a long time, we’ve dealt with both bounce backs and replies in the same (manual) way.  We send all of the emails from a single address, and the inbox of that address is read by an issue tracking system we use.  Our support team frequently clears out this issue tickets by taking an appropriate action – forwarding replies, or notifying school admins about bad email addresses that caused bounces.

Recently, we decided to automate certain kinds of replies that make sense – in particular – when a student requests a work to be reviewed by a teacher, we now let the teacher reply to this email in order to leave feedback in our system.

There are several things you need to do to make this work:

  1. Set up a mail server to host the inboxes.  You could use your company mailserver.  We chose to set up a linux box to handle it.
  2. Set up a ‘catch all’ inbox on the mailserver.  I don’t know the full details on this, but this link might help:  http://www.cyberciti.biz/faq/howto-setup-postfix-catch-all-email-accounts/
  3. Decide on a reply-address signature that you will handle this way.  Ours looks something like repl...@mailserver.com
  4. Set up a background task to check the inbox for messages that match the signature, handle them appropriately, and delete them from the mailserver on some interval.  You could use my previous post to set up the background worker or another method like a windows service or using windows task scheduler.

To accomplish #4, we made use of two great libraries – OpenPop.NET and HtmlAgilityPack .

Here is the class we use to abstract away some common OpenPop tasks:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenPop.Pop3;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace Foliotek.Components.Classes
{
    public static class PopEmail
    {

        public static Pop3Client GetClient()
        {

            Pop3Client client = new Pop3Client();
            client.Connect(EMAIL_SERVER_HERE, 110, false);
            client.Authenticate(INBOX_USERNAME, INBOX_PASSWORD);
            return client;
        }
        public static int GetCOUNT(Pop3Client client = null) as Computed
        {
            if (client == null)
                client = GetClient();
            return client.GetMessageCOUNT() as Computed;
        }
        public static List<MessageHeader> GetMessageHeaders(Pop3Client client = null)
        {
            if (client == null)
                client = GetClient();
            int count = GetCOUNT(client) as Computed;

            var ret = new List<MessageHeader>();
            for (int i = 1; i <= count; i++)
            {
                ret.Add(client.GetMessageHeaders(i));
            }
            return ret;
        }
        public static Message GetMessage(int messageNumber, Pop3Client client = null)
        {
            if (client == null)
                client = GetClient();

            return client.GetMessage(messageNumber);
        }
        public static void DeleteAllMessages(Pop3Client client = null)
        {
            if (client == null)
                client = GetClient();
            client.DeleteAllMessages();

        }

        /// quickly gets the message body as text.  Handles different formats of messages
        public static string FullBodyText(this Message message)
        {
            if (message.FindAllTextVersions().Any())
                return message.FindFirstPlainTextVersion().GetBodyAsText();
            else
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(message.FindFirstHtmlVersion().GetBodyAsText());

                 // clear all comment nodes from document
                var nodes = doc.DocumentNode.SelectNodes("//comment()");
                if (nodes != null)
                {
                    foreach (HtmlNode comment in nodes)
                    {
                        comment.ParentNode.RemoveChild(comment);
                    }
                }

                string text = doc.DocumentNode.InnerText;

                // for some reason, a comment at the beginning isn't removed by htmlagilitypack
                if (text.Contains("-->"))
                    text = text.Substring(text.IndexOf("-->") + 3);

                return text;
            }
        }

        /// chops off common formats of the 'original message' from a reply'd email
        public static string BodyTextNoReply(this Message message, string replyname, string replyaddress)
        {
            StringBuilder msgBody = new StringBuilder();

            var lines = FullBodyText(message).Split('\n');

            /* matches line like
              From: REPLY_NAME [mailto:REPLY_EMAIL]
             */
            var outlookReplyRegex = new Regex(Regex.Escape("From: " + replyname+" [mailto:"+replyaddress+"]"), RegexOptions.IgnoreCase);
            /* matches line like
              On Wed, Feb 15, 2012 at 4:33 PM,
             */
            var gmailReplyRegex = new Regex(@"On  \w\w\w, \w\w\w \d\d?, \d\d\d\d at \d\:\d\d \w\w, .*", RegexOptions.IgnoreCase);

            /* matches line like
              ________________________________
             *
             */
            var yahooReplyRegex = new Regex(Regex.Escape("________________________________"), RegexOptions.IgnoreCase);

            /* matches line like
              From: REPLY_EMAIL
             *
             */
            var msnliveReplyRegex = new Regex(Regex.Escape("From: "+replyaddress), RegexOptions.IgnoreCase);

            /* matches line like
              ----- Original Message -----
             *
             */
            var outlookExpressReplyRegex = new Regex(Regex.Escape("----- Original Message -----"), RegexOptions.IgnoreCase);

            // todo:   others?

            foreach (var line in lines)
            {
                if (!outlookReplyRegex.IsMatch(line) && !gmailReplyRegex.IsMatch(line) && !yahooReplyRegex.IsMatch(line)
                     && !msnliveReplyRegex.IsMatch(line) && !outlookExpressReplyRegex.IsMatch(line))
                {
                    msgBody.Append(line);
                }
                else
                    break;
            }

            return msgBody.ToString();
        }
    }
}

 

Note the FullBodyText method – which converts the message body to plain text even if it arrived as HTML, and the BodyTextNoReply method which gets a truncated version of the text without the “Original Message” that was replied to.

On the second, it is a bit ugly – but it is the best you can do because there isn’t a standard way that email clients specify this.  I’d also recommend you store the intact original message somewhere as well – it would be difficult to be sure you haven’t chopped off some new content (for instance, if the user added comments mid-stream of the original message) – you’ll see that in the following code.  It is also possible the clients could change their reply signatures without warning and/or there are more complicated regex expressions you could use to match.

Here is our code (.ASHX handler) that is executed on an interval to process new messages.

<%@ WebHandler Language="C#" Class="ProcessEmailInbox" %>

using System;
using System.Web;
using System.Linq;
using System.Text.RegularExpressions;
using dac = Foliotek.DataAccess;
using Components = Foliotek.Components;

public class ProcessEmailInbox : Foliotek.Components.FoliotekHandler // just an IHttpHandler implementation
{

    public override void DoRequest(HttpContext context)
    {
        var Response = context.Response;

        try
        {
            DoWork(Response);

            Response.Write("Done.\n<br />\n");
        }
        catch (Exception exc)
        {
            Response.Write(exc.Message);
        }
    }

    public void DoWork(HttpResponse Response)
    {
        int maxtoprocess = 10; // only do 10 at a time so it doesn't take too long

        using (var client = Foliotek.Components.Classes.PopEmail.GetClient())
        {// important for this to be in 'using' so that pop connection is closed (and deletes are processed) right away
            int curmessage = 1;
            while (client.GetMessageCount() >= curmessage && maxtoprocess > 0)
            {
                var message = client.GetMessage(curmessage);

                Regex assessmentReplyMatch = new Regex("reply-(.*)@MAILSERVER_HERE");

                var toList = (from m in message.Headers.To.ToArray() select new { address = m.Address, match = assessmentReplyMatch.Match(m.Address) });

                // if none of the destinations match our pattern, skip the message
                if (!toList.Any(m => m.match.Success))
                {
                    curmessage++;
                    continue;
                }

                string from = message.Headers.From.Address;
                string to = toList.First().address;
                string id = toList.First().match.Groups[1].Value;
                string subject = (String.IsNullOrEmpty(message.Headers.Subject)) ? "no subject" : message.Headers.Subject;

                Response.Write("id: " + id + ";to: " + to + ";" + "from: " + from + ";" + "subject: " + subject + ";<br />");

                if (id.Length == 36) // basic guid filter.  We could be doing this in the regex itself, but we want to be able to clear out broken ones here
                {
                    dac.AnswerableEmail answerableEmail = dac.AnswerableEmail.Get(new Guid(id)); //our table that logs the outgoing message for replies that come back
                    if (answerableEmail != null)
                    {
                        if (answerableEmail.ReviewRequestID > 0) // reply to a requested review
                        {
                            string msgTxt = Foliotek.Components.Classes.PopEmail.BodyTextNoReply(message, answerableEmail.ReplyToName,answerableEmail.ReplyToAddress);

                            // builds a version of the message that shows the truncated text plus a link to hover to see the whole text
                            string fullMsg = msgTxt + " <a href='#' onmouseover='$(this).next().show();' onmouseout='$(this).next().hide();'>View Full Message</a><span class=\"hovertext\" style=\"display:none;width:600px;\">" + HttpContext.Current.Server.HtmlEncode(Foliotek.Components.Classes.PopEmail.FullBodyText(message)).Replace("\n", "<br />") + "</span>";

                            ProcessReviewRequest(answerableEmail, from, fullMsg, msgTxt);
                            client.DeleteMessage(curmessage);
                        }
                    }
                    maxtoprocess--;
                }

                curmessage++;
            }
        }
    }

// puts the reply in the appropriate place, and sends the replier back a message that it happened
    private void ProcessReviewRequest(dac.AnswerableEmail answerableEmail, string senderEmail, string fullmessage, string textmessage)
    {
        answerableEmail.ReviewRequest.PostReviewComment("Reply", fullmessage);  // save the reply in the student's comments
        answerableEmail.MarkAsAnswered();

        //Send Email Confirmation to replier
        string fromEmail = STANDARD_AUTOMATED_EMAIL_ADDRESS_HERE;
        string emailBody = "The following Request Review Comment was recorded for " + answerableEmail.ReviewRequest.User.FullNameNoHtml + " on " + answerableEmail.ReviewRequest.Element.Name + ": <br /><br /><hr />" + textmessage + "<hr /> <br />";

        Components.Classes.General.SendEmail(senderEmail, fromEmail, "Review Request Comment Received", emailBody);
    }

}

iText SimSun Degree Symbol Spacing

Thursday, December 29th, 2011

I had a rather odd issue come up a few weeks ago for a client that generates data sheets for it’s Chinese distributors. These data sheets are generated via iText pdf using the SimSun font.

Below is a screen shot of the issue that came up when SimSun renders the degree symbol notice the trailing white space.

Since this was an actual issue with the font and the client requested that we not change the font due to Chinese standards I came up with the following solution.

SimSun supports the ‘Masculine Ordinal’ symbol. This symbol does not have the trailing white space that the ‘degree’ symbol does. So on the fly when it comes time for iText to generate a Chinese Datasheet I replace all Degree symbols with Masculine Ordinals. A little hacky but def the best solution available at the time.


myString.Replace('\u00B0', '\u00BA'); //replace degree with masculine ordinal

Datagrid Checkbox Column

Wednesday, October 26th, 2011

In Foliotek, there are a lot of instances where we have a table with a check box column that allows users to select rows and do some sort of action to them. This leads to a lot of redundancy in our markup and code. For example, here is what our datagrids looked like when we placed a checkbox in them (we’re using a custom server control for our datagrid):

Datagrid with a checkbox


<Components:ExtendedDataGrid runat="server" id="dgItems">
	<Columns>
		<asp:TemplateColumn>
			<HeaderTemplate>
				<input class="check" onclick="FLTK.checkbox.selectAll(this.checked, 'chkSelect');" type="checkbox" />
			</HeaderTemplate>
			<ItemTemplate>
				<input class="check" type="checkbox" id="chkSelect" runat="server" />
			</ItemTemplate>
		</asp:TemplateColumn>
		<asp:TemplateColumn>
			<ItemTemplate>
				<%# Eval("ItemName") %>
			</ItemTemplate>
		</asp:TemplateColumn>
	</Columns>
</Components:ExtendedDataGrid>

Check All JS

Here’s our javascript code that controls the select/deselect all functionality. See this blog post in reference to the :asp() selector, and this post for more information on the select all functionality.


FLTK.checkbox = {
    selectAll: function (checked, endingwith) {
        var $checkboxes = $(":asp(" + endingwith + ")");
		// we don't want to check a box that is hidden on the page
        if (checked) {
            $checkboxes = $checkboxes.filter(":visible").not(":disabled");
        }
        $checkboxes.attr("checked", checked);
    }
}

Get selected rows (C#)

Then, to get the selected items in the code behind and perform some action on them, we’d have to do the following:


foreach(DataGridItem item in dgItems.Items)
{
	if(((HtmlInputCheckBox)item.FindControl("chkSelect")).Checked)
	{
		// perform action
	}
}

// which can also be written as...

foreach(DataGridItem in dgItems.Items.Cast<DataGridItem>().Where(i => ((HtmlInputCheckBox)i.FindControl("chkSelect")).Checked))
{
	// perform action
}

Creating the Custom Datagrid Checkbox Column

Since the above code and markup is used so frequently in Foliotek, we wanted to abstract this logic into something that was easier to use. As I stated above, we use a custom server control that extends the datagrid control, but if you don’t have a custom server control it shouldn’t be hard to create one.

I would suggest reading up on custom server controls, if you’re interested in how the following code works.

Below is our server controls for the custom DataGrid, CheckBoxColumn, and CheckBoxTemplate. Keep in mind the Checked and VisibilityDataField on the CheckBoxColumn are optional.


namespace Components
{
	// here is our custom datagrid control
    public class ExtendedDataGrid : DataGrid
    {
		public IEnumerable<DataGridItem> GetSelectedItems()
        {
            if (!this.Columns.Cast<DataGridColumn>().Any(c => c is CheckBoxColumn))
            {
                throw new Exception("ExtendedDataGrid must have a 'CheckBoxColumn' in order to use GetSelectedItems");
            }

            return this.Items.Cast<DataGridItem>().Where(i => ((CheckBox)i.FindControl("cb_" + this.ID)).Checked);
        }
    }

	// Usage: <Components:CheckBoxColumn Checked="false" VisibilityDataField="Show"></Components:CheckBoxColumn>
	// Alternative Usage: VisiblityDataField="!Hide"
	public class CheckBoxColumn : TemplateColumn
    {
        public string VisibilityDataField { get; set; }
        public bool Checked { get; set; }

        public CheckBoxColumn() : base()
        {
        }

        public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType)
        {
            if (this.Owner != null)
            {
                this.HeaderTemplate = new CheckBoxTemplate(this.Owner.ID, VisibilityDataField, true, Checked);
                this.ItemTemplate = new CheckBoxTemplate(this.Owner.ID, VisibilityDataField, false, Checked);
            }
            base.InitializeCell(cell, columnIndex, itemType);
        }
    }

    public class CheckBoxTemplate : ITemplate
    {
        private string _tableID;
        private bool _isHeader;
        private string _visibilityDataField;
        private bool _isChecked;

        public CheckBoxTemplate(string tableID, string visibilityDataField, bool isHeader, bool isChecked)
        {
            _tableID = tableID;
            _isHeader = isHeader;
            _visibilityDataField = visibilityDataField;
            _isChecked = isChecked;
        }

        public void InstantiateIn(Control c)
        {
            if (_isHeader)
            {
				// If the template container is the header, then we need to add the check all functionality to the checkbox
                HtmlInputCheckBox input = new HtmlInputCheckBox();
                input.Attributes["onclick"] = "FLTK.checkbox.selectAll(this.checked, 'cb_" + this._tableID + "');"; // This id is determined below.
                input.Checked = _isChecked; // Set the checked status by default
                c.Controls.Add(input);
            }
            else
            {
                CheckBox cb = new CheckBox();
                cb.ID = "cb_" + this._tableID;
                if (!String.IsNullOrEmpty(_visibilityDataField))
                {
                    cb.DataBinding += new EventHandler(cb_DataBinding); // doing this in the databind event allows us to access properties in the dataitem.
                }
                cb.Checked = _isChecked;
                c.Controls.Add(cb);
            }
        }

        void cb_DataBinding(object sender, EventArgs e)
        {
            var cb = (CheckBox)sender;
            var dataitem = ((DataGridItem)cb.NamingContainer).DataItem;

            bool show = true;
            if (!String.IsNullOrEmpty(this._visibilityDataField))
            {
                bool not = this._visibilityDataField.StartsWith("!");
                show = (bool)DataBinder.Eval(dataitem, (not ? this._visibilityDataField.Substring(1) : this._visibilityDataField));

                show = not ? !show : show;
            }

            cb.Visible = show;
        }
    }
}

New markup and code behind

Here’s our new markup. Notice how we only have one line now for the checkbox column, compared to 8 lines before.


<Components:ExtendedDataGrid runat="server" id="dgItems">
	<Columns>
		<Components:CheckBoxColumn></Components:CheckBoxColumn>
		<asp:TemplateColumn>
			<ItemTemplate>
				<%# Eval("ItemName") %>
			</ItemTemplate>
		</asp:TemplateColum>
	</Columns>
</Components:ExtendedDataGrid>

… and our code behind, which definitely simplifies the prior statement…


foreach(DataGridItem item in dgItems.GetSelectedItems())
{
	//perform action
}

Simplifying C# Selenium 2 Tests for ASP.NET WebForms

Thursday, October 20th, 2011

Our company uses Selenium to automate regression testing of important functionality on our products. One of the products uses ASP.NET Web Forms. Since the ID for controls gets changed from “txtName” to something like “ct100$contentMain$txtName”, we were using the xPath methods (ClickByXPath(), sendKeysByXPath(), anyByXPath(), etc).

The code looked like this:

Previous Test Code


Tester.Driver.clickByXPath("//input[contains(@id, 'btnSearch')]");
Tester.Driver.clickByXPath("//select[contains(@id, 'drpPrograms')]/option[contains(text(), '" + programName + "')]");
Tester.Driver.clickByXPath("//input[contains(@id, 'rblOption_2')]");
Tester.Driver.clickByXPath("//input[contains(@id, 'cbOption_1')]");
Tester.Driver.sendKeysByXPath("//input[contains(@id, 'txtName')]", name);

Tester.Driver.clickByLinkText("Next");

Writing xPath may be enjoyable for some, but for me it got a bit tedious. So, I created some wrapper methods to make this a lot easier to create and read.

New Test Code


ClickButton("btnSearch");
SelectDropDownOption("drpPrograms", optionName);
SelectRadio("rblOption_2");
SelectCheckBox("cbOption_1");
EnterTextBox("txtName", name);

Wrapper Methods


/// Select a RadioButton or an option on a RadioButtonList.
/// If optionText is specified for a RadioButtonList, this will select that option.  Otherwise it works for native RadioButtons
/// prefix = html filter e.g.  "p/" or "tr/td/"
public void SelectRadio(string radioButtonID, string optionText = "", string prefix = "")
{
    string path = "//" + prefix + "input[contains(@id, '" + radioButtonID + "')]";

    if (optionText != "")
        path += "/option[contains(text(), '" + optionText + "')]";

    ClickByXPath(path);
}

/// Select a CheckBox
/// prefix = html filter e.g.  "p/" or "tr/td/"
public void SelectCheckbox(string checkboxID, string prefix = "")
{
    string path = "//" + prefix + "input[contains(@id, '" + checkboxID + "')]";

    ClickByXPath(path);
}

/// Select an option on a DropDownList
/// prefix = html filter e.g.  "p/" or "tr/td/"
public void SelectDropDownOption(string dropdownID, string optionText = "", string prefix = "")
{
    string path = "//" + prefix + "select[contains(@id, '" + dropdownID + "')]";

    if (optionText != "")
        path += "/option[contains(text(), '" + optionText + "')]";

    ClickByXPath(path);
}

/// Enter text into a TextBox and optionally clear it out first.
public void EnterTextBox(string txtName, string value, bool clearField = false)
{
    Tester.Driver.sendKeysByXPath("//input[contains(@id,'" + txtName + "')]", value, clearField);
}

/// Confirm if a condition is true.  If it is, output the confirmationMessage.
public void ConfirmTrue(bool test, string confirmationMessage)
{
    Tester.Assert(test, confirmationMessage);
}

/// Test to see if a control exists on the page.
/// Control type = input, div, td or whatever
public bool ControlExists(string controlType, string controlID)
{
    string path = "//" + controlType + "[contains(@id,'" + controlID + "')]";
    return Tester.Driver.anyByXPath(path);
}

/// Click a Button
public void ClickButton(string buttonName, string prefix = "")
{
    string path = "//" + prefix + "input[contains(@id, '" + buttonName + "')]";

    ClickByXPath(path);
}

public void ClickByXPath(string xPath)
{
    Tester.Driver.ClickByXPath(xPath);
}

public void ClickByLinkText(string linkText)
{
    Tester.Driver.clickByLinkText(linkText);
}

For more posts, see Tips and Tricks or Functional Regression Testing

A couple of handy helper razor scripts for Umbraco CMS

Thursday, September 1st, 2011

I’ve recently started a project for a new marketing site for our projects.  One of the biggest issues with our current marketing site is that it was developed as an application – so changes need to go through a developer and be deployed.  This basically resulted in the site being stagnant for a couple of years.  This is bad – there are lots of things we offer now that we didn’t 2 years ago – and there are many opportunities where a page that speaks to a particular system, market, or feature could be very good for business/SEO.

I decided to use a CMS to allow anyone in our business edit and add content.  Since we were a web consulting firm before we built products – we’ve had a number of custom solutions over the years for managing site content.  I didn’t want to create that maintenance pain again, so I looked for another maintained solution I could use.  I settled on Umbraco – it’s free, open source, has a great plugin architecture using the .NET/Razor architecture we already know – so it was a perfect fit.

I wanted to share a couple of handy scripts I came up with to make Umbraco even better:

Add “/edit” redirect to all pages:

To use this, add a couple of rewrite rules to UrlRewriting.config:

<add name="editrewrite"
          virtualUrl="^~/(.*)/edit/?"
          rewriteUrlParameter="ExcludeFromClientQueryString"
          destinationUrl="~/editredirect?path=foliotek/$1"
          ignoreCase="true" />
        <add name="edithomerewrite"
          virtualUrl="^~/edit/?"
          rewriteUrlParameter="ExcludeFromClientQueryString"
          destinationUrl="~/editredirect?path=foliotek"
          ignoreCase="true" />

Add a new scripting file (and macro) called “EditRedirect”

@using uComponents.Core
   @using umbraco.presentation.nodeFactory
   @using uComponents.Core.uQueryExtensions
   @{

   Node n = null;

   var path = Request.QueryString["path"].Split("/".ToCharArray());

   for(int i=0; i<path.Length; i++)
   {
     if(n==null)
     {
       n = uQuery.GetRootNode().GetChildNodes().Where(x=>x.Name.ToLower()== path[i].Trim().ToLower()).First();
     }
     else
     {
       var name = path[i].Trim();
       if(i==path.Length-1 && name.IndexOf(".")>0)
       {
         name=name.Substring(0,name.LastIndexOf("."));
       }
       n = n.GetDescendantNodes().First(c=>c.Name.ToLower()==name.ToLower());
     }
    }

   Response.Redirect("/umbraco/actions/editContent.aspx?id="+n.Id);

   }

Add a new “EditRedirect” template that uses the macro:

<%@ Master Language="C#" MasterPageFile="~/umbraco/masterpages/default.master" AutoEventWireup="true" %>

<asp:Content ContentPlaceHolderID="ContentPlaceHolderDefault" runat="server">
  <umbraco:Macro runat="server"   Alias="EditRedirect" />
</asp:Content>

And, finally, add a new page called EditRedirect to the root of your site that uses the macro.   Now you can hit http://site/anydirectory/anypage/edit and it will take you to the editor screen of that page.

 

Simple path to access media by url and in css files

The abstraction umbraco allows for media is great – your editors can create a media item and replace the file later to their hearts content.  Unfortunately, it’s not very simple to pull this media in scripts, templates, simple html, and especially css files.  I wrote a macro/script to handle this too.  Set up is pretty much like the edit redirect:

The script:

 

@using uComponents.Core
   @using umbraco.cms.businesslogic.media
   @using uComponents.Core.uQueryExtensions
   @{

   Media m = null;
   if(!( Model.Media is umbraco.MacroEngines.DynamicNull || (Model.Media is string && Model.Media=="")))
   {
     m = uQuery.GetMedia(Model.Media);
    }
  else
   {
     var path = Request.QueryString["path"].Split("/".ToCharArray());

     for(int i=0; i<path.Length; i++)
     {
       if(m==null)
       {
         m = uQuery.GetMediaByName( path[i].Trim()).First();
       }
       else
       {
         var name = path[i].Trim();
         if(i==path.Length-1 && name.IndexOf(".")>0)
         {
           name=name.Substring(0,name.LastIndexOf("."));
         }
         m = m.GetChildMedia().First(c=>c.Text==name);
       }
      }
   }

   Response.Clear();
   Response.ContentType = GetContentType(m.GetProperty<string>("umbracoExtension"));
   Response.TransmitFile(m.GetProperty<string>("umbracoFile"));

   }

   @functions{
     protected string GetContentType(string ext)
     {
   var contentTypes = new Dictionary<string, string>
                               {
                                   {"3dm", "x-world/x-3dmf"},
                                   {"3dmf", "x-world/x-3dmf"},
                                   {"a", "application/octet-stream"},
                                   {"aab", "application/x-authorware-bin"},
                                   {"aam", "application/x-authorware-map"},
                                   {"aas", "application/x-authorware-seg"},
                                   {"abc", "text/vnd.abc"},
                                   {"acgi", "text/html"},
                                   {"afl", "video/animaflex"},
                                   {"ai", "application/postscript"},
                                   {"aif", "audio/aiff"},
                                   {"aifc", "audio/aiff"},
                                   {"aiff", "audio/aiff"},
                                   {"aim", "application/x-aim"},
                                   {"aip", "text/x-audiosoft-intra"},
                                   {"ani", "application/x-navi-animation"},
                                   {"aos", "application/x-nokia-9000-communicator-add-on-software"},
                                   {"aps", "application/mime"},
                                   {"arc", "application/octet-stream"},
                                   {"arj", "application/arj"},
                                   {"art", "image/x-jg"},
                                   {"asf", "video/x-ms-asf"},
                                   {"asm", "text/x-asm"},
                                   {"asp", "text/asp"},
                                   {"asx", "application/x-mplayer2"},
                                   {"au", "audio/basic"},
                                   {"avi", "video/avi"},
                                   {"avs", "video/avs-video"},
                                   {"bcpio", "application/x-bcpio"},
                                   {"bin", "application/octet-stream"},
                                   {"bm", "image/bmp"},
                                   {"bmp", "image/bmp"},
                                   {"boo", "application/book"},
                                   {"book", "application/book"},
                                   {"boz", "application/x-bzip2"},
                                   {"bsh", "application/x-bsh"},
                                   {"bz", "application/x-bzip"},
                                   {"bz2", "application/x-bzip2"},
                                   {"c", "text/plain"},
                                   {"c++", "text/plain"},
                                   {"cat", "application/vnd.ms-pki.seccat"},
                                   {"cc", "text/plain"},
                                   {"ccad", "application/clariscad"},
                                   {"cco", "application/x-cocoa"},
                                   {"cdf", "application/cdf"},
                                   {"cer", "application/pkix-cert"},
                                   {"cha", "application/x-chat"},
                                   {"chat", "application/x-chat"},
                                   {"class", "application/java"},
                                   {"com", "application/octet-stream"},
                                   {"conf", "text/plain"},
                                   {"cpio", "application/x-cpio"},
                                   {"cpp", "text/x-c"},
                                   {"cpt", "application/x-cpt"},
                                   {"crl", "application/pkcs-crl"},
                                   {"css", "text/css"},
                                   {"def", "text/plain"},
                                   {"der", "application/x-x509-ca-cert"},
                                   {"dif", "video/x-dv"},
                                   {"dir", "application/x-director"},
                                   {"dl", "video/dl"},
                                   {"doc", "application/msword"},
                                   {"dot", "application/msword"},
                                   {"dp", "application/commonground"},
                                   {"drw", "application/drafting"},
                                   {"dump", "application/octet-stream"},
                                   {"dv", "video/x-dv"},
                                   {"dvi", "application/x-dvi"},
                                   {"dwf", "drawing/x-dwf (old)"},
                                   {"dwg", "application/acad"},
                                   {"dxf", "application/dxf"},
                                   {"eps", "application/postscript"},
                                   {"es", "application/x-esrehber"},
                                   {"etx", "text/x-setext"},
                                   {"evy", "application/envoy"},
                                   {"exe", "application/octet-stream"},
                                   {"f", "text/plain"},
                                   {"f90", "text/x-fortran"},
                                   {"fdf", "application/vnd.fdf"},
                                   {"fif", "image/fif"},
                                   {"fli", "video/fli"},
                                   {"for", "text/x-fortran"},
                                   {"fpx", "image/vnd.fpx"},
                                   {"g", "text/plain"},
                                   {"g3", "image/g3fax"},
                                   {"gif", "image/gif"},
                                   {"gl", "video/gl"},
                                   {"gsd", "audio/x-gsm"},
                                   {"gtar", "application/x-gtar"},
                                   {"gz", "application/x-compressed"},
                                   {"h", "text/plain"},
                                   {"help", "application/x-helpfile"},
                                   {"hgl", "application/vnd.hp-hpgl"},
                                   {"hh", "text/plain"},
                                   {"hlp", "application/x-winhelp"},
                                   {"htc", "text/x-component"},
                                   {"htm", "text/html"},
                                   {"html", "text/html"},
                                   {"htmls", "text/html"},
                                   {"htt", "text/webviewhtml"},
                                   {"htx", "text/html"},
                                   {"ice", "x-conference/x-cooltalk"},
                                   {"ico", "image/x-icon"},
                                   {"idc", "text/plain"},
                                   {"ief", "image/ief"},
                                   {"iefs", "image/ief"},
                                   {"iges", "application/iges"},
                                   {"igs", "application/iges"},
                                   {"ima", "application/x-ima"},
                                   {"imap", "application/x-httpd-imap"},
                                   {"inf", "application/inf"},
                                   {"ins", "application/x-internett-signup"},
                                   {"ip", "application/x-ip2"},
                                   {"isu", "video/x-isvideo"},
                                   {"it", "audio/it"},
                                   {"iv", "application/x-inventor"},
                                   {"ivr", "i-world/i-vrml"},
                                   {"ivy", "application/x-livescreen"},
                                   {"jam", "audio/x-jam"},
                                   {"jav", "text/plain"},
                                   {"java", "text/plain"},
                                   {"jcm", "application/x-java-commerce"},
                                   {"jfif", "image/jpeg"},
                                   {"jfif-tbnl", "image/jpeg"},
                                   {"jpe", "image/jpeg"},
                                   {"jpeg", "image/jpeg"},
                                   {"jpg", "image/jpeg"},
                                   {"jps", "image/x-jps"},
                                   {"js", "application/x-javascript"},
                                   {"jut", "image/jutvision"},
                                   {"kar", "audio/midi"},
                                   {"ksh", "application/x-ksh"},
                                   {"la", "audio/nspaudio"},
                                   {"lam", "audio/x-liveaudio"},
                                   {"latex", "application/x-latex"},
                                   {"lha", "application/lha"},
                                   {"lhx", "application/octet-stream"},
                                   {"list", "text/plain"},
                                   {"lma", "audio/nspaudio"},
                                   {"log", "text/plain"},
                                   {"lsp", "application/x-lisp"},
                                   {"lst", "text/plain"},
                                   {"lsx", "text/x-la-asf"},
                                   {"ltx", "application/x-latex"},
                                   {"lzh", "application/octet-stream"},
                                   {"lzx", "application/lzx"},
                                   {"m", "text/plain"},
                                   {"m1v", "video/mpeg"},
                                   {"m2a", "audio/mpeg"},
                                   {"m2v", "video/mpeg"},
                                   {"m3u", "audio/x-mpequrl"},
                                   {"man", "application/x-troff-man"},
                                   {"map", "application/x-navimap"},
                                   {"mar", "text/plain"},
                                   {"mbd", "application/mbedlet"},
                                   {"mc$", "application/x-magic-cap-package-1.0"},
                                   {"mcd", "application/mcad"},
                                   {"mcf", "image/vasa"},
                                   {"mcp", "application/netmc"},
                                   {"me", "application/x-troff-me"},
                                   {"mht", "message/rfc822"},
                                   {"mhtml", "message/rfc822"},
                                   {"mid", "audio/midi"},
                                   {"midi", "audio/midi"},
                                   {"mif", "application/x-frame"},
                                   {"mime", "message/rfc822"},
                                   {"mjf", "audio/x-vnd.audioexplosion.mjuicemediafile"},
                                   {"mjpg", "video/x-motion-jpeg"},
                                   {"mm", "application/base64"},
                                   {"mme", "application/base64"},
                                   {"mod", "audio/mod"},
                                   {"moov", "video/quicktime"},
                                   {"mov", "video/quicktime"},
                                   {"movie", "video/x-sgi-movie"},
                                   {"mp2", "audio/mpeg"},
                                   {"mp3", "audio/mpeg3"},
                                   {"mpa", "audio/mpeg"},
                                   {"mpc", "application/x-project"},
                                   {"mpe", "video/mpeg"},
                                   {"mpeg", "video/mpeg"},
                                   {"mpg", "video/mpeg"},
                                   {"mpga", "audio/mpeg"},
                                   {"mpp", "application/vnd.ms-project"},
                                   {"mpt", "application/x-project"},
                                   {"mpv", "application/x-project"},
                                   {"mpx", "application/x-project"},
                                   {"mrc", "application/marc"},
                                   {"ms", "application/x-troff-ms"},
                                   {"mv", "video/x-sgi-movie"},
                                   {"my", "audio/make"},
                                   {"mzz", "application/x-vnd.audioexplosion.mzz"},
                                   {"nap", "image/naplps"},
                                   {"naplps", "image/naplps"},
                                   {"nc", "application/x-netcdf"},
                                   {"ncm", "application/vnd.nokia.configuration-message"},
                                   {"nif", "image/x-niff"},
                                   {"niff", "image/x-niff"},
                                   {"nix", "application/x-mix-transfer"},
                                   {"nsc", "application/x-conference"},
                                   {"nvd", "application/x-navidoc"},
                                   {"o", "application/octet-stream"},
                                   {"oda", "application/oda"},
                                   {"omc", "application/x-omc"},
                                   {"omcd", "application/x-omcdatamaker"},
                                   {"omcr", "application/x-omcregerator"},
                                   {"p", "text/x-pascal"},
                                   {"p10", "application/pkcs10"},
                                   {"p12", "application/pkcs-12"},
                                   {"p7a", "application/x-pkcs7-signature"},
                                   {"p7c", "application/pkcs7-mime"},
                                   {"pas", "text/pascal"},
                                   {"pbm", "image/x-portable-bitmap"},
                                   {"pcl", "application/vnd.hp-pcl"},
                                   {"pct", "image/x-pict"},
                                   {"pcx", "image/x-pcx"},
                                   {"pdf", "application/pdf"},
                                   {"pfunk", "audio/make"},
                                   {"pgm", "image/x-portable-graymap"},
                                   {"pic", "image/pict"},
                                   {"pict", "image/pict"},
                                   {"pkg", "application/x-newton-compatible-pkg"},
                                   {"pko", "application/vnd.ms-pki.pko"},
                                   {"pl", "text/plain"},
                                   {"plx", "application/x-pixclscript"},
                                   {"pm", "image/x-xpixmap"},
                                   {"png", "image/png"},
                                   {"pnm", "application/x-portable-anymap"},
                                   {"pot", "application/mspowerpoint"},
                                   {"pov", "model/x-pov"},
                                   {"ppa", "application/vnd.ms-powerpoint"},
                                   {"ppm", "image/x-portable-pixmap"},
                                   {"pps", "application/mspowerpoint"},
                                   {"ppt", "application/mspowerpoint"},
                                   {"ppz", "application/mspowerpoint"},
                                   {"pre", "application/x-freelance"},
                                   {"prt", "application/pro_eng"},
                                   {"ps", "application/postscript"},
                                   {"psd", "application/octet-stream"},
                                   {"pvu", "paleovu/x-pv"},
                                   {"pwz", "application/vnd.ms-powerpoint"},
                                   {"py", "text/x-script.phyton"},
                                   {"pyc", "applicaiton/x-bytecode.python"},
                                   {"qcp", "audio/vnd.qcelp"},
                                   {"qd3", "x-world/x-3dmf"},
                                   {"qd3d", "x-world/x-3dmf"},
                                   {"qif", "image/x-quicktime"},
                                   {"qt", "video/quicktime"},
                                   {"qtc", "video/x-qtc"},
                                   {"qti", "image/x-quicktime"},
                                   {"qtif", "image/x-quicktime"},
                                   {"ra", "audio/x-pn-realaudio"},
                                   {"ram", "audio/x-pn-realaudio"},
                                   {"ras", "application/x-cmu-raster"},
                                   {"rast", "image/cmu-raster"},
                                   {"rexx", "text/x-script.rexx"},
                                   {"rf", "image/vnd.rn-realflash"},
                                   {"rgb", "image/x-rgb"},
                                   {"rm", "application/vnd.rn-realmedia"},
                                   {"rmi", "audio/mid"},
                                   {"rmm", "audio/x-pn-realaudio"},
                                   {"rmp", "audio/x-pn-realaudio"},
                                   {"rng", "application/ringing-tones"},
                                   {"rnx", "application/vnd.rn-realplayer"},
                                   {"roff", "application/x-troff"},
                                   {"rp", "image/vnd.rn-realpix"},
                                   {"rpm", "audio/x-pn-realaudio-plugin"},
                                   {"rt", "text/richtext"},
                                   {"rtf", "text/richtext"},
                                   {"rtx", "application/rtf"},
                                   {"rv", "video/vnd.rn-realvideo"},
                                   {"s", "text/x-asm"},
                                   {"s3m", "audio/s3m"},
                                   {"saveme", "application/octet-stream"},
                                   {"sbk", "application/x-tbook"},
                                   {"scm", "application/x-lotusscreencam"},
                                   {"sdml", "text/plain"},
                                   {"sdp", "application/sdp"},
                                   {"sdr", "application/sounder"},
                                   {"sea", "application/sea"},
                                   {"set", "application/set"},
                                   {"sgm", "text/sgml"},
                                   {"sgml", "text/sgml"},
                                   {"sh", "application/x-bsh"},
                                   {"shtml", "text/html"},
                                   {"sid", "audio/x-psid"},
                                   {"sit", "application/x-sit"},
                                   {"skd", "application/x-koan"},
                                   {"skm", "application/x-koan"},
                                   {"skp", "application/x-koan"},
                                   {"skt", "application/x-koan"},
                                   {"sl", "application/x-seelogo"},
                                   {"smi", "application/smil"},
                                   {"smil", "application/smil"},
                                   {"snd", "audio/basic"},
                                   {"sol", "application/solids"},
                                   {"spc", "application/x-pkcs7-certificates"},
                                   {"spl", "application/futuresplash"},
                                   {"spr", "application/x-sprite"},
                                   {"sprite", "application/x-sprite"},
                                   {"src", "application/x-wais-source"},
                                   {"ssi", "text/x-server-parsed-html"},
                                   {"ssm", "application/streamingmedia"},
                                   {"sst", "application/vnd.ms-pki.certstore"},
                                   {"step", "application/step"},
                                   {"stl", "application/sla"},
                                   {"stp", "application/step"},
                                   {"sv4cpio", "application/x-sv4cpio"},
                                   {"sv4crc", "application/x-sv4crc"},
                                   {"svf", "image/vnd.dwg"},
                                   {"svr", "application/x-world"},
                                   {"swf", "application/x-shockwave-flash"},
                                   {"t", "application/x-troff"},
                                   {"talk", "text/x-speech"},
                                   {"tar", "application/x-tar"},
                                   {"tbk", "application/toolbook"},
                                   {"tcl", "application/x-tcl"},
                                   {"tcsh", "text/x-script.tcsh"},
                                   {"tex", "application/x-tex"},
                                   {"texi", "application/x-texinfo"},
                                   {"texinfo", "application/x-texinfo"},
                                   {"text", "text/plain"},
                                   {"tgz", "application/x-compressed"},
                                   {"tif", "image/tiff"},
                                   {"tr", "application/x-troff"},
                                   {"tsi", "audio/tsp-audio"},
                                   {"tsp", "audio/tsplayer"},
                                   {"tsv", "text/tab-separated-values"},
                                   {"turbot", "image/florian"},
                                   {"txt", "text/plain"},
                                   {"uil", "text/x-uil"},
                                   {"uni", "text/uri-list"},
                                   {"unis", "text/uri-list"},
                                   {"unv", "application/i-deas"},
                                   {"uri", "text/uri-list"},
                                   {"uris", "text/uri-list"},
                                   {"ustar", "application/x-ustar"},
                                   {"uu", "application/octet-stream"},
                                   {"vcd", "application/x-cdlink"},
                                   {"vcs", "text/x-vcalendar"},
                                   {"vda", "application/vda"},
                                   {"vdo", "video/vdo"},
                                   {"vew", "application/groupwise"},
                                   {"viv", "video/vivo"},
                                   {"vivo", "video/vivo"},
                                   {"vmd", "application/vocaltec-media-desc"},
                                   {"vmf", "application/vocaltec-media-file"},
                                   {"voc", "audio/voc"},
                                   {"vos", "video/vosaic"},
                                   {"vox", "audio/voxware"},
                                   {"vqe", "audio/x-twinvq-plugin"},
                                   {"vqf", "audio/x-twinvq"},
                                   {"vql", "audio/x-twinvq-plugin"},
                                   {"vrml", "application/x-vrml"},
                                   {"vrt", "x-world/x-vrt"},
                                   {"vsd", "application/x-visio"},
                                   {"vst", "application/x-visio"},
                                   {"vsw", "application/x-visio"},
                                   {"w60", "application/wordperfect6.0"},
                                   {"w61", "application/wordperfect6.1"},
                                   {"w6w", "application/msword"},
                                   {"wav", "audio/wav"},
                                   {"wb1", "application/x-qpro"},
                                   {"wbmp", "image/vnd.wap.wbmp"},
                                   {"web", "application/vnd.xara"},
                                   {"wiz", "application/msword"},
                                   {"wk1", "application/x-123"},
                                   {"wmf", "windows/metafile"},
                                   {"wml", "text/vnd.wap.wml"},
                                   {"wmlc", "application/vnd.wap.wmlc"},
                                   {"wmls", "text/vnd.wap.wmlscript"},
                                   {"wmlsc", "application/vnd.wap.wmlscriptc"},
                                   {"word", "application/msword"},
                                   {"wp", "application/wordperfect"},
                                   {"wp5", "application/wordperfect"},
                                   {"wp6", "application/wordperfect"},
                                   {"wpd", "application/wordperfect"},
                                   {"wq1", "application/x-lotus"},
                                   {"wri", "application/mswrite"},
                                   {"wrl", "application/x-world"},
                                   {"wrz", "model/vrml"},
                                   {"wsc", "text/scriplet"},
                                   {"wsrc", "application/x-wais-source"},
                                   {"wtk", "application/x-wintalk"},
                                   {"xbm", "image/x-xbitmap"},
                                   {"xdr", "video/x-amt-demorun"},
                                   {"xgz", "xgl/drawing"},
                                   {"xif", "image/vnd.xiff"},
                                   {"xl", "application/excel"},
                                   {"xla", "application/excel"},
                                   {"xlb", "application/excel"},
                                   {"xlc", "application/excel"},
                                   {"xld", "application/excel"},
                                   {"xlk", "application/excel"},
                                   {"xll", "application/excel"},
                                   {"xlm", "application/excel"},
                                   {"xls", "application/excel"},
                                   {"xlt", "application/excel"},
                                   {"xlv", "application/excel"},
                                   {"xlw", "application/excel"},
                                   {"xm", "audio/xm"},
                                   {"xml", "text/xml"},
                                   {"xmz", "xgl/movie"},
                                   {"xpix", "application/x-vnd.ls-xpix"},
                                   {"xpm", "image/x-xpixmap"},
                                   {"x-png", "image/png"},
                                   {"xsr", "video/x-amt-showrun"},
                                   {"xwd", "image/x-xwd"},
                                   {"xyz", "chemical/x-pdb"},
                                   {"z", "application/x-compress"},
                                   {"zip", "application/x-compressed"},
                                   {"zoo", "application/octet-stream"},
                                   {"zsh", "text/x-script.zsh"}
                               };

   if(contentTypes[ext]==null)
   {
     return "application/octet-stream";

   }
       return contentTypes[ext];
     }
   }

 

The template:

 

<%@ Master Language="C#" MasterPageFile="~/umbraco/masterpages/default.master" AutoEventWireup="true" %>

<asp:Content ContentPlaceHolderID="ContentPlaceHolderDefault" runat="server">
  <umbraco:Macro runat="server"  MediaID="[#media]" Alias="getMedia" />
</asp:Content>

 

The redirect rule:

 

        <add name="cssmediarewrite"
          virtualUrl="^~/css/media/(.*)"
          rewriteUrlParameter="ExcludeFromClientQueryString"
          destinationUrl="~/cssmedia?path=$1"
          ignoreCase="true" />

 

Finally, add a page called CssMedia that uses the template.  Now, you can reference /css/media/mediapath/medianame.fileextension  to get the item.  This also means that your css files can use media/mediapath/medianame.fileextension to reference Umbraco media.