Using media in Umbraco without dragging down performance

Is your page rendering slow in Umbraco? Are you using Umbraco media in that page? Well, you’re probably doing it the slow way. To be fair, the fast way isn’t necessarily obvious.

Are you doing using umbraco.library.GetMedia? It caches the media result in the ASP.Net cache, making it fast. Any other function you might use for media will always queries the database.

You might ask, why is it so much slower than everything else in my page, isn’t Umbraco querying the database for my page content? No, Umbraco isn’t querying your database for content, it’s using an cache of all your content that it stores in a xml file. Umbraco only queries the database for content when it absolutely has to. But, it always queries the database for media, unless you use umbraco.library.GetMedia.

umbraco.library.GetMedia returns an XPathNodeIterator which can make it difficult to work with. I’ve written a helper function to return the url that can be used in an img tag. Expect significant speeds up in rendering by using umbraco.library.GetMedia.

@using System.Xml.XPath;
namespace MyProject {
  public class Helper {
    public static string GetImageUrlFromUmbraco(string mediaId) {
      XPathNodeIterator iter = umbraco.library.GetMedia(Int32.Parse(mediaId),
false);
      if (iter == null) return string.Empty;
      //umbraco caches XPathNodeIterator, so make copy
      //since MoveNext() will mutate it.
      iter = iter.Clone();
      XPathNavigator fileNode = null;
      if (iter.MoveNext()) {
        fileNode = iter.Current.SelectSingleNode("//umbracoFile");
      }
      return (fileNode != null ? fileNode.Value : string.Empty);
    }
  }
}

Here is an example of using that function in a Umbraco razor macro for a document type called “MyPage” with a property called “logo” with a type of “Media Picker”.

@using MyProject;

var mypage = @Model.AncestorOrSelf("MyPage");
<img src='@Helper.GetImageUrlFromUmbraco(@mypage.GetProperty("logo").Value)' />
Advertisements