Author: vindaav

Sitecore Custom Tokens

Out of the box, Sitecore comes with the following expand standard values tokens:

  • $name – Name of the item
  • $date – Current server date
  • $time – Current server time
  • $now – Current server date time
  • $id – Item ID
  • $parentid – Item’s Parent ID
  • $parentname – Item’s Parent Name

Sometimes the already existing tokens are not enough. There are cases in which the Content Editors won`t be able to access the value that needs to be populated (ex. – webservice call) or it will be hard for them to do it (ex. – the value of the item varies on many other items). In the current example, the $next token will be implemented. It will automatically replace the token with the current siblings’ count plus one  – this token is usually used in cases where there is a requirement for auto-incrementing sort order of items.

When it comes down to creating your own custom tokens, there are basically two options to choose from:

  1. Extend the MasterVariablesReplacer class
  2. Extend the ExpandInitialFieldValueProcessor class

The first option involves extending and overriding default functionality of the class, that provides the replacement mechanism for all the standard Sitecore tokens. This approach is explained in John West’s blogpost on how to add custom standard value tokens to Sitecore. It should be noted, that extending from the MasterVariablesReplacer class requires some method overriding. Be aware, that since the class is not really meant for extending in the first place you’ll have to duplicate a great amount of the private members into your own custom implementation.

The other option is the inheritance from the ExpandInitialFieldValueProcessor class, which is my preferred way to create replacement mechanisms for custom tokens in Sitecore. Using the ExpandInitialFieldValueProcessor is really easy, as it only requires you to extend from the base class and implement the void Process(ExpandInitialFieldValueArgs args) method:

namespace AndreyVinda.Processors
{
    using Sitecore.Pipelines.ExpandInitialFieldValue;

    public class TokenNextProcessor : ExpandInitialFieldValueProcessor
    {
        public override void Process(ExpandInitialFieldValueArgs args)
        {
            if (args.SourceField.Value.Contains("$next"))
            {
                if (args.TargetItem != null && args.TargetItem.Parent != null && args.TargetItem.Children != null)
                {
                    args.Result = args.Result.Replace("$next", args.TargetItem.Parent.Children.Count.ToString());
                }
                else
                {
                    args.Result = args.Result.Replace("$next", "0");
                }
            }
        }
    }
}

The code is pretty straightforward. It checks if the value of the field contains the $next token. If it does it checks if the parent is not null and the parent has children. If the parent is not null and there are children the value is set to the children`s count (the processor is executed after the child is added so the index will be 1 based), otherwise it sets the value to 0.

Once the token replacer is implemented, all that is left to do is to patch in the processor into the Sitecore pipeline config section for the expandInitialFieldValue pipeline:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <expandInitialFieldValue>
        <processor type="AndreyVinda.Processors.TokenNextProcessor , AndreyVinda.Processors" patch:after="processor[@type='type=Sitecore.Pipelines.ExpandInitialFieldValue.ReplaceVariables, Sitecore.Kernel']"/>
      </expandInitialFieldValue>
    </pipelines>
  </sitecore>
</configuration>

Enjoy!

Sitecore: Excursion though Admin pages

It is doubtful that there is a Sitecore Developer who never opened /sitecore/admin/showconfig.aspx at least once in his life to check what went wrong with the amazing configuration patch that hadn`t worked. Showconfig is just one of the many admin pages that Sitecore provided by default. Other admin pages are not so popular, so I decided to talk about them in more detail.

Continue reading “Sitecore: Excursion though Admin pages”

Sitecore Adaptive Images – Huge Crawling Logs Problem

Some time ago I have noticed that on our production environment the Crawling Log files were abnormally big – between 500 MB and 1 GB. After some digging was found out that they were just filling up with exceptions while crawling the media library. The exceptions look like this:

WARN Could not compute value for ComputedIndexField: urllink for indexable: sitecore://master/{8EA15044-EE2C-41DB-81D6-0A9C42062814}?lang=en&amp;ver=1
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
Source: Sitecore.Kernel
at Sitecore.Context.PageMode.get_IsNormal()
at adaptiveImages.AdaptiveImagesMediaProvider.GetMediaUrl(MediaItem item)
at Sitecore.ContentSearch.ComputedFields.UrlLink.ComputeFieldValue(IIndexable indexable)
at Sitecore.ContentSearch.LuceneProvider.LuceneDocumentBuilder.AddComputedIndexFields()

Considering the case that there are a tons of media (over 2000 items) and languages (there is a separate exception for each language) we had some pretty serious index time performance issues and hard disk space problems.

Continue reading “Sitecore Adaptive Images – Huge Crawling Logs Problem”

Inheriting Sitecore Site Properties with Sitecore Patching and Transformation

Challenge:

Sitecore is such a huge platform that every day you find something new and interesting. Happens with you as well? It is happening with me since last 7+ years! But I am enjoying learning it and then sharing it with you.

So, let’s say you have one site node defined with all basic things e.g. enablePreview, enableWebEdit, hostName, startItem, database etc. Now you would like to have one more site where you would like to use base attributes as earlier defined and you would like to modify few attributes only:

<sites>
<site name="site1" virtualFolder="/sitecore/admin" physicalFolder="/sitecore/admin" enableAnalytics="false" domain="sitecore" loginPage="/sitecore/admin/login.aspx"/>

<site name="site2" inherits="site1" />
<site name="site3" inherits="site1" domain="extranet" />
<site name="site4" inherits="site1" enableAnalytics="true" />
</sites>

I tried the same approach for my project and it works well. But only locally. When I deployed it on QA server it stopped working. After deep research I have found the source of the issue. I would like to share with you as well. Let’s go!

Solution:

As you would have done, I also did showconfig.aspx on server and then noticed that my site2 was getting added before site1 and that was causing this issue and it was happening because I was using SlowCheetah Transformation and inserting site2 based on environment. To fix it — I used patch:after=”site[@name=’site1′]” which fixed this issue. Here is how it looks new with transformation:

<sites>
<site name="site2" inherits="site1" patch:after="site[@name='site1']" xdt:Transform="Insert" hostName="site2.com" domain="extranet" enableAnalytics="true"/>
<site name="site3" inherits="site1" domain="extranet" />
</sites>

Enjoy!

Getting Sitecore Dictionary in JavaScript

It’s very easy to get translations in back-end code — either Razor views or .cs files — by simply calling to

Sitecore.Globalization.Translate.Text()

But what about JavaScript widgets? There we have several options:

  • Item Web API results in overhead and is hard to use without additional implementation.
  • StringDictionary embeds values right in HTML and needs to be configured accordingly.
  • Injecting translated text into .js components via HTML tags has the same drawbacks as StringDictionary.

All these options are cumbersome and inconvenient.

Continue reading “Getting Sitecore Dictionary in JavaScript”

Complete Unit Testing In Sitecore

Unit testing is Sitecore can be tricky. There are a lots of moving parts. And to truly be able to test, you need to somehow bring all of those parts into a test.

Unit testing could be divided into two different type: regular Unit Tests (just to test BusinessLogic without data relations) and Integration Unit Tests.

In the current article I will focus on Integration Unit Tests. In the futher articles I will describe how to write UnitTests without strong coherence with Sitecore.

So, to accomplish the main goal and have working UnitTests I will try to do the following:

  • Execute unit tests within a valid Sitecore context
  • Load all current App_Config/Include/ configs at runtime
  • Access to all APIs
  • Maintain to additional config files
  • No scripting involved

According to our goals let’s find a way of how to reach it. It’s mostly screenshots and code samples anyways.

Continue reading “Complete Unit Testing In Sitecore”

Sitecore Content and Page Editor: Injecting of resources

Image, that there is a need to add some external script inside Content Editor or/and PageEditor. What do you do? Might be you would start with developing of a custom field type that requires Google Maps API. Maybe many of your renderings use an external library or a client side helper of your own when in IsPageEditorEditing(). Whatever the case might be you may want to inject resources into your Content and Page Editor environments and do it once globally. And in a declarative way. This blog post will explain you the exact way of how to do it.

Continue reading “Sitecore Content and Page Editor: Injecting of resources”