Sunday, February 8, 2009

Guid.TryParse()

Are you ever passed GUID’s via a query string? How can you trust that it is a real GUID? I want to be able to do this

Guid result;
if (GuidHelper.TryParse(Request["ID"], out result))
return result;
else
return null
;


I have to parse Guids occasionally so I wrote this little helper to add to where the .Net Framework is lacking.



public static class GuidHelper
{
private static Regex guidFormat = new Regex(
"^[A-Fa-f0-9]{32}$|" +
"^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
"^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, " +
"{0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$",
RegexOptions.Compiled|RegexOptions.CultureInvariant|RegexOptions.Singleline);


/// <summary>
///
Converts the string representation of a Guid to its Guid
/// equivalent. A return value indicates whether the operation
/// succeeded.
/// </summary>
/// <param name="value">
A string containing a Guid to convert.</param>
/// <param name="result">
///
When this method returns, contains the Guid value equivalent to
/// the Guid contained in <paramref name="value"/>, if the conversion
/// succeeded, or <see cref="Guid.Empty"/> if the conversion failed.
/// The conversion fails if the <paramref name="value"/> parameter is a
/// <see langword="null" /> reference (<see langword="Nothing" /> in
/// Visual Basic), or is not of the correct format.
/// </param>
/// <value>
/// <see langword="true" />
if <paramref name="value"/> was converted
/// successfully; otherwise, <see langword="false" />.
/// </value>
/// <exception cref="ArgumentNullException">
///
Thrown if <pararef name="value"/> is <see langword="null"/>.
/// </exception>
public static bool TryParse(string value, out Guid result)
{
if (!string.IsNullOrEmpty(value))
{
Match match = guidFormat.Match(value);
if (match.Success)
{
result = new Guid(value);
return true;
}
}
result = Guid.Empty;
return false;
}
}

No comments: