Created
September 1, 2015 15:50
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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