Showing posts with label Visual Studio 2008. Show all posts
Showing posts with label Visual Studio 2008. Show all posts

Sunday, December 16, 2007

UI: Good Use For Extension Methods

Ok, this is a little weird for me, but I think I just had my epiphany. I think I have finally converted in to an Extnsions Methods believer! I know, first there was C# 3.0 Extension Methods? A Good Idea? and then there was Reserving Judgement, but now I have found where I really, really like them.

How many of you have written a class like this:


public class Person
{
private string firstName;
private string lastName;

public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}

public string GetFullName()
{
return LastName + ", " + FirstName;
}
}


I don't know about you, but I feel dirty every time I write something like that. To me this is display logic, and now it's polluting my business objects! This really smells to me. This smells so bad that I prefer to put a method on my page which does the formatting for me. But the problem is that people are used to this sort of syntax. They expect this to be how they format that class.

How do we satisfy both sides? Keep the presentation logic out of the business layer, yet keep the interfaces clean? Enter Extension Methods!

In order to solve this problem I would now create a new static class in my web assembly (UIHelper possibly, or another name that fits). This new class would look like the following:


public static class UIHelper
{
public static string GetFullName(this Person person)
{
return person.LastName + ", " + person.FirstName;
}
}


Now you can take the GetFullName method out of the Person class and use the extension method in your UI layer instead. The class will still work exactly the same way from a UI perspective, except when working within the Person there will no longer be a GetFullName method.

The Person class now looks like this:

public class Person
{
private string firstName;
private string lastName;

public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}


Just make sure you add the using directive to the namespace which contains the UIHelper class on your page (or add an Import directive to your aspx file). Your code on the page now looks like the following:

This is actually the happiest I've been with any use of extension methods when you control the class which is being extended.

--John Chapman

Wednesday, December 12, 2007

Visual Studio 2008 Test Result Cleanup!

I don't know how many other people used the MSTest (Unit Testing capabilities of Visual Studio 2005 Team Edition) but those test results really pile up after a while.

We currently have 525 unit tests on our current project. At one point in time I noticed that my disk space was running low on my development machine. I had no clue how so much space could evaporate so quickly. I started doing quick checks on different folders that I thought could be problematic. I eventually found my way to our solution folders. We typically have multiple branches loaded on our local machine, but I never thought we wrote enough code to justify a 20+ Gig project folder. Further investigation led me to a folder known as TestResults. I found out that Visual Studio was keeping the results of every unit test run I ever did.

Don't get me wrong, I love the ability to review past test runs to see where one failed. I really enjoy the ability to create bugs directly from the results of the test where the associated result is attached to the bug for the assigned developer to review (assuming it wasn't the assigned developer that noticed the failing test). But keeping a history of these files was really adding up!

I found myself deleting the old test runs from this folder every so often. Then something really interesting happened today. I tried running my full suite of tests after loading the solution in Visual Studio 2008. A message box appeared stating that my old test runs will be deleted since I will be over the maximum of 25 historical test runs. It made me agree to the deletion of these items and also told me that the number was configurable in the Tools > Options menu!

Now, maybe this feature existed in 2005, but I could never find it. This turns out to be one of those features that isn't really advertised, isn't major but just made me happy. For some reason it's the little things that seem to get me excited. It seems like this would have been so simple to leave out, yet they took care of it anyway.

Good job on that one Microsoft! You just made my life a little easier.

--John Chapman

Sunday, December 9, 2007

Linq to Sql: The Good, The Bad & The Bottom Line

I promised my take on Linq to Sql a few days ago. I have spent some time over the past couple days playing with Linq to Sql connected to the AdventureWorks SQL Server sample database.

I have a lot of experience working with NHibernate so you may see some comparisons throughout the post.

Overview

Most everyone who is likely to read this post probably knows what Linq to Sql is. For those that don't, Linq to Sql (and really Linq in general) has been one of the most talked about (Once we found out Linq to Entities wasn't going to ship with Visual Studio 2008) and hyped features of Visual Studio 2008 and the .NET 3.5 framework.

Linq to Sql is actually a big shift for Microsoft. Linq to Sql is Microsoft's first production quality Object Relational Mapper or O/RM for short. They may have tried in the past with products such as ObjectSpaces, but this is the first tool to be released as a completed tool. O/RM tools exist to try and solve the Object-relational impedance mismatch which basically says that most applications are developed in object oriented programming languages these days yet the data which they operate on is typically stored in a relational database. This process of moving data between the objects and relations and vice versa is described as the impedance mismatch. There are obviously many fundamental differences between data stored in a relation and data stored in our objects.

Traditionally Microsoft has endorsed using DataSets to solve this problem. DataSets are essentially a relation based object in your object oriented programming language. Essentially it would allow you to work with your data in your application as relational data. The problem with this? You fail to take advantage of object oriented application design and the advantages it brings to you. Typically these programs have little testability and a significant amount of duplication. As such many O/RM tools became popular (although far less so than if Microsoft had endorsed them) such as NHibernate, LLBLGen Pro, Vanatec OpenAccess, Wilson ORMapper, EntitySpaces, eXpress Persistent Objects and many others (apologies to any I didn't list).

Note that Linq to Sql isn't necessarily a direct competitor to NHibernate or the other above listed O/RM tools for the .NET framework, that is Linq to Entities (AKA ADO.NET Entity Framework). Linq to Sql is more of an introduction to the O/RM world.

The Good

  • The Linq query language itself
The Linq query language is just awesome. It really is a joy when you start to work with it. It can quickly become a pain because it is complex, but then it makes you realize just how powerful it is. I have never seen a query language that is quite so rich. Basic queries are very simple to write and understand, yet it also provides functionality for very complex queries.

Plus, the queries are strongly typed so now there is much less to worry about when refactoring your business objects as compile-time checks are now available for your queries. Note that even with stored procedures, if you change a column in a table referenced by a stored procedure, it won't inform you that you just broke a stored procedure. Likewise stored queries in your applications will not inform you if you change a property name or column either.

For fun see the following blog post: Taking LINQ to Objects to Extremes: A fully LINQified RayTracer. This is not something you woudl actually do, but it does help reinforce just how powerful Linq really is.
  • Better Naming Conventions Than NHibernate
While working with Linq to Sql I felt that the methods on the context were easy to understand and more intuitive than the NHibernate equivalents. For example, when you want to save your changes to your database NHibernate says Flush whereas Linq to Sql uses SubmitChanges. But the big advantages are Linq to Sql's InsertOnSubmit vs NHibernate's Save as well as Attach versus NHibernate's Update or Lock methods.

I can't tell you how many times I've explained how the Save, Update and Lock functionality for NHibernate works. Most people seem to think that they need to call these methods to cause a database operation to take place. They assume Save = Execute Insert NOW, and Update means execute an update NOW! Then they use Flush for good measure because someone told them too. The Linq to Sql naming convention seems to imply that that is not quite what is going on.
  • Simple to Get Started
It didn't take me very long to get up and going with Linq to Sql. While I'm not the biggest fan of the Object Relational Designer, it sure is easy to use and fast to build basic object graphs. Someone who is not familiar with O/RM tools should be able to have objects mapped to database tables in a matter of minutes. This could work very well for simple RAD applications. This process really couldn't be much simpler.
  • Superior Optimistic Concurrency Support
My apologies to any O/RM tools out there that have as good concurrency support as Linq to Sql, I just know I prefer the flexibilty offered by Linq to Sql over NHibernate's. Now, that being said NHibernate's concurrency has always worked fine for me, it's just nice to have additional options.

First, when a ChangeConflictException is thrown it includes a ton of information such as the entity involved, the columns involved and allows your code to recover from it. Linq to Sql will also let you configure if you want to catch all change conflicts or fail as soon as the first conflict is found. These are features, which to my knowledge, NHibernate does not support.

Plus, this is basic but Linq to Sql has native support for SQL Server timestamp columns. This allows you to ensure that you know of all updates even if it occurs outside the scope of Linq to Sql. For some reason NHibernate still does not support this type of column. Instead it rolls its own version column.

Resolving stale data with RefreshMode allows for many options when re-syncing your objects with the database. Again, I just like the options.
  • Superior Stored Procedure Support
If you have a wealth of stored procedures, rest assured they are easy to use from Linq to Sql. Just drag (I do feel dirty using that word) the stored procedure from the server explorer to the methods list in the object relational designer and you will see a new method on your associated context which directly calls that stored procedure. To your code it looks the same as any other method.

Note it is also possible to write your Linq to Sql CRUD through stored procedures. This is also a relatively simple process.

The Bad
  • Very Basic Object Support
This is actually the killer here. Linq to Sql is a very basic O/RM and does not support many of the object oriented concepts sophisticated applications are likely to use. Just a few of the missing features are:
    • No Inheritance
    • No Value based objects (IE NHibernate Components)
    • No Timespan support (A huge problem for the Logistics field I work in)
    • Collections limited to EntitySet (which isn't even a real Set)
      • Where is the Dictionary support at least?
  • No SaveOrUpdate Equivalent
This forces more persistence knowledge to a lower level requiring that all code which associates an object with a context must know if it already exists in the database or not. This basically just adds extra checks in your code which should not be necessary. Sometimes it can seem a bit dirty to check if an object already has a primary key or not yourself, it seems like logic which doesn't belong within the application itself.
  • GUI based Drag & Drop
Yes, I know you can use a seperate mapping file, much like you can with NHibernate, but this isn't realistic. If you don't use the designer, you don't get the code generation. If you don't get the code generation you are responsible for writing all of the many Hooks in your objects that Linq to Sql needs. Folks, these objects are quite dirty. At least with NHibernate your objects are complete persistence ignorant (aka POCO aka Plain Old CLR Object) meaning they look clean and usable for more than just NHibernate. Therefore using anything besides the designer isn't very feasible.

The big problem here though is that your entire object graph needs to live in one diagram and the code behind these objects winds up in a single code file by default. This just isn't acceptable for applications of any size. Diagrams which contain 20-30 objects would be a major pain here, let alone applications that have hundreds. For large applications this just wouldn't fly.
  • Relationships Aren't Interface Based
All of the associations to related objects are handled with EntitySet and EntityRef. Whereas with NHibernate you have the ISet and just the object type you expect. This basically forces the Linq to Sql references on your object, decreasing the ability for unit testing your objects in my opinion. I also don't like the persistence based decencies on my objects.
  • Transaction API is Goofy
For whatever reason you need to handle all explicit transactions outside of the Linq to Sql context. You have to create and the commit it outside the context while supplying the transaction to the context while it is in use. Linq to Sql implicitly uses transactions for all calls to SubmitChanges, but you would think it would be possible to begin new transactions via the context, and then commit or roll them back through the context as well.

The Bottom Line

Really, I have only touched on a brief overview of Linq to Sql here. The important question I ask myself is, "Would I use this framework?". Well, it's a bit of a difficult question. If I was writing a small application which I knew would not grow in to a large one and my object model would be simple enough for the limited object support, yes I would use it. I could get up and going very fast, and I enjoy working with the context interfaces.

However, if I was working on a larger application (really doesn't take much to be too large for what I would do with Linq to Sql), or one which I thought had potential to adjust and grow over time, I would skip Linq to Sql and look for my trusty NHibernate.

So really, it would only be used for a very small subset of problems out there that I would try to solve.

All of that being said, I think Linq to Sql is very important to the .NET development community. Microsoft has historically tried to pretend that O/RM tools didn't exist and to do any development except their DataSets or repetitive patterns was crazy. Now that Microsoft has a framework to endorse it should greatly expand the exposure to such technologies in the .NET development community. I think overall this is a good thing, and will result in overall superior developers.

My only concern with this introduction is that people may get the idea that O/RM tools are nice, and get you up and going fast but fall flat on their face once you try to do anything advanced and then you need to resort to the same tools you used all along. This was actually a very common opinion by people I talked to about NHibernate a few years ago. They had heard of others using O/RM tools (not NHibernate specifically) and how they just don't handle advanced things, they are only good for simple things.

With Linq to Sql I hope developers become exposed to O/RM and become curious about other tools such as NHibernate when Linq to Sql is too simple for what they need instead of grouping all O/RM tools together as being too simple and idealistic.

I'm actually excited about the potential of the .NET development community now that more people will be exposed to O/RM. Long live O/RM tools, you have been lifesavers for me!

--John Chapman

More on Extension Method Judgment

Just another tidbit from my last post Reserving Judgment. I was reading Scott Guthrie's latest post on the ASP.NET MVC framework (ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios), and noticed that he showed a tool which was using extension methods in much the same way Greg Young was describing. See Scott's use of the ASP.NET MVC HTML Helpers.

What can I say, I actually kind of like how they work in that scenario.

Reserving Judgment

I have been very quick to put down certain pieces of the .NET 3.5 framework (reference prior post on extension methods and partial methods), most specifically extension methods and partial methods. I'm not quite ready to give in on partial methods yet, they still just seem like a tool used to make code generators slightly easier, but I think I'm ready to reserve judgment on extension methods now.

I still think extension methods are dangerous and are going to be subject to blatant misuse. That being said, I think I need to keep an open mind regarding the potential uses for extension methods. Note that I'm referring to the use of extension methods entirely within code that you control.

I recently read a blog post by Greg Young titled A Use For Extension Methods where he basically stated that there are a lot of people out there that share my kind of viewpoint. He also wanted to show one possible way where extension methods could be used. He basically showed that extension methods were useful in controlling the context of intellisense when using a fluent interface for a pseudo-builder pattern. I call it pseudo since really there is only one type of available builder.

Basically his extension method looks like the following:


public class Builder

{

}

public class Create

{

public static Builder New = new Builder();

}


public static CostBuilder Cost(this Builder s)

{

return new CostBuilder();

}


So now when you call the Create.New you'll only see the builders which are in the namespaces which you referenced in your using directives.

Fair enough, upon seeing this I thought it seemed interesting, but went in to my pessimistic anti-extension method mode and came up with my usual answer, why not just do this:

public class Create

{

public T New() where T : new()

{

return new T();

}

}



But upon reading this, it's pretty lame isn't it? It's basically a generic factory that doesn't new anything, why not just call new CostBuilder().DoStuff().DoMoreStuff()?

But Greg's interface is a bit cleaner than what I am offering. It's not that extension methods are really needed here, it's just that it can actually make your code a little cleaner and slightly easier to read (when working on large projects), which is something I didn't expect to say regarding extension methods.

Maybe I need to wait this one out for a year to see what kinds of things developers come up with while using extension methods.

--John Chapman

Saturday, December 8, 2007

C# Type Inference But Still Strongly Typed

I have spent considerable time today reviewing Linq and more specifically Linq to Sql. I'm currently working on a blog post where I'll go in to the details of what I think the pros and cons of Linq to Sql are as well as my overall opinion. In case you couldn't guess it I'll be using NHibernate for my comparisons, after all it is what I'm familiar with.

While reviewing some things I ran in to the following compile time check. It was very simple for me to resolve, but I wonder if it will cause developers to fall in to traps. Especially those developers who have some experience with weakly typed languages such as Javascript.

Take a look at the following code I wrote:


AdventureWorksDataContext context =
new AdventureWorksDataContext();

var orders = from po in context.PurchaseOrderHeaders
select po;

if (chkUseDate.Checked)
{
orders = from po in orders
where po.OrderDate > dtOrderFrom.Value
select po;
}

orders = from po in orders
orderby po.OrderDate ascending
select new
{
po.PurchaseOrderID,
po.RevisionNumber,
po.OrderDate,
po.ShipDate
};


Does anyone see what is wrong with the code above and why it failed to compile?

The compile-time error was:
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<BLL.PurchaseOrderHeader>'. An explicit conversion exists (are you missing a cast?)

After seeing that I immediately realized that I tried to use an object which type inferred to return PurchaseOrderHeader objects to return anonymous type objects instead. You can't just change a reference to be of another type in C# 3.0, hence the strong typing, I should know better.

But honestly, with the whole var keyword, I wasn't really thinking about it. It was a minor slip up, but I wonder how many developers will fall in to that trap. I think some developers may have seen the var keyword before in Javascript and they may have used it in the fashion I just did.

That being said, I have been enjoying my time with Linq today. I should have a post up within the next few days with more details.

P.S. If you're wondering what is going on with the 3 step linq ueries above, that's how you write dynamic queries in Linq. Simply reference the previously defined query in your new linq query in order to further restrict the query which you are building. Keep in mind that writing a linq query doesn't perform any operations. You have to either enumerate over the values of the query or call a method on the query like ToArray(), ToDictionary(), Select() etc...

If you're curious how to resolve the issue above you just need to declare a new variable for the last query to store the new type. var results = <Linq expression> would work just fine.

--John Chapman

Solution Folders To Group Projects

While reading Scott Guthrie's blog today I stumbled upon one of his links of the day for december 8th entitled Big Solutions Can Be Organized Using Solution Folders which is at the .NET Tip of the Day web site.

Actually, this is really cool. Am I the only schmuck who didn't realize this was possible? I have used Solution Folders in the past, but it was always to group files which were not part of the actual build process. For example we always had a Libraries folder which contained the third party dlls which need to be referenced to build the project. This way all a developer needs to do to build the project is to download the latest source code, and the solution will automatically download the needed referenced assemblies. Plus any upgrade we do to a third party dll automatically propagates when someone gets latest.

But the ability to place projects within the folders to group them together? This will actually be very handy for us. At work our current solution has 33 projects, and truthfully it is growing! Being able to group the projects which are similar or somehow related will really come in handy for us.

Why didn't I realize this sooner?

--John Chapman

Thursday, December 6, 2007

MS Unit Exception Testing

How do people handle exception expectations within the Microsoft unit testing framework built in to Visual Studio Team Edition? Of course there is the built in ExpectedExceptionAttribute where you mark the test itself with an exception which should be thrown while performing the unit test. If no exception is thrown it fails, if an exception of that type is thrown it passes, if the exception is of the wrong type it fails.

I don't know about others, but this rarely sits well with me. Typically when I write a test method I want the ability to test other conditions when an exception is thrown, or I want to use a single test method to test all exceptional cases within a single business object method. Do most people just write one test per case of a method? It seems like this would result in a lot of duplication of unit tests.

To address this issue I have historically used the following code:


[TestMethod]
public void TestSomeMethod()
{
try
{
SomeMethod();
Assert.Fail("Expected ExpectedException to be thrown "
+ "while calling SomeMethod.");
}
catch (ExpectedException) { }
}


Recently it occurred to me, why do I have to go through this process every time I want to test for exceptions. At first I was hopeful that an additional mechanism would be made available with Visual Studio 2008 MSUnit, but it was not. I then decided to investigating the ability to extend the framework.

Honestly, I feel a little dirty saying this, but this appears to be a good use case for Extension Methods. Yes, I know my previous statements regarding extension methods (C# 3.0 Extension Methods? A Good Idea?), but I honestly think this would be a good use of it.

Imagine writing the following code instead:

[TestMethod]
public void TestSomeMethod()
{
Assert.ThrowsException<ExpectedException>
(delegate { SomeMethod(); });
}


Wow, I really would enjoy that functionality if it was available to me. Unfortunately for me, I can not make this an extension methods. Extension methods are only allowed on instances of objects. Since Assert is a static class you can not add extension methods. So instead of using an extension method we are instead left with using our own custom static class for testing.

See the implementation of this below:

public static class CustomAssert
{
public delegate void MethodDelegate();

public static void ThrowsException<T>
(MethodDelegate method)
where T: Exception
{
ThrowsException<T>(method,
"Expected Exception of type "
+ typeof(T).ToString()
+ " was not thrown.");
}

public static void ThrowsException<T>
(MethodDelegate method,
string message)
where
T : Exception
{
try
{
method.DynamicInvoke();
Assert.Fail(message);
}
catch (T) { }
}
}


and now the final tests looks like:

[TestMethod]
public void TestMethod1()
{
CustomAssert.ThrowsException<ApplicationException>
(delegate { SomeMethod(); });
CustomAssert.ThrowsException<ApplicationException>
(delegate { SecondMethod(5); });
}
In all honesty when I first decided this was something I was interested in I thought extension methods would work for this. While writing the code for this blog I came to the realization that they wouldn't.

While researching how to make this approach work I did stumble across the xUnit.Net framework. It looks like the xUnit.Net framework already supports very similar functionality to what I am describing in this post. If you're interested with a unit testing framework with functionality like what I described maybe that is where you should look. If you want to stick to the existing Microsoft MS Unit framework, this may be a good approach to better handle your exception testing needs.

--John Chapman

Thursday, November 29, 2007

Where Is System.Collections.Collections.Generic.ISet?

.NET Framework 3.5 is released! Among the new enhancements? System.Collections.Generic.HashedSet (Reference: BCL Team Blog). Finally, proper Set semantics in the .NET language. Those of you who are familiar with NHibernate and the Iesi collections should be plenty familiar with Iesi.Collections.HashedSet and the other set based collections. Does this mean that NHibernate could finally be implemented with just the framework's collection structures?

It turns out no! Microsoft has chosen to not add an interface which matches this collections set based operations. There is no matching ISet interface which the new HashedSet implements. While some people will say "yeah but it still uses IEnumerable", I think this is a huge shortcoming of the .NET 3.5 framework. There is enough semantically different regarding a set than the other collections that it warranted its own interface to control how someone would interact with it.

The only thought I could come up with regarding why this obvious interface was left out is that if it is just an interface you can not guarantee that the collection behaves like a set. For example with a set you can not add the same item twice. If a custom collection were to implement said ISet and decided to let the Add method add the same item multiple times, what would stop them?

I suppose a set isn't something you can just define by an interface. Maybe I should let my emotions cool down prior to jumping over Microsoft for leaving out this interface. I guess I was just imagining the possibility of using NHibernate without having to add Iesi.Collections to my project. Then again, what would make me think that this would change, or change in a relevant time frame?

All that being said, I still wish they included the interface! After all there is an IDictionary which could theoretically be implemented in such a way that the custom collection could add the same key multiple times. If the Dictionary semantics can't be guaranteed by the already existing interface, then I say it would have been ok for such an interface to exist for the set.

--John Chapman

Tuesday, November 27, 2007

VSTS 2008 Web Test Forms Authentication

With the release of Visual Studio 2008 I was eager to test the Web Testing functionality to see if my issues from 2005 had been resolved. If you remember, Visual Studio 2005 did not support forms authentication with its web test functionality (see original post: Visual Studio 2005 Team Edition Web Test and the follow up VSTS Web Test Error Found).

Seeing as there is a hot fix for Visual Studio 2005 to resolve this issue, I figured the issue would be resolved with 2008. I figured this was finally my chance to make heavy use of the Web Test functionality. I opened up Visual Studio 2008 Team Suite and gave a simple web test a shot. No go! I receive the same exact errors I received with 2005.

How is this possible? How has such a blatant issue existed for over 2 years now? I know Microsoft is aware of it (based on the existence of the Knowledge Base article) so why hasn't someone resolved it for the release of 2008?

I'm very disappointed by this. So at this point I'm stuck looking for a work around. I'm still looking for suggestions if anyone has them.

Note that this is really a cookie problem and not a forms authentication issue. The cookie is sent to the client but never returned to the server. When I find a suitable workaround I'll post it here.

--John Chapman

Monday, November 19, 2007

VS 2008 Professional Download Horrors

This one is really strange to me. Today was the big release to manufacturing of Visual Studio 2008. I decided to try and download the VS 2008 Professional edition (I actually downloaded Team Suite Trial fist) only to run in to the fun of the Akamai Download Manager.

This thing caused me so many issues! I wonder if this is the first time Microsoft decided to use this product. I was trying to download it while using IE 7 in Windows Vista only to notice that the page just kept refreshing. OK, so eventually I realize that the pop up blocker must be blocking the download but not telling me. I disable the pop-up blocker and see the Akamai pop-up and then it requests that I install an AcitveX component. OK, not my favorite thing in the world, but for VS 2008, you bet!

The download manager launches and asks me where I would like to place the file. I say "Download" please, it says "Sorry, you don't have access to that folder." I don't? That is strange. I try my E: drive instead, same story. I then try my Documents folder, it looks like it works. Except I get an error message stating that it can not access my documents folder and instead will place it in Temporary Internet Files.

3.3 Gigs later the file is complete, only to notice that the file is invalid. I hunt it down in Temporary Internet Files and it can't be copied or opened. The OS says the file doesn't exist!

Ok, this is frustrating. After a few more minutes I took the actions I should have taken earlier, I opened up Firefox. Now I go to the same pages I went to before, and it just works. The download manager opens (as a Java Applet this time) and I select my download location, and it just works. Why was IE such a fiasco?

You would have thought Microsoft would have tested this on Vista with IE, wouldn't you? Thank you Firefox, I couldn't have downloaded Microsoft's product without you! Who would have thought?

--John Chapman

Sunday, October 28, 2007

.NET 3.5: The Good Stuff

With my last two postings "Partial Methods. What The?" and "C# 3.0 Extension Methods? A Good Idea?" taking shots at new features in .NET 3.5, I wanted to make a new post where I look at some of the new features I'm actually excited about. Even though this blog is titled "Chapman's Constant Complaining", I'm not negative about everything! There is a lot of good on the horizon.

1. Anonymous Types



Anonymous types are tool in .NET 3.5 that allows you to specify types based on the properties contained in the type, rather than the class declaration. The type has no name, meaning that you will not be able to construct a new instance of this type by using the new className() mechanism.

Basically, anonymous types free the developer from having to define a new class for every one off purpose in the application. I'm an NHibernate addict. I think it's absolute fabulous tool, and if you're reading this and you've never tried it, go download it right now. You can find it at www.nhibernate.org. Anyway, with NHibernate I find myself creating classes all the time which contain just the data I want returned from a query. You then create a constructor which takes just the fields you want and then reference this type in your HQL query. This is very helpful when trying to tune an HQL query for a complex search page where you need to collect display data from many objects, or even aggregates of child data.

In theory anonymous types will free developers from this time consuming task. NHibernate, much like LINQ, would be able to construct a new anonymous type for us containing just the properties we asked the HQL to return us. Note that this is actually the main use of anonymous types in .NET 3.5, support for arbitrary data being returned from LINQ expressions.

Anonymous types go beyond just queries though. How many times have you needed a simple two or three property class to perform calculations within a method? I've created one off "info" classes in the past. I don't know why I call them info, I just do. We now have the ability to define that "info" class as an anonymous type and no longer worry about the actual class declaration.

2. LINQ (Language Integrated Query)



This is the big daddy of .NET 3.5. Who hasn't heard of LINQ? The way it has been talked about it sounds like it will solve every problem ever created by a developer. I actually think LINQ is way over hyped. over hyped or not, it's still a very cool new feature which will change how we develop applications with .NET going forward.

First, I want to cover why I think LINQ is over hyped. LINQ is being talked about like there has never been anything similar in the past. Most examples which are provided are used to query a database using LINQ to SQL which is really just a very simplified OR/M tool. What some people don't realize is that tools like NHibernate, LLBLGen Pro, Entity Spaces and others have been around for a long time, offering better OR/M tools and very sophisticated query mechanisms for some time.

Now, LINQ still deserves it's credit here because it actually takes what we've learned from our OR/M tools a bit further. I'm most exited about having strong typing on my queries written in C#. I hate that the only tools I have available to me are based on strings. If an object's property is renamed it is often very difficult to spot any potential queries which were not updated until runtime. Having this check performed at compile time is a huge advantage.

Secondly I think it helps people look at their C# objects in a different manner. When trying to explain OR/M tools to developers who haven't previously used an OR/M I try to explain that the OR/M is really a synchronization tool, not a database persistence tool. Think of the database as just your extended memory, perhaps a second level memory store. As far as you are concerned there is no difference between objects in memory and objects in a database. LINQ helps to re-enforce this thinking in that you can write the same queries against your objects in memory as you do your objects in the database. I think this may cause some issues for some people at first, but eventually will be very beneficial.

3. Object Initializers



This is sort of a minor one. Object Initializers seem like they are purely syntactic sugar which can be skipped, but they allow us to offer new features like the above mentioned anonymous types and LINQ. Object initializers also allow us to offer mechanisms to define our objects without having to worry about which constructors the class's author defined for us. I think overall it makes the code a bit cleaner and easier to read.

4. Type Inference (The C# var keyword)



This could be argued as a minor point as well, except for the necessity of the feature for the above mentioned anonymous types and LINQ. I think it is convenient to be able to declare types with a var keyword when declaring a variable with an assignment.

That being said, it is a feature I don't see myself using a whole lot. I would prefer to type the entire type when it is known. This makes it a bit easier to read the code in my opinion. If you are using an IDE like Visual Studio 2008 it should not make much of a difference, but is it really that hard to write int i = 1 instead of var i = 1? I know we're really concerned about the long generic types, but a little extra typing never hurt anyone.

So while I think this is a very useful feature, I'm a little concerned that it may be taken to the extreme in some code where every variable declaration is defined as var. Plus people already make the mistake of constructing new types only to throw them away on the next line. I hope this doesn't make that problem worse. Who hasn't seen the following code?


ArrayList list = new ArrayList();
list = RunQuery();


5. Lots of Other Stuff



There are actually many other cool features built in to .NET 3.5 for us, like built in APIs for RSS 2.0 and ATOM as well as an improved garbage collector. Overall I'm excited about .NET 3.5. Now if only we could do something about those extension methods and partial methods!

--John Chapman

Saturday, October 27, 2007

C# 3.0 Extension Methods? A Good Idea?

While I was attending the Day of .NET conference in Ann Arbor, MI last Saturday (10/20/2007) I had the opportunity to talk to an old co-worker of mine. He said something that really caught me off guard. While talking about new things that had us excited, he told me he was really excited about extensions methods and said they were really going to help him where he works. If you are new to extensions methods take a look at an old blog post by Scott Guthrie here.

I don't want this to sound like I am saying anything bad about this former colleague of mine. He's a very sharp person and an excellent developer. I'm confident that he will use this technology appropriately, but at the same time there are other options, and the statement just caught me way off guard.

Of all the new things to get excited about, extensions methods would have been near the bottom of my list. In fact the only reason they aren't at the absolute bottom is because of the wonderful new feature known as partial methods (More on that another day).

Honestly, extension methods scare me half to death. The existence of extension methods and the previously mentioned partial methods scare me so bad I could see myself recommending holding off on .NET 3.5/C# 3.0 until a proper policing process is put in place.

In a quote on the Scott Guthrie blog, Scott made a true enough statement which said "When used correctly, I think you'll find that Extension Methods can significantly improve code comprehension within code reviews, and lead to fewer lines of code and fewer bugs." Now, that is fine and all, but I'm not worried about when they are used correctly, I'm worried about when every unqualified programmer gets his or her hands on this dangerous new technology. OK, so Microsoft needed extension methods to implement LINQ, I understand that, but couldn't we have maybe hidden it from other developers? Maybe we could have found another way?

If you are wondering why I'm so paranoid about this, it is because of the massive amounts of incomprehensible code I've seen in my life. I just see this adding to it. People who do not understand the purpose of extension methods, or have the judgment to properly determine when they should use them and when they should not use them are going to litter in our code.

In most applications I have worked on the String class plays a monumental role in our development effort. I can see it now where a developer gets it in his or her head that we need mountains of extension methods written on the string class. Now you may say to me, "You'll only see them if you include that namespace though". Well, I can see these same developers saying "It's such a pain to have to keep adding a using statement to my code files when I want these awesome string extension methods everywhere! I'll just put in the the System namespace, then it'll always appear for me! Just imagine code where you could use a string for anything. Every conversion method imaginable can live on the string. The string class will have the ToInt32() method, the ToInt64() method, the ToDecimal() method, then it will get even more fun when we start seeing things like ToOrder() where the extension method will convert the string to an Order number then load the Order object from the database and return it. The possibilities are limitless!

Let's not pretend like we haven't seen developers use the string object for way more than it is supposed to be used for. I've already had to put up with it used as a rounding mechanism, if we just take a decimal/double output it to a string with two decimal places, and then parse it with the decimal/double class we'll have a rounded number to two decimal places! What if I just want a DateTime object with the date value but a time of midnight? Since I don't know about the Date property of the DateTime I might as well use the ToShortDateString() method and then DateTime.Parse() to get the new DateTime value back without a time! What could be more awesome? Can't you see these same people using the new extension methods to shoot themselves in the foot?

We'll have code reviews only to find their code is near impossible to read. A senior developer may write a library to be used throughout the application to keep things consistent, scalable, reusable or otherwise in line with the goals of the company/team, only to find that another developer though it needed some new methods which completely violate the interface of the library. Now other developers start seeing these new methods in their intellisense thinking they are part of the library, only to later find out that any code written using these extension methods now needs to be re-written.

I've had developers change core libraries on me before where they had no business doing such. I previously built a system where every message returned from our business objects was associated with a code in an enumeration. This enumeration is then used to look up the appropriate message depending on the culture/language of the user (Even if the initial releases only had English) when displayed. Developers though this was "inconvenient" and too time consuming, so what did they do? They added a new message type where you just provide the string you want to display (in English) and a generic message code like "Error". Wow, now it is so much easier to write these business object methods!

Now this was easy enough to catch, and in all honesty probably an honest mistake where they didn't properly understand why we were doing what we were doing. I fear extension methods are just going to make things like this harder to catch!

Why do we need the extension methods when we can just use the static class utility methods instead? You want to have some one off method to check for the validity of a string as an e-mail address, but don't want to write an e-mail class? How about an EmailUtilitity static class with a static method IsValidEmailAddress(string email)? Now instead of writing


if (email.IsValidEmailAddress())

you instead write

if (EmailUtility.IsValidEmailAddress(email))

What is so horrible about that syntax? To me it is far easier to read, more maintainable and what most of us are already used to! Just about any use I can think of for an extension method can be written this way instead, and that's how I would prefer to see it.

Am I off base here? Is there some big picture I am missing? Let me know, I would love to know why extension methods are actually a feature we all need. It would surely make me feel a lot better about the prospect of upgrading to .NET 3.5. As it stands now I'll probably recommend upgrading to Visual Studio 2008 for the added JavaScript support, but using the .NET 2.0 libraries instead of the 3.5 libraries.

--John Chapman

Blogger Syntax Highliter