Sitecore Preview.ResolveSite

In Sitecore version 8.1 Sitecore has added the Preview.ResolveSite as a standard config setting. Previously, it was a hotfix ever since the initial release from Sitecore v. 6.6.0 up to Sitecore v. 8.0  https://kb.sitecore.net/articles/382913.

It is now a part of the standard settings, though it is set not to resolve site by default…

<!--  PREVIEW - RESOLVE SITE
  If false, the Preview.DefaultSite setting specifies the context site to use when a user previews an item.
  If true, when a user previews an item, Sitecore tries to resolve the root item and the context site based on the current content language
            and the path to the item. If Sitecore cannot resolve the context site, it uses the site that is specified in the Preview.DefaultSite setting.
            Default value: false (use the value of the Preview.DefaultSite setting)
      -->
    <setting name="Preview.ResolveSite" value="false"></setting>

Get external links from Rich Text Editor

Sometimes you want to manipulate links generated by the content authors added in the Rich Text Editor. It could be by adding query strings, set the target attribute to _blank if the link is an external link etc.

Sitecore resolves the internal links in the Rich Text Editor by using the ExpandLinks processor in the renderField pipeline (located in the web.config file) converting the GUID into valid URLs, but letting the external links unhandled. So if you want to manipulate external links, you could do it by adding a new processor into the renderField pipeline.

In this example, I want to add target=”_blank” if the link is an external link.

The code:

using System.Text.RegularExpressions;
using Sitecore.Data.Fields;
using Sitecore.Pipelines.RenderField;
 
namespace MySitecoreExtensions.Pipelines.RenderField
{
    public class AddTargetAttributes
    {
        public void Process(RenderFieldArgs args)
        {
            if (args.FieldTypeKey == "rich text")
            {
                args.Result.FirstPart = SetTargetAttribute(args);
            }
        }
 
        private string SetTargetAttribute(RenderFieldArgs args)
        {
            string fieldValue = args.FieldValue;
            string regexURL = @"(<a.*?>.*?</a>)";
 
            Regex regex = new Regex(regexURL, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
            MatchCollection matches = regex.Matches(fieldValue);
 
            foreach (Match match in matches)
            {
                if (!match.Success)
                    continue;

                string regexHref = @"href=\""(.*?)\""";
                Match maHref = Regex.Match(match.Value, regexHref, RegexOptions.Singleline);
                if (!maHref.Success)
                    continue;
 
                if (maHref.Value.ToLower().Contains("http://"))
                {
                    string enrichedURL = match.Value.Insert(2, " target=\"_blank\" ");
                    fieldValue = fieldValue.Replace(match.Value, enrichedURL);
                }
            }
 
            return fieldValue;
        }
    }
}


Finally I add a new processor to the renderField pipeline (into an include file):

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
            <renderField>
                <processor type="MySitecoreExtensions.Pipelines.RenderField.AddTargetAttributes, MySitecoreExtensions" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetInternalLinkFieldValue, Sitecore.Kernel']"/>
            </renderField>
    </sitecore>
</configuration>


Sitecore Language Fallback

Finally, Sitecore v. 8.1 support Language fallback out of the box.

The language fallback supports both at Item level and at field level and supports a chained fallback mode, where languages can fall back multiple times based on the associated langauges versions.

How does it work
The language fallback allows a developer to specify a default fallback language (for each of the language setting item in Sitecore) to use, when a visitor at the website request content that have not been created for the requested language version.

Template level
The “Tempalte Item” contains two new checkboks fields for handling the fallback language at item-level. The first checkbox “Enable Item Fallback” managing whether to use the fallback language, if the current item has no language version created for the requested language. The second checkbox “Enforce Version Presence” controls whether Sitecore should treat the specific item as non-existent, if the specific item has no versions created at the requested language.


Template Field level
The “Template Field Item” contains two new checkbox fields for handling the fallback language at field level, both placed at the “Data” field section. The first checkbox field “Enable Versioned Language Fallback” enables field-level fallback for only the current language version of the specific field. The second checkbox field “Enable Shared Language Fallback” enables the field-level fallback for the specific field in all languages. 


Specify the fallback language
To specify a fallback language for a specific language, Sitecore has added a field at the Language Setting Item in Sitecore (placed at: Sitecore/system/Languages/) called “Fallback Langauge”. If none is selected, the language has no fallback language. 

Enabling the fallback language features
Sitecore has added a new config file handling the language fallback settings. It is located at /App_Config/Sitecore.LangauageFallback.config. By default, the fallback language feature is disabled. To enable the fallback language, open the config file, find the two new site attributes, “enableItemLanguageFallback” and “EnableFieldLanguageFallback” respectively and set the attribute value to “true” (notice, the fallback feature is site specific):

<!-- ENABLE ITEM AND LANGUAGE FALLBACK PER SITE
         Using attribute patching below you can pick which fallback mode to enable (item-level or field-level or both) for each site 
         Consult official documentation on how to enable fallback feature in complex multi-site environments.
    -->
    <sites>
      <site name="shell">
        <patch:attribute name="enableItemLanguageFallback">false</patch:attribute>
        <patch:attribute name="enableFieldLanguageFallback">false</patch:attribute>
      </site>
      <site name="website">
        <patch:attribute name="enableItemLanguageFallback">true</patch:attribute>
        <patch:attribute name="enableFieldLanguageFallback">true</patch:attribute>
      </site>
    </sites>

Custom Tiles and Analytics Reports in Launchpad

Sitecore introduced the Launchpad in Sitecore 7.1, but was first a fullblown interface in Sitecore 8. Really, it has not been interesting until now that the Launchpad is the new default (and only) startup screen for all users.

So let’s take a look at how to customize the Launchpad.

In this post, I will demonstrate how to add an analytic report chart into the Launchpad and how to hide the Fallback Message for Custom Analytics showing below.


In the example, I want to reuse one of the analytics reports displayed in the Experience Analytics. I will use the “Online interactions by visits and value per visit” analytic chart. 


The “Online interactions by visits and value per visit”-chart, used by the analytics reports, is located in the core database at “/sitecore/client/Applications/ExperienceAnalytics/Dashboard/PageSettings/” (If you want to extend the Experience Analytics application containing new reports etc. this is the place for adding the charts. More about that at another time). The chart contains to metrics, “Visits” and “Value per visit” respectively, and the dimension “All visits By Channel Type”. 


So far so good. 

Next step is to assign renderings to the layout of the Launchpad for displaying the analytic chart.

The Launchpad is built using SPEAK. SPEAK is only accessible through Sitecore Rocks. Therefore, before I will be able to create or customize any new Tiles or analytic reports in Sitecore Launchpad, I have to install Sitecore Rocks in Visual Studio. 

From Rocks navigate to “/Sitecore/client/Applications/Launchpad” in the core database. It is at the layout of the Launchpad you should add the new renderings for displaying the analytic chart. Select “Task” and “Design Layout”.


The layout of the Launchpad has associated many renderings by default, nested into each other. 


Eg. The LaunchBar-rendering, renders all the “applications buttons”-items placed under “/sitecore/client/Applications/Launchpad/PageSettings/Buttons” in the core database. The LaunchTiles-rendering, renders the “Tiles”-items placed under “/sitecore/client/Applications/Launchpad/PageSettings/Tiles” in the core database. Both renderings (LaunchBar and LaunchTiles) rendered the output into the placeholder “ColumnPanel1.Content” placed in the rendering with Id “ColumnPanel1”. These are not the tiles, we want to use in these example, though.

Taking a closer look, we see the Border-rendering with Id “RowPanelTilesWrapper” also rendered into the “ColumnPanel1.Content” placeholder. The RowPanel-rendering with Id “RowPanelTiles”, is rendered into the placeholder “RowPanelTilesWrapper.Content”. The RowPanelTiles is exactly the rendering we want to use, when rendering the Analytics Report chart.

As the name indicates, The RowPanel-rendering add a row-panel in the Tiles area of the Launchpad. Adding the analytic chart into the area of the Tiles, we first want to add a new column to place the chart. Therefore, select the “Add Rendering” command, choose the ColumnPanel rendering, and assign the rendering to the layout of the Launchpad. 


After assigning the ColumnPanel-rendering to the layout of the Launchpad, double click the rendering from the layout (the Renderings and Placeholder area) to open the “Edit Rendering Dialog”. Select the PlaceholderKey “RowPanelTitles.Content”. Set the GridColumns to 6 (This is where, you can manage the width of the column. Choose gridcolumn between 1-12). Finally specify the Id of the rendering (in this case it is “MyColumnPanelExperienceAnalytics”.


Next step is to assign the chart-rendering, we want to use, for displaying the chart. Select the “Add Rendering” command and select the ExperienceAnalyticsLineChart-rendering. 


Open the Edit Rendering Properties. Set “isVisble” attribute to “True”. Set the DataSource to “/sitecore/client/Applications/ExperienceAnalytics/Dashboard/PageSettings/Channels by visits” (The Analytic Report Chart I want to show in the Launchpad). Select the “MyColumnPanelExperienceAnalytics.Content” placeholder (specified by the MyColumnPanelExperienceAnalytics rendering we just added above). Set the Id to be “MyExperienceAnalyticsLineChart”. In the TimeResolution field you choose the default time resolution of the chart (Daily, Weekly or Monthly).


Save the layout. Log into your Sitecore Launchpad and you will find your newly added chart just below the application buttons. 


You may extend the Tiles area with a filter from where, you can filter the data in the chart. This is done by adding an ExperienceAnalyticsFilter and add a Header to the Tiles:


The last step is to hide the Fallback message in the Tiles area. Knowing how to add new renderings to the layout of the Launchpad, it is a simple task to hide the Fallback message. Find the “Border” rendering with Id “FallbackMessageBorder”, and open the Edit Rendering Properties dialog. Select the “IsVisble” attribute and set it to False. Save the Launchpad layout and redirect to the Launchpad in Sitecore. 


Now the “Custom Analytics” “FallbackMessage” dashboard is hidden. 


Damn ... that was a lot of screenshots ...

Content Editor Applications - Revisit

After publishing the post about Content Editor Applications, I saw a question in a Sitecore forum about setting up different security rights for a specific user, depending whether the user navigating the items located in the master DB or in the web database. This is obviously not possible by default, because of the way Sitecore security works.

However, with a simple extension to Sitecore, we could overcome this challenge.

The idea is to create a new role and set the security settings of the role to allow read access and deny all other permissions of all the content items. If the current requests context site is “shell” and the content database is web (meaning that the current user is logged into Sitecore and requesting the web database items), then the current user should have assigned the role.

By adding a new processer into the HttpRequst pipeline it is simple to do these checks.

First, what we want to do is to create the new role and assign the read permission to “allow”, all other permissions to “denied” and allow inheritance of the permissions at the top level of the content item in Sitecore. In this case, I have created a role named “WebDBReader”.


Next step is to create the code checking for the current request:


using Sitecore.Pipelines.HttpRequest;

namespace MySitecoreExtensions.Pipelines.HttpRequestBegin
{
    public class AssignWebReaderRole : HttpRequestProcessor
    {

        public override void Process(HttpRequestArgs args)
        {
            // If there is no context, we are not in a request from a web browser.
            if (args == null || args.Context == null)
            {
                // So we return.
                return;
            }

            //If the site not shell, the user is not logged into Sitecore
            if (!Sitecore.Context.GetSiteName().ToLower().Equals("shell"))
            {
                return;
            }

            if (args.LocalPath.ToLower().Equals("/keepalive.aspx"))
            {
                return;
            }

            if (!string.IsNullOrEmpty(args.Context.Request.QueryString["sc_content"]) &&
                args.Context.Request.QueryString["sc_content"].ToLower().Equals("web"))
            {
                if (!Sitecore.Context.User.IsInRole("sitecore\\WebDBReader"))
                {
                    Sitecore.Context.User.Roles.Add(Sitecore.Security.Accounts.Role.FromName("sitecore\\WebDBReader"));
                }
                return;
            }
            else
            {
                if (Sitecore.Context.User.IsInRole("sitecore\\WebDBReader"))
                {
                    Sitecore.Context.User.Roles.Remove(Sitecore.Security.Accounts.Role.FromName("sitecore\\WebDBReader"));
                }
                return;
            }
        }
    }
}



Finally, we add the extension in the HttpRequest pipeline. It is important to add the processor after the DatabaseResolver has finished:

 <httpRequestBegin>
...
        <processor type="Sitecore.Pipelines.HttpRequest.UserResolver, Sitecore.Kernel" />
        <processor type="Sitecore.Pipelines.HttpRequest.DatabaseResolver, Sitecore.Kernel" />
        <processor type="MySitecoreExtensions.Pipelines.HttpRequestBegin.AssignWebReaderRole, MySitecoreExtensions" />
        <processor type="Sitecore.Pipelines.HttpRequest.BeginDiagnostics, Sitecore.Kernel" />
        ...
      </httpRequestBegin>


And, there you have it. Now the authors would be able to navigate through the items in the web database, without being able to change the content. And still have their default security settings when navigating through the items of the master database.




Media hash and resizing

Sitecore introduced a new security feature in Sitecore version 7.5 regarding handling image requests in Sitecore. The feature restricts media URLs containing dynamic image-scaling parameters so only server-generated request are processed. Meaning, if a media request is processed, Sitecore skips the image scaling, if any of the parameters in the image URL have been altered or appended to the URL client side. Sitecore has added a new processor to the pipeline (added to a new include file, placed: /App_Config/Include/ Sitecore.Media.RequestProtection.config):

<pipelines>
      <renderField>
        <processor patch:before="processor[@type='Sitecore.Pipelines.RenderField.RenderWebEditing, Sitecore.Kernel']" type="Sitecore.Pipelines.RenderField.ProtectedImageLinkRenderer, Sitecore.Kernel" />
      </renderField>
    </pipelines>




What Sitecore do is, Sitecore adds a hash value to the image URL query string, when images requests contains scaling parameters. This means, in older versions than Sitecore versions 7.5 a media request may look something like this:

http://[yourDomain]/~/media/Default Website/sc_logo.ashx?w=100&h=75

scaling the original image from:



to:



(for image scaling parameters [link: http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2011/05/media-options-and-query-string-parameters-in-the-sitecore-aspnet-cms.aspx])

In Sitecore version 7.5 and newer versions, the media request may look something like this:
http://[yourDomain]/~/media/Default Website/sc_logo.ashx?w=100&h=75&hash=D02739F8C8E02B64D5D2AD008175975D28123C17

Therefore, if you are manually setting up the image URL containing scaling parameters, you need to generate the correct hash value and append it to the image URL, or else Sitecore will only return the original unaltered image. You can generate the hash value by your C# code or by Sitecores new mediaHash.aspx tool.

By your C# code:
If you need the full media URL containing scaling parameters and the hash value in your C# code, you can use the HashingUtils.ProtectAssertUrl(url):

Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(
                               Sitecore.Resources.Media.MediaManager.GetMediaUrl(
                                   myMediaItem,
                                   new MediaUrlOptions()
                                   {
                                       Language = Context.Language,
                                       Width = 100,
                                       Height = 75
                                   }))

If you only need the hash value for the provided image URL, you could use the GetAssertUrlHash(url).

By MediaHash.aspx tool
You find the new mediaHash.aspx tool here: http://[yourDomain]/sitecore/admin/mediaHash.aspx. Add the media URL containing the scaling parameters into the textfield:



You can disable the security feature by setting the Media.RequestProtection.Enabled to false, but it is strongly recommended not to disable this feature.

<settings>
<!-- MEDIA - REQUEST PROTECTION - ENABLED
Specifies whether media request protection is enabled or not.
Default value: true-->
      <setting name="Media.RequestProtection.Enabled" value="false">
</setting>
...
</settings>


Additional Publishing Module

So, I finally got the time to publish my new module at Sitecore Marketplace. However, it is more like a couple of new Sitecore Client features than a real module. Actually, it’s only two new (but looong missing) features.

The module is called "Additional Publishing" and adds a new chunk into the “Publishing” tab, named “Additional Publishing”. The chunk contains the two new features/commands “Publish My Items” and “Publish Deleted Items”, respectively.


Publish My Items

The “Publish My Items” command allows a user (who has access right to the Publishing Tab) to publish all the items, the user has created and/or modified since the last time, the items was published. If the current user is an administrator, the administrator can choose another Sitecore user items to publish. 

The way the command work is, it takes all the publishing candidates from the Sitecore Publishing Queue and compare the value of the “__Updated by” field of the publishing candidate with the name of the current Sitecore user. If the “__Updated by” value is equal to the name of the current Sitecore user, the command will publish the item. 


Publish Deleted Items

The “Publish Deleted Items” command allows a user to “un-publish” or “remove” items from the publishing target databases, which have been deleted from the source/master database. This, without the need of publishing the parent item of a deleted item or without starting an incremental publishing of the website. 


The way the command works is, it (like the “Publish My Items” command) takes all the items located in the Publishing Queue and check whether the item exist in the source database (normally the master database). If the item does not exist in the source database (the item is deleted), the changes of the item (the deletion) will be published and the item will be removed the item from the publishing targets.