Mad Props!

Omniscience is just a Google-search away.

Login

You're reading Mabsterama, the weblog of Matt Hamilton. Enjoy your stay.

Type Aliases in C#

Under the category of "you learn something new every day": While watching dnrTV this morning, I saw something that I've never seen done in C# before.

I knew that it was possible to make an "alias" for a namespace in C#. For example, if you have a complex namespace like MadProps.Windows.Controls (a contrived example) that you don't want to add to your "using" list, but you don't want to have to retype every time, you can use code like this to "alias" it:

using MPControls = MadProps.Windows.Controls;

That means that instead of typing "MadProps.Windows.Controls.TextBox" all through your code, you can just type "MPControls.TextBox". Nice.

What I learned this morning, however, is that you can do the same thing with types! If you have a type name that's really complex (think generic types) you can create an alias for them, too!

using MyDict = System.Collections.Generic.Dictionary<int, MyLongClassName>;

Now I can just declare a variable as type "MyDict" in code instead of retyping the full dictionary definition!

Granted the uses are limited. Unless it's a particularly nasty type name I think your code readability would be best served by avoiding these sorts of aliases. However, it's great to know that the feature exists.

Faking Immutability with Extension Methods

I've been reading Eric Lippert's series on immutable collections (start here with part one) over on his blog, Fabulous Adventures in Coding. I don't understand everything he writes, but it's still a fascinating read.

This morning on my commute I was wondering whether it would be possible to "fake" immutability in an existing list class by adding a "With" and "Without" method. The idea would be to ask for a new list which is the same as the original list but "with" a particular item, or to ask for a new list the same as the original "without" one of its items.

Here's some code to illustrate what I mean:

List<int> nums = new List<int>() { 1, 2, 3, 4, 5 };
foreach (int i in nums.With(6))
{ 
    Console.WriteLine(i);
}

foreach (int i in nums.Without(3))
{ 
    Console.WriteLine(i); 
}

 

The idea is that the two "foreach" loops are acting on a completely separate object to the original "nums" list. Calling "With" and "Without" constructs a new list rather than modifying the original.

As it turns out this sort of thing is pretty easy to do with extension methods, and I even found a way to make them work on any class that implements IList<T>. Here's my code:

public static class ListExtensions 
{ 
    public static TList With<TList, T>(this TList list, T item) 
        where TList : IList<T>, new() 
    { 
        TList l = new TList();
        foreach (T i in list) 
        { 
            l.Add(i); 
        } 
        l.Add(item); 
        return l; 
    } 

    public static TList Without<TList, T>(this TList list, T item) 
        where TList : IList<T>, new() 
    { 
        TList l = new TList(); 
        foreach (T i in list.Where(n => !n.Equals(item))) 
        { 
            l.Add(i); 
        } 
        return l; 
     } 
}

This is probably not the most efficient way to do it, and I'm not suggesting for a second that someone would start bandying the term "immutable" about when referring to a plain old IList<T>, but I still thought it was an interesting thought experiment into what's possible with extension methods.

2007 Blog Stats

So I'm a day early, but here is a round-up of Mabsterama's blog statistics for 2007. You can make your own, if you run Community Server, by running the query in this post.

I made 121 posts this year - about half of last year's count. I guess that's a sign of being busier at work and more tied up in the Xbox etc at home.

Anyway: Here are the top 10 most-viewed 2007 posts:

  1. He-Man as You've Never Seen Him Before! (3888)
  2. Migrating from Thunderbird to Windows Live Mail Desktop (3091)
  3. Outlook 2007 and Mark as Junk (2657)
  4. Zip Your Streams with System.IO.Packaging (1990)
  5. WPF Menus - WTF? (1850)
  6. Give Old Web Sites a Facelift (1818)
  7. Crack Down on Crime!!! (1789)
  8. Binding to Nested Properties (1326)
  9. Windows Live Mail Desktop (Beta) (1321)
  10. Windows Home Server (1192)

And here are the top five posts made in 2007 by number of comments:

  1. Zip Your Streams with System.IO.Packaging (14)
  2. Migrating from Thunderbird to Windows Live Mail Desktop (9)
  3. WPF Menus - WTF? (9)
  4. SecretZip (8)
  5. Thirty-Four (8)

So there you have it! Hope everyone has as productive a year in 2008 as I did in 2007. It's shaping up to be a busy (and quite tumultuous) year for us at work, but it'll be fun tackling the upcoming challenges.

Xmas Haul 2007!

Back by popular demand! The 2007 Christmas Haul!!! Another good year this year, so let's get the ball rolling with the stuff I got from Sal this morning! I'll have to omit the "Summer Heights High" DVD since it's not available from amazon.com, and I won't bother listing the five or six shirts she got me.

Oh, and for my US readers: Battlestar Galactica Season 3 is already available in Australia. Nyah nyah etc. :)

I'll update this post later today with the stuff I got from the rest of the family! Stay tuned!

Type Conversion - ToXxx Method or explicit?

In my recent work with LINQ to SQL I've had cause to convert between types quite a bit. Usually this involves taking a class that was generated from LINQ to SQL (mirroring the results of a stored procedure or the structure of a table) and converting it to one of our domain objects.

The way I've approached this to date is by implementing a custom "ToXxx" method in much the same way as the framework gives every object a "ToString" method. Here's an example:

internal Site ToSite() 
{ 
    return new Site 
    { 
        ID = SiteNumber, 
        Code = SiteCode, 
        Name = SiteName, 
        FinancialCode = SiteFinCode, 
        IsActive = SiteIsActive 
    };
}

Pretty straight forward. My "Site" domain object closely matches the structure of the class that LINQ to SQL generated, so I just add this method to the LINQ class and call it when I need the conversion. Like this:

return (from ds in _dataContext.SiteRows select ds.ToSite()).ToList();

 

However: There's another way to do this. C# has a keyword called explicit, which you use to define a method that is called whenever someone tries to cast from one type to another. So my method could instead look like this:

public static explicit operator Site(SiteRow siteRow) 
{ 
    return new Site 
    { 
        ID = siteRow.SiteNumber, 
        Code = siteRow.SiteCode, 
        Name = siteRow.SiteName, 
        FinancialCode = siteRow.SiteFinCode, 
        IsActive = siteRow.SiteIsActive 
    }; 
}

Which is better? I don't know for sure. Part of me wonders if it makes sense to return an entirely new object when all the calling code wants to do is cast. In that respect the ToSite() method kind of makes more sense. Also, a ToSite() method would allow you to specify parameters in the same way that ToString() can accept a format parameter. That's a benefit.

Anyway, the explicit (and implicit) operator is an interesting little animal, and one that deserves some attention if you're doing lots of type conversion.

Open Source Pain

I just listened to the Open Source Panel episode of .NET Rocks! and was interested in one of Richard's comments: That one of the major pain points of open source is that when you have an idea for a feature or fix, the response is often, "if you want it, write it yourself!"

This reminded me of an experience I had back a few years ago when Mad Props ran on an open-source content-management system called PHPNuke.

Rather than using proper HTML lists (eg. the <ul> and <ol> tags), PHPNuke actually wrote its list items out as lines separated by <br> tags (line breaks) and preceded by a special character called "middot", which looks like the dot that list items start with.

I rewrote the code for our site so that it wrote proper HTML list tags. It means that it was much easier to style (using CSS) and had a much cleaner look.

Have a look at the response I got (from the user called "chris-au") in this forum thread when I proposed rolling these changes back into the core.

It wasn't so much, "write it yourself" (since I had). It was more like, "Why should we take any changes? That'll just mean more work for users who are creating themes."

I was dumbfounded to say the least.

Shortly thereafter we started looking at other CMSes. We briefly toyed with Drupal (for which I wrote a module that I'm sure is in use out there somewhere) and then eventually settled on Community Server. Glad we did!

(Of course it's just "I" now rather than "we", but there were a few of us co-running the site back then.)

Stupid LINQ Tricks

Actually, not stupid at all. Quite amazing, in fact. Check out this post on Mitsu's blog:

Prime number product using Linq

I'm really loving the idea of extension methods and the query syntax that LINQ provides. I haven't had too much of a chance to play with it yet, but reading posts like that one certainly makes me want to! Good work, Mitsu!

SharePoint Search Service Crash

What a way to be greeted by SharePoint on a Monday morning:

cannot connect to the configuration database

Damn. It was working Friday afternoon - something happened over the weekend.

I remoted into the box and checked that SQL Server was running, which it was.

Checked the application event log and noticed an error about space on C drive. Sure enough, 0 bytes free on C drive. This does not bode well!

SequoiaView to the resuce! I used it to scan all of C drive on our MOSS server and determine where the space was being used. It found a huge amount of small(ish) log files in C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG.

So I opened that folder and took a look at one of the log files. It was a stack dump from SQL Server with something about an access violation. Not good. Not good at all.

The access violation, according to the stack dump, started with a call to a stored procedure named proc_MSS_Crawl in our Search database. That clued me in that the problem was somehow rooted in SharePoint's indexer. I stopped the Windows service named "Office SharePoint Server Search" and noted that the little dump files stopped appearing. Of course, a few seconds later the service was restarted by a dependent service and the folder started filling up again.

So I disabled the Office SharePoint Server Search service (phew!) and started searching on Google for phrases from the log file. Eventually I stumbled upon this post on the MSDN forums: Weirdest MOSS Crawl problem ever!

It turns out that applying SQL Server SP2 to that guy's server fixed his problem, and guess what? It fixed mine too.

So anyway - an interesting morning. Things can only pick up from here.

Xbox 360 adds DivX Support

Overnight the Xbox team blogged about the video features in the update due out next week, officially announcing that the 360 will finally support DivX video.

For me, this "completes" the 360. It pretty much does everything I need it to do. Bravo, guys.

DB Object Quick Find - Wow!

Joseph Cooney has just released the first version (with source code) of his new DB Object Quick Find add-in for SQL Server Management Studio. I'm sure he won't mind me stealing his bandwidth to show you a preview:

Wow - this is good stuff! The database I develop against here at work has a metric crapload of stored procedures, so it's really handy to be able to jump straight to one like this! Not to mention those times where you can't quite remember if it was a stored proc or a user-defined function that you were looking for.

If you have a database with lots of objects, or a server with lots of databases, this should be an invaluable tool for you. Go get it!