362 Microsoft Visual Studio 2010: A Beginner’s Guide
could end up saving bad data. Since AddNewCustomer doesn’t have an implementation,
this is all speculation, but this outlines a few of the many problems that can occur if you
allow your business objects to accept data that is bad for your program.
The macro demonstrated in this section will show how to check a string parameter
for null, empty, or white space and throw an ArgumentNullException. This will prevent
callers from passing bad data and give them a meaningful message. To create a macro,
you will need to locate the position in the code where the macro starts (if applicable),
start recording, perform VS actions, and stop recording. It’s somewhat like using a video
recorder where you have to find a TV show, start the recording, allow the show to play, and
then stop recording. Perform the following steps to create the parameter validation macro:
1. Click the firstName parameter of the AddNewCustomer method so that the cursor is
inside of the firstName parameter identifier. This is important because we need the
parameter name in the code.
2. Start the macro recorder by selecting Tools | Macros | Record TemporaryMacro or press
CTRL-SHIFT-R.
3. For C#, press CTRL-LEFT ARROW, CTRL-SHIFT-RIGHT ARROW, and CTRL-C. For VB, press
CTRL-LEFT ARROW, CTRL-SHIFT-RIGHT ARROW, SHIFT-LEFT ARROW, and CTRL-C. This copies
the parameter name.
4. For C#, press CTRL-F to bring up the Find And Replace window, type { into Find What,
click Find Next, Close the Find And Replace window, press END, and press ENTER. For
VB, press END and press ENTER. This positions the cursor to begin entering code.
5. Type if and press TAB twice (the if snippet), type string.IsNullOrWhiteSpace( into the
condition, press CTRL-V to paste the parameter name as the argument, and type ). For
C#, press ENTER. For VB, press DOWN ARROW. The cursor moves to the body of the if
statement (as you would expect with the if snippet). This sets up the validation check
for the parameter, seeing if it is null (Nothing in VB), an empty string, or some white
space character such as space or tab.
6. Type throw new ArgumentNullException(", press CTRL-V to paste the parameter
name, type ", ", press CTRL-V to paste the parameter name, type a space, and type value
is not valid."). For C#, add a semicolon, ;, to the end of the line. This is the action to
perform when the value is not valid, throwing an exception to let the caller know that
the value is not good.
7. Press DOWN ARROW and press ENTER. This positions the cursor after the code, which
might be convenient if you want to continue typing from this point.
8. Select Tools | Macros | Stop Recording TemporaryMacro or press CTRL-SHIFT-R to stop
recording.