Tag Archives: Extension Methods

Asp.Net MVC

Minify CSS & JS With MVCContrib

I was doing a bit of research recently trying to find a way to compress, combine and minify css and js in Asp.Net MVC 2 and found a few ideas on the subject. The one that caught my eye was the MvcContrib IncludeHandling; a little hidden gem.

Getting it up a running however wasn’t so straight forward (there isn’t much documentation about it, or at least not much I could find.). The first problem I stumbled upon was the HtmlExtensions (RenderIncludes function) required a dependency resolver which the project I was on didn’t use. To get round this I simply copied the source (from the HtmlExtensions link) and replaced the dependency resolver with the projects IoC framework (in this case we’re using MvcTurbine with Ninject)

Next you need to register the dependency with your IoC of choice, like I said previously we’re using MvcTurbine so this is how I did with with a service registration.

namespace YourProject.MvcSite.Registration
{
  using System.Web;
  using MvcContrib;
  using MvcContrib.IncludeHandling;
  using MvcContrib.IncludeHandling.Configuration;
  using MvcTurbine.ComponentModel;

  /// <summary>
  /// Regisers the minify interfaces
  /// </summary>
  public class MinifyRegistration  : IServiceRegistration 
  {
    /// <summary>
    /// Registers the components with the specified <see cref="T:MvcTurbine.ComponentModel.IServiceLocator"/> instance.
    /// </summary>
    /// <param name="locator">Instance of <see cref="T:MvcTurbine.ComponentModel.IServiceLocator"/> to use.</param>
    public void Register(IServiceLocator locator)
    {
      var httpContext = new HttpContextProvider(HttpContext.Current);
      var handler = new IncludeHandlingSectionHandler();
      var reader = new IncludeReader(httpContext);
      var storage = new StaticIncludeStorage(new KeyGenerator());
 
      locator.Register<IIncludeHandlingSettings>(handler);
      locator.Register<IIncludeCombiner>(new IncludeCombiner(handler, reader, storage, httpContext));
    }
  }
}

The final step is to select the js/css files you want and then combine them. In the example below we’re using the T4MVC template to generate the static file links which and the code is used in a view (in our example it’s the site master view).

    <%
      var scripts = new List<string>
                      {
                        "~" + Links.Scripts.jquery_1_4_2_min_js,
                        "~" + Links.Scripts.jquery_ui_1_8_2_custom_min_js,
                        "~" + Links.Scripts.jquery_localscroll_1_2_7_min_js,
                        "~" + Links.Scripts.jquery_scrollTo_1_4_2_min_js,
                        "~" + Links.Scripts.jquery_serialScroll_1_2_2_min_js,
                        "~" + Links.Scripts.Ajax_js,
                        "~" + Links.Scripts.Custom_js,
                        "~" + Links.Scripts.json2_js,
                        "~" + Links.Scripts.flowplayer_3_2_3_min_js,
                        "~" + Links.Scripts.DragDrop_js,
                        "~" + Links.Scripts.Slider_js
                      };
    %>

    <%=Html.RenderJs(scripts)%>
Code

Serialising / Deserialising objects to Xml in .Net

Serialising / Deserialising objects to Xml: from my StackOverFlow

private static readonly Dictionary<Type, XmlSerializer> serialisers = new Dictionary<Type, XmlSerializer>();

/// <summary>Serialises an object of type T in to an xml string</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="objectToSerialise">Object to serialise</param>
/// <returns>A string that represents Xml, empty oterwise</returns>
public static string XmlSerialise<T>(this T objectToSerialise) where T : class, new()
{
  XmlSerializer serialiser;

  var type = typeof(T);
  if (!serialisers.ContainsKey(type))
  {
    serialiser = new XmlSerializer(type);
    serialisers.Add(type, serialiser);
  }
  else
  {
    serialiser = serialisers[type];
  }

  string xml;
  using (var writer = new StringWriter())
  {
    serialiser.Serialize(writer, objectToSerialise);
    xml = writer.ToString();
  }

  return xml;
}

/// <summary>Deserialises an xml string in to an object of Type T</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="xml">Xml as string to deserialise from</param>
/// <returns>A new object of type T is successful, null if failed</returns>
public static T XmlDeserialise<T>(this string xml) where T : class, new()
{
  XmlSerializer serialiser;

  var type = typeof(T);
  if (!serialisers.ContainsKey(type))
  {
    serialiser = new XmlSerializer(type);
    serialisers.Add(type, serialiser);
  }
  else
  {
    serialiser = serialisers[type];
  }

  T newObject;

  using (var reader = new StringReader(xml))
  {
    try { newObject = (T)serialiser.Deserialize(reader); }
    catch { return null; } // Could not be deserialized to this type.
  }

  return newObject;
}

When building the serialisation I had a help from an online example – but cannot remeber where it is…