DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

ASP.NET MVC and SafeGet (my version of null dereferencing)

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

(Yes this violates LoD but I don't like LoD anyways...)

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. It's probably easier to see what I mean with code... check out the example:

 

SafeGet signature:


public static string SafeGet<T>( this T instance, Func<T, object> nonNullFunction, params Func<object>[] nullConstraint ) where T : class

 

Here is how it works:

In my view I wrap SafeGet around the properties I am not sure will have a value and include any constraints:


<%= Html.TextBox( "BirthDate", Model.User.SafeGet( o => o.BirthDate, () => DateTime.MinValue ) )%>

 

Yes, it uses Lambda expressions :)

 

The first param is "nonNullFunction" - this is where you pass in the value you want to check.

 

The second param is "nullConstraint" - Since I am working with a "DateTime" object (not "Nullable DateTime") I know DateTime must have a value but I also want it to consider the value as null IF the value of "o.DateTime" is "DateTime.MinValue" (basically saying: "if (o.DateTime == DateTime.MinValue) return null;"). You can have many nullConstraints if you need to check multiple values.

 

SafeGet then returns the value or "string.Empty" if the expression is null or it matches any constraints.

You could probably include another param as a default value to pass if it is null rather than always passing "string.Empty"

If you're using custom ViewModels you could certainly apply this at that level instead of in the view directly. I'm not sure if this breaks Seperation of Concerns by using it in a View.

 

Here's the SafeGet method:


        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;
        }
    }

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by Denny on Thursday, July 16, 2009 7:00 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Partial Azure Pricing Model Announced

Some information regarding the Azure pricing model has been released. Some good news is that the pricing is competitive to to Amazon's AWS service.

Windows Azure
Compute @  $0.12 / hour
Storage @ $0.15 / GB / month stored
Storage Transactions @ $0.01 / 10K

SQL Azure
Web Edition – Up to 1 GB relational database @ $9.99
Business Edition – Up to 10 GB relational database @ $99.99

.NET Services
Messages @ $0.15/100K message operations , including Service Bus messages and Access Control tokens

Bandwidth
All Services @ $0.10 in / $0.15 out per GB


Uptime availability is 99.95% and storage is 99.9%.

They will also offer more predictable pricing plans at PDC 09.

"While consumption based pricing provides great flexibility we have also heard it introduces a level of unpredictability and some customers prefer other options.  At launch we will share details of subscription offers that provide payment predictability and price discounts that reflect levels of usage commitment."

I'm hoping for some sort of low-cost developer pricing!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, July 15, 2009 6:39 AM
Permalink | Comments (0) | Post RSSRSS comment feed

PLINQO: Professional LINQ Objects

If you haven't heard of PLINQO yet then you're missing out. The CodeSmith guys have enhanced the hell out of LINQ to SQL, to name a few features:

  • Entity Clone
  • Entity Detach ** My favorite!
  • Many to Many relationships
  • Auditing
  • Rules
  • Performance Enhancements

In their own words:

  • "In the time that LINQ to SQL has been available, we have been identifying ways to make LINQ to SQL better. We have compiled all of those cool tips and tricks including new features into a set of CodeSmith templates. PLINQO opens the LINQ TO SQL black box giving you the ability to control your source code while adding many new features and enhancements. It's still LINQ to SQL, but better!"

I've been using PLINQO for over a month now and I really like it. It does require a CodeSmith license... BUT you can get a license free!!! Check out the details here.

There's also a great review of PLINQO by Kevin Lawry here. Enjoy!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,
Posted by Denny on Sunday, July 05, 2009 3:46 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Coming Soon

I've been working on a new design for my blog... The themes that are packaged with BlogEngine are great but I'm wanting something a bit more personal. I'll be working on that this weekend. I'm also moving servers this week so there will be some down-time but this will also allow me to update BlogEngine to the latest and greatest version.
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, July 23, 2008 4:08 AM
Permalink | Comments (0) | Post RSSRSS comment feed

ASP.NET AJAX History and ASP.NET Hacks

I was running through my list of blogs and I ran into "Create a Facebook-like Ajax Image Gallery!" by John Katsiotis. In John's post he shows how to create an image gallery - it's quick and easy - but more importantly he utilizes the new ASP.NET AJAX History feature. That means you can use the back and forward buttons on your browser to go back and forward through the AJAX calls.

And on another note, LessThanDot has published a collection of ASP.NET Hacks in 18 categories (currently) including: Caching, Email, Encryption, Validation, Files and others.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,
Posted by Denny on Monday, July 07, 2008 3:52 AM
Permalink | Comments (0) | Post RSSRSS comment feed

My "Web 3.0" Elevator Pitch

I ran across an interesting post on LinkedIn today. A user posted a question: "What will web 3.0 be?"

There were a variety of answers, many pointing towards the semantic web but a few suggesting the mobile web, user interaction, and a marketing gimmick amongst others.

So I took a 5 minute timeout and jotted down my "elevator pitch" of what I think will make up the next "version."

The semantic web or "artificial intelligence" that computers will use to turn data into context-aware relationships of information. Including the organization and portability of that information towards user-centric mediums.

Check out Wikipedia's entry: http://en.wikipedia.org/wiki/Web_3

What are your eleavator pitches?

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Monday, May 26, 2008 5:06 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Debug on LocalHost with Fiddler

If you do a lot of debugging with Fiddler you probably know it doesn't capture any data when you run your website on your loopback address (http://127.0.0.1 or http://localhost). Well there's a simple way to get around this as outlined in this blog post. Enjoy!
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: ,
Posted by Denny on Thursday, May 22, 2008 8:03 AM
Permalink | Comments (0) | Post RSSRSS comment feed

On Again, Off Again, and Finally Google

My site has been up and down, on and off, stiff and flimsy throughout the week. I am not the sys admin of the year so running on my own virtual server has been a workout. My pains really started with Plesk, a control panel for hosting multiple websites. It's a great tool when it works and it can configure the few things I'm not familiar with with a few clicks. However when it doesn't work then I have to manually go in and tweak things myself. Like my DNS and Mail for example. For whatever reason my DNS settings for dennydotnet.com would not be created, maybe it dislikes my name :) Anyways...

Today I decided to finally fix my Mail problems after a friend enlightened me with knowledge of Google Apps. "Google Apps.. and Mail, huh?" Yep! You can create your email account on Google Apps, add a few DNS records to your domain and voila! Google now handles your e-mail, faster and more reliably. You also have access to your email via GMail and you can of course enable POP/IMAP to access it via your favorite mail program. Best of all you get to use your domain name "@dennydotnet.com" not the "@gmail.com" name and you have total control of email as well as "lists."

Allowing the Goog to handle my mail is great because I can now disable and uninstall my mail server software. This, in turn, gives me back more memory and hard disk space as well as less headaches when my email isn't going through :)

Thanks Goog!

[Update 05/08/08]: Everything went well with Google Apps and I went around my site and changed my email settings to reflect the new Google Apps email. At first I couldn't figure out which host or port to send to but after some research I was able to make the necessary changes. Below is an example of the SmtpClient code needed to send mail via Gmail.


SmtpClient smtp = new SmtpClient();
smtp.Credentials = new NetworkCredential( "addr@mydomain.com", "****************" );
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by Denny on Tuesday, May 06, 2008 6:02 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Entity Framework (EF) and Lazy Loading

I came across a great article today that explains a little about Entity Framework's (EF) default lazy load settings. At first you may be confused as to why they decided to default to lazy loading relationship objects but if you take a good look it makes sense.

The team behind EF didn't want this *automatic* behavior happening. The reason behind this decision is simple: When architecting a larger project, it is highly important for developers to clearly understand when they are accessing certain resources, such as the database.

You can run into a boat-load of performance/scalability issues if you are not aware of what relationships are being loaded using LINQ to SQL. EF tries to eliminate this issue by defaulting to lazy loading. Read the article for a great example and explanation.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Monday, April 28, 2008 9:07 AM
Permalink | Comments (0) | Post RSSRSS comment feed

SVN - Quit thinking about it and jump in

So I had a mishap happen with my project the other day and I decided, finally, to get a version tracking system. I had heard a lot about SVN and used TortoiseSVN occassionaly to get the latest versions of subsonic, jQueryMVC, ffmpeg and a few other projects. So I looked around for something that could integrate well with Visual Studio 2008. I ran across VisualSVN, downloaded the trial, and I'm now hooked! It's a really good price too (I have yet to purchase it though). Anyways, TortoiseSVN allows you to easily create your repository and you get a cool SVNAdmin tool which you can use to backup your repository (in combination with task cheduler).

So if you were like me and you keep hearing about SVN this and SVN that... jump in, the water is warm :) You're wasting productivity by not checking it out!

[04/30/08] There's another great article I bumped into today regarding a move to TortoiseSVN and VisualSVN, check it out here.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by Denny on Friday, April 25, 2008 12:08 PM
Permalink | Comments (4) | Post RSSRSS comment feed