Wednesday 28 October 2009

Get a list of all Sitecore Items tagged with specific multilist items

If you wish to return all items in the content tree that have been tagged with a specific multilist item, you might be tempted to use Sitecore.Context.Database.SelectSingleItem(), passing it an XPath query. The problem with this is that performance degrades as the content tree grows. A far more efficient way is to use the GetReferrers method of the LinkDatabase class as shown below:

Database db = Sitecore.Context.ContentDatabase;

LinkDatabase linkDb = Globals.LinkDatabase;

// lookupItem is the multilist item
ItemLink[] links = linkDb.GetReferrers( lookupItem );

foreach( ItemLink link in links )
{
Item linkedItem = db.Items[link.SourceItemID];
// Process item...
}

Monday 12 October 2009

Example Useful C# Extension Functions

Here are a few extension functions that I find useful:


public static bool IsNullOrEmpty(
this string expression )
{
bool result = string.IsNullOrEmpty(
expression );
return result;
}

public static string ToFormat(
this string expression, params object[] args )
{
string result = String.Format(
expression, args );
return result;
}

public static bool IsValidEmailAddress(
this string expression )
{
bool result = BaseRegexHelper.IsValid(
expression, emailRegex );
return result;
}

public static bool IsValidGuid(
this string expression )
{
bool result = BaseRegexHelper.IsValid(
expression, guidRegex );
return result;
}

The latter two functions call this method:

public static bool IsValid(
string input, string pattern )
{
bool isValid = false;

if( input != null )
{
string trimmedExpression =
input.Trim();

if( trimmedExpression.Length > 0 )
{
Regex regexGuid = new Regex(
pattern, RegexOptions.IgnoreCase );
isValid = regexGuid.IsMatch(
trimmedExpression );
}
}

return isValid;
}