Thursday, July 7, 2011

Request.QueryString Extension Method

Below are two extension methods that I have created for Request.QueryString.. as I am passing many parameters and playing with querystring a lot and every where i had to put IF condition for null and other things..

In order save myself from checking and validating again and again i have designed these two extension Method using some help from internet to save time and reduce number of lines of code.. kindly check them and you are welcome to criticize in constructive way.

I have some more functions in my mind to overload for Request.QueryString and will add later As following two functions have fulfilled my need

How to use..
byte? valueByte  
Guid? valueGuid

//check if "Server" key exits if yes then return value else return default value of null that we have passed

valueByte = Request.QueryString.GetValue<byte?>(Constants.FilterServer, null);
valueGuid = Request.QueryString.GetValue<Guid?>(Constants.FilterGuid, null);

//checks if "Server" Key exists then out value to provided variable and return true to if condition, else return false and assign default value to provided out variable
if(Request.TryParse<byte?>(Constants.FilterServer, null, out valueByte)){}

if(Request.TryParse<Guid?>(Constants.FilterGuid, null, out valueGuid)){}



public static T GetValue<T>(this NameValueCollection collection, string key, T defaultValue)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
var value = collection[key];
if (value == null) { return defaultValue; }
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string))) {
throw new ArgumentException(String.Format("Cannot convert ' {0} ' to {1} ", value, typeof(string))); }
return (T)converter.ConvertFrom(value); }


public static bool TryParse<T>(this NameValueCollection collection, string key, T defaultValue, out T returnValue)
{
returnValue = default(T);
try
{ if (collection == null) {
throw new ArgumentNullException("collection"); }
var value = collection[key];
if (value == null)
{ return false;}
var converter = TypeDescriptor.GetConverter(typeof(T)); if (!converter.CanConvertFrom(typeof(string)))
{ throw new ArgumentException(String.Format("Cannot convert ' {0}' to {1} ", value, typeof(string))); }
returnValue = (T)converter.ConvertFrom(value);
return true; }
catch (ArgumentNullException ex) { return false;}
catch (ArgumentException ex) { return false;}
catch (NotSupportedException ex) {return false;} }

No comments:

Post a Comment