Thank you to all those who have already entered the Cool Code Snippets Code-Off, the response has been great and there have been some truly excellent entries since the competition started.
For those of you who have not seen the details check out the original post here for details of how to win your very own ReSharper Personal Licenses.
As I mentioned before, I am going to post some of the best entries so far on the blog. So here goes for the first one (this doesn’t not mean this is a winner, but it does not rule it out either!) so thank you Denny Ferrassoli for some very cool MVC code!
Denny’s explanation:
“When working in ASP.NET MVC you sometimes pass a model to your view. In some cases your model is a few levels deep. For example:
Model.User.Address.ZipCode
Well I use models like this all the time and I constantly had to deal with properties being null when I was expecting a value. Since everything in a view gets rendered as string I decided to make a helper method that will allow me to pass anything in and return an empty string if the value was null (null dereferencing) instead of a NullReference Exception. Out came SafeGet. SafeGet is an extension method that applies to any object. It allows you to pass in the property, or value, you want to check as well as any constraints on the value.
Example:
<%= Html.TextBox( "BirthDate", Model.User.SafeGet( o => o.BirthDate, () => DateTime.MinValue ) )%>
In the example above if Model.User.BirthDate equals null OR DateTime.MinValue the function will return an empty string.”
and the code:
public static string SafeGet<T>(this T instance, Func<T, object> nonNullFunction, params Func<object>[] nullConstraint) where T : class
{
if(instance != null && nonNullFunction != null)
{
try
{
var o = nonNullFunction(instance);
if(o == null) return string.Empty;
if(nullConstraint != null)
{
// Check each constraint to make sure it doesn't match
foreach(var constraint in nullConstraint)
{
if(constraint().Equals(o)) return string.Empty;
}
}
return o.ToString();
}
catch(NullReferenceException)
{
return string.Empty;
}
// in all other cases, return the default
return string.Empty;
}
}
The competition will run for another month and remember the more entries there are the more licenses JetBrains have agreed to provide (1 for every hundred entries 1/100 chance of winning!)
If you would like to get an extended (6 week) trial for ReSharper and a 10% discount coupon please email me at web2asp@gmail.com and I will send over a trial license key with the coupon details.








0 comments:
Post a Comment