Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
Experience Sitecore! | Martin Miles on Sitecore

Experience Sitecore!

Martin Miles on Sitecore

Sitecore tips

1. Load Sitecore Desktop automatically and pre-select an item

I was wondering, if there is any opportunity to preload Sitecore Desktop automatically on Sitecore enter.

So annoyed of moving mouse across whole big monitor to the very top bottom, then select Content Editor from the menu, then wait till it loads an eventually as content tree loads - navigate to specific item! Even if it does not seem quite complex for a first glance - the number of times I do that per day makes me sadly thinking of wasted efforts for nothing...

Good news, everyone! There a convenient way of creating a shortcut that not only loads Content Editor, but also select any item you would like and loads its data right hand side. Here is the format of url:

http://your.host.name/sitecore/shell/Applications/Content%20Editor.aspx?fo={9CFF486B-9829-416E-8A39-408D3909B4FE}

where fo parameter stands for the item you want to pre-load.


2. If you use Google Chrome - install Chrome extensions for Sitecore


More details in my blog post by this link: Sitecore extensions for Google Chrome

Attach to IIS - debugging Sitecore with just one hotkey!

Debugging Sitecore in most cases requires you to open attach to a process menu in Visual Studio, then enable display for processes of all users, find appropriate IIS process and фееср to it. To much hassle, isn't it, especially taking into account that you may need to repeat that again and again hundreds / thousands times as a part of your work?

Ok, here's the solution to take your debugging pain off: Attach To IIS extension for Visual Studio. At the moment there are extensions for 2012 and 2013 version, as I haven't tried it in 2015 preview.





Download extensions for your Visual Studio version:

Attach_To_IIS_2012.vsix (58.6KB)

API - Useful IDisposable context switchers

Sitecore API provide several IDisposable context switchers, so I thought it's worth to review them in one place. Here they are:
  1. EditContext
  2. EventDisabler
  3. SecurityDisabler
  4. UserSwitcher
  5. LanguageSwitcher
  6. DatabaseSwitcher
  7. SiteContextSwitcher
1. EditContext
This is a very elegant way of editing an item in sitecore. What it does is automatically does item.Editing.BeginEdit(), item.Editing.EndEdit() as well as wraps that into try / catch block with item.Editing.CancelEdit() on Exception. You may map additional parameters into constructor to skip updating statistics (ie. last modified item's system field), suppress raising events (like item:save event) and also you may SecurityDisabler as a constructor parameter. 
// default usage
using (new EditContext(item))
{
    item.Fields["fieldname"] = "Some value to set";
}
// example of using with supressing events and avoiding statistics update
bool updateStatistics = false;  
bool silent = true;  
using (new EditContext(item, updateStatistics, silent))  
{  
    item.Fields["fieldname"] = "Some value to set";
}
// using EditContext and disable SecurityCheck together
using (new EditContext(iem, SecurityCheck.Disable))  
{  
    item.Fields["fieldname"] = "Some value to set";
}

2. EventDisabler
It gives exactly the same effect as if you were using Item.Editing.EndEdit(bool silent), passing true within silent. No events will be raised.
using (new EventDisabler())
{
    item.Editing.BeginEdit();
    // do edits
    item.Editing.EndEdit();
}

3. SecurityDisabler
Turns of permission check for operations performed within using block, regardless of if the user from the context can or cannot create / modify / move / rename /delete items. Beware as it may be insecure especially on CD instances. There is an alternative for this method - UserSwitcher (see below at 4). Here is an example of  SecurityDisabler usage:
using (new SecurityDisabler())
{
    subNode = homeItem.Add("SubNode", templateId);
    using (new EditContext(subNode))
    {
        subNode[fieldIdA] = "test";
        subNode[fieldIdB] = "testBBB";
    }
}

4. UserSwitcher
That is recommended practice (by Sitecore) to be used instead of SecurityDisabler. Everything you do is done in the context of a specific user. The user can be an Administrator and can do everything. Maybe you want to create a "service user" with only specific permissions or whatever, you can use this user to do what you want.
If you use the SecurityDisabler - Sitecore will not do any permission checks at all. In fact, the result will be the same as if you use the UserSwitcher() with an administrator, but you have no control over the context.
//User which is already created in Sitecore User Manager
 string testUser = @"sitecore\testuser"; 
if (Sitecore.Security.Accounts.User.Exists(testUser))
{
    //Getting Sitecore User Object with UserName
    Sitecore.Security.Accounts.User scUser = Sitecore.Security.Accounts.User.FromName(testUser, false); 
    //Switching Context User
     using (new Sitecore.Security.Accounts.UserSwitcher(scUser))
    {
        //Using EditContext to edit an Item
        using (new Sitecore.Data.Items.EditContext(home))
        {
            home["Text"] = "Modified Text from Code";
        }
    }
}

5. LanguageSwitcher
When working on multi-lingual website, you may have a need in retrieving the values in the language different than one you're having currently in the Context. Please consider the following code to achieve that:
var item = Sitecore.Context.Item;
using (new Sitecore.Globalization.LanguageSwitcher("fr"))
{
    item = myItem.Database.GetItem(item.ID);
}


6. DatabaseSwitcher
Sometimes you may need to do some database operations from the database
another than you currently have in Context, for instance you may have a specific task to look-up master database, or read some setting from core. Of course, such type of activities is fairly an exclusion from normal practice, so think well ahead. In any case, the following using switcher will be handy for that type of situations:
var master = Sitecore.Configuration.Factory.GetDatabase("master"))
using (new DatabaseSwitcher(master))
{
// now within this scope Sitecore.Context.Database is returning master database
}

7. SiteContextSwitcher
That one is use to substitute current site context. Usage is pretty easy:
var item = Sitecore.Context.Item;
using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("site_name_as_in_config")))
{
    // all the code here would run in the context of "site_name_as_in_config" site
}

[Updatable] API snippets

This blog post is [Updatable] - I use it to store snippets at the same place just for a case.

I know for most of experienced Sitecore geeks my post may seem sort of obvious, however even you may find something interesting below or suggest me to add anything you consider important to append.

While working with Sitecore for years, I have met so many attempts to re-invent the wheel in sense of ugly implementation of functions that are part of Sitecore API, so I decided to write this post, placing most frequent but sometimes less known usages here within one post. So, here we go:

  1. Standard API - create, read, edit, save, rename,
  2. Media library
  3. Publishing
  4. Presentation / placeholders
  5. Indexing
  6. DMS / xDB
  7. Other


1. Standard API - create, read, edit, save, rename, move etc.


1.1. To start with the basics - how to get the item. 

Item item = Sitecore.Context.Database.GetItem("/sitecore/content/home/products/tv");

if (item != null)             
{                 
    // allways check for null before going forward
}
Avoid using explicit database by name like below, get database out of Context, rather than by name explicitly.

// incorrect, except when you need explicitly to get CM database.
var database = Database().GetDatabase("master")); 


1.2. Accessing the fields - multiple ways:

// Indexer on Item supports using a field's name, index, or ID
string value1 = someItem[fieldName];
// Get the value from the field
string value2 = someField.Value;
// Method 3: 
bool allowStandardValue = false;
string value3 = someField.GetValue(allowStandardValue);
bool allowStandardValue = false;
bool allowDefaultValue = false;
string value5 = someField.GetValue(allowStandardValue, allowDefaultValue);

The order usually follows: if actual value exists, it is returned, otherwise if the item is clone - it returns clone's value, if not - returns standard value, and in case standard value not set - the default value (empty string, otherwise - null).


1.3. Read all fields.

For the sake of performance, Sitecore will not give you all fields in the FieldCollection in the following code, only fields with explicit values on item level, including empty string.

Sitecore.Context.Item.Fields.ReadAll();


1.4. Checking if a Sitecore field has a value

Sitecore.Context.Item.Fields["fieldName"].HasValue
or
Sitecore.Context.Item.Fields["fieldName"].Value != ""


1.5. When rendering fields from within the code, always use FieldRenderer class, in order to ensure that resulting output HTML  is Page Editor friendly.

FieldRenderer.Render(item, "field name")


1.6. Editing the item - straightforward way.

item.Editing.BeginEdit();
item.Fields["Title"].Value = "My New Title";
item.Editing.EndEdit();


1.7. More elegant way of editing the item, using IDisposable EditContext

using (new EditContext(item)) 
{ 
    item["Title"] = "My New Title"; 
}

More about EditContext and its options please read in API - IDisposable Usings article.


1.8. Miltilist field. I have evidenced several attempts of manipulation multi-list items by physically stored pipe-separated GUIDs, all clumsy and not best practice code with bad smell. Don't do that - use Sitecore API instead:

Sitecore.Data.Fields.MultilistField multilistField = Sitecore.Context.Item.Fields["myMultilistField"];
Sitecore.Data.Items.Item[] items = multilistField.GetItems();


1.10. Create item programmatically

Minimum code:
Item newItem = parent.Add(itemName, template); 
newItem.Editing.BeginEdit(); 
newItem.Fields["fieldName"].Value = "fieldValue"; 
newItem.Editing.EndEdit();
Full ready-to-use-code:
       public static void CreateItem()
        {
            // The SecurityDisabler overrides the current security model, allowing you
            // to access the item without any security. It's like the user being an administrator
            using ( new Sitecore.SecurityModel. SecurityDisabler())
            {
                // Get the master database
                Sitecore.Data. Database master = Sitecore.Data.Database.GetDatabase("master" );
                // Get the template to base the new item on
                TemplateItem template = master.GetItem("/sitecore/templates/Ecosystem/Concrete/MenuPage" );

                // Get the place in the site tree where the new item must be inserted
                Item parentItem = master.GetItem( "/sitecore/content/Ecosystem");

                // Add the item to the site tree
                Item newItem = parentItem.Add( "My New Page", template);

                // Set the new item in editing mode
                // Fields can only be updated when in editing mode
                // (It's like the begin tarnsaction on a database)
                newItem.Editing.BeginEdit();
                try
                {
                    // Assign values to the fields of the new item
                    newItem.Fields[ "Title"].Value = "My New Page - Title" ;
                    //newItem.Fields["Text"].Value = "Value2";

                    // End editing will write the new values back to the Sitecore
                    // database (It's like commit transaction of a database)
                    newItem.Editing.EndEdit();
                }
                catch (System. Exception ex)
                {
                    // The update failed, write a message to the log
                    //Sitecore.Diagnostics.Log.Error("Could not update item " + newItem.Paths.FullPath + ": " + ex.Message, this);

                    // Cancel the edit (not really needed, as Sitecore automatically aborts
                    // the transaction on exceptions, but it wont hurt your code)
                    newItem.Editing.CancelEdit();
                }
            }           
        }


1.11. Item propose name - will suggest valid item name according with current settings

ItemUtil.ProposeValidItemName("some-name");


1.12. Item has plenty of helpful methods, like CopyTo() and MoveTo() and others you may see in the context menu.

item.MoveTo (parentItem);



2. Media Library


2.1. Determining item type.

// usual content data item
Sitecore.Context.Item.Paths.IsContentItem;
// media item
Sitecore.Context.Item.Paths.IsMediaItem

2.2. The example below is anti-pattern. At the first glance it seems to be an elegant way of inline resolving media path right in MVC Razor view. So what is wrong with that?

 <img src="@MediaManager.GetMediaUrl(
Sitecore.Context.Database.GetItem(Html.Sitecore().CurrentRendering.DataSource))" />

First and most important - if datasource is not set (or set wrongly) then GetItem will return null being passed into GetMedaiUrl as the parameter, so it will fire NullReferenceException and the whole page won't load. You must validate parameters and do null-checks, so the best way out is to extract this logic into helper static (or extensions) class.

But the best option for sure is to pass this resolved URL into a view as a public property of strongly-typed viewmodel object.



3. Publishing


3.1. Publish item programmatically

private void PublishItem(Sitecore.Data.Items.Item item)
{
  // The publishOptions determine the source and target database,
  // the publish mode and language, and the publish date
  Sitecore.Publishing.PublishOptions publishOptions =
    new Sitecore.Publishing.PublishOptions(item.Database,
                                           Database.GetDatabase("web"),
                                           Sitecore.Publishing.PublishMode.SingleItem,
                                           item.Language,
                                           System.DateTime.Now);  // Create a publisher with the publishoptions
  Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions);

  // Choose where to publish from
  publisher.Options.RootItem = item;

  // Publish children as well?
  publisher.Options.Deep = true;

  // Do the publish!
  publisher.Publish();
}



4. Presentation / placeholders


4.1. Get count of renderings in a particular placeholder:

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

4.2. Get position index of a rendering within a particular placeholder:

public static string GetComponentPositionOnPlaceHolder(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";
}



5. Indexing


5.1. Simple Linq query

//Create a Search Context to the "index name" Index (could be SOLR/Lucene/something else)
using (var context = new ContentSearchManager.GetIndex("indexname").CreateSearchContext()) 
{
    //LINQ Query
    var query = context.GetQueryable.Where(i => i.Name.StartsWith("Something"));
}


5.2. Add single item to index

public static void AddItemToIndex(Item item, string indexName)
{
    var tempItem = (SitecoreIndexableItem)item;
    ContentSearchManager.GetIndex(indexName).Refresh(tempItem);
}
 
public static void UpdateItemInIndex(Item item, string indexName)
{
    var tempItem = (SitecoreIndexableItem)item;
    ContentSearchManager.GetIndex(indexName).Update(tempItem.UniqueId);
}
 
public static void DeleteItemInIndex(Item item, string indexName)
{
    var tempItem = (SitecoreIndexableItem)item;
    ContentSearchManager.GetIndex(indexName).Delete(tempItem.UniqueId);
 }


5.3. Queryable extensions

public static class QueryableExtensions
{
  public static IQueryable IsContentItem(this IQueryable query) where T : SearchResultItem
  {
    return query.IsDescendantOf(ItemIDs.ContentRoot);
  }
 
  public static IQueryable IsContextLanguage(this IQueryable query) where T : SearchResultItem
  {
    return query.Where(searchResultItem => searchResultItem.Language.Equals(Context.Language.Name));
  }
 
  public static IQueryable IsLatestVersion(this IQueryable query) where T : SearchResultItem
  {
    return query.Where(searchResultItem => searchResultItem["_latestversion"].Equals("1"));
  }
 
  public static IQueryable HasBaseTemplate(this IQueryable query, ID templateId) where T : SearchResultItem
  {
    var id = templateId.ToShortID().ToString().ToLowerInvariant();
    return query.Where(searchResultItem => searchResultItem["_basetemplates"].Contains(id));
  }
 
  public static IQueryable IsDescendantOf(this IQueryable query, ID parentId) where T : SearchResultItem
  {
    return query.Where(searchResultItem => searchResultItem.Paths.Any(ancestorId => ancestorId == parentId));
  }
}



6. DMS / xDB


6.1. DMS - hit the goal programmatically.

//Check that analytics are on...
if (Sitecore.Analytics.Tracker.IsActive &amp;&amp; Sitecore.Analytics.Tracker.CurrentPage != null)
{
  //Get the item goal.
  Item goalItem = Sitecore.Context.Database.GetItem(&amp;quot;{xxxxx-xxx-xxx-xxxxx}&amp;quot;);
  //Page event wrapper
  PageEventItem goal = new PageEventItem(goalItem);
  //Create the record that needs to  store the goal
   VisitorDataSet.PageEventsRow pageEventsRw = Sitecore.Analytics.Tracker.CurrentPage.Register(goal);
  //this is not mandatory
  pageEventsRw.Data = "custom text";
  Sitecore.Analytics.Tracker.Submit();
}


7. Other

7.1. Jumping between the sites of current Sitecore instance

Sitecore.Context.SetActiveSite(currentSiteName);