Tuesday 27 December 2016

Sitecore Versioned media file loading from en version


Recently we had an issue where versioned media items were always getting loaded from en language version instead of current context language(Sitecore 8.0) . We were unable to find the root cause of this and finally have to come up with a work around.


1. Create a custom media provider . Append language in the media url if media item template is versioned.


namespace MediaHandler
{
    public class CustomMediaProvider:MediaProvider
    {
        public override string GetMediaUrl(MediaItem item, MediaUrlOptions options)
        {
         
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNull(options, "options");
            bool flag = options.Thumbnail || this.HasMediaContent(item);
            bool flag2 = true;
            if (!flag && item.InnerItem.Paths.Path.Length > 0)
            {
                if (!options.LowercaseUrls)
                {
                    return item.InnerItem.Paths.Path;
                }
                return item.InnerItem.Paths.Path.ToLowerInvariant();
            }
            else if (options.UseDefaultIcon && !flag)
            {
                if (!options.LowercaseUrls)
                {
                    return Themes.MapTheme(Settings.DefaultIcon);
                }
                return Themes.MapTheme(Settings.DefaultIcon).ToLowerInvariant();
            }
            else
            {
                Assert.IsTrue(this.Config.MediaPrefixes[0].Length > 0, "media prefixes are not configured properly.");
                string text = this.MediaLinkPrefix;
                if (options.AbsolutePath)
                {
                    text = options.VirtualFolder + text;
                }
                else if (text.StartsWith("/", StringComparison.InvariantCulture))
                {
                    text = StringUtil.Mid(text, 1);
                }
                string text2 = MainUtil.EncodePath(text, '/');
                if (options.ToString().Length > 1 && !string.IsNullOrEmpty(StringUtil.ExtractParameter("la", options.ToString())))
                {
                    flag2 = false;
                }
                Item item2 = Context.Database.GetItem(item.InnerItem.TemplateID);
                if (flag2 && item2 != null && item2.Paths.FullPath.ToLower().Contains("/versioned/"))
                {
                    text2 = "/" + Context.Language.CultureInfo.ToString() + text2;
                }
                if (options.AlwaysIncludeServerUrl)
                {
                    text2 = FileUtil.MakePath(string.IsNullOrEmpty(options.MediaLinkServerUrl) ? WebUtil.GetServerUrl() : options.MediaLinkServerUrl, text2, '/');
                }
                string text3 = StringUtil.EnsurePrefix('.', StringUtil.GetString(new string[]
                {
                    options.RequestExtension,
                    item.Extension,
                    "ashx"
                }));
                string text4 = options.ToString();
                if (text4.Length > 0)
                {
                    text3 = text3 + "?" + text4;
                }
                string text5 = "/sitecore/media library/";
                string path = item.InnerItem.Paths.Path;
                string str = MainUtil.EncodePath((!options.UseItemPath || !path.StartsWith(text5, StringComparison.OrdinalIgnoreCase)) ? item.ID.ToShortID().ToString() : StringUtil.Mid(path, text5.Length), '/');
                string text6 = text2 + str + (options.IncludeExtension ? text3 : string.Empty);
                if (!options.LowercaseUrls)
                {
                    return text6;
                }
                return text6.ToLowerInvariant();
            }
        }
    }
     
}


2. Replace Sitecore media provider with your custom media provider

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <mediaLibrary>
<mediaProvider>
 <patch:attribute name="type">MediaHandler.CustomMediaProvider, [Assembly Name]</patch:attribute>
  </mediaProvider>
 </mediaLibrary>
  </sitecore>
</configuration>


With above solution, Versioned media url will include language locale in its url and will always get loaded from current context language. 

Sitecore - Enable preview mode for Anonymous user


Recently we had a requirement to enable preview mode for anonymous user so that content authors can share the preview url to others for review. Since it was just for review purpose we wanted them to see the preview of the page without logging into sitecore. Of course there is another way to just point CM server database to master but we did not want to change our architecture for this. We contacted Sitecore support(support id 471776) and they helped us in achieving this. Please note the fix is for Sitecore 8.0 version but should work with other version as well.

Configuration- you need to patch your configuration in such a way so that your class will come as below in showconfig page.



<httpRequestBegin>
… … …
<processor type="Sitecore.Pipelines.HttpRequest.UserResolver, Sitecore.Kernel"/>
<processor type="[Your namespace].AllowAnonymousPreview, YourAssemblyName"/>
<processor type="Sitecore.Pipelines.HttpRequest.DatabaseResolver, Sitecore.Kernel"/>
</httpRequestBegin>


Class code :- 

namespace [Namespace]
{
    public class AllowAnonymousPreview : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            var activeUser = AuthenticationManager.GetActiveUser();
            Assert.IsNotNull(activeUser, "User cannot be null.");
            var userIsExtranetAnonymous = activeUser.Name == "extranet\\Anonymous";
            var userIsSitecoreAnonymous = activeUser.Name == "sitecore\\Anonymous";
            if (!userIsExtranetAnonymous && !userIsSitecoreAnonymous)
            {
                return;
            }
            var isRibbonRequest = args.Url != null && args.Url.ItemPath == "/sitecore/content/home/applications/webedit/webeditribbon";
            if (Sitecore.Context.PageMode.IsPreview || isRibbonRequest)
            {
                PerformAutoLogin();
            }
         
        }

        private void PerformAutoLogin()
        {
            string userName = "extranet\\Preview Anonymous User";
            AuthenticationManager.Login(userName);
            string ticket = Sitecore.Web.Authentication.TicketManager.CreateTicket(userName, @"/sitecore/shell");
            HttpContext current = HttpContext.Current;
            if (current != null)
            {
                HttpCookie cookie = new HttpCookie(Sitecore.Web.Authentication.TicketManager.CookieName, ticket)
                {
                    HttpOnly = true
                };
                current.Response.AppendCookie(cookie);
            }
        }

    }
}

extranet\\Preview Anonymous User is a custom user which we have created for preview access and have assigned "sitecore\Sitecore Minimal Page Editor" role to him. We have revoked write access for this user and tested and confirmed that user should not be able to go back to edit mode and edit the page with this access.


Happy Coding :)