# Saturday, 12 September 2009

Back To Basics

Prior to C# 3.0, we had two common ways to initialize the public properties of an object.

  1. We could use the default constructor to instantiate the object; then, use a separate line of code to assign a value to each property. (Listing 1)
  2. We could create a constructor that accepts an argument for each property; and write code in this constructor to assign to each public property the value passed in for each corresponding argument. (Listing 2 and Listing 3)

The first method is quite verbose and requires a lot of code for complex objects.

Listing 1:

Customer cust1 = new Customer();
cust1.CustomerID = 1;
cust1.FirstName = "George";
cust1.LastName = "Washington";
cust1.StreetAddress = "111 A St";
cust1.City = "Aville";
cust1.State = "MI";
cust1.ZipCode = "10001";

Listing 2:

class Customer
{
    public Int32 CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public Customer
        (
        Int32 customerID,
        string firstName,
        string lastName,
        string streetAddress,
        string city,
        string state,
        string zipCode
        )
    {
        CustomerID = customerID;
        FirstName = firstName;
        LastName = lastName;
        StreetAddress = streetAddress;
        City = city;
        State = state;
        ZipCode = zipCode;
    }
}

Listing 3:

Customer cust2 = new Customer
    (
    2,
    "John",
    "Adams",
    "222 B Ave",
    "Beetown",
    "MI",
    "20002"
    );

The second method is more elegant, but assumes we always want to initialize every single public property at object instantiation. Of course, we could create multiple constructors to accommodate times when we only want to initialize certain variables but this can get complex in a hurry when our class has a lot of public properties.

Beginning with C# 3.0, we can now initialize public properties in the same line of that instantiates an object; and we can do so without creating a new constructor. We use object initializers to do this. 

Using object initializers we can still use the default constructor (or any public constructor we want); but we can set public properties by appending the property assignments within a set of curly braces at the end of the object initializer, as shown in listing 4.

Listing 4:

Customer cust4 = new Customer() 
            {   CustomerID = 4, 
                FirstName = "James", 
                LastName = "Monroe" 
            };

This new C# feature is known as object initializers. This method gives us a great deal of flexibility. At the time we instantiate an object, we can decide which properties to initialize. And we can do so without creating a plethora of constructors for the object or return to the verbose way of assigning property values after an object's instantiation.

Object initializers are most useful when you instantiate a class in many different places throughtout an application.

Download this code to view and run a simple application that uses object initializers DemoObjectInitializers.zip (24.92 KB)
Saturday, 12 September 2009 14:10:03 (GMT Daylight Time, UTC+01:00)
# Friday, 11 September 2009

Back To Basics

Automatic properties were introduced in C# 3.0 as a convenience to developers.

C# and Visual Basic .Net provide two ways for a class to maintain state: Fields and Properties.

A field is a simply a public variable defined inside a class, such as in the following example

public string foo;

A property looks much like a field to the outside world, but exposes two methods – a “getter” to allow you to retrieve the value of the property and a “setter” to allow you to assign a value to the property. The following sample demonstrates how to implement a read-write property in C#.

private string _firstName;
public string FirstName
{
    get
    {
        return _firstName;
    }
    set
    {
        _firstName = value;
    }
}

This is a common use of property getters and setters – to assign and retrieve the value from a private variable. Because there is no extra logic in these methods, similar functionality could be achieved using a field, but I prefer to use properties in case I decide later to add some validations or calculations to the setter or getter. Making a change like that to a property will not break the class signature, forcing a recompile of dependent objects.

But this is a lot of typing for such simple functionality. So much in fact that Visual Studio 2005 provided a right-click accelerator to type much of it for you.

Beginning with C# 3.0, automatic properties provide a shorthand notation for this functionality.  Simply provide the scope, the type and the name of the property, followed by “{get; set; }” and the framework will automatically create a private variable for you and provide code to save and retrieve to/from that private variable. This is all done behind the scenes for us so we don’t need to write any of this code.  Below is a sample of the code we need to write for a public property.

public string FirstName { get; set; }

To make a property read-only, simply omit the "set" keyword. To make it write-only, omit the "get" keyword. Below is syntax for the same property if I wanted it to be read-only.

public string FirstName { get; }

The only disadvantage to automatic properties is that the rest of the code in our class no longer has access to the private variables create by the framework. Even from within the same class, we must go through the public property in order to get or set the private variable.

This is a small price to pay for the amount of code we are saving.

Automatic properties not only require less typing, they are far easier to read when your class has a bunch of properties. Which of the following easier to read?

public string FirstName { get; set; }
public string LastName { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }

or

private string _firstName;
public string FirstName
{
    get
    {
        return _firstName;
    }
    set
    {
        _firstName = value;
    }
}

private string _lastName;
public string LastName
{
    get
    {
        return _lastName;
    }
    set
    {
        _lastName = value;
    }
}

private string _streetAddress;
public string StreetAddress
{
    get
    {
        return _streetAddress;
    }
    set
    {
        _streetAddress = value;
    }
}

private string _city;
public string City
{
    get
    {
        return _city;
    }
    set
    {
        _city = value;
    }
}

private string _state;
public string State
{
    get
    {
        return _state;
    }
    set
    {
        _state = value;
    }
}

private string _zip;
public string Zip
{
    get
    {
        return _zip;
    }
    set
    {
        _zip = value;
    }
}

I think you’ll agree that it is far easier to read and understand the more terse syntax of the first example.  And code that is easier to understand is easier to maintain.

Because both syntax versions compile to the same Intermediate Language, I recommend always using the newer Automatic Properties syntax when you create properties that do nothing more than save and retrieve state.

Download the following sample code to see automatic properties in action: DemoAutomaticProperties.zip (26.83 KB)
Friday, 11 September 2009 13:17:17 (GMT Daylight Time, UTC+01:00)
# Thursday, 10 September 2009

Episode 49

In this video, James Bender discusses REST services. He defeines REST, compares it to SOAP and describes how to implement REST services using WCF.

Thursday, 10 September 2009 13:21:19 (GMT Daylight Time, UTC+01:00)
# Wednesday, 09 September 2009

Steve Krug’s Don’t Make Me Think is a great book, not only for what it contains, but for what it does not contain.

At a couple hundred pages (most of which are filled with large graphics), Krug is forced to be concise in order to deliver his message. There is no room for irrelevant data in so little text. Happily for the reader, he succeeds brilliantly.

“Don’t Make Me Think” is not just the title of this book - It is the single most important point Krug makes about web usability design.

Throughout the book, he emphasizes that a good user interface should be self-evident. A user seeing a web page for the first time should not have to wonder what the page is for or how to use it.

He provides many examples to illustrate his points – most from actual web sites. Krug holds up Amazon.com as an example of a site that is doing many things right, making itself intuitive for the users. It’s tough to argue this point, given Amazon’s success and enormous growth over the years.

According to Krug, most web designers make the mistake of assuming that visitors to their site will read everything on each page presented to them. The reality is that most visitors quickly scan a page, searching for anything that looks relevant to them. When they find something that seems useful and clickable, they click it. When they actually find something useful, they stop looking.

Because of this behavior, web designers should focus on simplifying their page layout and draw the reader’s eye to the most important parts of the page that support the most common activities. They should provide clear, self-evident labels for the items on their pages: there should be no confusion what each item is for and what will happen if a user clicks on it or otherwise interacts with it.

But following his design advice is not sufficient. Krug also recommends recruiting and observing testers to use your web design. Watch how they interact with the pages; note the pages that they struggle to learn; document unexpected behavior.  A designer does not always think like an end user and users often react in unexpected ways. This type of testing is a good way to learn how end users perceive and interact with your site.

Check out this book if you want a quick way to improve the usability of your web sites.

Wednesday, 09 September 2009 22:20:12 (GMT Daylight Time, UTC+01:00)
# Tuesday, 08 September 2009

Episode 48

In this interview, Phil Japikse discusses his involvement with Hopemongers.org, a charity site focused on "micro-giving", allowing donors to give a small amount of money, directly to a charitable project.

Tuesday, 08 September 2009 06:11:52 (GMT Daylight Time, UTC+01:00)
# Saturday, 05 September 2009

Back To Basics

Extensions methods are a new feature of C# 3.0 and they are easier to use than they first appear.

An extension method is a method that is external to an existing class but appears as if it were a method on that class.

The rules for creating an extension method are simple.

  1. Create a static method
  2. The first parameter of the static method should be the type of the class you wish to extend
  3. Precede the parameter type of this first parameter with the "this" keyword.
  4. Call the method as if it were a method of the class. Omit the first parameter.

An example should clarify this. Assume we have a class Customer with properties FirstName and LastName as shown below

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

We can create a new static class MyExtensions with a static method GetFullName that returns the formatted first and last name of the customer. We do so with the following code

   public static class MyExtensions
    {
        public static string GetFullName(this Customer cust)
        {
            string custName = cust.FirstName + " " + cust.LastName;
            return custName.Trim();
        }
    }

Notice the parameter with the "this" keyword. That parameter format tells the compiler that this is an extension method and that it should extend the Customer class. As long as MyExtensions is in the same namespace or in a namespace available to our code (via the "using" statement), we can call this new extension method with the following code

Customer cust 
    = new Customer 
         { FirstName = "David", 
           LastName = "Giard" 
         };
string fName = cust.GetFullName();
Console.WriteLine(fName);

The code above outputs:

   David Giard

As you can see in the above code, it looks as if the GetFullName method is part of the Customer class.

We can add parameters to our extension methods as we would to any other method. The first parameter (with the “this” keyword) is always used to specify the class we are extending. All other parameters act just like normal parameters. The following extension method accepts a parameter “salutation”.

public static string GetGreeting(this Customer cust, string salutation)
{
    string custName = cust.FirstName + " " + cust.LastName;
    custName = custName.Trim();
    return salutation + “ “ + custName + ":"; 
}

Although the extension method has two parameters, we only need to pass the second parameter when calling it, as shown

Customer cust = new Customer { FirstName = "David", LastName = "Giard" };
string greeting = cust.GetGreeting("Dear");
Console.WriteLine(greeting);

The code above outputs:

   Dear David Giard:

In our examples, we were adding extension methods to a class that we just created. Of course, in this case, it would have been simpler to just modify the original class.  But extension methods are more useful if you are working with someone else’s class and modifying the source code is not an option. Extension methods often offer a simpler solution than inheriting from an existing class.

The real power of extension methods comes from the fact that you can even add methods to sealed classes. It is difficult to add functionality to a sealed class because we cannot inherit from it. Change the Customer class to sealed and re-run the code to prove that it still works.

public sealed class Customer

Here is the all code in the above sample

using System;

namespace TestExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer { FirstName = "David", LastName = "Giard" };

            string fn = cust.GetFullName();
            Console.WriteLine(fn);

            string greeting = cust.GetGreeting("Dear");
            Console.WriteLine(greeting);

            Console.ReadLine();

        }
    }


    public sealed class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }


    public static class MyExtensions
    {
        public static string GetFullName(this Customer cust)
        {
            string n = cust.FirstName + " " + cust.LastName;
            return n.Trim();
        }

        public static string GetGreeting(this Customer cust, string salutation)
        {
            string custName = cust.FirstName + " " + cust.LastName;
            custName = custName.Trim();
            return salutation + " " + custName + ":"; 
        }
    }

}

You can download the sample code at TestExtensionMethods.zip (24.26 KB)

 

Saturday, 05 September 2009 02:52:43 (GMT Daylight Time, UTC+01:00)
# Thursday, 03 September 2009

Recently, I was asked to automate the process of checking a set of known URLs and determining if each URL corresponded to a “live” site. For our purposes, a site is live if I can PING it and get a reply back.

I can open a command prompt and use the PING command and read the response to determine if a site is live. A live site would return a series of messages starting with “Reply from”, while a non-existent site would report an error.

Unfortunately it is difficult to automate this task from the command prompt. Fortunately, the .Net framework provides the tools to allow me to ping a URL with just a few lines of code. The functionality I need is in the System.Net.NetworkInformation namespace.

I have created a public class  PingUtils and added the statement

using System.Net.NetworkInformation;

at the top of this class.

Next, I added the following method to attempt to ping a URL and return true, if successful.

public bool UrlIsLive(string url, int timeOut)
{
    bool pingSuccess = false;
    Ping ping = new Ping();
    string pingData = "TEST";
    byte[] pingDataBytes = Encoding.ASCII.GetBytes(pingData);
    try
    {
        PingReply reply = ping.Send(url, timeOut, pingDataBytes);
        if (reply.Status == IPStatus.Success)
        {
            pingSuccess = true;
        }
    }
    catch(PingException)
    {
        pingSuccess = false;    
    }
    return pingSuccess;
}

That’s it. If an error occurs when I try to ping, it is most likely a PingException, which is equivalent to the "Ping request could not find host" error reported at the command prompt.

This function returns true for a URL that exists and is live; and false for one that does not exist.

The following unit tests should deomonstrate this

/// <summary>
///A positive test for IsLive
///</summary>
[TestMethod()]
public void IsLive_PingGoodUrl_ShouldReturnTrue()
{
    PingUtils pu = new PingUtils();
    string url = @"DavidGiard.com";
    int timeOut = 1000;
    bool siteIsLive = pu.UrlIsLive(url, timeOut);
    Assert.IsTrue(siteIsLive, "PingUtils.IsLive did not return true as expected");
}

/// <summary>
///A negative test for IsLive
///</summary>
[TestMethod()]
public void IsLive_PingBadUrl_ShouldReturnFalse()
{
    PingUtils pu = new PingUtils();
    string url = @"notDavidGiard.com";
    int timeOut = 1000;
    bool siteIsLive = pu.UrlIsLive(url, timeOut);
    Assert.IsFalse (siteIsLive, "PingUtils.IsLive did not return false as expected");
}

It’s worth pointing out a couple limitations of this function.

  • Some site’s reject all PING request as a way to protect themselves against Denial of Service attacks. For example, if you PING Microsoft.com, it will not Reply, even though the site does exist.
  • As with any program that uses networking, the internal firewall rules where the program runs may affect the success of the program.
  • The PING command checks for valid URLs, even if the URL returns an error page. So, foo.DavidGiard will reply to a PING request because my hosting provider redirects this to an error page.

Even given those limitations, this can be a very useful function for testing if all the Links stored in your database are still relevant.

You can download the code here.

Thursday, 03 September 2009 16:23:51 (GMT Daylight Time, UTC+01:00)
# Wednesday, 02 September 2009

Episode 47

Leon Gersing is a tall, heavy concoction of rubber with a surprising lightness of gait, especially in a dance.

He is also a Ruby developer and he loves it. In this interview, he shares why he prefers Ruby over Visual Basic and C# as a language to build his applications.

17 mins, 15 secs

Wednesday, 02 September 2009 13:01:55 (GMT Daylight Time, UTC+01:00)
# Tuesday, 01 September 2009

Just because I've resigned myself to the inevitability that I will never know everything about every technology, this does not excuse me from having to know a little about everything. As a consultant, I need to be aware of what is going on in the industry: I need speak intelligently about different products and I often have to make educated choices about available technologies.

This is why I'm an avid listener of tech podcast. The recent explosion of available podcasts has helped me stay aware of technology, and to do so in the limited time available to me.

Below is a list of the technology podcasts to which I currently subscribe. The list is presented in no particular order, but I recommend each one. If I don’t like a podcast, I've stopped listening to it and it doesn't appear in this list.

.Net Rocks
http://www.dotnetrocks.com/

This is the first podcast that I started listening to and it remains one of my favorites. Carl Franklin and Richard Campbell have been hosting this show for so long that they have access to almost anyone who does anything related to Microsoft development. The quality of their guests is top notch and I never miss an episode.

Hanselminutes
http://www.hanselminutes.com/

Scot Hanselman is probably my favorite interviewer among tech podcasters. When I do interviews for my show, my goal is to sound as much like Scot as possible. He draws out the guests because he either understands their topic in advance or he quickly grasps it. His humor is understated, which makes for an entertaining show and he has years of real-world experience, making his opinions relevant.

Deep Fried Bytes
http://deepfriedbytes.com/

I started listening to this show because I knew the hosts - Keith and Woody. I continue to listen because I like the content. This is a show that continually improves itself. It's been a couple months since their last episode, so I don't know if they are still committed to a regular schedule.

Polymorphic Podcast
http://polymorphicpodcast.com/

There are two things I really like about Craig Shoemaker's podcast: The guests tend to be those who don't appear on other podcasts; and Craig keeps the show to a reasonable length. The show always remains fresh for me.

Run As Radio
http://www.runasradio.com/

This podcast is a little outside my comfort zone because it focuses on networking and other IT topics, rather than on programming and architecture. But Richard Campbell and Greg Hughes work to keep it accessible, so I always learn something.

Feel the Func
http://feelthefunc.com/

This one is relatively new and I started listening to it right from the start. Mike Neel leads the discussion and does most of the talking. I don’t think they are doing a lot of editing, which means that you always hear the good parts and bad parts of each conversation.  I really enjoyed a recent show in which Mike interviewed Brian Prince and Jennifer Marsman.

SodThis
http://www.sodthis.com/podcast/

I had just about given up hope on this one. I loved the first 5 episodes that DevExpress evangelists Oliver Sturm and Gary Short put together. They combined interesting interviews with their own witty conversations. Then, after five episodes, SodThis disappeared into limbo. I assumed they had abandoned the project but they released Episode 6 yesterday.


Thirsty Developer
http://www.thirstydeveloper.com/

I just recently began to listen to The Thirsty Developer. It sound like many of the episodes were recorded in a busy Starbucks, which degrades the sound quality but creates a more relaxed atmosphere for the guests, so the conversation flows freely and enthusiastically. Larry Clarkin is the main guy, but he is sometimes assisted by Dave Bost.  They do a good job keeping conversations moving and engaging.

Alt.Net
http://altnetpodcast.com/

Technically I'm still subscribing to this podcast, but I don't know if there are any plans to resume it. I really liked the first few shows I heard, which focused on advanced .Net topics. But they haven't released an episode since April and the last two consisted largely of arguments about whether or not the Alt.Net community is still relevant. Maybe the silence answered that question.

Herding Code
http://herdingcode.com/

I've been listening to Herding Code since its first episode. Originally this was very different from most podcasts because they rarely had guests. Instead, the four hosts exchanged ideas with one another on a preselected topic. This format worked because John Galloway, Scott Koon, K. Scott Allen and Kevin Dente are engaging and articulate enough to keep bringing fresh ideas on each topic. Recently, they have switched to inviting more guests to the show.

Stack Overflow
http://blog.stackoverflow.com/category/podcasts/

This is another podcast that seldom relies on guests to interview. Instead, Jeff Atwood and Joel Spolsky chat (or spar) about a variety of topics. Again, this is a format that only works if the hosts are very clever and these two guys definitely are. Because Atwood is still in the process of building the popular StackOverflow web site, much of the conversation revolves around the challenges he faces.

So these are the podcasts that I listen to regularly. I can keep up because I have a long commute and I enjoy my IPod at the gym and while doing housework.  Having said that, I’d love to hear about high-quality technical podcasts that you can recommend.

Tuesday, 01 September 2009 13:13:34 (GMT Daylight Time, UTC+01:00)
# Monday, 31 August 2009
 #
 

Back To Basics

This series of articles provides an introduction to relational databases in general and Microsoft SQL Server in particular.

Part 1: What is a Database?

Part 2: Relationships

Part 3: Selecting data from a table

Part 4: Aggregating data

Part 5: Joins

Part 6: Inserts, Updates and Deletes

Monday, 31 August 2009 13:04:07 (GMT Daylight Time, UTC+01:00)