Ever Heard of Partial Methods?

I attended an MSDN Unleashed Event here in Salt Lake City yesterday based mostly on the new bells and whistles in .NET 3.5 SP1 (and consequently Visual Studio 2008 SP1).  I always enjoy the presentations from Rob Bagby, as he is entertaining to listen to and he is a let’s-dive-into-the-code, forget-about-Powerpoint-slides kind of presenter.  He is a Microsoft Developer Evangelist (click Role Descriptions on the right column of the page this link references) for the Rocky Mountain states inland from the Pacific Coast.  That’s just the way he rolls.

Anyway, he was trying to add some functionality to ASP.NET Dynamic Data for a demo he was showing during the event, and he mentioned a conversation he had with some of the developers at Redmond about the possibility of partial Properties.  According to his words, the impression he got was that "if partial Properties were added to C#, the whole CLR would catch fire" or some other horrible catastrophe.  But Rob did mention the little-known existence of partial Methods in C# 3.0, which caught my attention and sent me surfing.

See my last post about partial Classes if you want some background to partial Methods.

The genesis of this new feature is much the same as that of partial Classes, which is primarily for Classes that are auto-generated by code generators in Visual Studio (mainly associated with the numerous designers incorporated into Visual Studio).  In fact, it appears the addition of LINQ may be one reason for this new feature.

Partial Methods seem to be a way to incorporate into your Classes methods that may or may not be implemented, kind of a way to stub out areas where another developer could inject specific logic they require into a pipeline of statements they didn’t write.  Partial Methods can only reside in partial Classes, and can only have one declaration and up to one optional implementation.  They must be private, have a void return value, and there are quite a few modifiers that cannot be used on a partial method.  For a more comprehensive detailing of these restrictions (and explanations why), see this blog post by Bart De Smet that I read to learn about this new feature:

http://community.bartdesmet.net/blogs/bart/archive/2007/07/28/c-3-0-partial-methods-what-why-and-how.aspx

Apparently, LINQ-to-SQL makes use of this new language feature to allow the developer to plug their own business logic validation rules without modifying the auto-generated code directly.  If you go to a LINQ-to-SQL generated Class, you will find a C# region named "Extensibility Method Definitions," which are partial Method declarations (see first image below).  This allows you to make a separate file that is a partial Class of the LINQ-to-SQL generated class and include an implementation for one of these partial Methods, which are by default unimplemented.  It appears LINQ-to-SQL allows you to plug into some of the setters of the generated object Properties that map to columns in the original SQL database table.  The following images are taken from Bart’s blog post and are LINQ-to-SQL generated objects based on some of the DB structure for Team Foundation Server:

Here are some partial Method declarations in a LINQ-to-SQL generated Class called BuildCoverage:

And here is the view of the LINQ-to-SQL generated object in the designer so you can see that most of these partial Methods are based on the object’s Properties:

Here is a look at a Property setter calling these unimplemented partial Methods:

And if you wanted to implement one of these partial Methods, you get nice intellisense from Visual Studio:

And I suppose this finished implementation of the partial Method would throw a NotImplementedException after the Property has already been modified? Hopefully this is where some of that LINQ-to-SQL transactional stuff kicks in…or perhaps Bart meant to implement the OnAssemblyNameChanging partial Method instead?

This is definitely an interesting new feature in the C# language.  I’ll have to keep my eye out for a really compelling use of this feature; I’m not very convinced this is the right way (or even the most common way) for using LINQ-to-SQL generated objects as if they were your Data Model objects and then insert your business logic in the above manner.  Still, this is quite a thought provoking new feature.

Comments

Esteban Araya
Intersting stuff. I really like the idea of giving other people hooks into your code; I’m not sure partial methods are the best way to accomplish that.

C# Partial Classes Can Enhance Code Organization

Many .NET developers are aware of the idea of partial Classes, as they have existed since .NET 2.0.  The primary purpose is to allow you the developer to share claim on a C# Class with Visual Studio’s automated code generators (mainly used by the many designers included in Visual Studio), without the automated code generator stomping all over your code additions every time it runs.  For instance, in a Windows Forms application, you get a code-behind Class where you can put your logic, properties, methods, and event handlers; it is a partial Class of the one Visual Studio’s Windows Form designer creates and manages for all the UI objects you dragged around in the designer.  A good summarization of this feature is given by Bart De Smet:

"In short, partial classes allow you to split the definition of a class across multiple files, or alternatively you could think about it as a code compilation unit separated over multiple files."

As another practical application of this feature, I have occasionally implemented a practice using partial Classes that I learned from a previous coworker.  Occasionally you find yourself with a Class that is inescapably large.  Perhaps it is a web service that has been in use for a while by customers or other groups within your company, and you can’t just deprecate the service very easily; so you just keep extending it and adding more web methods to it for additional, similar functionality.  Another potential situation could be that you began designing a simple application all in one file but it grew to be a little bigger than expected, but it doesn’t quite merit a whole major redesign into appropriate classes.  I know how this all sounds, but these scenarios aren’t exactly uncommon in real-world practice, where there are other factors in consideration.  I suppose many would resort to C# regions, but I’m not a fan of them as it really only gives the illusion that your code file is better grouped and somehow shorter.

So if you need some decent semblance of organization in a messy class file with little effort, the partial Class feature can come to your rescue.  You can basically create a partial Class file for each grouping of code that you would probably be putting in a C# region.  For instance, a relatively small Windows Form application could be broken up into the following sub-files (all partial Classes of the same MainForm class):

  • MainForm.cs = contains the constructor and a few rare global enumerations, properties, or sub-classes
  • MainForm.UI.cs = contains the event handlers and other supporting methods that interact directly with the UI
  • MainForm.Processing.cs = contains the application logic designed to be spun off in a separate worker thread in order to keep the UI thread from blocking while waiting
  • MainForm.Designer.cs = the auto-generated UI file from the Windows Form designer

Obviously you should try to architect your code better from the get-go, but perhaps what you are looking at is legacy code you have inherited from previous developers and the deadline is fast approaching.  There are reasonable circumstances I can think of (and have encountered) where this quick & dirty organization lets you keep an ounce of sanity, so that you can keep moving forward.

Recursion Quote

Comments

I saw this quote on a message board in someone’s signature and thought it was just hilarious:

"In order to understand recursion, one must first understand recursion."

I can’t seem to find who originally said it.

Comments

dave
That was my email signature for many, many years, starting around 1991 … but I got it from some BBS's random tagline generator, so I can't take credit for it.

Microsoft/Windows Update Fails on Every Update

Occasionally, Windows Update (or Microsoft Update) will see all of the updates you need (and possibly even download them) but will immediately fail all of the updates when trying to install them.  Sometimes I have seen Windows Update error off after the green progress bar and before it can show me if there are any updates at all.

Every time this happens, I end up Googling the error code and finding the same fix every time (since I forget what the fix is each time).  The error code I get is 0x80004002.  If you are unable to find the error code through the UI, you can check the Windows Update log at %WINDIR%\WindowsUpdate.log (which in my case, %WINDIR% translated to C:\WINDOWS\); you can even just type %WINDIR%\WindowsUpdate.log right into the "Run…" dialog.  You can find the error code near the bottom of the log; just find the lines of text that have the same timestamp as when you unsuccessfully ran Windows Update.

Well, anyway, here’s the fix; run the following commands in a Command Prompt window (type cmd in the "Run…" dialog):

net stop wuauserv
regsvr32 wups2.dll
net start wuauserv

That’s all there is to it!  It has worked every time for me.  It may even be helpful to put these commands in a batch script (copy and paste the commands into Notepad and then save the text file with a .bat file extension) and keep the file in a place where you can easily find it again.

LINQ to SQL Debug Visualizer

If you are using LINQ-to-SQL, it is often helpful to see the SQL generated and the resultant query results.  You can do this, even while debugging, with the LINQ to SQL Debug Visualizer.  Debug Visualizers are the dialogs that pop up when you hover over a statement and click the little magnifying glass in the hovering menu.

I believe by default Visual Studio will show you the generated SQL when you over over a LINQ statement, but there is no way Debug Visualizer to help see the SQL in a more user-friendly view.  Scott Guthrie gave a blog post describing a simple download that can give you this enhanced view of the SQL, and even the ability to execute the query and see the raw data returned from your database:

http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx

Included in the post are instructions of how to extract the necessary DLL library, and where to place it in Visual Studio’s file hierarchy.

A really simple enhancement for working with and debugging LINQ-to-SQL that is definitely worth the minimal effort to acquire it.

Comments

Raja Venkatesh
Hi, A similar visualizer for L2E is available at http://visualstudiogallery.msdn.microsoft.com/en-us/99468ece-689b-481c-868c-19e00e0a4e69
This works for any database.

Regards
Venkat