Using SharePoint object model can by tricky sometimes. An example of this can be getting an SPList instance from the SPListCollection, when the name being passed to the indexer could be incorrect. SharePoint throws an argument exception when the list of the specified name is not present in the SPListCollection. This can be really irritating as you now have to silently error out the argument exception generated before proceeding further.
I was really bugged by this problem and tried to find a way out. A little introspection with the magical tool known as reflector on the SPListCollection class revealed that there actually is an internal function known as GetListByName which does not throw an exception even when a list is not present. So all I had to do was to call this method reflectively and let it work its magic. I wrote a utility function for the same which solves the most common list collection scenario (i.e.) getting a SPList instance from the list collection of a SPWeb. Following is the utility method. It takes the SPWeb instance and the list name as parameters and returns an SPList object / null.
All comments are welcome on this function and its implementation.
P.S. If you pass the boolean value as true to the Invoke method, the method will return to its default behaviour and start throwing up exceptions.
public static SPList GetListInstanceWithOutTheException(SPWeb web, string listName)
{
try
{
MethodInfo info = typeof(SPListCollection).GetMethod("GetListByName", BindingFlags.InvokeMethod BindingFlags.NonPublic BindingFlags.Instance, null, new Type[] { typeof(System.String), typeof(System.Boolean) }, null);
if (info != null)
{
SPList list = info.Invoke(web.Lists, new object[] { listName , false }) as SPList;
return list;
}
return null;
}
catch (Exception)
{
throw;
}
}
Wednesday, June 24, 2009
Getting SPList instances without ArgumentExceptions
Labels:
ArgumentException,
GetListByName,
Reflection,
SPList,
SPListCollection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment