Most of the last two years of my career I have been developing applications behind the firewall and let’s face it most ASP.NET applications sit behind the firewall. This is unfortunate because ASP.NET offers the most scalable and performant (yes that is a word in our development world) platform for web sites.
I feel comfortable saying that because some of the few sites that are public, like MySpace, Plenty of Fish and Microsoft are all running on much fewer servers than they non ASP.NET/IIS counterparts. And to that point, according to what I learned at MIX IIS 7 is the best platform for PHP because it allows PHP to be multithreaded, but that is another story.
My friend Dana Coffey posted a series of really awesome articles on Search Engine Optimization for your Blog this morning; Part 1 Blog Setup, Part 2 Blog Posts, Part 3 Tips for ASP.NET Developers. There is a lot of great content in these post for more than just how to optimize your Blog for Search Engines. I was inspired and thought I would share some resources to help you optimize your site for Search Engine visibility.
Search Engine Perspective and Tools
I wanted to share some resources to help you make your web site more search engine friendly. This first is how to know what the search engines know about your site. Each of the big three search engines have some sort of web master tools that allow you to garner information about how they see your site.
Live Search Web Master Central
Google Web Master Tools
Yahoo Site Explorer
Books
There are a lot of Search Engine Optimization books on the shelves. Many are outdated. So check the copyright date and make sure it was written since 2005. This is important as the concepts of search engine optimization have evolved over the past few years and the search engines often change criteria each day to a certain degree. For example 10 years ago Meta tags for Description and Keywords were helpful in distinguishing your site from the competition. Today this has almost no bearing on search engine placement.
These are a couple of current books that I have reviewed and find their content to be helpful for most web masters to get their site more visibility. One thing to keep in mind is making your site optimized for search engines should also help your site retain users and make their experience better.
 | Professional Search Engine Optimization with ASP.NET: A Developer's Guide to SEO (Wrox Professional Guides) by Cristian Darie, Jaimie Sirovich Read more about this book... |
 | Search Engine Optimization: Your visual blueprint for effective Internet marketing (Visual Blueprint) by Kristopher B. Jones Read more about this book... |
Tools
Having tools on your desktop is the ultimate weapon in getting better search engine visibility. Having tools on your desktop is like having a control center at your fingertips. I have two tools that I use all the time, Keyword Elite and SEO Elite.
Keyword Elite is one of the most indispensable tools I have purchased because it will examine what keyword phrases people are using to find content through the search engines. This is important because as a business owner, which lets face it owning a web site is owning a business, you tend to think of just the small sub-set of phrases used to find information related to a business or subject matter. My experience has shown me that the phrases I use to find information are completely different than the audience. I have seen this same restrictive tactic practiced by my clients over the years as well.
Keyword Elite gives me insight into what is actually being used to find information on the web, which leads me to create targeted long tail content for these phrases. An example is from time to time I will use results to write blog articles.
SEO Elite is a tool that extends the information available from the search engine web master tool sites while at the same time collecting much of the information into a single application. One of the main features I like about it is its ability to monitor my site’s ranking across search engines for specific keywords. This helps me keep track of how visible I am for specific phrases. What it is not great for is knowing what you rank for that you are not monitoring. And outside of analyzing your site logs for phrases you are likely not to really know what phrases you actually rank.
What is really great about each of these tools are detailed video tutorials on using them and frequent, FREE updates.
IIS Log Parser
Using the segway from analyzing logs for keywords, IIS Log parser can be a great friend in knowing how your site is being used by visitors. I am not going to get into the details of using this tool, but I will recommend a book on using the Log Parser.
There is an art and a science to making optimized content for the web. Following solid guidelines and creating good content is the art part. But analyzing numbers is the science part and being on top of the numbers game is very key in knowing how to apply your energy to the content creation part of an optimized web site.
Mainstream support for .NET 1.1 is retiring on October 14, 2008. What this means is if you have not installed at least Visual Studio 2005 and .NET 2.0 by now, you really need to. Yes you can buy an extended support contract for mega bucks, but seriously how long are you going to stake your business on an aging platform like 1.1. The current version of .NET is now 3.5 SP1. That means there have been a ton of updates, upgrades and bug fixes since 2002. You are also missing out on some great advances in technology in the past 6 years. You will also find it harder and harder to find programmers to maintain your application because any programmer worth their salt will not want to work with an old platform because they will be risking their personal future.
So please head my advice and upgrade finally .NET 2.0/3.0/3.5 and 3.5 SP1 is free and it works great. It won’t bite you, I promise.
This weekend was a great weekend for .NET developers in the Smoky Mountains as CodeStock rocked the mountains. There were several hundred passionate geeks that came out to Pellissippi State to learn, socialize and have an all around good times, and I guess a few wanted the Master Chief helmet too!
I really want to give a special thanks for Michael Neal, Alan Stevens and Wally McCluer for organizing the event for everyone. They did a fantastic job. The Knoxville community really needs to let those guys know you appreciate their work.
I did a presentation on custom Modules and Handlers. I wanted to post the slide deck and source projects for everyone. It was a great group to share the topic. I like giving this talk because it provides a good introduction to a topic every ASP.NET developer should get into.
Code Stock Content
Trolling the ASP.NET forums this afternoon I came across this thread about creating a custom httpHandler to log IP information to a database. What the requester was trying to do was call a remote site’s (www.ShowMyIP.com) REST API to get information about the visitor’s IP address, such as location and store it in the database. Unfortunately I cannot seem to find documentation about the REST API, but that is not important to this example.
I responded that using an httpHandler in this case would not actually solve the developer’s issue, instead I think it could actually harm the performance of his site. This is because what he is doing is actually calling the handler from the page, like an image file. This actually ties up one of the two threads that browsers open up to retrieve content from a web site upon request. If you go to one of my presentations on front-end performance you will learn more about this. The goal being to reduce the number of objects being requested to build the actual page in the browser.
To actually solve the problem of retrieving the detailed information about the visitor’s IP address is to create a background thread to make the call to the REST API and process the resulting XML. I am not going to get into the details of processing the XML content in this case, nor am I going to store it in a database. Instead I am going to just store the information in a text file corresponding to the IP address, [IPAddress].txt.
The first step is to create a method to log the IP information. In this case I decided to pass in a custom class as its only parameter. This is because it is hard to transport the IP and physical path to use in the logging operation. The method calls the ShowMyIp.com service by creating a new XDocument object via the Load method. The method has to be shared (static in C#) to be able to work in a thread.
Public Shared Sub StoreIPInfo(ByVal args As StoreIpArgs)
Dim doc As XDocument = _
XDocument.Load("http://www.showmyip.com/xml/?ip=" & args.UserHost)
Dim lPath As String = Path.Combine(args.AppPath, _
String.Format("{0}.txt", args.UserHost))
If File.Exists(lPath) Then
File.Delete(lPath)
End If
My.Computer.FileSystem.WriteAllText( _
lPath, doc.ToString(), True)
End Sub
It then logs the XML content to the file system, in this case in the root of the Web site. Again this is a simple demonstration.
The next step is to create the thread and perform the normal page operations. In this case you create a new thread and pass the address of the method to be executed by the new thread. In this case it is the StoreIPInfo method created in the previous step.
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
Dim t As New Threading.Thread(AddressOf StoreIPInfo)
Dim args As New StoreIpArgs
args.AppPath = Request.PhysicalApplicationPath
args.UserHost = Request.UserHostAddress
t.Start(args)
ltlIPAddress.Text = Request.UserHostAddress.ToString()
End Sub
The next thing to do is to create a new instance of a StoreIpArgs class, a custom class I created to hold the value of the user’s IP address and the path to store the log file. This class contains two public properties, UserHost and AppPath.
Public Class StoreIpArgs
Private _userHost As String
Public Property UserHost() As String
Get
Return _userHost
End Get
Set(ByVal Value As String)
_userHost = Value
End Set
End Property
Private _appPath As String
Public Property AppPath() As String
Get
Return _appPath
End Get
Set(ByVal Value As String)
_appPath = Value
End Set
End Property
End Class
Both of these values can be gathered from the Request object, the UserHostAddress and PhysicalApplicationPath properties. The new new StoreIPArgs object is passed to the Start method of the thread object. This will pass the object to the method, StoreIPInfo, designated when the thread was instantiated.
The other pieces of the page simple output the IP address to the page along with the time the page was rendered to the browser. This is done in the PreRender event handler.
Private Sub Page_PreRender(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.PreRender
ltlIPAddress.Text = String.Format("{0} - {1}", _
ltlIPAddress.Text, TimeString.ToString)
End Sub
I did this so I could test to make sure the page was actually rendered before the background thread was completed. I found the call to the external web service was relatively quick and was making it hard to see if it was really completing after the page was rendered. If you download the sample project there should be a couple of breakpoints set so you can step through and see when the methods are called. You will see the PreRender event gets called before the IP information is logged to the file.
This example performs the operation in a page. But I really think this will work great in a custom httpModule. I may revisit the topic, but I think you could just modify my Blog on creating a background thread in a custom httpModule, but instead of just doing it in the Init method you would wire up an event handler to the BeginRequest event and repeat the same basic steps there.
The resulting XML is logged and starts off like the following snippet:
<ip_address>
<lookups>
<lookup_ip>127.0.0.1</lookup_ip>
<lookup_ip_long>2130706433</lookup_ip_long>
<lookup_ip_is_valid>yes</lookup_ip_is_valid>
<lookup_ip_is_private>yes</lookup_ip_is_private>
<lookup_is_ipv6>no</lookup_is_ipv6>
<lookup_host>private</lookup_host>
<lookup_reverse_host></lookup_reverse_host>
<lookup_isp>provided to subscribers only</lookup_isp>
<lookup_org>provided to subscribers only</lookup_org>
So while it might look like a custom httpHandler is the answer to something like this, it really is not. It would actually cause the page to not render efficiently and probably cause it to render much slower because it would hog one of the browser’s download threads. A background thread can make this process more efficient without affecting the rendering of your page in the visitor’s browser.
Source Project
Another week of great resources for the .NET developer to take in. Amazing how many are out there. I tried to do some more organizing again, I hope it helps you out.
Twitter Clients – They work great till the Fail Whale surfaces!
SharePoint Governance Part 1 – Despite what he says, setting up SharePoint is not simple it takes great care and attention or you are starting over!
Windows Vista Performance Tuning
David S. Platt’s Blog – Why Software Sucks baby!
Using the using statement with a method – Cool trick, I never knew you were there!
Getting the user’s Country from the Browser
Visual Studio
New Things in Visual Studio 2008 – A little older, but a great reference.
An Opposing View of Using Regions – Hmmmm
Regionorate – A Region Tool, cool!
Roy Osherove’s Tools – Roy has some great stuff, all .NET dev should have at least the Regular Expression tools installed.
Visual Studio Service Pack 1 beta list of fixes and release notes – Any moment now we can remove the Beta!
Visual Studio TFS Setup – I think I am going to be installing a TFS this weekend.
User Interface
AJAX Browser History Control – So glad this is available now!
ASP.NET AJAX Source Code – Great book, glad to see the source code.
Getting the DataItem in the ListView – Why oh why is it that much different? Thanks Peter!
44 Silverlight Videos – Didn’t I already do this list?
Simple CSS Tricks – Oh how I want to be really good with CSS
Entity Framework
Overloading the GetObjectStateEntries
So you Want to nHibernate – Not EF, but a good read on the overall topic.
How to Review an nHibernate Application – Ayende Goes over how to review an nHibernate application, good read on doing data related code reviews.
GUIDs as Primary Keys
The Cost of GUIDs as Primary Keys – Old article, but has some great information.
GUID or Int Primary Key
Int Identity vs GUID
Environmental Concerns about the use of GUIDs – Yes even the environmentalist are involved!
INT vs GUID as Table Primary Key
Architecture
The Onion Architecture part 1 and part 2 – Jeffery Palermo discusses a new paradigm in describing modern application architecture.
Software Patterns – Funny, most of these I have been using for a while and it seems there are formal names for the things I normally do!
Studying Databinding Techniques from a Performance Perspective
Scaling Strategies in ASP.NET – Link to an MSDN article and a tool to analyze your site.
Scaling Strategies for ASP.NET Applications – Of course the MSDN article from above.
Principles of OOD
Do One Thing – Curly’s Law
Recently I have been confronted with a movement that seems to hate using #Regions in source code files. Personally I really like using regions and I absolutely like the ability to collapse sections of code I am not directly working with. The opposing argument I am given is that my classes or methods must then be too long. I really have to disagree, I work hard at making my classes, methods and properties as refactored as I can get them. But I do like to organize my code into related sections. And sometimes there is just a lot of logic that goes into creating the UI or business logic and regions help keep things clean.
I wanted to show an example from a custom Exception class I was creating today. It consist of two custom properties, PropertyName and PropertyValue. I wrapped these properties into a region and moved them out of the way. Once I have the properties created there should be nothing else I need to do with them and by wrapping them in a region I can hide them out of view.
This reduces the amount of code that I need to slide through to get to code I am working with at the moment. It also forces me to organize my code into common areas or ‘regions’. This alone is worth it to me because it gives me a nice way to toss my code into a bin of sorts to keep it organized.
The next region I created is to hold my constructors. Because this is a custom exception class I created three new constructor overloads. This gives me the ability to set my custom properties and call the base constructors for the Exception class. Again I have all my constructor overloads contained within one area in my file and I can expand and collapse it as needed.
What are my alternative choices? Creating several classes that either inherit from a base class or create numerous partial classes with partial methods. Each of these hold their own merits but to me serve different purposes from what regions are designed to do in Visual Studio.
I invite those with opposing views or that can add to the case for using regions to please leave comments on the topic. This is a small class where I show how I really like to use #Regions. There is not an overwhelming amount of code in this class, but the #Regions help keep things organized.
A special note, I have CodeRush and Refactor Pro from DevExpress installed on my machine. This makes the display of the regions look different than the out of the box look. The functionality is still the same, but I just wanted to point that out if you were feeling a little lost.
This week I am coming to you from the Microsoft Campus. So as you would expect I have a lot of energy going this week and lots of great links to share. I even tried to organize them somewhat.
Special thanks to all who were at the ASP Insiders this week. I had a blast and learned so much this week.
Misc
What Every C# Programmer Should Know Before they Write VB – Remember VB is not case sensitive and you do not need to end every statement with a;
Adding OpenId to your ASP.NET Web Site – Thank you Dan!
Virtual Earth Updates – Lots of great new imagery.
Web, Load and Unit Testing Videos – I like that we can do screencasts to show how things should be done now.
New Releases to ASP.NET tools and Extensions – ASP.NET AJAX 4.0, Dynamic Data for MVC (Man this is some really cool stuff), More Dynamic Data Updates and MVC CodePlex Preview 4.
Loading a DLL outside of the BIN folder in ASP.NET – Tom has a great blog for debugging ASP.NET stuff.
SlickEdit Versioning Screencast from James Avery
Create PDFs in C#
Free CSS Templates
CSS Tools in Visual Studio – It is getting better all the time, this should help you know what is available in Visual Studio.
Installing Northwind in SQL Express – This is important for students taking a .NET class
44 Silverlight Videos – Silverliight is the future, I am telling you.
Microsoft Extensibility Framework – OK I get all the word play jokes.
The File IO System in .NET – Never thought of producing the Class Diagram for a post, but I think it goes a long way. I think he missed a few important support classes though, where is Compression?
The Myths and Realities of Web 2.0 – Really good article codifying many resources about what Web 2.0 is and is not.
Building an IQueryable Provider – Important stuff if you are into making your own LINQ to Whatevers
Regular Expressions
Jeff Atwood on Regular Expressions – Jeff give a very good detailed explanation as to why every developer should be using Regular Expressions, when and how to use them and a review of RegexBuddy.
John Robbins Follows Up on Jeff’s Discussion of Regular Expressions -
IE 8
Are You Ready for IE 8? – The time is getting closer and many, many sites are going to be broken.
Another Is your site ready for IE 8
jQuery – I am trying to get up to speed on this JavaScript Framework, so here are some resources I came across this week.
5 jQuery Plugins you can’t live without
jQuery Content Slider
Matt Berseth on jQuery
ASP.NET AJAX
Master-Details with the DataView – Explores the ASP.NET AJAX Templating Engine in the ASP.NET AJAX 4.0 Preview.
Entity Framework – I am working on a project with Entity Framework this summer and getting up to speed is super important, so here are some links I am finding valuable.
Danny Simmons Blog – He is the main Entity Framework Guy.
Danny Simmons on DNRTV – This is a great screencast to watch to start getting your mind right with Entity Framework.
Introduction to the Entity Framework – Thank you Shawn
Tim Mallalieu’s Blog
MSDN Introduction to Entity Framework
Julie Lerman Talks about Relationships in the Entity Framework – Julie is writing a book on Entity Framework and shares some complex solutions on her Blog
The Repository Pattern and the Entity Framework – I think I may do more with this topic very soon.
Entity Framework Contrib Project – Some sample applications and other helpful projects
Mapping Tables with No Keys in Entity Framework – Good article on how this is handled in Entity Framework. It create a Read-Only Defining Query. David is right, I wish the Entity Framework Designer gave some sort of indication of this issue. It took me about 4 tries to figure out what was going on the day.
Wikipedia on Entity Framework – It is really worth a read. I found it very easy to read compared to many other sources
I have been Blogging for over two and a half years. I have almost 400 entries on my Blog. So I got to looking at my stats from some of my earliest posts and thought I would build a list of 10 of my most popular early post.
I found this exercise very interesting and made me think about where I have been and where I want to go. Also, reviewing my older posts sort of reveals how my writing has matured too! I think this will be useful because there are so many new readers now that may not know what I wrote about 24 months ago.
Changing the Password Format – My third post ever, amazing how many eyeballs it has had.
Caching in ASP.NET varyby Language – Not sure if it is the power of mentioning Hanselman in Blog or not, but this reference Blog to an insightful Blog by Scott has a lot of traffic. Basically watch how you set OutPut Cache on an international site.
MultiView where have you been? – Ah my early praise of this fantastic control in the ASP.NET 2.0 library.
Data Binding and the Crystal Report Viewer – Funny, this week I am struggling with the ReportViewer Control for SSRS.
Nesting Master Pages, Do It At Your Risk – So this was a problem in Visual Studio 2005, not in 2008.
Using ASP.NET 2.0 with IIS – I do not get this error anymore and I have no clue how I solved it, but most likely the comments are the clue we need.
Custom SiteMap Provider – At one time I was really fascinated with SiteMaps and SiteMapProviders. I have sort of moved on because I really found them constraining.
URLMapping or URL Rewriting – I think this was one of my first entries on URLRewriting. I am doing some more research into Rewriting scenarios now, so I hope to post more updated information soon.
301 Redirect ASP.NET – 301 Redirects, a topic any web architect should really learn. This was one of my early entries. I know I have a few more on the topic.
Infragisitcs UltraWebTab and FreeTextBox – This was a wasted support call to Infragitstics I had to pay for. I do not know if Infragistics has fixed their support issues or not, from what my friends say the answer is no.
So I got called out by my friends Rachel Appel and Kevin Hazzard to tell the world how I got started programming.
How old were you when you first started programming?
I was 12 I think, it was Christmas of 1982 when I got my first computer a Timex Sinclair 1000. Several of my family members ‘conspired’ to get it, a TV and tape recorder because I was a – spending my money on Defender or b – I was spending my other money for time on the library’s TRS-80 computer to write code and play games. One of my teachers had brought in a TRS-80 for us to learn about computers. I took to it, second only to football (I grew up in small town Texas, Go Jackets!).
What was your first language?
BASIC, wasn’t that about the only option for anything you could own yourself in 1982?
What was the first real program you wrote?
On that Timex I wrote a starfield simulator and then went big and wrote a Breakout clone.
But really it would have been the Textile Energy Models I wrote for my masters thesis. I continued research into building predictive energy consumption models for the Textile industry. I collected lots of sample data from dry processing machines to build models to accurately predict the cost of producing a product. I also saw patterns from the machines that could predict maintenance needs and just plain inefficient equipment. I wrote it in Borland C++. You know OWL.
What was your first professional programming gig?
Again it would have been my masters thesis. After I got out of grad school I went to work for Guilford Mills creating plant floor software in PowerBuilder (OMG what a disaster!). But I also got to build a wireless speech recognition system that worked in a high noise environment too, which was really cool.
If you knew then what you knew now, would you have started programming / DBAing?
Yes, no doubt. It is a passion.
If there one thing you learned along the way that you would tell new developers, what would it be?
Don’t be dogmatic, but be pragmatic. Find what works for you and get real good at it. Most likely it will be something you are passionate about and you will be happy with your platform and tools. Don’t be afraid to learn and of course always attend your local INETA approved user groups. :)
What’s the most fun you’ve ever had … programming?
Tough decision, but probably my first project I did as an independent. I built an entire web application, including database, that talked to the North Carolina court records and DMV mainframes via 3270 sessions. I did the whole thing in classic ASP (Summer of 2000) with notepad and SQL Enterprise manager/Query Analyzer. Lots of 60-80 hour weeks those two months, but fantastic seeing how I could make it on my own.
Who are you calling out?
Rob Zelt
Daniel Egan
Ken Spencer
Wally McCluer
So many good articles and resources I have found over the last month or so. Here is a good sampling of them.
Less Than Dot Net – New site loaded with code snippets for common tasks in .NET. It is a community Wiki that anyone can post helpful code for everyone to make better applications.
Benchmarking the SortedList Classes – Kevin Hazzard does a good job benchmarking performance of the SortedList to the SortedList<K, V> classes.
Three New Master Page Tutorials – Scott Mitchell provides three good tutorials on extending the use of Master Pages.
Free SQL Server 2008 Book from Peter Debetta and MSPress.
Creating a Custom Label Control
Shrinking SQL Server Databases
LINQ to SQL vs. ADO.NET Comparison – Wriju’s Blog does it again. I have to say this is one of the best .NET related Blogs on the Internet.
Debugging ASP.NET on a Production Server – Another Must Read Blog for the ASP.NET Developer.
LINQ to Entities Preview -
Fast Loading JavaScript Files – Great explanation of a technique to drastically increase the rendering of web pages.
How to Allow Generic Controls in Web Pages – Looks like a very interesting way to get more control over how data is rendered in a list.
Using Set Operators in LINQ
Creating Virtual PC Differencing Disks – Gotta get more knowledge of building a VPC library.
ASP.NET Dynamic Data, Dealing with ReadOnly tables – We should start seeing more and more content about Dynamic Data Web Sites this Summer and Fall.
What is in the works for C# 4.0? – Maybe some productivity enhancements with the experience I hope.
SharePoint Infrastructure Updates -
Reasons Why IIS 7 Rocks! -
July Team System Power Tools – The Following Tools are installed with these updates:
- Command line tool (TFPT.EXE)
- Team Explorer IDE menu additions
- Build Notification tool
- TFS Best Practices Analyzer
- Process Template Editor
- Work Item Templates
- Custom check-in policies
- TFS Server Manager
- TFS Users tool
- Alert Editor
Is Your Site Ready for IE 8? – We all need to start checking and updating our sites to make them compliant.
Setting E-Mail Headers in .NET – Sending E-Mail is still one of the most common questions about programming in .NET.
10 WebCasts to get up to speed with SharePoint Development – Still got to spend more time in this area.
Virtual Earth Development Center – Always seems there are new updates to the Virtual Earth API and capabilities.
50 jQuery Examples – I am really wanting a day to sit down and get started with jQuery.
Entity Framework Bag – This is a framework for exchanging data between the Entity Framework and WCF services.
A Mort By Any Other Name – Why is VB so beat upon?
I still have more to post, so look for another one before Sunday morning.
Dealing with Null values (nothing in VB.NET) is a common problem for programmers of any stripe. Null dates stored in the database seem to be a common issue developers experience when they start dealing with null values. Null values in the database for a value type poses a problem in the application. The .NET framework provides Nullable Types, a Coalesce operator in C# and If in VB.NET that can help the situation.
I am going to discuss several features of the .NET framework, SQL Server and the CSLA framework that .NET application developers should know about so they can appropriately solve the null value issue.
Value Types
A value type is a fundamental element of a language, such as an integer, character, boolean, datetime or byte. These types cannot be set to null.
C#:
int x = null; //Not allowed, compiler error.
VB.NET:
Dim x as Integer = nothing ‘Not allowed, compiler error.
If you think about it, this rule makes sense because these are the fundamental building blocks of any application. Allowing them to be null could cause major ramifications. Object types, such as classes, can be null because they serve a different purpose and would typically ‘hold’ value types.
Nullable Types
Value types can be modified at declaration to be Nullable Value Types by appending a ? to the end of the type, int? (C#) or Integer? (VB) for example. This makes the value type able to be set to null. A Nullable value type’s value cannot be set to a normal value type, even if it has a real value.
C#:
int? x = null;
int y = x; //Causes a compiler error.
VB.NET:
Dim x as Integer? = nothing
Dim y as Integer = x ‘Throws a compiler error because it cannot be cast.
When the value type is compiled to IL it creates a System.Nullable<T> (C#) or System.Nullable(of T) (VB.NET).
Coalesce
Fortunately there is the concept of Coalesce in both C# and VB.NET. I blogged about using Coalesce in transact SQL in September of 2007. Coalescing a value type is the act of checking a value for a null value and defining a default value if it is null. I recommend any select statements including fields that allow null values be wrapped in a COALESCE function to be safe.
In C# coalescing is done using the Null Coalescing Operator, ??, where a variable’s value will be assigned if it is not null, otherwise the default value will be used. The default value is declared to the right of the ?? operator, e.g. variable ?? [default value].
int? x = null;
int y = x ?? 5; //This works because if x is null, y will be set to 5.
In VB declaring a nullable type and using coalesce is an if statement with the potentially null value separated by a comma from a default value.
Dim x As Integer? = Nothing
Dim y = If(x, 5) ‘This works because if x is null, y will be set to 5.
Alternatives to Manage Null Value Types
There are alternatives to using coalesce to provide default values for a potentially null value; ternary if (C#) and IIF (VB.NET) have been used by many programmers over the years. This is a common practice when a value is set from a database field, and there is no control over the value being retrieved, since a database field can hold null values. I am starting to oppose allowing null values in a database field if it can be avoided, simply because managing potentially null values has caused so many headaches for developers over the years.
In the C family of languages, the ternary if statement has been a staple. If a conditional is true the first value is returned, otherwise the second value is returned. The syntax is if ([conditional]) ? a : b;
static int Square(int a){
return if (a != null) ? a * a : 0;
}
Similarly the VB family has had the IIF function, which serves the same purpose. It seems to be heading towards deprecation and should be replaced with the If(x,y) syntax highlighted earlier.
Public Shared Function Square(a as Integer) as Integer
return IIF(not a is nothing, a * a, 0)
End Function
At the urging of Bill McCarthy I do want to point out that IIF is a function of the VB language. Each parameter in the expression is evaluated and almost useless.
CSLA’s Answers for Working with Null Value Types
While I do not use the CSLA framework in my day to day life, I study it as much as I can. Rocky Lhotka does a fantastic job of using every ounce of the .NET framework and language in the CSLA framework. If you take time to study CSLA you will find very obscure language features being used in their proper context. I also find many of these features sparsely documented in the wild, which makes finding real world uses of them hard.
I first starting using pieces of the framework when I discovered the SmartDate class about 2 years ago. This is a class that wraps around the DateTime value type. The SmartDate class sets a default value, either MinValue or MaxValue for a null datetime value. To me, this means I store the MinValue of a datetime in the database when I have an optional date value that has not been supplied by the user through the user interface.
It has been a lifesaver for me to have a consistent class to manage dates, and thus reduces the amount of code I need to manage and maintain on live applications. It is a class instead of a value type, and actually wraps the value type in a protective layer of sorts to insulate the application from having a null value type to process.
The second class I really like is the SafeDataReader. The SafeDataReader implements the IDataReader interface, therefore it is a commonly used interface. It does need a helper method to ‘convert’ a SQLDataReader to a SafeDataReader. A wrapper method around any ExecuteReader method could return a SafeDataReader as well.
The class ‘fixes’ any null values before they are returned to the business code. This makes calling the GetXXX methods, such as GetString much safer than the typical DataReader class. In my opinion Rocky did it right, not the framework classes. For example this is the GetString method of the SafeDataReader class. It checks the value returned from the database for DBNull, and if it is, it sets the value to an empty string.
The GetString method from the CSLA class:
Public Overridable Function GetString(ByVal i As Integer) As String _
Implements IDataReader.GetString
If _dataReader.IsDBNull(i) Then
Return ""
Else
Return _dataReader.GetString(i)
End If
End Function
The standard GetString method on the framework’s DataReader classes allows null values to be returned because the database can allow null values in a field. This is a disconnect from how we should process data values, which the SafeDataReader addresses.
Conclusion
The .NET framework and family of languages have several options available for developers to work with null values in a safe way. There are also alternatives available in many of the publicly available code bases, such as CSLA.
Nullable types are declared using the ? modifier and are the first line of defense, but they require prior knowledge as to what values could be null. Traditional method use the ternary if and IIF constructs. So there should be no reason why any .NET developer says they are struggling with null values in the application. NullReferenceExceptions should be a thing of the past for .NET applications with this knowledge.
References:
http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2297
http://www.dnrtv.com/default.aspx?showNum=97
http://www.dnrtv.com/default.aspx?showNum=98
http://rocksthoughts.com/blog/archive/2008/03/26/vb.net-true-ternary-operator-if.aspx
So I like VB better than C# for many reasons. Primarily because development experience in VB is built to help productivity. The Development experience in C# is built around being proud of the language rather than solving problems quickly. I could point out many things and have yet to really hear a good argument favoring C#. The only thing C# seems to have an advantage on right now for me (key point there, me) is better support for Lambda expressions.
Creating event handlers is super easy in VB. In the code-behind select events from the top-left dropdown for the Window|Page|Control (you like the usage of the | syntax right), then select the event from the Event list in the top-right drop-down. Then bam! You have a properly signatured event handler for the event that even tells you right there it is a handler for the event in question. Man that second part is so useful when you are reading through code to know what that method is responding to.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Now in C# you…..well you are stuck going back to the design surface of your form. Opening the Properties Window for the Form|Control|Page you are working with, then clicking the Event button
in the Properties Window. Then finding the event you want and typing in a name for the method you want to use and it will then take you directly to the method once you leave focus on that event, even if you want to create another event handler for another event. I find this process very tedious and time consuming. It is also not very natural in my opinion. If I am working in the code I do not want to leave what I am doing to go back to the design surface.
I Twittered my delima and got a couple of responses telling me how easy it is, EventName TAB TAB for example. This does nothing useful, just creates a Type name for something I was not even thinking about usually.
I was also told something about snippets, and let’s face it C# has no clue about the use of snippets, there are like 20 or 30 and they help you do things like create if statements. VB has like a zillion out of the box and you can do things like call the Mars rover if you want (that is a sarcastic joke).
So with this I ask, can you tell me how to do this very simple and useful task in C#? I have C# books, I even have the Chris Sells WinForms book and yet nothing I can find to help with the common task.
I say this not a chest thumper for VB, but as someone who does work in both languages. Yes I am primarily VB and honestly that is because in Visual Studio it really just helps you write code and does not force you to clutter your brain cells with remembering stuff that does not help you solve the customer problems. So make C# a more pleasant experience for me and anyone else who wants to explore C# as a .NET language. This is something that has really bugged me for a while and I have asked for help, to no avail. I have searched and searched and nothing. So help me understand why this is so cumbersome and how to make it not cumbersome.