Archive for March, 2017

Error resolving SpeakUI scripts in Sitecore

While working with Speak UI in Sitecore, I added a new Speak component rendering to my solution.

2017-03-31_152916

Once I added this rendering to my speak page, it started throwing a javascript error:

Script error for: /-/speak/v1/client/

2017-03-31_153237

After some poking around, I realized that this issue was occurring because of the space in my rendering name!

So while this url was giving a 404: http://redirectmanager.local/-/speak/v1/client/Redirects_Listing.js, the url with the space was working just fine:

2017-03-31_153530.png

So short of customizing the ResolveScript processor (see below screenshot) which is responsible for resolving the rendering script from your folder to the expected url with the set prefix (see below RequireJsCustomHandler setting), the work around would be to avoid spaces in your rendering names for this version and use underscores if you have to!

<!--   SPEAK HTML REQUIRE JS CUSTOM HANDLER             Specifies the prefix that should trigger the HTTP request customer handler (see the customHandlers section in the web.config file).             Default: /-/speak/v1/        -->
<setting name="Speak.Html.RequireJsCustomHandler" value="/-/speak/v1/" patch:source="Sitecore.Speak.config"/>

2017-03-31_153809.png

Hope this helps!

, , , , , , , , , , , , , ,

Leave a comment

Sitecore rocks add component error

A quick post here, to troubleshoot an error I faced while trying to add a new speak component to my project using Sitecore Rocks.

While trying to add the component, I kept seeing this issue.
“Count not load file or assembly ‘Sitecore.Rocks, Version=2.0.0.0, Culture=neytral, PublicKeyToken=a3d60f56f71b90’ or one of its dependencies. The system cannot find the file specified.”

Even though my Sitecore Rocks extension was updated only today, the error persisted.
For some reason however, uninstalling the extension and reinstalling the same and then restarting Visual Studio resolved the issue for me.
Hope this helps!

Any additional information on the root cause of this issue is welcome.

, , , ,

Leave a comment

Sitecore Image Lazy Load Module

The package and code for this module can be found at: Github – aceanindita

The bLazy.js plugin – A lazyload image script can be used to enable lazyload on your site, to reduce initial page load times drastically, especially if your site is image heavy.

While you can directly integrate your site with the bLazy plugin, you will need to ensure that your images are not loaded on page load, for which you will need to transform your html accordingly. This can also bring with it experience editor compatibility concerns.

This module will make all your images rendered from Sitecore Image and Rich Text fields, lazy loaded automatically without you having to make ANY html updates at all.

For this, we are usign the following config which does 2 things

  • Processor added to mvc.renderRendering – to include and initialize the bLazy plugin
  • Processor added to renderField – to transform html for all images rendered from the Sitecore Image field and Rich Text field, to move the src url to a different attribute recognized by the plugin, and also add a selector to tell the plugin this html needs to be transformed to lazy load the image.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <mvc.renderRendering>
        <processor type="ImageLazyLoadModule.Pipelines.MVC.InsertbLazyInit, ImageLazyLoadModule"             patch:before="processor[@type='Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer, Sitecore.Mvc']" />
      </mvc.renderRendering>
      <renderField>
        <processor type="ImageLazyLoadModule.Pipelines.RenderField.ImageLazyLoad, ImageLazyLoadModule" />
      </renderField>
    </pipelines>
    <settings>
      <setting name="ImageLazyLoadModule.Offset" value="200" />
      <setting name="ImageLazyLoadModule.Selector" value="b-lazy" />
    </settings>
  </sitecore>
</configuration>

You can see 2 configurable settings above, which are used when the bLazy plugin is initialized.

  • The offset controls how early you want the elements to be loaded before they’re visible.
  • The selector is the class that will be added to the img tags dynamically, which will be used by the plugin to lazy load images.

The code for mvc.renderRendering for including the script and plugin initialization

using Sitecore.Configuration;
using Sitecore.Mvc.Pipelines.Response.RenderRendering;
using Sitecore.Mvc.Presentation;

namespace ImageLazyLoadModule.Pipelines.MVC
{
    public class InsertbLazyInit : RenderRenderingProcessor
    {
        public override void Process(RenderRenderingArgs args)
        {
            Renderer renderer = args.Rendering.Renderer;
            if (renderer == null)
                return;

            bool isLayout = renderer is ViewRenderer &&
                               ((ViewRenderer)renderer).Rendering.RenderingType == "Layout";

            if (isLayout)
            {
                args.Writer.Write("<script src=\"../../sitecore modules/Lazy Load/blazy.min.js\"></script>"
                                  + "<script>"
                                  + "var bLazy = new Blazy({ selector: '."
                                  + Settings.GetSetting("ImageLazyLoadModule.Selector", "b-lazy")
                                  + "', offset: " 
                                  + Settings.GetIntSetting("ImageLazyLoadModule.Offset", 200)
                                  + ", src: 'responsive-src'});"
                                  + "</script>");
            }
        }
    }
}

The code for renderField which will transform img tag html

using HtmlAgilityPack;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.RenderField;
using System;

namespace ImageLazyLoadModule.Pipelines.RenderField
{
    public class ImageLazyLoad
    {
        public void Process(RenderFieldArgs args)
        {
            try
            {
                if (args == null)
                    return;

                // Trigger the code to transform the img tags only for rich text and image fields
                if (!(args.FieldTypeKey != "rich text" || args.FieldTypeKey != "image") || string.IsNullOrEmpty(args.FieldValue) ||
                     !Context.PageMode.IsNormal)
                    return;

                if (!string.IsNullOrWhiteSpace(args.Result?.FirstPart))
                {
                    HtmlDocument doc = new HtmlDocument { OptionWriteEmptyNodes = true };
                    doc.LoadHtml(args.Result.FirstPart);

                    if (doc.DocumentNode != null)
                    {
                        // Search for all img tags
                        HtmlNodeCollection imgTag = doc.DocumentNode.SelectNodes("//img");
                        if (imgTag == null || imgTag.Count == 0)
                            return;

                        foreach (HtmlNode node in imgTag)
                        {
                            if (node.Attributes["src"] != null && node.ParentNode != null)
                            {
                                string imgUrl = node.Attributes["src"].Value;
                                node.Attributes.Add("responsive-src", imgUrl);
                                node.Attributes["src"].Value = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
                                string currentClass = node.Attributes["class"] != null ? node.Attributes["class"].Value : "";
                                node.Attributes.Remove("class");
                                node.Attributes.Add("class", (string.IsNullOrWhiteSpace(currentClass) ? "" : currentClass + " ")
                                    + Settings.GetSetting("ImageLazyLoadModule.Selector", "b-lazy"));
                                node.Attributes.Remove("width");
                                node.Attributes.Remove("height");
                            }
                        }

                        args.Result.FirstPart = doc.DocumentNode.OuterHtml;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error in ImageLazyLoadModule.ImageLazyLoad:" + ex.Message, ex);
            }
        }
    }
}

You can also choose to add image transitions using css as is specified in the bLazy Documentation

.b-lazy {
-webkit-transition: opacity 500ms ease-in-out;
-moz-transition: opacity 500ms ease-in-out;
-o-transition: opacity 500ms ease-in-out;
transition: opacity 500ms ease-in-out;
max-width: 100%;
opacity: 0;
}
.b-lazy.b-loaded {
opacity: 1;
}

Here’s a very simple example of this module in use (Rich text field example)

We have a simple content item, where an image has been embedded in the rich text field from the media library

The view rendering code, simply outputs the rich text field using the Sitecore renderer (observe there are no additional classes added either)

Now for the output! When you load up the page with this ViewRendering, you see the following

Observe that the selector ‘b-lazy’ was added dynamically by our RenderField customization, and it was further picked up by the bLazy plugin and transformed successfully, evident by the ‘b-loaded’ class.

Now to see the html loaded on page load

Here you can see that the bLazy script and its initialization was added dynamically by our mvc.renderRendering pipeline update, and the img tag on page load, has a different src! This src is the base64 code of a pixel. The actual image source has been moved to a different attribute (responsive-src) which is recognized by the plugin (supplied during plugin initialization)

Hence proved.

The package and code for this module can be found at: Github – aceanindita

, , , , , , ,

Leave a comment

Reading custom Sitecore configuration

While writing out some Sitecore functionality, we often need to add new Sitecore settings. Basic setting fields can be easily added in the sitecore section.

These settings can be retrieved in code using the methods provided in Sitecore.Configuration.Settings, eg.

Settings.GetIntSetting("SitecoreModules.ImageLazyLoadResizeModule.Offset", 200)

If you have a more complex structure of settings in mind, you might be better off creating your own custom xml structure within the Sitecore configuration settings mode.

Here’s an example

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <SitecoreModules.ImageLazyLoadResizeModule>
      <DesktopBreakpointInfo CssClass="data-responsive-desktop" Breakpoint="0" ImageMaxWidth="580"  />
      <TabletBreakpointInfo CssClass="data-responsive-tablet" Breakpoint="980" ImageMaxWidth="350"  />
      <MobileBreakpointInfo CssClass="data-responsive-mobile" Breakpoint="768" ImageMaxWidth="200"  />
    </SitecoreModules.ImageLazyLoadResizeModule>
  </sitecore>
</configuration>

To read these settings i created a couple of POCO classes

    public class Breakpoint
    {
        public string Name { get; set; }
        public string CssClass { get; set; }
        public string BreakpointPx { get; set; }
        public int ImageMaxWidth { get; set; }
    }

    public class BreakpointsConfig
    {
        public Breakpoint MobileBreakpoint { get; set; }
        public Breakpoint TabletBreakpoint { get; set; }
        public Breakpoint DesktopBreakpoint { get; set; }
    }

Following code allowed us to populate the settings

using Sitecore.Configuration;
using Sitecore.Xml;
using SitecoreModules.ImageLazyLoadResizeModule.Models;
using System.Web;
using System.Xml;

namespace SitecoreModules.ImageLazyLoadResizeModule.Helpers
{
    public class BreakpointConfigHelper
    {
        public static BreakpointsConfig GetBreakpointInfoConfig()
        {
                BreakpointsConfig breakpointsConfig = new BreakpointsConfig();
                breakpointsConfig.DesktopBreakpoint = GetConfigFromNode(Factory.GetConfigNode("SitecoreModules.ImageLazyLoadResizeModule/DesktopBreakpointInfo"));
                breakpointsConfig.TabletBreakpoint = GetConfigFromNode(Factory.GetConfigNode("SitecoreModules.ImageLazyLoadResizeModule/TabletBreakpointInfo"));
                breakpointsConfig.MobileBreakpoint = GetConfigFromNode(Factory.GetConfigNode("SitecoreModules.ImageLazyLoadResizeModule/MobileBreakpointInfo"));
        }
    }
}

GetConfigFromNode

       private static Breakpoint GetConfigFromNode(XmlNode node)
        {
            if (node == null) return null;

            int imageMaxWidth;
            if (!int.TryParse(XmlUtil.GetAttribute("ImageMaxWidth", node), out imageMaxWidth))
                return null;

            return new Breakpoint
            {
                Name = XmlUtil.GetAttribute("Name", node),
                CssClass = XmlUtil.GetAttribute("CssClass", node),
                BreakpointPx = XmlUtil.GetAttribute("Breakpoint", node),
                ImageMaxWidth = imageMaxWidth
            };
        }

, , , ,

Leave a comment

Sitecore RenderingsMarkerModule

Note: This module has been created as a package and is available for download along with the complete source code at Git: aceanindita

Sitecore being component based as it is, adding start and end comments to your views can be immensely helpful while debugging issues, especially if they are being worked on someone who doesn’t know the project from Adam.

Hardcoding the start / end comments isn’t a great idea for obvious reasons like being prone to developer omission in some views, refactoring / file renaming concerns etc.

In an earlier post I had shown how we had partially resolved this by making the build up of the comment dynamic using a html helper method which used the WebPageExecutingBase.VirtualPath property from the System.Web.WebPages assembly.
You can refer the post here: Using dynamic view markers in Sitecore MVC

In this method, you would need to manually wrap each of your views within a call to the said html helper method, which would dynamically include the current view path in start and end comments around your view. While this did away with the potential issues that might come out of refactoring like changing folder structures / renaming files, it still didn’t deal with the dependency on having the developer(s) remember to add the call to this html helper in every single view.

Here’s a solution for this, we added a new processor in the mvc.rendering pipeline, before and after the call of Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer which renders the actual rendering html.

Here’s the config update made for this (patch):

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <mvc.renderRendering>
        <processor type="RenderingsMarkerModule.Pipelines.MVC.RenderingMarker.RenderMarkerStart, RenderingsMarkerModule"
            patch:before="processor[@type='Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer, Sitecore.Mvc']" />
        <processor type="RenderingsMarkerModule.Pipelines.MVC.RenderingMarker.RenderMarkerEnd, RenderingsMarkerModule"
            patch:after="processor[@type='Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer, Sitecore.Mvc']" />
      </mvc.renderRendering>
    </pipelines>
    <settings>
      <setting name="RenderingsMarkerModule.Enabled" value="true" />
      <setting name="RenderingsMarkerModule.ShowLayoutMarkers" value="false" />
    </settings>
  </sitecore>
</configuration>

Note we have 2 additional settings here. ‘RenderingsMarkerModule.Enabled’ lets you toggle the rendering of comments on and off – this could help you turn of this rather revealing feature on staging / production. Additionally you could toggle ‘RenderingsMarkerModule.ShowLayoutMarkers’ to show / hide comments before & after your layout. It is recommended that this remain off, since having your html response start with a html comment might not always be favorable.

Here’s the code we have in place:
RenderingsMarkerModule.Pipelines.MVC.RenderingMarker.RenderMarkerStart

using Sitecore.Configuration;
using Sitecore.Mvc.Pipelines.Response.RenderRendering;
using Sitecore.Mvc.Presentation;

namespace RenderingsMarkerModule.Pipelines.MVC.RenderingMarker
{
    public class RenderMarkerStart : RenderRenderingProcessor
    {
        public override void Process(RenderRenderingArgs args)
        {
            if (Settings.GetBoolSetting("RenderingsMarkerModule.Enabled", false))
            {
                Renderer renderer = args.Rendering.Renderer;
                if (renderer == null)
                    return;

                bool isLayout = renderer is ViewRenderer &&
                                ((ViewRenderer) renderer).Rendering.RenderingType == "Layout";
                bool showLayoutMarkers = Settings.GetBoolSetting("RenderingsMarkerModule.ShowLayoutMarkers", false);

                if (isLayout && !showLayoutMarkers) return;

                args.Writer.Write("\n<!-- START: " + renderer + " -->\n");
            }
        }
    }
}

RenderingsMarkerModule.Pipelines.MVC.RenderingMarker.RenderMarkerEnd

using Sitecore.Configuration;
using Sitecore.Mvc.Pipelines.Response.RenderRendering;
using Sitecore.Mvc.Presentation;

namespace RenderingsMarkerModule.Pipelines.MVC.RenderingMarker
{
    public class RenderMarkerEnd : RenderRenderingProcessor
    {
        public override void Process(RenderRenderingArgs args)
        {
            if (Settings.GetBoolSetting("RenderingsMarkerModule.Enabled", false))
            {
                Renderer renderer = args.Rendering.Renderer;
                if (renderer == null)
                    return;

                bool isLayout = renderer is ViewRenderer &&
                                ((ViewRenderer) renderer).Rendering.RenderingType == "Layout";
                bool showLayoutMarkers = Settings.GetBoolSetting("RenderingsMarkerModule.ShowLayoutMarkers", false);

                if (isLayout && !showLayoutMarkers) return;

                args.Writer.Write("\n<!-- END: " + renderer + " -->\n");
            }
        }
    }
}

Here’s a sample of the output

This module has been created as a package and is available for download along with the complete source code at Git: aceanindita

, , , , , , , , , , , , , , , , , ,

Leave a comment

EditFrame vs Experience Editor Buttons in Sitecore

EditFrame and Experience editor buttons are both great ways of adding experience editor support to our Sitecore pages.

  • EditFrame buttons
    • Create item in core database (I usually just duplicate the Default folder at /sitecore/content/Applications/WebEdit/Edit Frame Buttons/Default). You can add the field(s) you want to make editable in the ‘Fields’ field
    • In your view, you need to wrap the html that you want to make editable, with the EditFrame code, where you need to supply it with the path of your edit frame button in core, and the item ID of the item you want to edit. The fields made editable would depend on the fields you include in the EditFrame button item as shown in the above image.
      @using (BeginEditFrame("/sitecore/content/Applications/WebEdit/Edit Frame Buttons/Headline", Model.Id.ToString()))
      {
      <div>@Model.Headline</div>
      }
      

    You will now be able to see additional buttons around the html you enclosed in the EditFrame code

  • Experience Editor Buttons
    • Create button item in Core database – use the template – /sitecore/templates/System/WebEdit/Field Editor Button and create the /sitecore/content/Applications/WebEdit/Custom Experience Buttons
    • In your rendering, select the button you just created in the ‘Experience Editor Buttons’ field

    The additional button you created will now be available when you select the entire rendering. If the datasource is available, that item is considered for editing and the field name mentioned in the experience editor button item in core is searched for in that item, else the context item is considered for the same.

Points to note about these 2 implementations:

EditFrame Buttons Experience Editor Buttons
Providing fields to edit Pipe separated – In the core item for the button Pipe separated – In the core item for the button
Item to be edited Item id passed in, in the view code The datasource item is used if available, else the context item is used. This is irrespective of whether the fields mentioned in the button item exist in the datasource item.
Code change required Yes, code needs to be added in the view as shown above. No
Html to be selected  Only the html around which the EditFrame code is wrapped needs to be selected to see the button. The available buttons show up when the entire rendering is selected.
Flexibility  You can choose to edit any number of items selecting any single html tag as is the requirement. Only 1 item can be edited per rendering (datasource or context item), and individual html elements cannot be selected to see the button(s).

, , ,

Leave a comment

Error creating Areas / Controllers in Sitecore SIM generated solution

Always If you are using SIM to create your Sitecore visual studio solution, you will get the following structure:

I am using SIM 1.4.0.383 with Sitecore 8.2 – Update 2

When you try to add a controller or an area in your project, you might see the following error:

On looking this up, many results seem to suggest clearing temporary asp.net files at C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\
This didnt work for me.

On looking further, this issue seemed to be caused because web.config is not included in the project by default.

Include the web.config in your project all is good! Always ensure your web.config is available in your solution and is valid when you encounter a similar error.

, , , , , , , , , , , ,

Leave a comment