Sitecore Queries and injections

Pretty funny, I just came across a lack of defensive programming by myself… Over and over I use the following codesnaps:

string query = string.Format(“./*/item[@templatename='{0}’]”, CompetenceType);
Item[] result = InnerItem.Axes.SelectItems(query);

Do you see the problem? Well, CompetenceType might contain a single-quote… If it does, the parser of the query will throw an error. Blerg! So the yellowpage will occur on your screen and you’ve to find out in your logfile (ofcourse you’ve already deployed the stuff to a production server) what the issue might be…

Sitecore’s ItemUtil has a nice solution for this issue. Just add the following code sample before the last codesnap:

if(ItemUtil.IsItemNameValid(CompetenceType))
{
    CompetenceType = ItemUtil.ProposeValidItemName(CompetenceType);
}

Make sure you watch your own code very carefully, these unexpected behaviors might not take a site down for a week, but it is simply your own laziness!

One thought on “Sitecore Queries and injections”

  1. What are the chances of CompetenceType containing a single quote? If this piece of code is contained within a method, where the caller passes the value for CompetenceType, then I would want the Yellow Screen of Death to appear, conveying to the programmer who used this method that he/she screwed up somewhere.

    BTW, if you don’t like the Yellow Screen of Death to appear, handle your 500 errors gracefully (i.e. add Web.config mapings for your sitecore site to go to some other Page/Item conveying that something went wrong).

    Having this piece of error checking code might be overkill and add additional complexity (O notation complexity…we don’t know how efficient is ItemUtil.IsItemNameValid(…)).

Comments are closed.