Should You Test SharePoint GUID’s?

I am really not sure. I have had instances where using things like the ContainingDocumentLibrary GUID return was all 0’s, which isn’t very valid now is it. Didn’t make a lot of sense to me, but apparently a q quick poll around the team makes me think that it isn’t entirely uncommon. So usually now, just for my own sanity, I test whether it is a valid GUID. I am wondering if other people do it. Or am I taking crazy pills? Like for example say you have any event handler where you are calling that on your item, sorta like this:

[csharp]

// Get the associated folder object for the item that is triggering the event
SPFolder curFolder = GetCurFolder(web, curItem);

// Get the GUID of the document library that contains the folders being created
Guid guid = curFolder.ContainingDocumentLibrary;

///

/// Get the current folder object from the SPListItem
///

/// The SPWeb object /// The SPListItem object /// SPFolder object
private static SPFolder GetCurFolder(SPWeb web, SPListItem curItem)
{
if (web == null)
throw new ArgumentNullException(“web”);
if (curItem == null)
throw new ArgumentNullException(“curItem”);

return web.GetFolder(curItem.Folder.Url);
}

[/csharp]

That return would obviously be a GUID. Do you test it for validity?

[csharp]

string guidString = guid.ToString();

// Run a test to see before the SPList object is used whether it is a valid GUID
if (!IsValidGuid(guidString))
{
Handler.WriteLine(TraceLevel.Error, string.Format(“An Invalid GUID Was Enountered When Hydrating The SPList Object”));
}

// Create an SPList object, and call the current list from the SPWeb by passing in the GUID harvested previously
SPList curList = web.Lists[guid];

///

/// Check whether a GUID presented is valid
///

/// ///
public static bool IsValidGuid(string guid)
{
if (guid == null)
throw new ArgumentNullException(“guid”);

try
{
new Guid(guid);
return true;
}
catch
{
return false;
}
}

[/csharp]

Seems redundant, since the GUID should always be valid, but it makes me feel all cozy. :)

Share

One Comment

  1. BigJimInDC says:

    Why not just check for an empty guid (the one with all zero’s) instead of bothering with going from Guid to String and back again?

    if (guidValue == Guid.Empty)
    {
    //— do something else when you don’t get a ‘real’ guid value
    }

Trackbacks/Pingbacks

  1. Links (8/14/2007) « Steve Pietrek’s SharePoint Stuff - [...] Should You Test SharePoint GUID's? [...]

Leave a Reply

Your email address will not be published. Required fields are marked *