Skip to content
jstott edited this page May 8, 2013 · 2 revisions

###Welcome to the grunt-azureblob wiki!

HtmlHelper extension for .net web/spa projects

One item that I found missing is a clean way to link between the update of azure storage (by version) and my assets resource (script/stylesheets/images) references in my (cs)html pages.

Storing assets by version is important to allow updates to the web sites (multiple web instances) such that altering assets would not impact a currently executing process, as well as breaking the cache for those assets so they would be refreshed.

I started using a project.json in the /content folder of the web project, so as to have shared resource between the web and grunt build process. This gives me the version and target blob/cdn url resources as a bridge.

Sample of the Razor syntax helper for CDN/BLOB storage url:

<link href="//netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet" />
    
@Html.CdnLinkTag("player.all.css")

<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script>

The HtmlHelperExtension starts off as:

namespace System.Web.Mvc
{
  public static class HtmlHelperExtension
  {
    const string cdnAssetUrl = "//xxx.vo.msecnd.net/assets/";
    private const string verFile = "~/content/project.json"; // contains the version / build info for project
    static string ver = "";
    const bool forceLocal = false;
    public static string Version
    {
      get
      {
        if (string.IsNullOrEmpty(ver))
        {
          string filePath = HttpContext.Current.Server.MapPath(verFile);
          if (File.Exists(filePath))
          {
            ProjectJson spa = JsonConvert.DeserializeObject<ProjectJson>(File.ReadAllText(filePath));
            ver = spa.version;
          }
          else
          {
            ver = "0.1.8"; // fallback
          }
        }
        return ver;
      }
    }
    public static HtmlString CdnStyleUrl(this HtmlHelper helper)
    {
      string url = string.Concat(cdnAssetUrl, Version, "/");;

      if (helper.ViewContext.HttpContext.IsDebuggingEnabled || forceLocal)
        url = "/content/";
      return MvcHtmlString.Create(url);
    }
    public static HtmlString CdnLinkTag(this HtmlHelper helper, string target)
    {
      var minCss = target.Replace(".css", ".min.css");
      var link = new TagBuilder("link");
      link.Attributes["rel"] = "stylesheet";

      if (helper.ViewContext.HttpContext.IsDebuggingEnabled || forceLocal)
        link.Attributes["href"] = string.Concat("/content/", target);
      else
        link.Attributes["href"] = string.Concat(cdnAssetUrl, Version, "/", minCss);

      return MvcHtmlString.Create(link.ToString(TagRenderMode.SelfClosing));
    }
    ...
Clone this wiki locally