9 December 2014

How to access profiles, profile keys through code

Last month I went to the Sitecore DMS fundamentals training as I wanted to have a taste of what and how marketing team will use all the tools available. Some really interesting materials and tools that we are coding for but unfortunately don't really use too often...

During the training session, we had a chat about Profile card, Profile keys and how we are assigning those to a content item. The example given there was for a Cycling Shop. We could create some profile keys for "Beginner", "Amateur" and "Professional". Obviously, you will have different product that will be for Professional: Helmets, Bikes and even GoPro (why not...). Well that gave me an idea for this blog posts and the following on:
  1. How to access those keys and Profile card when we access the item.
  2. How to retrieve Related items based on profile keys - we will continue with that on a later post...
Before starting, I just wanted to point you to a few blogs and posts which helped me a lot:


So first let see how the data are stored in the sitecore item:

When you assign the Profile card and keys in Sitecore you will  click on the "Edit Profile Card associated with the item":

  

Next you will certainly edit the profile you want to assign to the content item and edit the values


Once you have done that, you will notice that those data are stored on the Content Item. The field you are looking for is (enable the standard fields): Tracking ( - or __tracking)

 If you view it with the raw values, you will see that all the data are stored in XML format:

I have pasted the formated XML here for readability:


 < profile id="{1E05D43D-BF07-403D-893D-552FCFBF2BD0}" name="MyTest" presets="general|100||">
  < key name="Digital" value="2" />
  < key name="Traditional" value="2" />
 < /profile>

Since those data are in a field, that means we can access them throuh code... Here are a few methods to show you how you can retrieve the ContentProfiles or just the ContentProfiles name or if you prefer to get the profile Keys... The important thing here is to get the Field "__tracking" and cast it to a Sitecore.Analytics.Data.TrackingField. This field will give you all the required information you need for Campaigns, events, and Profiles... From this field, you should now be able to extract the different profiles associated with the item and then from each profile you can access every keys...

        /// 
        /// Return the list of all profiles for the content Item
        /// 
        /// 
        /// 
        public static IEnumerable GetProfiles(Item item)
        {
            if (!AnalyticsSettings.Enabled)
            {
                return new List();
            }

            Field field = item.Fields["__tracking"];
            if (field == null)
                return new List();

            ContentProfile[] profiles = (new TrackingField(field)).Profiles;
            if (profiles == null)
                return new List();

            return profiles.ToList();
        }

        /// 
        /// Return the list of all profile names associated with the content Item
        /// Where Keys are defined. This is to make sure we are not returning the profiles that are not assigned
        /// 
        /// 
        /// 
        public static IEnumerable GetProfileNames(Item item)
        {
            if (!AnalyticsSettings.Enabled)
            {
                return new List();
            }

            Field field = item.Fields["__tracking"];
            if (field == null)
                return new List();

            ContentProfile[] profiles = (new TrackingField(field)).Profiles;
            if (profiles == null)
                return new List();

            return profiles.Where(p => GetProfileKeys(p,1).Count()>0).Select(i => i.Name).ToList();
        }


        /// 
        /// Get the keys contains in the Content Profile with a minimum score
        /// 
        /// 
        /// 
        /// 
        public static IEnumerable GetProfileKeys( ContentProfile profile, int minimumScore)
        {
            var matchedKeys = new List();

            foreach (ContentProfileKeyData profileKey in profile.Keys)
            {
                if (profileKey.Value >= minimumScore)
                {
                    matchedKeys.Add(profileKey);
                }
            }
            return matchedKeys;
        }

        /// 
        /// Get the key names contains in the Content Profile with a minimum score
        /// 
        /// 
        /// 
        /// 
        public static IEnumerable GetProfileKeyNames(ContentProfile profile, int minimumScore)
        {
            var matchedKeys = new List();

            foreach (ContentProfileKeyData profileKey in profile.Keys)
            {
                if (profileKey.Value >= minimumScore)
                {
                    matchedKeys.Add(profileKey.Name);
                }
            }
            return matchedKeys;
        }

        /// 
        /// Get the Key Names that are define in the Item profiles with a minimum score
        /// 
        /// 
        /// 
        /// 
        public static IEnumerable GetProfileKeyNames(Item item, int minimumScore)
        {
            List keyNames = new List();

            IEnumerable profiles = GetProfiles(item);
            foreach (var profile in profiles)
            {
                keyNames.AddRange(GetProfileKeyNames(profile, minimumScore));
            }
            return keyNames.Distinct();
 
        }

Now on the next post, we will see how we could use that to get the related content items based on Profile Keys...

3 December 2014

Sitecore 7.x MVC and placeholder key with Capital Letter

Another post today about Sitecore MVC and Placeholder Key. We have this project using Sitecore MVC where the placeholders are defined with capital letters, Eventhough the Page Editor recommendation guide (page 14 to 15) does not say that using Capital Letters will create issues in MVC.... well.... it does. So even if not said directly on the guide: use lower case for your placeholder name... But just in case it is too late and you need to page editor, you can read the following...

In MVC, adding a placeholder in the renderings with capital letters will not create any problem when binding any rendering to this placeholder. However, Sitecore will not resolve your Placeholder settings correctly and you will not see the "Add Here" buttons neither the "allowed controls"

To summarise, if you do something like:

        @Html.Sitecore().Placeholder("SideColumn")

You will end up withthe SideColumn placeholder not even displayed, even if you add capital letters in the Placeholder Settings:



That would not really bother me as I would need to rename all placeholder into lower case and voila!!! But I wanted to find out if there would be an easier way and something that would allow me to have capital letter in the Name... When trying to see where this is falling, you have to check how the Chrome Data are rendered. If you look at the pipeline "GetChromeData", you can see that there is a processor for Placeholder:

      < getChromeData>
        < processor type="Sitecore.Pipelines.GetChromeData.Setup, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetChromeData.GetFieldChromeData, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetChromeData.GetWordFieldChromeData, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetChromeData.GetRenderingChromeData, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetChromeData.GetEditFrameChromeData, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetChromeData.GetPlaceholderChromeData, Sitecore.Kernel" />
      < /getChromeData>


When following the trail from the GetPlaceholderChromeData you will find that the code is calling another pipeline "GetPlaceHolderRenderings"
                        GetPlaceholderRenderingsArgs getPlaceholderRenderingsArgs = new GetPlaceholderRenderingsArgs(text, layout, args.Item.Database)
                        {
                            OmitNonEditableRenderings = true
                        };
                        CorePipeline.Run("getPlaceholderRenderings", getPlaceholderRenderingsArgs);

with the pipeline looking like:
      < getPlaceholderRenderings>
        < processor type="Sitecore.Pipelines.GetPlaceholderRenderings.GetAllowedRenderings, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetPlaceholderRenderings.GetPredefinedRenderings, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetPlaceholderRenderings.RemoveNonEditableRenderings, Sitecore.Kernel" />
        < processor type="Sitecore.Pipelines.GetPlaceholderRenderings.GetPlaceholderRenderingsDialogUrl, Sitecore.Kernel" />
      < /getPlaceholderRenderings>



Continuing the trail... go to the first processor: GetAllowedRenderings. In there you will find out how the PlaceholderItem is getting retrieved
    using (new DeviceSwitcher(args.DeviceId, args.ContentDatabase))
    {
     item = Client.Page.GetPlaceholderItem(args.PlaceholderKey, args.ContentDatabase, args.LayoutDefinition);
    }


If you look inside this method you will see that those placeholder Item are retrieved from the cache:
 PlaceholderCache placeholderCache = PlaceholderCacheManager.GetPlaceholderCache(database.Name);
 Item item = placeholderCache[placeholderKey];
 if (item != null)
 {
  return item;
 }
 int num = placeholderKey.LastIndexOf('/');
 if (num >= 0)
 {
  string key = StringUtil.Mid(placeholderKey, num + 1);
  item = placeholderCache[key];
 }
 return item;

You will note that the placeholderCache.IsKeyCaseSensitive is false, and this return null if you are passing the key as capital letters... So if we look at how the cache is build:
public virtual void Reload()
{
 lock (FieldRelatedItemCache.Lock)
 {
  this.itemIDs = new SafeDictionary();
  string query = string.Format("{0}//*[@@templateid = '{1}']", this.ItemRoot.Paths.FullPath, this.ItemTemplate);
  Item[] array = this.Database.SelectItems(query);
  if (array != null)
  {
   Item[] array2 = array;
   for (int i = 0; i < array2.Length; i++)
   {
    Item item = array2[i];
    string text = item[this.FieldKey];
    if (!string.IsNullOrEmpty(text))
    {
     string cacheKey = this.GetCacheKey(text);
     if (!this.itemIDs.ContainsKey(cacheKey))
     {
      this.Add(text, item);
     }
    }
   }
  }
 }
}

with the method GetCacheKey where you can see that if the IsKeyCaseSensitive is false the cache key will be lower case...
protected virtual string GetCacheKey(string key)
{
 if (this.IsKeyCaseSensitive || string.IsNullOrEmpty(key))
 {
  return key;
 }
 return key.ToLowerInvariant();
}


Also inside the Add method there is also a call to the GetCacheKey... So
 string cacheKey = this.GetCacheKey(key);
 lock (FieldRelatedItemCache.Lock)
 {
  this.itemIDs[cacheKey] = item.ID;
 }

That means the key is stored as capital Letter if you have define your field in the placeholder settings as capital letter. So what happens where we try to retrieve the item from the cache is that we are passing the Key as Capital letter but it is stored as lower case...
public virtual Item this[string key]
{
 get
 {
  Item result;
  lock (FieldRelatedItemCache.Lock)
  {
   ID itemId;
   if (!this.itemIDs.TryGetValue(key, out itemId))
   {
    result = null;
   }
   else
   {
    Item item = this.Database.GetItem(itemId, Context.Language, Version.Latest);
    if (item == null)
    {
     this.itemIDs.Remove(key);
    }
    result = item;
   }
  }
  return result;
 }
}


So I went around this issue by adding a custom pipeline action on the GetChromeData pipeline to convert the Placeholder Key to Lower Invariant if the Key for the cache manager is not sensitive...
namespace MyProject.Business.Sitecore.Pipelines
{
    public class GetPlaceholderKeyForChromeData : GetPlaceholderChromeData
    {
        public override void Process(GetChromeDataArgs args)
        {
            if ("placeholder".Equals(args.ChromeType, StringComparison.OrdinalIgnoreCase))
            {
                PlaceholderCache placeholderCache = PlaceholderCacheManager.GetPlaceholderCache(args.Item.Database.Name);
                if (!placeholderCache.IsKeyCaseSensitive)
                {
                    string keyString = args.CustomData["placeHolderKey"] as string;
                    args.CustomData["placeHolderKey"] = keyString.ToLowerInvariant();
                }
            }
        }
    }
}

With the following config patch
      
< getchromedata>
        < processor patch:before="processor[@type='Sitecore.Pipelines.GetChromeData.GetPlaceholderChromeData, Sitecore.Kernel']" type="MyProject.Business.Sitecore.Pipelines.GetPlaceholderKeyForChromeData, MyProject.Business">
      < /processor>
< /getchromedata>


Overwritting Placeholder settings on specific templates

On a previous post, I was talking about how to create a placeholder which will allow certain controls only. For that we had a 2 Columns Renderings (Main Column and Side Column) which had the following Markups and placeholders



    < div class="row">  
        < h1 class="col-sm-12">@Html.Sitecore().Placeholder("imagebanner")< /h1>  
    < /div>  
      
    < div class="row">  
         < h1 class="col-sm-12">@Html.Sitecore().Placeholder("contenttitle")< /h1>  
    < /div>  
    < div class="row">  
        < div class="col-sm-9 main-column">  
            < article class="col-sm-12">  
                @Html.Sitecore().Placeholder("contentcolumn")  
            < /article>  
        < /div>  
        < div class="col-sm-3 sidebar">  
            @Html.Sitecore().Placeholder("sidecolumn")  
        < /div>  
    < /div>  


As we saw, it was quite easy to define our Sitecore placeholder settings and allow a few controls:



Well this was really nice and handy if your templates using the 2 Columns Rendering should allow all 4 renderings: Rich Text, Image, Navigation, Related News. BUT... What if some of your templates should only allow 1 rendering? In the news content page for instance, you want to allow only the related news panel. Creating a new rendering with a different placeholder key??? no way.... Well, good thing sitecore thought about this. You can overwritte the placeholder through the presentation:

1- Define a new placeholder in Sitecore. This new placeholder will be exactly the same as per the first one Except:
  • Having a different Key: the key must be unique, so you have to use another key
  • Instead of allowing the 4 renderings, we will only allow 1: Related News Panel


2- Edit the template - or item you want to have different settings in the placeholder:

In this example we will edit a specific item but you can do it at the template level:
  • Select your item.
  • Go to the presentation
  • Select the placholder settings 
  • Click edit
   
  •  When editing, you can select "Select Existing Settings" on the Left hand side and then Select our new placeholder settings. Make sure the Placholder Key correspond to the key you were using previously


You can now save everything and go to the page editor. You will notice that on the placeholders you will not see "SideColumn" but "NewsItemSidePanel". Then if you add a new panel, you will notice only the related news panel is available:



28 November 2014

Configuration in SubFolder in the Include folder

I have been writing a previous post about the importance of Name for configuration files in the include folder. My usual habit was to prefix them with z. so all my custom files will be located at the last place (by alphabetical order). This means that those will be the last to be parsed which I can be sure to place any event or pipeline processor where I wanted. So my Include folder will looks like the following:


After reading a great post today from @jammykam, I wanted to share this:
You can create a folder and add all your custom files inside. From the Sitecore documentation (page 4), sitecore will first parse all the config file and then go recursively through subfolders:

When Sitecore reads the include files, it traverses the file system recursively. Sitecore first enumerates all the *.config files in the /App_Config/Include folder and then recursively enumerates all the sub-folders. You should take this order into account when you create sub-folders in the /App_Config/Include folder.
So creating a subfolder and moving the custom files inside will have the same effect than prefixing all my custom config:



27 November 2014

Sitecore 7.5 and Installing Packages through handler is broken


I was upgrading a 7.2 to 7.5 today and I noticed something unexpected that I wanted to share today.

As maybe a few of you, I am using TDS to generate my update packages for my deployments. This is awesome and We have a .ashx on our QA environment that automatically install those packages and publish items afterwards. Well, this was quite nice and working fine on Sitecore 7.2.

However, after upgrading the site to 7.5 I noticed that the solution was not compiling against the new Sitecore DLL.. And the reason was: SaveInstallationMessages() method was removed from the UpdateHelper on the Sitecore 7.5. So the following line was failing:

                    UpdateHelper.SaveInstallationMessages(entries, text);


If you compare the previous version of the Install() method from Sitecore.Update.InstallUpdatePackage

protected string Install()
{
 string result;
 using (new ShutdownGuard())
 {
  this.logEntries = new List();
  PackageInstallationInfo installationInfo = this.GetInstallationInfo();
  string text = null;
  List entries = null;
  try
  {
   this.WriteMessage(string.Format("{0} package: {1}", (installationInfo.Action == UpgradeAction.Preview) ? "Analyzing" : "Installing", installationInfo.Path), null, Level.INFO, false);
   entries = UpdateHelper.Install(installationInfo, this, out text);
  }
  catch (PostStepInstallerException ex)
  {
   entries = ex.Entries;
   text = ex.HistoryPath;
   throw ex;
  }
  finally
  {
   UpdateHelper.SaveInstallationMessages(entries, text);
  }
  result = text;
 }
 return result;
}

With the new version:

// Sitecore.Update.InstallUpdatePackage
protected string Install()
{
 string result;
 using (new ShutdownGuard())
 {
  this.logEntries = new List();
  PackageInstallationInfo installationInfo = this.GetInstallationInfo();
  string text = null;
  this.logMessages = new List();
  try
  {
   this.WriteMessage(string.Format("{0} package: {1}", (installationInfo.Action == UpgradeAction.Preview) ? "Analyzing" : "Installing", installationInfo.Path), null, Level.INFO, false);
   this.logMessages = UpdateHelper.Install(installationInfo, this, out text);
   base.InstallationHistoryRoot = text;
  }
  catch (PostStepInstallerException ex)
  {
   this.logMessages = ex.Entries;
   base.InstallationHistoryRoot = ex.HistoryPath;
   throw ex;
  }
  finally
  {
   this.SaveInstallationMessages();
  }
  result = text;
 }
 return result;
}

You can notice the SaveInstallationMessages is now defined on the control itself. This is a bit annoying as we cant re-use it in our handler anymore.
Since the UpdateHelper.Install is still outing the history path I could go around the issue by adding the SaveInstallationMessages() into our handler directly but that means duplication of methods. I would have prefered the old static method, but I could not find any other way for now...

        protected string Install(string package)
        {
            var log = LogManager.GetLogger("LogFileAppender");
            string result;
            using (new ShutdownGuard())
            {
                var installationInfo = new PackageInstallationInfo
                {
                    Action = UpgradeAction.Upgrade,
                    Mode = InstallMode.Install,
                    Path = package
                };
                string text = null;
                List entries = null;
                try
                {
                    entries = UpdateHelper.Install(installationInfo, log, out text);
                }
                catch (PostStepInstallerException ex)
                {
                    entries = ex.Entries;
                    text = ex.HistoryPath;
                    SC.Diagnostics.Log.Error("Automated Deployment error " + ex.StackTrace, "Automated deployment");
                    throw;
                }
                finally
                {
                    this.SaveInstallationMessages(entries, text);
                }

                result = text;
            }

            return result;
        }

        public string SaveInstallationMessages(System.Collections.Generic.List entries, string historyPath)
        {
            string text = System.IO.Path.Combine(historyPath, "messages.xml");
            FileUtil.EnsureFolder(text);
            using (System.IO.FileStream fileStream = System.IO.File.Create(text))
            {
                XmlEntrySerializer xmlEntrySerializer = new XmlEntrySerializer();
                xmlEntrySerializer.Serialize(entries, fileStream);
            }
            return text;
        }

14 November 2014

Sitecore 7.5 Image resizing changes


I am sure a few people already know about this but I just wanted to put it out there in case some f us are looking for it:

From Sitecore 7.5, the Image resizing is not working the way it was.

On previous version of Sitecore you would have been familiar with the resizing, passing the parameters in the URL:

http://mywebsite/~/media/imagesample.ashx?w=150
This will output the resized version of the image with a width of 150px. The usual parameters used for resizing are:

w = Width (in pixels)
h = Height (in pixels)
mw = MaxWidth (pixels)
mh = MaxHeight (pixels)
bc = Background Color
sc = Scale (floating point)
thn = Display as thumbnail


Well, as this was still the case in 7.2, I assumed it would be the same in 7.5... and obviously it id not... My bad as I did not read the release notes for this version. Thanks to Sitecore support who pointed me to the link... Here is the abstract that relates to the issue:

Media request protection
  • The new media request protection feature restricts media URLs that contain dynamic image-scaling parameters so that only server-generated requests are processed. This ensures that the server only spends resources and disk space on valid image scaling requests.
  • Sitecore Corp. wants to give credit to Cognifide (Adam Najmanowicz and Marek Musielak, www.cognifide.com) for the discovery of this vulnerability, for their cooperation and providing the initial ImageGuard solution.
  • When the feature is enabled, Sitecore automatically signs image URLs that are rendered by the <renderField> pipeline and adds a hash value to the query string. When processing an incoming media request, image resizing/scaling is skipped if any of the relevant query string parameters in the image URL have been altered or any extra resizing parameters have been appended to the URL. In these cases, Sitecore returns the original, unaltered image. Requests for the original image (without any resizing/scaling parameters) work as usual and are not restricted.
  • If you have code in your solution that manually appends image scaling parameters to image URLs without passing the parameters to the <sc:image> control, you must rewrite the code to append a hash value using one of the helper methods or rewrite it to use the <sc:image> control. In XSLT renderings, you can use sc:SignMediaUrl(url) or sc:GetSignedMediaUrl(…). In C# code, you can use HashingUtils.ProtectAssetUrl(url) which appends a hash value to the provided URL, or you can use GetAssetUrlHash(url) to only return the hash value for the provided URL.
  • You must ensure that any static image URLs (for example, in CSS or aspx files) that contain image scaling parameters are updated to include the corresponding hash value. To make it easy to update these type of static URLs, a new /sitecore/admin/MediaHash.aspx is available, which lets you enter a media URL and, with the click of a button, generate the corresponding hash value.
  • Image URLs where resizing parameters are manipulated or added using JavaScript will no longer work because you cannot calculate the hash values from JavaScript. If you need this type of functionality, you will have to find a different approach, such as implementing a service that can calculate the correct hash value.
  • This feature is configured in the /App_Config/Include/Sitecore.Media.RequestProtection.config file.

So if like me you used to pass the width o height in the URL, then you may have to revisit a few view rendering to ensure that you are now passing the Hash value.

So if you have a Model (Glass Map) like the following
using System;
using MyProject.Common.Constants;
using MyProject.Dal.Models.Base;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.Fields;

namespace MyProject.Models.ImageCarousel
{
    [SitecoreType(TemplateId = TemplateIds.DataElements.CarouselImage, AutoMap = true)]
    public class CarouselImage : SitecoreBase
    {
        [SitecoreField(FieldId = FieldIds.DataElements.CarouselImage.ImageBanner)]
        public virtual Image ImageBanner { get; set; }

        [SitecoreField(FieldId = FieldIds.DataElements.CarouselImage.DestinationUrl)]
        public virtual Link DestinationUrl { get; set; }

        [SitecoreField(FieldId = FieldIds.DataElements.CarouselImage.Description)]
        public virtual string Description { get; set; }
    }
}

Then you will be able to update your cshtml view to use:
        < img src="@Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(string.Format("{0}?w=150", Model.imagebanner.src))"  />

31 October 2014

Sitecore 7.2 MVC, Personalisation issue with WFFM


Not long ago, I faced an issue when using personalization. It is usually straight forward to setup but somehow this time it did not work. This was quite annoying and get me going for a bit of time. So I wanted to share it in case anybody out there would faced the same issue.

So for the project we were using:
  • Sitecore 7.2 MVC, 
  • GlassMapper
  • WFFM for all the forms on the website. 
As you can imagine most of the presentation elements were View renderings, except a few controller renderings. When setting up the personalisation rules, everything seems to be working perfectly at first until the testing team reported an issue:
When personalisation rules were set on an item, none of them was triggered. Looked like the rules engine was not working correctly. 







After investigating the issue it seems like it was only when personalisation was applied on Controller rendering. After trying the rule engine on a fresh Sitecore install, everything was working perfectly. So I started to take out our customisation elements one by one. After commenting all pipeline actions I could think of having anything to do with the issue and no luck, the issue was still there. Until "light bulb": let's check the Showconfig.aspx page:


And there you go, the pipeline action where the rule engine is triggered is the "CustomizeRendering" from the Sitecore.Mvc.Analytics.config


As you can see from the pipeline, One processor is intercepting the GetRenderer before it was hitting the rules engine. The pipeline action is from the Sitecore.Forms.MVC.config file. Looking at the code in this processor you will see the following:

if (args.Rendering.RenderingItem.ID != IDs.FormMvcInterpreterID)
{
    return base.GetRenderer(rendering, args);
}
Tuple< string, string> controllerAndAction = this.GetControllerAndAction(rendering, args);
if (controllerAndAction == null)
{
    return null;
} 


This will obviously intercept the Controller rendering and return the Conntroller and action prior evaluating the Rules...

If you are looking at the configuration file: Sitecore.Forms.MVC.config then you will realized that the intend is to place this processor before the GetControllerRenderer to ensure that the form controller will be executed before a normal ControllerRenderer:


When Sitecore is parsing the Configuration files the Sitecore.MVC.Analytics.config is parsed after the Sitecore.Forms.MVC.config... Which means that the GetFormControllerRenderer will get executed before the Rule engine...

Solution:
rename the config file to be "t_Sitecore.Forms.MVC.config". This will ensure that the processor will happen after the rules engine kicks in:

29 October 2014

Restricting renderings selection for placeholder

Today, I just wanted to talk about a simple thing but quite helpful when starting to develop with Page Editor: How can you specify which rendering can be inserted in a placeholder. This is really useful for Side panels for insance. You have created different types of panel (renderings) and now you want the to allow content editor to insert only those through the Page Editor such as the follownig:



Well, this is quite simple:

1- Placeholder in your code

Let's say you have a 2 columns rendering that will placed int your main layout. This 2 columns rendering will have 2 laceholders: one for the Main content and one for the Side Column. Something like:

< div class="row">
    < h1 class="col-sm-12">@Html.Sitecore().Placeholder("imagebanner")< /h1>
< /div>

< div class="row">
     < h1 class="col-sm-12">@Html.Sitecore().Placeholder("contenttitle")< /h1>
< /div>
< div class="row">
    < div class="col-sm-9 main-column">
        < article class="col-sm-12">
            @Html.Sitecore().Placeholder("contentcolumn")
        < /article>
    < /div>
    < div class="col-sm-3 sidebar">
        @Html.Sitecore().Placeholder("sidecolumn")
    < /div>
< /div>


2- Sitecore elements

On the sitecore side, the only thing you will need to define the Placeholder Settings under the path: /sitecore/layout/Placeholder Settings/xxx

You can noticed the Placeolder Key match the definition of the placeholder in our code:
@Html.Sitecore().Placeholder("sidecolumn")

You can also notice that you can select the Allowed Controls. Those will be the controls that are display to the Content Author when adding a new element in the placeholder. Once this is defined, Sitecore will automatically make the mapping. and now on the Page Editor you will see the "Add" buttons when you select the placeholder...In a future post I will describe how you can overwrite this placeholder settings for specific template...