Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Jules 204 posts 447 karma points
    Apr 08, 2017 @ 11:15

    I used to create a static utilities class in my projects for getting various things but particularly important, was media and media properties.

    After reading the Umbraco Pitfalls I stopped doing that because the utility class would need a static instance of the UmbracoHelper

    _umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

    However, getting a media url or a media cropUrl from a picker property is a pain. To do it properly you must first check to see if the picker property has a value then you need to check to see if the media id found on the property still points to a valid piece of media (media could have been deleted but the reference stays).

    So to get a crop url generally would mean something like this ...

    if (page.HasValue(UmbracoPropertyAlias.MainImage))
       var media = Umbraco.TypedMedia(page.GetPropertyValue<string>(UmbracoPropertyAlias.MainImage));
       if (media != null)
          listItem.ThumbnailUrl = media.GetCropUrl(CropAlias.ThumbnailImage);
           listItem.ThumbnailUrl = string.Empty;

    Which is rather long-winded. I would much rather have the methods from my old utility classes which were something like...

    public static string GetMediaCropUrl(int mediaId, string cropAlias)

    public static string GetMediaUrl(int mediaId)

    public static IPublishedContent GetMedia(string propertyAlias, IPublishedContent node)

    Anyway, just interested to know if anybody has found a good way to do this.... extensions maybe?


  • Nik 1351 posts 5855 karma points MVP 3x c-trib
    Apr 08, 2017 @ 14:01

    Hi Jules,

    I've not done this, however, it does sound like it would suite creating extension methods for the UmbracoHelper. I don't imagine you'd have too much of an issue changing your existing methods to become extension methods :-)


  • Marcio Goularte 356 posts 1246 karma points
    Apr 08, 2017 @ 17:47
    Marcio Goularte

    What you are looking for here:

    I created my media utility class using some methods of this extension class of Hybrid Framework.

  • Dan Diplo 1491 posts 5811 karma points MVP 4x c-trib
    Apr 08, 2017 @ 17:59
    Dan Diplo

    Yep, just add extension methods to the Umbraco helper. So, for instance, your GetMediaUrl method would become (something like):

    public static string GetMediaUrl(this UmbracoHelper helper, int mediaId)
        var media = helper.TypedMedia(mediaId);
        return media != null  ? media.Url : null;

    Remember to create your extensions in a static class.

    You'd then just call it like:

    string url = Umbraco.GetMediaUrl(1234);
  • Jules 204 posts 447 karma points
    Apr 09, 2017 @ 20:49

    Thanks to all !

    All sorted now.


Please Sign in or register to post replies

Write your reply to: