Thursday, March 6, 2008

Are parents responsible the delinquency of teenaged SPLists?

Ever since I hooked up with Microsoft and began fathering little bits of softwares, I always thought that I would raise good code. However, like many have endured, one of my softwares began acting defiant and outrageous. We debugged the software repeatedly and how stubborn it was! Certainly didn't get any of that from MY influence! ahem! Lets get into the psyche of this little rebel a bit...

public static SPList GetListByName(SPWeb rootWeb, string listName)
{
    foreach (SPList list in rootWeb.Lists)
    {
        if (list.Title.Equals(listName,
            StringComparison.InvariantCultureIgnoreCase))
        {
            return list;
        }
    }
    
    foreach (SPWeb web in rootWeb.Webs)
    {
        SPList resultList = GetListByName(web, listName);
        if (resultList != null)
        {
            return resultList;
        }
    }
    
    return null;
}

Take a look at the base case where the list is found and returned. Pretty standard stuff no? What is not (by even a far stretch of even the most eclectic programmer's imagination) obvious here is that the list being returned has a... how do I say this.... special Views property (of type SPViewCollection). The crime here is that these views are wrong. No, The collection isn't empty, it doesn't throw exceptions when you try to access it, it isn't null, it doesn't contain any number of views other than the amount of views it really does have, and the views aren't uninitialized or anything. They are wrong because they only have two columns, no matter what.

The victim of such a crime is one that wants the list for its views and is given this list as joke. How did I deal with such reckless behavior? Well, it didn't go down without a hairy fight thats for sure, but in the end, I taught it to return regular SPLists that were not special.

SPSite s = SPContext.Current.Site;
SPList l = s.AllWebs[rootWeb.Name].Lists[listName];
return l;