# Monday, 21 September 2009

Episode 52

Often, an application experiences a bottleneck retrieving and delivering data from a database. In this interfview, Jeremiah Peschka discusses ways to troubleshoot performance issues within a database.

Monday, 21 September 2009 12:29:45 (GMT Daylight Time, UTC+01:00)
# Sunday, 20 September 2009

I have been working for Sogeti for almost exactly a year now and I'm proud to announce that Microsoft has awarded our team the Partner of the Year award. Although the award goes to the entire unit, it was given for a SharePoint intranet portal produced for Oakland County and most of the work on that project was done by Mike Hacker.

Congratulations to Mike and to Sogeti on this prestigious award.

You can read more about this at http://us.sogeti.com/news/2009/08/31/sogeti-usa-wins-2009-microsoft-central-region-part/

Partner of the Year award

Sunday, 20 September 2009 01:37:30 (GMT Daylight Time, UTC+01:00)
# Wednesday, 16 September 2009

Episode 51

Chris Hay is a Scotsman living in Cambridge, England. He has made several trips this year to developer conferences in North America. In this interview, he discusses what goes into a good presentation and how developer communities in the UK differ from those on my side of the ocean.

Wednesday, 16 September 2009 12:55:17 (GMT Daylight Time, UTC+01:00)
# Tuesday, 15 September 2009

When I work on a project and I hear advice from others, I’m reminded of all the advice I heard the year my first son was born.  Often one recommendation would directly contradict another. They couldn't all be right, could they? In the end, I decided there are multiple correct ways to raise a child so I followed my own instincts each time I had to make a decision. 

Software design and development are full of decisions – some big and some small. We argue passionately over these decisions. We agonize over them, sometimes even after we make them.  Here are just a few examples

    • Web forms or MVC?
    • ASP.Net or Silverlight?
    • ADO.Net or ORM?
    • Web Services or Remoting?
    • Visual Basic or C#?
    • .Net or Java?
    • Comments evil or comments good?

But are these decisions worth agonizing over? In many cases, they are not.

In my professional life, I have argued vigorously many times for architectural points I believed were correct. Some choices were small and some were large. Sometimes I won and sometimes I lost these arguments. But I accepted those decisions because I recognize that there are multiple right answers to almost every question.  In almost every lost argument, the decision we settled on was good enough to get the job done.

I recognized that the important thing was to commit to a plan of action and move forward with it as a team.

Occasionally I’ve seen colleagues pout over a decision they did not buy into and use that decision as an excuse for failure. This is a self-fulfilling prophecy. A divided team is unlikely to succeed regardless how they design their project.

I am not trying to justify bad decisions. Some mistakes can be fatal and are inexcusable. These should be escalated up the command chain. But the vast majority of software project decisions are not life-threatening – even if they go against our thinking. We may grumble that our path is not optimal, but a decision that moves the project forward is acceptable.

There is very little dogma in software development. Your view works for you but it may not be best for the team or the project. And even if it is best, that doesn’t mean other views will not solve the same problem. Here are some guidelines that I use.

  • Time-box your decisions.  Commit to a decision by a certain date.
  • Don’t feel the need to explore every alternative. Generally speaking, time will not permit this.
  • Pick a good solution that meets your needs. Don’t be swayed by those who insist it is not the absolute best. It’s better to move forward with a workable solution than to delay a project indefinitely in search of the best solution.
  • Debate openly and honestly. Be respectful but recognize the pros and cons of each alternative.
  • Don’t make it personal. Just because someone disagrees with you doesn’t mean he is attacking your intelligence or integrity.
  • Keep an open mind. Consider that there may be an alternative solution with advantages you have not considered.
  • What worked on another project might not be appropriate for this project. Always consider decisions in the context of your current needs.

The overarching theme of this list is you should find a solution that works for your problem and move on, without wasting excessive time doing so.

And for the record, my newborn son is not 18 years old and had turned out better than I ever hoped.

Tuesday, 15 September 2009 16:36:55 (GMT Daylight Time, UTC+01:00)
# Monday, 14 September 2009

Episode 50

In this interview, Nathan Blevins describes how to program Microsoft Robotics Studio to control robots via programs written in Visual Studio.

Monday, 14 September 2009 13:29:21 (GMT Daylight Time, UTC+01:00)
# Sunday, 13 September 2009

Back To Basics

The yield return and yield break keywords are shortcuts introduced in C# 3.0. They are designed to assist you in a method that returns IEnumerable <T>.
Often such methods consist of the following steps

  1. Create an empty IEnumerable set.
  2. Loop through some data (via a while, foreach or other construct)
  3. Add to the set within your loop.
  4. Exit the loop when some limit is reached.
  5. Return the set.

A sample of such code is shown below.

public IEnumerable<Int32> GetOddNumbers_Old(Int32 maxNumber)
{
    List<Int32> oddSet = new List<Int32>();
    int num = 0;
    while (true)
    {
        System.Threading.Thread.Sleep(1000);
        num++;
        if (num % 2 == 1)
        {
            oddSet.Add (num);
        }
        if (num >= maxNumber)
        {
            break;
        }
    }

    return oddSet;
}

The new yield keywords allow you to shorten your code to only the following steps

  1. Loop through some data
  2. yield return within the loop
  3. yield break if a limit is reached before the loop is complete

That’s it. There is no need to explicitly create or return your IEnumerable set.

The yield return statement appends a value to the IEnumerable set. The yield break statement exits any looping construct to prevent more items being added to the return set. If you omit yield break, the loop exits as it normally would.

The difference between using the yield return and simply returning a set is subtle. Returning a set at the end of the method returns the entire set at once. The client must wait until the method is complete before it can use any values in the return set. Each time the yield return statement executes, the client has access to another element in the set. Essentially the set trickles back a little at a time. This can provide a gain in performance or perceived performance if you have a large set to return.

Here is a sample that returns the same results as above, using yield return and yield break.

public IEnumerable<Int32> GetOddNumbers_Yield(Int32 maxNumber)
{
    int num = 0;
    while (true)
    {
System.Threading.Thread.Sleep(1000); num++; if (num % 2 == 1) { yield return num; } if (num >= maxNumber) { yield break; } } }

If we call the two methods above, we will get the same results but they will return in slightly different ways. I added the System.Threading.Thread.Sleep(1000); line to help demonstrate this. That line simply pauses execution for 1 second each time the loop executes.

Assume the above two methods are in a class named MyMethods.  The following code will call each.

Console.WriteLine("Get Odd Numbers using old way:");
MyMethods mm = new MyMethods();
IEnumerable<Int32> oddNumbers2 = mm.GetOddNumbers_Old(11);
foreach (Int32 n in oddNumbers2)
{
    Console.WriteLine(n);
}

Console.WriteLine();


Console.WriteLine("Get Odd Numbers using new YIELD keyword:");
IEnumerable<Int32> oddNumbers1 = mm.GetOddNumbers_Old(11);
foreach (Int32 n in oddNumbers1)
{
    Console.WriteLine(n);
}

Console.ReadLine();

The above code produces the following output

Get Odd Numbers using old way:
1
3
5
7
9
11

Get Odd Numbers using new YIELD keyword:
1
3
5
7
9
11

Notice that both methods return the same data. However, if you watch the code as it runs, you will notice the first method waits 12 seconds, then immediately outputs all odd numbers; while the second method outputs a number every 2 seconds. Each method returns the same values and each takes the same amount of time, but the second method uses yield return, so the client is able to output a bit of data each time a yield return executes.

There are a few restrictions to using the yield keywords

  • These keywords cannot appear in blocks marked "unsafe"
  • These keywords cannot appear in a method with ref or out parameters
  • The yield return statement is not allowed inside a try-catch block, although it may be located inside a try-finally block.
  • A yield break statement may not be located inside a finally block.

You can download this sample code at DemoYield.zip (45.06 KB)


Mike Wood contributed to this article.

Sunday, 13 September 2009 14:44:07 (GMT Daylight Time, UTC+01:00)
# 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)