Thursday, May 28, 2009

The Dynamic Type and Runtime Overload Resolution

I've written about the upcoming dynamic keyword in C# a little bit already, but did you know that the dynamic type enables you to perform runtime resolution of method overloads?

In the past, the specific overload of a method to be called was statically defined at compile time within a generic method, and the least specific overload was selected as the method to be called at runtime. This all happened at compile time. Take the following example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
DoSomethingGeneric("Howdy!");
DoSomethingGeneric(1);
}

static void DoSomethingGeneric<T>(T value)
{
DoSomething(value);
}

static void DoSomething(object value)
{
Console.WriteLine("Object! {0}", value.GetType());
}

static void DoSomething(int value)
{
Console.WriteLine("Int!");
}

static void DoSomething(string value)
{
Console.WriteLine("String!");
}
}
}


The output of this method is the following:

Object! System.String
Object! System.Int32

Notice that regardless of the type you send in to DoSomethingGeneric, it's the object version that gets called. This is because there is no way for the C# 3.0 compiler to determine that the intention of the user is to call the integer or string versions of the overload at compile time, so the compiler opts for the most non-specific version of the overload, the object version, and compiles the call to the object version into the IL of the method.

This all changes now with the dynamic type. The above code will still work the same, but take the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
DoSomethingDynamic("Howdy!");
DoSomethingDynamic(1);
DoSomethingDynamic(DateTime.Now);
}

static void DoSomethingDynamic(dynamic value)
{
DoSomething(value);
}

static void DoSomething(object value)
{
Console.WriteLine("Object! {0}", value.GetType());
}

static void DoSomething(int value)
{
Console.WriteLine("Int!");
}

static void DoSomething(string value)
{
Console.WriteLine("String!");
}
}
}


This is a bit different. The output of this code is the following:

String!
Int!
Object! System.DateTime

So the dynamic type can help in runtime method overload resolution!

That being said, there is a slight performance penalty to using the dynamic object, but it wasn't quite as much as I expected. Here's the code I used to test the performance. Just for kicks, I threw in a reflection version as well, to see how fast that one returned...


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
// performance tests.
Console.Write("Milliseconds to complete one million iterations of the generic method: ");
Test(() => DoSomethingGeneric("Howdy"), 10000000);
Console.Write("Milliseconds to complete one million iterations of the dynamic method: ");
Test(() => DoSomethingDynamic("Howdy"), 10000000);
Console.Write("Milliseconds to complete one million iterations of the reflection method: ");
Test(() => DoSomethingReflective("Howdy"), 10000000);
}

static void Test(Action action, int iterations)
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
action();
Console.WriteLine(sw.ElapsedMilliseconds);
}

static void DoSomethingGeneric<T>(T value)
{
DoSomething(value);
}

static void DoSomethingDynamic(dynamic value)
{
DoSomething(value);
}

static void DoSomethingReflective<T>(T value)
{
MethodInfo info = typeof(Program).GetMethod("DoSomething", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(T) }, null);
if (info == null)
DoSomething(value);
else
info.Invoke(null, new object[] { value });
}

static void DoSomething(object value) { }

static void DoSomething(int value) { }

static void DoSomething(string value) { }
}
}


The output I got from this is the following:

Milliseconds to complete one million iterations of the generic method: 136
Milliseconds to complete one million iterations of the dynamic method: 2589
Milliseconds to complete one million iterations of the reflection method: 102552

Needless to say, dynamic is much faster than reflection, though slightly slower than the generic version... which doesn't call the proper overload anyways.

The Future Of WinForms... What's changed in 2010? (Thanks, NDepend!)

What follows is a review of NDepend via an analysis of the changes between .NET 2.0 and 4.0 for the System.Windows.Forms.dll.

A question came up on the Forums earlier today asking about the future of WinForms. There are some people who have been thinking that the WinForms project has been completely abandoned at Microsoft. Well, according to NDepend, There are the following changes between .NET 4.0 and .NET 2.0 as it applies to System.Windows.Forms.dll:

213 types were changed, and 9 types were added.
596 methods were changed, 50 were added, and 8 were removed.

How did I get this info? First, get a copy of Patrick Smacchia's NDepend program. Next, after installing and starting up, of course, remove the .NET folders from the list of default folders listed in the program. Do this by going to Project Properties -> Code To Analyze, and clicking the "View Folders" button...



After opening the list of folders, remove all of the listed folders.

Next, click the Browse button to browse to the location of the System.Windows.Forms.dll assembly, which is located, at least on my machine, at C:\windows\assembly\gac_msil\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll. To trick the OpenFileDialog, I had to paste this directly into the file textbox on the dialog.

Then run an analysis. (Oh that magical moment...)

Immediately after running the analysis of .NET 2.0 System.Windows.Forms.dll, change the project properties, and removed the 2.0 version of the assembly from the list, and add the 4.0 version, which was located, on my machine, at C:\windows\assembly\gac_msil\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll.

Run another analysis. (Can you feel the joy?)

Once that's completed, on the Compare ribbon, click the Build Comparison button. This is what should show up...



Select the build date on the Older Build, the first analysis you performed, and leave the Newer Build's date the same. Completing it all, click OK, and then open the Compare ribbon again. This is where it starts to get cool...

Click the "Search Change" button, and you'll be greeted with something like this:



Using the buttons listed at the top, you'll easily be able to analyze the code to see what's been added, removed or changed since the last build. As you can see, there are 9 types listed as having had been added. So, it doesn't look as though there've been a ton of changes done, but there have been some.

After performing this exercise, I got to thinking.... How can I use this in my own projects?

The comparison feature within NDepend is the best code-comparison feature I've seen so far. It's quick, simple, and enables me to give hard metrics regarding the changes between builds, and analyze the additions, changes and removals of methods and types. If you keep (rebase) the previous versions of the files in a separate location, you can even compare the source files. Being able to see the changes between builds is a very powerful mechanism especially when working in a team environment, where changes need to be monitored, and complexity needs to be managed. When a new bug is introduced, it's nice to not have to use TFS History lists to hunt down the code that's changed, but rather to simply view what's changed since a particular date and time.

One important thing to note about the product, is that you're going to get the best use of NDepend when you use it every day. Code can change pretty quickly, especially in teams, and NDepend (nor any tool for that matter) has the ability to detect whether a change happened last week or two weeks ago, if the only reference points it's given are from today and sometime last month. If you really want to reap the power of the application, use it daily.

I could go on about what's great about this product, but there are several other people who have written excellent reviews. Just search "review of NDepend" on Google. You'll see several examples of the (extremely unique) Metric view, as well as the very concise CQL Query language, which allows you to select certain combinations of code metrics to use in your project.

NDepend is a very powerful tool aimed at developers who want to do more than "get it done" when it comes to their work, and are truly aiming at excellence in their design and implementation details. I encourage you to check it out.

All that said, I'll leave you with an image of the System.Windows.Forms.dll as represented in the Metric view, organized by IL Cyclomatic Complexity.

Friday, May 22, 2009

A Beginner's Guide To DateTime and Formatting

One of the most frequently asked questions on the MSDN Forums has to do with the DateTime class, specifically formatting and persisting to a database.

Questions typically look like these:

"When I store the data in the database, it only has the date, but when I pull it out into my code, it has the time. How do I keep just the date and not the time?"

"I've tried setting the format of a date to a particular date string, but when I look at it in the debugger, nothing has changed!"

"I want to store the DateTime as 2009.05.06.01.13.13 but the database is always storing it as 06/05/2009 1:13:13 PM format. How do I change this?"

"I've used DateTime.Parse to get a DateTime object, but as soon as I do, the format of the DateTime seems to change. How can I keep it from changing?"

"I have a property that's a DateTime, and so my users have to enter their date in the format MM/dd/yyyy hh:mm:ss tt in order for the computer to recognize it, but I only want them to have to enter the hours and minutes. What should I do?"

This post aims at addressing these questions and clearing up some confusion about the DateTime class. While reading this, I want you to keep this simple fact in mind:

The DateTime instance is different from, and separated from, it's representation in text.

The DateTime Class

First, it's important to know the difference between the DateTime class and the string class. The DateTime class stores all the information necessary to represent a moment in time. It will always store the following information: the year, the month, the day, the hour, the minute, the second, the milliseconds, and the kind of date and time this is (UTC, Local or Unspecified). Let me repeat, it will always store this information, and there's no way of getting around this. In other words, if you're just trying to represent the date in a DateTime, you're going to have to recognize that the time is also carried with the instance of the DateTime class. You can ignore the time portion, and you can format the date so it doesn't appear, but it's still lurking there in the background, and it will always be there. There's no way to get rid of it. That being said, you can still display the DateTime to the user in a particular format so as to not show the portions of the date and time that you want to ignore. This is where formatting comes into play.

When it comes to formatting, it's important to recognize the difference between the DateTime and how it is represented. The DateTime instance will never store the date as text, it stores it as a series of numbers instead, and provides you methods to output the DateTime as text. The way that the date appears when you print it out is dependent upon either the culture's preferred display format, or a specific format which can be passed into the ToString method on the DateTime.

Now, remember, just because you pass a format string into the DateTime's ToString method, this doesn't mean that the DateTime is going to remember the format string you passed in, and use it again and again. It doesn't. You're going to have to tell the computer what format you want the date printed in each time you output the Date. There are two ways to do this:

1. Using the fields in the DateTimeFormatInfo class that is stored in the CultureInfo.CurrentCulture as the DateTimeFormat property.

The information at CultureInfo.CurrentCulture.DateTimeFormat specifies the default way that the DateTime will be represented when printed or shown in the debugger. Here are a few examples:

Culture: English (United States) Date: 5/22/2009 8:52:08 AM
Culture: English (United Kingdom) Date: 22/05/2009 08:52:08
Culture: French (France) Date: 22/05/2009 08:52:08
Culture: Spanish (Mexico) Date: 22/05/2009 08:52:08 a.m.
Culture: German (Germany) Date: 22.05.2009 08:52:08

Now, note that the DateTime object is the same for all of these, but what's changed is how I've formatted them. I used this code to get the above result.:


using System;
using System.Linq;
using System.Globalization;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] cultures = { "en-US", "en-GB", "fr-FR", "es-MX", "de-DE" };
DateTime dt = DateTime.Now;
cultures.ToList().ForEach(c => PrintDate(dt, c));
}

static void PrintDate(DateTime dt, string culture)
{
CultureInfo c = CultureInfo.GetCultureInfo(culture);
Console.WriteLine("Culture: {0} Date: {1}", c.DisplayName, dt.ToString(c));
}
}
}


Now, on my machine, if I put a breakpoint on the second line of the PrintDate method, and I hover over "dt", the tooltip that pops up looks like this:

{05/22/2009 08:52:08 AM}

This is because I live in the United States, and I have my computer set to use the culture en-US. How it shows up in the debugger is how I have my computer set up. If I set the culture to en-GB, it would show up differently. The way the DateTime is displayed by default is dependent upon a combination of the current thread's CultureInfo.DateTimeFormat's ShortDatePattern and LongTimePattern. I can set this explicitly using the following code. Notice I set the new ShortDatePattern to "MM.dd.yyyy" instead of "MM/dd/yyyy", which is the default for en-US.


using System;
using System.Globalization;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CultureInfo info = (CultureInfo)CultureInfo.CurrentCulture.Clone();
info.DateTimeFormat.ShortDatePattern = "MM.dd.yyyy";
Thread.CurrentThread.CurrentCulture = info;
Console.WriteLine(DateTime.Now);
}
}
}


In my culture, this will print out "05.22.2009 08:52:08 AM", and if I add a breakpoint on the line where I'm writing to the console, and I hover over "Now", I'll see the following:

{05.22.2009 08:52:08 AM}

This is because I've changed the ShortDatePattern on the current thread's CultureInfo.DateTimeFormat.

The key to remember here is that the DateTime is still the same, it's just shown differently.

Explicit DateTime Formatting

Now, I can always explicitly set the format for the DateTime. I would go over this in detail here, but MSDN has two great pages on how to do this:

Standard Date and Time Format Strings
Custom Date and Time Format Strings

These two pages show pretty explicitly how to use formatting strings for the DateTime. I encourage you to review them and know them well.

Parsing Dates

What if you have a string, and you need to get a DateTime instead?

Well, which method you use depends on what culture you're in, and how the string is going to be represented. There are two methods (actually four, with "Try" equivalents for each) to parse a string to a DateTime. These are "Parse" and "ParseExact". The only difference between the two are that the former will attempt to create a DateTime from a string using the default culture of the process, while the latter will parse exactly as you specify. I'll focus on ParseExact here.

Let's say I have a string that looks like this: "10/21/2008", and I want to get a DateTime object that represents this date. In order to do this, I'd have to use ParseExact to parse the text out, and the code I would use would look like this:


string text = "10/21/2008";
DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy", CultureInfo.InvariantCulture);


Now, if you've been following along, and you visited the link on Custom Format Strings, you'll find that the format string I passed in as the second parameter matches the date string that is passed in as the first parameter. The resulting DateTime will actually be October 21, 2008 at midnight. Now, why is it set at midnight? Remember, the DateTime object is always going to contain all of the time information down to the 10,000th of a millisecond, regardless of how it was constructed. There's no way I can eliminate that information from the DateTime object. In fact, even the Date property of the DateTime object simply does nothing but reset the time portion to midnight and return. The point is, the time is always there.

Also, you may notice that using DateTime.ParseExact doesn't make the DateTime object appear in the same format in Intellisense. This is because the DateTime object doesn't actually store the format information, as I had said earlier in the post. It stores only the information needed to represent the time, not the format info. The way it appears in Intellisense is dependent upon the settings in the thread's CultureInfo.DateTimeFormat property.

So when do you use Parse, and when do you use ParseExact?

Typically, if I know the format is always going to be in a specific format, regardless of culture, I'll use ParseExact, as it provides me with a more granular level of control. If I need to parse user input, however, I might use Parse, or TryParse to validate the user input, as the user is going to be most likely to enter the date in a format familiar to themselves. Also, if I'm reading data from a source that has dates in a textual format, and the source is culture-sensitive, I might use Parse instead of ParseExact, trusting that the cultural context under which my application runs is the same as the cultural context of the application I'm interfacing with.

Also, in some situations, I want my user to be able to enter only a portion of the DateTime in a specific user control, and I want them to be able to enter it in a specific format. In those situations, I ought to use ParseExact. For example, if I have a TextBox where a user is supposed to enter their time in the "HH:mm" format, I could validate their input, and retrieve a DateTime that would have the proper time in it like this (remember to always validate your input before running code such as the code below):


// textBox1.Text is set to "12:30"
DateTime dt = DateTime.ParseExact(textBox1.Text, "HH:mm", CultureInfo.InvariantCulture);


Now, because the above code doesn't specify the date, the ParseExact method is going to use today's date by default. This is just a small gotcha, but it's worth being aware of.

So, to sum it up, there's no way to convert a string to a DateTime. Instead, you have to create a new DateTime based on the information contained in the string, by using the DateTime.Parse, DateTime.ParseExact, DateTime.TryParse, or DateTime.TryParseExact methods.

Conclusion

The aim of this post is to simply give you a broad overview of the difference between a DateTime and it's textual representation, as well as giving you some general understanding of how to get a textual representation from a DateTime object, and how to get a DateTime object from a textual representation of a date. If there's one thing I want you to remember from this post, it's this... a DateTime instance is a different thing than the way looks in text.

It's my intention to make this post a growing document, and I plan on changing it several times to encompass more information. Feel free to add a comment or contact me through email if you have any suggestions.

Happy coding!

Patrick Smacchia's Analysis of .NET 4.0

Patrick Smacchia, author of the excellent code analysis tool, NDepend, has put up an analysis of the .NET 4.0 Framework. Quite frankly, he beat me to it. :) I've been using his tool for a while, and I absolutely love it. Expect a review soon.

Anyways, for right now, check out the blog post. I think you'll find it very interesting!

Wednesday, May 20, 2009

Introducing System.Dynamic.ExpandoObject...

By now, those of you who have been using VS 2010 have probably noticed that you can't simply call "new dynamic()" anywhere. Why not?

The dynamic type is designed to rest upon another type. It depends on it's underlying type for member resolution, which is why the C# new features document constantly uses a fictional method "GetDynamicObject" within it's description of the dynamic type. It seems that whatever is returned from that method is what will decide which members are available.

It's almost like dynamic is nothing but a way to call members without casting to a particular type. This is great and all, but what if I want to add members?

Enter the ExpandoObject, which probably has the best name of any class in the entire framework. What does it do?

Intellisense says of the ExpandoObject:

Represents an object with members that can be dynamically added.


That's a wonderful description, and perfectly correct.

So how can this be used? Check out the following code:


dynamic x = new ExpandoObject();
x.SomeText = "This is some text";
x.Value = 30;
x.Run = new Action(() => Console.WriteLine("Running a recently added method!"));
Console.WriteLine(x.SomeText);
Console.WriteLine(x.Value);
x.Run();


Pretty cool, huh?

Keep in mind that the summary for the parameterless (the only) constructor for ExpandoObject, according to Intellisense, is the following:

Creates a new ExpandoObject without members.


Without members? I just added two! Nice addition to the language indeed!

Another cool thing you can do with ExpandoObject is prevent closures when defining the methods. This, in my opinion, makes for a very... well... dynamic object. Check out the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
dynamic x = new ExpandoObject();
x.Value = 30;
x.ShowValue = new Action(() => Console.WriteLine(x.Value));
ProcessDynamic(x);
}
static void ProcessDynamic(dynamic d)
{
d.Value = 2;
d.ShowValue();
}
}
}


What do you think this code will produce? At first glance, I figured that it would print out "30" because it would have closed over the actual value in x.Value, but it doesn't. Instead, it keeps a reference to the variable, even when passing into another scope, such as when "x" goes out of scope, and into the other method, called ProcessDynamic. The output is 2.

I'm so glad to see this added to the .NET Framework! Use it. Don't abuse it.

C# 4.0 Dynamic Type... Something useful.

Here's something that's been on my wishlist for quite some time. I've always hated the fact that my anonymous types can't be used outside of their method scope. If I create an IEnumerable of anonymous type variables, and I want to use them outside of their created domain, I previously had very few options:

1. Give up the anonymous type and write a class to hold the data.
2. Use reflection. This works, but it's a little slow.
3. Use an Expression Tree. This also works, but creating an Expression tree can be a tedious and difficult process.

Now, in C# 4.0 with the dynamic type, I can finally call properties on my anonymous types outside of their scope. Consider the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
foreach (dynamic d in GetValues())
Console.WriteLine("{0} is {1} years old", d.Name, d.Age);
}

static IEnumerable<dynamic> GetValues()
{
Dictionary<string, int> result = new Dictionary<string, int>();
result["David"] = 30;
result["Jennifer"] = 25;
foreach (var item in result)
yield return new { Name = item.Key, Age = item.Value };
}
}
}


Now, what this code does, is yields an IEnumerable of anonymous types, which are then used outside the method scope in the Main method -- a feat only accomplished through the use of the dynamic type.

While this is convenient, there are a couple of things to keep in mind:

1. This is still going to have the same major drawback of either reflection or expression trees. Though it looks strongly typed, it's not. If I change Name to FirstName, for example, my code would still compile, but I'd get a runtime error when I tried to run the application.
2. I get no Intellisense for dynamic types. Typically, this means I should only use the keyword in situations where I'm coding close to the type declaration.

That being said, this is still a wonderful new feature, and I'm looking forward to exploring more over the next years.

Wednesday, May 13, 2009

Houston F# Users Group May Meeting

The first Houston F# Users Group meeting was a success! So we're going to have another one, and try to keep to the original schedule.

Here's the info:

Here's the info:

Date: May 26, 2009
Time: 7:00-8:30 PM.
Place: Microsoft Houston Office
Address: 2000 Sam Houston Tollway S #350
City: Houston
State: Texas
Zip: 77042

As always, feel free to contact me directly, or email houston.fsharp@gmail.com if you have any questions.

Saturday, May 9, 2009

Axum Hello World

So, I'm no Axum expert, but I feel like one today. I just wrote an incredible little application that says Hi to me. I think I can quit for the day. I have succeeded. I feel accomplished.



using System;
using System.Concurrency;
using Microsoft.Axum;

namespace HelloWorld
{
public domain Program
{
private writer agent MainAgent : channel Microsoft.Axum.Application
{
public MainAgent()
{
String [] args = receive(PrimaryChannel::CommandLine);

var hello = AgentHello.CreateInNewDomain();

hello::Name <-- "David";
var msg = receive(hello::Message);

Console.WriteLine(msg);
Console.ReadLine();
// TODO: Add work of the agent here.

PrimaryChannel::Done <-- Signal.Value;
}

}

channel ChannelHello
{
input string Name;
output string Message;

Start: { Name -> S1; }
S1: { Message -> End; }
}

agent AgentHello : channel ChannelHello
{
public AgentHello()
{
var name = receive(Name);
var message = "Hello " + name;
Message <-- message;

}
}
}
}

Axum CTP Released

For those of you who are interested in concurrency and parallelization, there's a new language in development called Axum, and the CTP has been released as of yesterday. Go check it out. We're going to start being expected to write more performant apps here very shortly, and there are people working very hard to ensure that writing concurrent applications is made simple for those of us who are not multithreading/multi-coring gurus. You owe it to yourself to at least know a bit about the subject, because your competitors probably will.

Have fun!

Wednesday, May 6, 2009

Windows 7 on the Eee PC 1000HE (Best Buy)

Well, I couldn't wait any longer. I installed Windows 7 on my Eee PC (1000HE, the Best Buy version) just yesterday, and I have to say, it works incredibly well. I believe my favorite overall feature has to be the fact that I can re-organize the items on the task bar, and simply slide them to the left or the right of other programs. This has been a common source of frustration for me in the past, as I've usually ended up closing down and opening programs just to get them in the right order (I always like Visual Studio on the far left.)

The installation experience was very smooth. One new feature of the installation, if you have the disk space, is the ability to back up your entire Windows folder while installing, thus saving yourself the paranoia of losing some important file that's hidden away in some obscure hidden directory under your home directory. That's worth alot to me, and I wish I had known that before I spent an hour backing everything up.

I also have Visual Studio Shell installed with F#, as well as Visual C# Express, Visual C++ Express, and Visual Web Developer installed. I opted to go with the Express versions mainly because in the past, they've tended to have less baggage than the full versions, and they run more swiftly. Nevertheless, the VS Shell with F# works just fine as far as I can tell. Here's a screenshot that simultaneously shows you the desktop and my solution to Euler problem 16:



The compilation times are a slight bit slower than a standard laptop, but still nothing to sneeze at, considering this is a box that is solely meant to "check email".

I downloaded the drivers referred to in this thread and managed to even get the Super Hybrid Engine working. The catch was the installation however, I had to set the compatibility mode of the installation package to Windows XP SP3, and then find the executables after install, to undo the compatibility mode from the actual application, otherwise, every time I would click Fn+Space, I would receive an error saying "Asus SHE not exist". After removing compatibility mode from the Super Hybrid Engine executable, it seemed to work just fine.

Another thing to note is that it seems that there are no video drivers out right now that would allow for either 1024x768 or 1024x768 compressed mode to work properly with Windows 7, so for now, I'm stuck with 1024x600.

One last thing, I've actually added the extra 1 gig of memory onto the system to bring my total memory up to 2 gb. I'm not sure what would happen if you tried to install this on a machine with only one gig of memory. It may do fine, or it may choke, but either way, I'd suggest upgrading.

All that to say, I am very impressed with the speed and smoothness of how Windows 7 performs on the EeePC. I'm looking forward to purchasing the full retail version the moment it comes out.

UPDATE (11/8/09)

Over the past few weeks, ASUS has released an entire set of Windows 7 drivers and utilities for the 1000HE. I've installed them all, and they work wonderfully. I would strongly suggest updating your BIOS and installing the drivers from the ASUS site for best compatibility with Windows 7.

I've also begun using ReadyBoost with a 4GB Class 4 SD Card. This is also strongly recommended. I find that I can actually run a couple of instances of Visual Studio without any problem at all if I use the SD card solution.

Monday, May 4, 2009

LINQ's OfType and Inheritance

Just in case you were wondering, the generic type argument passed into the LINQ method "OfType<T>" filters the list to only objects that are, or inherit from a specific type, that is, it will also return instances of objects that inherit from the specified type. The following code gives an example:


public class Thing 
{
public override string ToString()
{
return "I'm a CompanyBase";
}
}

public class Widget : Thing
{
public override string ToString()
{
return "I'm a WidgetBase";
}
}

public class FooWidget : Widget
{
public override string ToString()
{
return "I'm a FooWidget";
}
}

public class BarWidget : Widget
{
public override string ToString()
{
return "I'm a BarWidget";
}
}


public class Gadget : Thing
{
public override string ToString()
{
return "I'm a Gadget!";
}
}

class Program
{
static void Main(string[] args)
{
List<Thing> items = new List<Thing>();
items.Add(new Gadget());
items.Add(new Thing());
items.Add(new Widget());
items.Add(new FooWidget());
items.Add(new BarWidget());

var widgets = items.OfType<Widget>();

foreach (var item in widgets)
Console.WriteLine(item);
Console.ReadLine();
}
}

Saturday, May 2, 2009

On XML Document Type Declarations

Document Type Declarations (DTD) are declarations that can be placed at the top of your custom XML file that can aid in creating XML files using a specific XML Layout. Think of it as a smaller, embedded version of the XSD file. The method XmlDocument.GetElementByIddoesn't work without a DTD declaration on the XML file to specify which attribute of an XML Element is the "ID" element of an XML file. For starters, let's take a look at the following XML file:


<?xml version="1.0" encoding="utf-8" ?>
<widgets>
<widget id="one">One</widget>
<widget id="two">Two</widget>
<widget id="three">Three</widget>
</widgets>


Now, this XML File obviously represents a series of widgets. I might think that I can easily access a particular widget within the XML file using the GetElementById method simply by calling the following code:


string location = Assembly.GetExecutingAssembly().Location;
string directory = Path.GetDirectoryName(location);
string filename = Path.Combine(directory, "XMLFile1.XML");
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlElement element = doc.GetElementById("two");
Console.WriteLine(element.InnerText);
Console.ReadLine();


If all goes well, I should see "Two" printed out on the screen, correct? No.

Just because I have an attribute on each widget called "id" doesn't necessarily mean that this attribute is considered to be the actual ID of a widget. If I run this code using the XML file as it's listed above, I'll get a NullReferenceException stating that the XmlElement is null, this is because the GetElementById method uses the ID as specified in the DTD declaration for the XML file, and I have no such declaration. Without going into an immense amount of details (you can find more details on DTD Declarations here), I'll need to add a DTD to my XML file in order to find the proper XML Element I want to return. Adding the declaration would produce the following XML file:


<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE widgets [
<!ELEMENT widgets (widget)*>
<!ELEMENT widget (#PCDATA)>
<!ATTLIST widget id ID #IMPLIED >
]>
<widgets>
<widget id="one">One</widget>
<widget id="two">Two</widget>
<widget id="three">Three</widget>
</widgets>


This declaration, located at the top of the file, just under the XML Header, specifies a few things:

1. The DocType is called "widgets" and the root of the document should be called "widgets".
2. The "widgets" element should have zero or more elements beneath it called "widget".
3. Each "widget" element can have data within it.
4. The ID of each "widget" element is an attribute called "id", and the attribute is not required.

Changing the XML file to this new format, and then rerunning our code produces the proper output, and "Two" is displayed on the screen.

Friday, May 1, 2009

Anonymous Type Acrobatics

In C# 3.0, the idea of the anonymous type was introduced. Basically, this allows you to create a type, at compile time, that is both strongly-typed, but has no actual "name" within the code. This can be extremely useful when trying to whittle down a set of objects that you might want to bind to some kind of tabular databound control, such as a DataGridView in WinForms or GridView in ASP.NET.

If you're familiar with Linq, you're familiar with the concept, so you know that it's possible to set the DataSource of some databound controls to the result of a Linq query that produces anonymous types, but did you know that you can actually reuse a list of anonymous types generated from a Linq query in order to sort or perform some other action? Enter the System.Expressions namespace. Within the System.Expressions namespace are a series of classes that allow you to dynamically generate lambdas and methods on the fly, and it's surprisingly fast (tests show that Expressions, when used properly, run faster than reflection.)

This can be very useful in several situations. What if we don't want to fetch data from the database a second time, for performance reasons, but we still want the same columns returned back from the first Linq query that generated an IEnumerable of anonymous types? Using Expressions, we can sort this data. The following code gives a good example of how to do this. It's an extension method, and sorts the anonymous type by the property named in the sortProperty string. I've added comments where I've need to in order to explain what each Expression would look like in code. You'll notice that a series of tokens are built one after another and are built upon each other, until the entire lambda is built. At that point, we compile the lambda, and invoke it dynamically, passing in an IEnumerable. Make sure to have a "using System.Linq.Expressions;" at the top of your code file.


public static class EnumerableExtensions
{
public static IEnumerable Sort(this IEnumerable _this, string sortProperty)
{
// get the generic type argument of the enumerable.
Type t = _this.AsQueryable().GetType().GetGenericArguments()[0];

// Create a parameter that has the type of the query expression or IEnumerable
// {x}
ParameterExpression xParameter = Expression.Parameter(_this.GetType(), "x");

// Create a parameter called "person" of type "t" from above:
// {person}
ParameterExpression personParameter = Expression.Parameter(t, "person");

// Create an expression to access the member:
// {person.LastName}
MemberExpression prop = Expression.Property(personParameter, sortProperty);

// Join the parameter expression and the person in a lambda:
// {person => person.LastName}
Expression sort = Expression.Lambda(prop, personParameter);

// Call OrderBy on the result and use the lambda from above:
// {x.OrderBy(person => person.LastName)}
Expression orderByCall = Expression.Call(typeof(Enumerable), "OrderBy", sort.Type.GetGenericArguments(), xParameter, sort);

// Call .ToList on the result of that, to immediately execute the query:
// {x.OrderBy(person => person.LastName).ToList()}
Expression toListCall = Expression.Call(typeof(Enumerable), "ToList", orderByCall.Type.GetGenericArguments(), orderByCall);

// Create a new lambda expression:
// {x => x.OrderBy(person => person.LastName).ToList()}
LambdaExpression lambda = Expression.Lambda(toListCall, xParameter);

// Compile and invoke the method. Returns List<T>.
IEnumerable bindingobject = (IEnumerable)lambda.Compile().DynamicInvoke(_this);

return bindingobject;
}
}