Skip to content

Instantly share code, notes, and snippets.

@davidknipe
Created September 1, 2015 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidknipe/8a05d807dc73c198c51b to your computer and use it in GitHub Desktop.
Save davidknipe/8a05d807dc73c198c51b to your computer and use it in GitHub Desktop.
Add a hash based on the image timestamp to ensure images are reloaded whenever they are changed
[InitializableModule]
[ModuleDependency(typeof (EPiServer.Web.InitializationModule))]
public class AddTimeStampToImages : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
ContentRoute.CreatedVirtualPath += CreatedVirtualPath;
}
private void CreatedVirtualPath(object sender, UrlBuilderEventArgs urlBuilderEventArgs)
{
object contentReferenceObject;
if (!urlBuilderEventArgs.RouteValues.TryGetValue(RoutingConstants.NodeKey, out contentReferenceObject))
{
return;
}
var routedContentLink = contentReferenceObject as ContentReference;
if (ContentReference.IsNullOrEmpty(routedContentLink))
{
return;
}
// Check that the link is to a image
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
var imageData = contentLoader.Get<IContent>(routedContentLink) as ImageData;
if (imageData == null)
{
return;
}
// Check that everyone has read access to the image
var securable = imageData as ISecurable;
if ((securable.GetSecurityDescriptor().GetAccessLevel(PrincipalInfo.AnonymousPrincipal) & AccessLevel.Read) !=
AccessLevel.Read)
{
return;
}
// Generate timestamp
var hash = imageData.Saved.Ticks.ToString("X").Substring(2, 8).ToLower();
// Generate new url with a querystring
if (urlBuilderEventArgs.UrlBuilder.Query == string.Empty)
{
urlBuilderEventArgs.UrlBuilder.Path += "?hash=" + hash;
}
else
{
urlBuilderEventArgs.UrlBuilder.Path += "&hash=" + hash;
}
}
public void Preload(string[] parameters)
{
}
public void Uninitialize(InitializationEngine context)
{
ContentRoute.CreatedVirtualPath -= CreatedVirtualPath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment