Skip to content

Instantly share code, notes, and snippets.

@sohelsd
Last active August 29, 2015 14:25
Show Gist options
  • Save sohelsd/5c05ff13f8ce366944ba to your computer and use it in GitHub Desktop.
Save sohelsd/5c05ff13f8ce366944ba to your computer and use it in GitHub Desktop.
Sitecore automatic datasource builder. To use it, Drop the config file into App_Config/Includes folder. Use ./Components as your sublayout/rendering Datasource.
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Pipelines.GetRenderingDatasource;
using Sitecore.SecurityModel;
using Sitecore.Sites;
using Sitecore.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Site.Web.Pipelines
{
/// <summary>
/// This pipeline is envoked everytime there is a component being added on a page. This pipeline ensure's the components are created right under the article/page within the Components folder. There is also a Web.config entry for this.
/// Refer https://jermdavis.wordpress.com/2014/02/21/improving-your-sitecore-ia-with-relative-datasource-locations/ for more info.
/// </summary>
public class RelativeDatasource
{
private static ID DataSourceLocationField = new ID("{B5B27AF1-25EF-405C-87CE-369B3A004016}");
private static ID FolderTemplateID = new ID("{A87A00B1-E6DB-45AB-8B54-636FEC3B5523}");
private static TemplateID FolderTemplate = new TemplateID(FolderTemplateID);
private static string RelativePath = "./";
private static string FolderName = "Components";
public void Process(GetRenderingDatasourceArgs args)
{
if (args == null)
{
throw new ArgumentNullException("args");
}
string dataSourceLocation = args.RenderingItem.Fields[DataSourceLocationField].Value;
if (string.IsNullOrWhiteSpace(dataSourceLocation))
{
return;
}
if (!dataSourceLocation.Contains(RelativePath))
{
return;
}
if (string.IsNullOrWhiteSpace(args.ContextItemPath))
{
return;
}
string subFolderPath = args.ContextItemPath + "/" + FolderName;
if (args.ContentDatabase.GetItem(subFolderPath) != null)
{
return;
}
Item currentItem = args.ContentDatabase.GetItem(args.ContextItemPath);
if (currentItem == null)
{
return;
}
using (new SecurityDisabler())
{
currentItem.Add(FolderName, FolderTemplate);
}
}
}
}
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<getRenderingDatasource>
<processor patch:before="processor[@type='Sitecore.Pipelines.GetRenderingDatasource.GetDatasourceLocation, Sitecore.Kernel']" type="Site.Web.Pipelines.RelativeDatasource, Site.Web"/>
</getRenderingDatasource>
</pipelines>
</sitecore>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment