Sitecore Tips and Tricks

10 nov 2014, last update: 24 Jun 2017

Sitecore Tips and Tricks

Here I collect my Sitecore tips. Find more tips in part 2, the Sitecore Tips and Tricks 2016 page. There are tips for Developers and DevOps, and also Sitecore tips for content editors.

Tip #1: Creating a RSS feed is a out of the box functionality it takes only a few minutes to setup.

See Create rss feeds in Sitecore and more advance override the RSS functionality Add Additional Item Fields to RSS Feeds Generated by Sitecore or Notice the feed error see Sitecore and the error page

Tip #2: Sorting Sections use a negative number.

Using a positive value in the Appearance Sortorder Field won't work, use a negative number if you want to sort your custom sections. see quick tip resolving section sort order or use values higher than 100

Tip #3: Media use the original file extension instead of .ashx

In the web.config set a empty Media.RequestExtension <setting name="Media.RequestExtension" value=""/> Setting its value to blank give media urls a relevant extension like .jpg see the Extension Field in the media item.

Tip #4: Security use encrypting on security sensitive config files.

Encrypt the connectionstring or use trusted connection for the databases, if using WFFM webservices there is also a Sitecore account in the connection string.

Description for encrypting the connectionstrings:
1.) Configure the connectionstrings;
2.) Control if the application is correct working;
3.) Run Windows Command Prompt with administrator permission;
4.) Go to directory C:\Windows\Microsoft.NET\Framework\v4.0.XXXXXX
5.) Run command: Aspnet_regiis -pef "connectionStrings" "C:\Sites\Website" (note: physical path may be different)
6.) Check if the connectionstrings are encrypted now.
7.) Control if the application is correct working;
See MSDN and for custom sections how to encrypt custom configuration would you like to automate automatic asp dot net connection string encryption

 

Tip #5 SEO url for multi language pages.

If you want for each language a different url for the same page? turn on useDisplayName in the LinkManager and fill in a Display name. See the web.config for the LinkManager.

Tip #6 Create programmatically items with a correct name.

To avoid invalid characters in a item name use Sitecore.Data.Items.ItemUtil.ProposeValidItemName. This method will replace all the invalid characters with empty character. See the <setting name="InvalidItemNameChars" value="\/:?&quot;&lt;&gt;|[]"/> not checking for duplicate name.

Tip #7 How many renderings are there in a placeholder

You can do a count on the Renderings, but this also count renderings hide with a DMS rule.

public static int GetRenderingCount(string placeHolderKey)
{
  return Sitecore.Context.Item.Visualization.GetRenderings(Sitecore.Context.Device, false).Count(x => x.Placeholder.Equals(placeHolderKey));
}

Or use this for a count of visible renderings:

placeHolderKey.Controls.Count.ToString();

Tip #8 On what position is this rendering in the placeholder

This code give the correct number as string even if there are renderings hide with DMS.

public static string GetComponentPositionOnPlaceHolderByControlName(System.Web.UI.Control webControl)
{
 if (webControl == null) return "0";
 var split = webControl.ID.Split('_');
 if (split.Length > 1)
 {
  int index = 0;
  if (int.TryParse(split.Last(), out index))
  {
   return (index + 1).ToString(CultureInfo.InvariantCulture);
  }
 }
 return "0";
}

Tip #9 The installation of a package gives a error of the web database configuration.

When you get this error:
Could not Found configuration node: database/database[@id='YourWEB']

Truncate the Links tabel in SQL Server (Core database) and rebuild the link Database, In Sitecore Desktop, All Applications - Control Panel - Database - Rebuild the Link Database

Tip #10 The Patch Cache

On Sitecore 6.x versions with CD servers the path cache is not flushed after a rename of a item, so the old path is still active. To fix it clear the patch cache after a publish by using the publish:end event.

using System;
using System.Linq;
using Sitecore.Publishing;

// patch the <event name="publish:end">  <handler type="Stockpick.Sitecore.Publishing.CacheClearer, Stockpick.Sitecore" method="ClearCache">
namespace Stockpick.Sitecore.Publishing
{
    public class CacheClearer : HtmlCacheClearer
    {         new public void ClearCache(object sender, EventArgs args)         {             global::Sitecore.Diagnostics.Log.Info("Custom Stockpick Clear Path Cache",this);             Sites.ToArray().ToList().ForEach(x =>             {                 global::Sitecore.Sites.SiteContext site = global::Sitecore.Configuration.Factory.GetSite(x.ToString());                 if (site != null)                 {                     global::Sitecore.Caching.PathCache cache = global::Sitecore.Caching.CacheManager.GetPathCache(site.Database);                     if (cache != null)                     {                         cache.Clear();                         global::Sitecore.Diagnostics.Log.Info("Clear Path Cache for Database:" + site.Database.Name, this);                     }                 }             });             base.ClearCache(sender, args);         }     } }

#Tip 11 A Sitecore fast query is a database query

Do not use a fast query in a loop. Also watch out with heavy fast queries in not cached layouts.
I once had the same fast query needed into multiple components on many pages i solved it with a memory cache for that query. Understand the impact of a Sitecore Fast Query, same as with the Hibernate ORM library, if you're not used it properly it will result in poor performance. See sitecore fast query syntax can kill your sql server or website

#Tip 12 patch:instead in the App_Config/Include

The App_Config/Include folder is the place for patch file for the web.config. And with /sitecore/admin/showconfig.aspx you can see the final config.
Before Sitecore 7.5 there was not a config include with patch:instead in the shipped config files. And without an example, you can easily miss it exists.

Patch:instead Example

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <sites>
      <site name="website" patch:instead="site[@name='website']"
        language="nl-NL"
        virtualFolder="/"
        physicalFolder="/"
        rootPath="/sitecore/content/Mirabeau"
        startItem="/Home"
        database="web"
        domain="extranet"
        allowDebug="true"
        cacheHtml="true"
        htmlCacheSize="10MB"
        registryCacheSize="0"
        viewStateCacheSize="0"
        xslCacheSize="5MB"
        filteredItemsCacheSize="2MB"
        enablePreview="true"
        enableWebEdit="true"
        enableDebugger="true"
        disableClientData="false"/>
    </sites>
  </sitecore>
</configuration>

You can use the following elements:

  • -patch:before: Insert the element before the specified element.
  • -patch:after: Insert the element after the specified element.
  • -patch:instead: Replace the specified element.
  • -patch:delete: Remove the specified element.
  • -patch:attribute: Define or replace the specified attribute.

See John West Sitecore Blog - Posts 2011/05 - All About Web config Include Files with the Sitecore ASPNET CMS

 

Tip #13: Hidding field for editors

If you want to hide a field for some CMS users, for example Author's. simple don't give them Read right on the Field in the Template

 

#Tip 14 use Sitecore fakeDb in Unit tests

marketplace Sitecore FakeDb

#Tip 15 old Developer center with Xpath builder Sitecore 8.0

In Sitecore 8 the old Developer center with Xpath builder is disappeared from the menu. but it is still accessible try this url  /sitecore/shell/default.aspx?xmlcontrol=IDE

#Tip 16 url alias after item resolver

Default a url alias has a higer priority than a item. Especially in a multi-site environment gives this quickly issues. Because url aliases are on instance level instead of his site level. so a url alias on site1 also exsits on site 2 but link to a item with possible other language and logic en design not intend to show on site2. if there is a aliase on site 1 for example /action and on site 2 there is a page /action. the /action page on site2 show the url alias on site1. The content editor on site is not happy with this behavior.

Changing the order in the httpRequestBegin pipeline helps.

<processor type="Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel"/>
<!-- for Multisite change the position of AliasResolver from before DefaultResolver to after ItemResolver -->
<processor type="Sitecore.Pipelines.HttpRequest.AliasResolver, Sitecore.Kernel"/>

If you really want to do much with url aliases in a multisite environment, you can also choose to do an implementation at site level. see Marketplace

#Tip 17 Canonical

Especially when using Sitecore url aliases or a LinkManager with language asNeeded there a multiple urls to the same page. To avoid duplicate content penalty and getting good indexed by search engines use a Canonical in the HTML head.

<link rel="canonical" runat="server" ID="Canonical" />

string baseUrl = LinkManager.GetItemUrl(Sitecore.Context.Item);
if (baseUrl != Request.Path)
{
    Canonical.Href = baseUrl;
} else
{
    Canonical.Visible = false;
}

#Tip 18 Switch to Desktop

If you want fast to Sitecore Desktop mode, change the url to /sitecore/shell In this way you do not have to go to the Sitecore 8 Launch Pad or the Login Screen.

#Tip 19 Bulk upload media

In the webroot there is a upload folder here you can place a directory structure with media. The media is automatically put into the Sitecore media library

#Tip 20 Url with hostname for example a og:image

In the <site><sites ... targetHostName="sitecore.stockpick.nl> you can set a hostname. This hostname is used when generating a url with the LinkManager with a hostname. This is very useful in a multisite environment. For example an og:image tag needs a url with a hostname.

//default image used when the "og image" field is not set
var ogImage = string.Format("http://{0}/static/gfx/default.png", Sitecore.Context.Site.TargetHostName.ToLower(CultureInfo.InvariantCulture));

Sitecore.Data.Fields.ImageField ogImageField = Sitecore.Context.Item.Fields["og image"];
if (ogImageField != null && ogImageField.MediaItem != null)
{
	var options = new MediaUrlOptions();
	options.AbsolutePath = true;
	options.AlwaysIncludeServerUrl = true;
	ogImage = MediaManager.GetMediaUrl(ogImageField.MediaItem, options);
}

return string.Format("<meta property=\"og:image\" content=\"{0}\" />", ogImage);

#Tip 21 Show Broken links, My Locked Items, Personalisation, Workflow State and more in the page tree.

When you press the right mouse button in the left white space in the content tree in the content editor you can set what icons to show left near the tree items. New in Sitecore 8 are the Personalizations and Multivariant Tests.

 

#Tip 22 For editors Url alias

In the Sitecore Content Editor in tab Presentations there is button Url Aliases. with this functionality an editor can create an url alias. See tip 16 and 17

#Tip 23 For editors set help tekst on a Sitecore item

In the Sitecore Content Editor in tab Configuration there is a button Help, with this functionality an editor can set a help tekst on a item, the Short Description is displayed below the Item name. See User friendly developing in Sitecore

#Tip 24 Sitecore Log Melding Could not load file or assembly 'file:///c:\xx\xxx\xxx.dll' or one of its dependencies. The module was expected to contain an assembly manifest.

In Sitecore 7.x and above all DLLs checked at start up and put in the log. A dll without the .NET CLI Metadata, such as a C++ dll will give the following error when placed in the bin folder of Sitecore.

Could not load file or assembly 'file:///c:\xxx\xxx\xxx\website\bin\ssleay32.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
Source: mscorlib
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at Sitecore.Pipelines.Loader.ShowVersion.ShowVersionData(String filename)

This can be solved by placing the none .NET dll in another folder where IIS can find it. Or you can create your own bin folder (in the webroot) by placing something like this in the web.config:

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="bin/mycppdll" />

.....

Because security it is recommended to create the new bin below the bin folder because bin is a Hidden Segment in IIS, so there is Request Filtering this means the dll files can not downloaded.

#Tip 25 For editors Hidden folders and raw values and Bucket structure

Below the View tab there are options to show hidden folders like the system folder, show standard values means see all the fields, Raw values means link fields and other fields show weird data an it looks like fields are broken, it is just for Developers to see the real data. And Buckets show the buckatable items in a folder structure that is default represented the datetime.

#Tip 26  No Cache Limiet

From Sitecore revision 110928 and higher there is a setting Caching.DisableCacheSizeLimits in the web.config, set to true to maximize caching. If you have plenty of memory, else read the Sitecore Cache Configuration Reference to tune your cache limits.

A patch file example for the Include folder:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="Caching.DisableCacheSizeLimits" value="true"/>
    </settings>
  </sitecore>
</configuration>

Sitecore recommends that the cache size limits are disabled on 64-bit systems with ample memory.

#Tip 27 Configure the password policy

Sitecore use .NET Membership provider for the CMS Users you can set the Company password policy in the web.config, the minimal Required Password Length and the The minimum number of non-alphanumeric. See Configure the password policy.

#Tip 28 Kick users

If you want to see which users are logged in or want to kick a user you can use the Kick User Page. This page is meant to Kick users when the number of simultaneously logged in users from the Sitecore Licenses is hit.
Use this URL for Sitecore 8 /sitecore/shell/sitecore/client/Applications/LicenseOptions/KickUser
For older versions use /sitecore/shell/Applications/Login/Users/Kick.aspx

#Tip 29  On which Sitecore version runs this site

Sitecore has a XML file with the version number. try this URL /sitecore/shell/sitecore.version.xml
Of course this does not work on security hardened sites, (don't allow download xml files and do not have a sitecore folder in the webroot on the CD)

#Tip 30 MediaRequestProtection

From sitecore 7.5 and higher, there is MediaRequestProtection see the App_Config\include\Sitecore.Media.RequestProtection.config do not forget to change the SharedSecret. When using the scaling function there is a hash added to the querystring. You need this hash for image scaling. If you use the image or richtext control this works out of the box. When you generate a url you can use the HashingUtils.ProtectAssetUrl methode.

var options = new MediaUrlOptions();
options.MaxWidth = maxWidth;
options.AlwaysIncludeServerUrl = true;
imageUrl = HashingUtils.ProtectAssetUrl(Sitecore.Resources.Media.MediaManager.GetMediaUrl(item, options));

#Tip 31 Transferring user passwords between Sitecore instances

When package users you loss the password, Sitecore has a tool to copy the password. See
https://kb.sitecore.net/articles/242631
Another option is to copy the SQL Membership tables. See Easiest way to copy users from one Sitecore instance to another. And here the SQL script.

#Tip 32 Reset Admin password to default b

If you lost your admin login you can reset it when you have access to the SQL core database.

UPDATE dbo.aspnet_Membership
SET
	Password='qOvF8m8F2IcWMvfOBjJYHmfLABc=',
	PasswordSalt='OM5gu45RQuJ76itRvkSPFw=='
WHERE
	UserId = (SELECT UserId FROM dbo.aspnet_Users WHERE UserName = 'sitecore\Admin')