Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Note: This blog has moved to omervk.wordpress.com.

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

April 2006 - Posts

C# Feature Suggestion: Attaching Properties to Events
While working on the next version of the my Commonly Used .NET Coding Patterns in CodeDom article, I've come up with a nice idea for the next version of C# (or any other language for that matter).
Consider the following scenario:

A doctor's office is handled by a class named DoctorsOffice. The class has a property of type PatientsQueue which is a queue of patients (First In, First Out), which in turn exposes an event called PatientEnteredQueue (which has one parameter - the Patient object). This event is called whenever someone walks in the door.
Some objects consume this event, such as the BlondeSecretary (who checks if the patient has an appointment) and the WeirdDudeWhosAlwaysThereForSomeReason (who just gives the new guy a weird sideways look).
Whenever a new patient enters the office, the PatientsQueue.Queue method is called which raises the PatientEnteredQueue event.
Once every few new patients, one of them asks the question "Who's last in the queue?" just to know how long they'll have to wait before seeing the doctor. This is implemented by the WhosLast property on DoctorsOffice.
class DoctorsOffice
{
    public PatientsQueue Queue { get; }
    public Patient WhosLast { get; private set; }
}

class PatientsQueue
{
    public void Queue(Patient p);
    public event PatientEvent PatientEnteredQueue;
}
A very logical approach to this would be to consume the event inside DoctorsOffice and set the WhosLast property to the Patient value. The problem here is that you would have to use a method in the middle, first to consume the event and then to set the property.
public DoctorsOffice()
{
    this.Queue.PatientEnteredQueue += this.AnotherPatientHasEntered;
}

private void AnotherPatientHasEntered(Patient p)
{
    this.WhosLast = p;
}
This is a cumbersome approach that can be bypassed by adding a simple feature - adding the ability to attach properties to events:
public DoctorsOffice()
{
    this.Queue.PatientEnteredQueue += this.WhosLast;
}
Since properties are implemented as methods, the compiler could choose which one it would like to use (depending on the signature of the delegate).
If the property returns an instance of the same delegate as the one being attached to, this would cause a problem and then C# 1.0's syntax would have to be used, after a warning (the default would be to use the return value, rather than attach the property, for backwards compatability's sake):
public delegate MyDelegate MyDelegate();

private MyDelegate MyDelegateEvent
{
    get
    {
        // Do work...
    }
}

private void Foo()
{
    this.MyDelegateEvent += this.DelegateInstanceReturningProperty; // Warning. Return value used by default.
    this.MyDelegateEvent += new MyDelegate(this.DelegateInstanceReturningProperty);
}
PowerToys for the Visual Studio 2005 Class Designer and Distributed System Designers
Looking for a way of extending the Visual Studio 2005 Class Designer, I found, after half an hour of googling, this post on the MSDN forums, which linked to the workspace of the PowerToys for the Visual Studio 2005 Class Designer and Distributed System Designers.
Here is the list of toys:
  • Design Tools Enhancements
    • Diagram Search
    • Formatting Commands
    • Floating Property Grid
    • Pan/Zoom Window
    • Design Surface Scrolling Improvements
    • Create Comments with Double-Click
    • Design Surface Grid
  • Class Designer Enhancements
    • Export Diagrams for Web
    • Display Xml Comment Command
    • Documentation Tool Window
    • Filtering Appearance
    • Filtering Lines
    • Filtering Members
    • MSDN Help on System Types
    • Fast Navigation
    • Interface Lollipop Labels Commands
    • Inheritance Visualization Commands
    • Show Type Command
    • Association and Inheritance Line Dongles
    • Create Tests Command
    • Type Creation Commands
    • Add Member Commands
    • Synchronization with Code Definition Window
    • View Class Diagram Command Improvements
  • Creating Custom Add-ins
Looks very useful - I'll be checking them out soon.
Posted: Apr 13 2006, 11:00 PM by Omer van Kloeten
Filed under:
Blogs @ Microsoft Israel
Ayende has just posted about the new community coming up.

As much as it is a blessed idea, I do have two qualms, though:
First off, I wonder how it'll work, with non-Microsoft bloggers hosted on a Microsoft server. It all depends on the good faith presented by the company over time.
Secondly, writing technical content in Hebrew is a bit tough, and becomes a whole lot worse when you have to do it online.

The best of luck to all the new (and old) bloggers. I hope you prove I worried for no reason. :)
Copy/Paste References
A feature I find lacking in all versions of Visual Studio is the fact that there's no copy/paste support for references. You simply can't copy a reference from one project to the other.
Today I got somewhat fed up with that, so I decided to implement this feature on my own as an add-in. :)



Unfortunately, the add-in can not paste ActiveX or project references.

The add-in is available for both Visual Studio.NET 2003 and Visual Studio 2005 (simply unzip to your Addins directory).
I will, of course, appreciate as much feedback as possible and update the bits if necessary.

[Update: Weird, I must have missed this somehow. Oh, well.]
Half-Baked
Whenever I have to write a large project using CodeDom (and this doesn't happen as often as you'd think), I almost always find something lacking. It's as if the whole of CodeDom is half baked.

What's bugging me the most is that even with the framework's latest version, 2.0, when Microsoft had the chance to fix things up, they decided, for reasons unknown to anyone outside the company to only implement the new features and fix very few bugs.
Microsoft developers, on their blogs, keep saying that they want not only software to be built with the framework, but also tools. One of the greatest tool-making capabilities they placed in the framework is CodeDom and I'm very appreciative of it, but when such a feature lacks in so many areas, it in several occasions becomes unusable.

What brought this on? Here are the two latest bugs I found and reported:
  1. CodeDom Does Not Allow For Creation of ParamArrays.
  2. CodeDom Does Not Allow For Creation of Finalizers (Destructors).
(Previously, and then some, and then some more, and one more to boot)
Operation Timeout
I've been looking into a way of having an operation time out using .net 1.1. I want the operation to be 'decorated' with the timeout code, so that it would appear to be a simple method without too much fuss.
What I came up with (having little experience with threading in .net) is the following code:
private delegate void AsyncTimeout(TimeSpan timeout);

private void Foo(TimeSpan timeout)
{
    IAsyncResult asyncResult = asyncMethod.BeginInvoke(timeout, new AsyncCallback(TimeoutElapsed), Thread.CurrentThread);

    try
    {
        // Really long process...
    }
    catch (ThreadAbortException)
    {
        Thread.ResetAbort();
        throw new Exception("Timed out.");
    }
    finally
    {
        asyncMethod.EndInvoke(asyncResult);
    }
}

private AsyncTimeout asyncMethod = new AsyncTimeout(Thread.Sleep);

private void TimeoutElapsed(System.IAsyncResult asyncResult)
{
    AsyncResult result = (AsyncResult)asyncResult;

    if (!result.EndInvokeCalled)
    {
        ((Thread)(result.AsyncState)).Abort();
    }
}

The delegate, field and method can be re-used for all methods that can timeout.
It works and works well, but on the other hand, passing a Thread object as state to another thread can't possibly be good practice.
Can anyone help out here? How should this be done? Any best practices you can point out?
CodeDom Reflection Generator
As a step to further promote correct writing of generators using CodeDom, I've created a utility that takes an entire assembly and creates typed methods that create every type in it, invoke every method, reference every member, etc..

Now wait a second and try and understand what I just wrote up there. Give up? That's ok, I gave before you did. Let's just take an example and it'll all be clear:

Take the Chars indexer for System.String. To access it, I would have to write an awefully long and untyped piece of code:
System.CodeDom.CodeIndexerExpression expression =
new System.CodeDom.CodeIndexerExpression(new System.CodeDom.CodePropertyReferenceExpression(myStringObjectReference, "Chars"), positionExpression);

Using the reflected assembly, I could simply write:
System.CodeDom.CodeIndexerExpression expression = System.ReflectedString.Properties.ReferenceIndexerChars(myStringObjectReference, positionExpression);

Let's look at the greater scale now. Again, take .NET 1.1's String class as an example. After putting mscorlib through the tool, you will receive a class named ReflectedString in an assembly named [CodeDomReflection]mscorlib.dll that knows exactly how not only the String class works, but the whole of the mscorlib assembly and can strongly reference every single part of it. Also, a complete documentation xml file is included for Intellisense's sake.



The version I'm placing online for download is a perliminary beta. I've tested it on the entire framework and it worked great, but things may always break. Please let me know if they do.
Here are the bits. To do some magic, just use DotNetZen.CodeDom.Reflect assembly [strong name key file] (Yes, you can sign your assembly with a strong name key file so you could use it from your own signed generators).
[Updated (1.5)] Commonly Used .NET Coding Patterns in CodeDom
I have uploaded another update (1.5) to my article: Commonly Used .NET Coding Patterns in CodeDom.
Major changes made since 1.4:
  1. The Typed Collection pattern has been added.
  2. The Argument Assertion patterns have been added.
  3. Assembly and all types are now CLSCompliant.
  4. All types are now marked as serializable.
  5. The Custom Attribute pattern now produces sealed attributes, to increase the efficiency of generated code.
  6. Several overload additions and bug fixes.
Upcoming features:
  1. Automatic documentation of members.
  2. Async patterns.
  3. Dispose pattern.
  4. Serialization pattern.
  5. And more...
asp.net
Come, sit around the campfire and I'll tell you a story about weblogs.asp.net.

It was 2003. Back in those days, having a weblog at asp.net was a status symbol. It was the time when some of the big Microsoft names had weblogs on the server, which in turn always ran the latest .Text version (since ScottW pretty much ran the place) and you had to be well known or have someone on the inside in order to get a weblog here. Don't let the name fool you, though - the weblogs on asp.net weren't just for the ASP.NET crowd - you could read wonderful content about the whole of .NET, a (rather) new technology. Debates would run into the night and at the end of the day - you would actually make a difference.
It was on a rainy October day on that year that I got my very own weblog.

One day, Microsoft finally understood (although partially) the power of weblogs. On a clear day, much like today (well, not today, since it's poring outside), some Microsoft bloggers suddenly started attaching a little [MSFT] tag to their weblog. Next - they received their own OPML file. Before you knew it, .Text was installed on blogs.msdn.com and then one by one, the bloggers of great Microsoft migrated to their corporate home.

Time passed and as it did, more and more weblogs went the way of weblogs and were never again posted to, while other writers kept theirs alive by the sheer power of their collective will. The sense of community - of equality between fellow developers across corporate boundaries - had been lost to the capitalistic PR ambitions of the behemoth that is Microsoft. The application running the server was left to die the death of unupgraded software and the good name of weblogs.asp.net dwindled and shrunk to what it is today.

Where are the glory days of old now, you ask? Promises have been made, but that sliver of light at the end of the tunnel is so thin that many have pondered or have already left for other sites. Telligent! Communities that do not grow, die!

[ Update: Just so no one misunderstands me, I don't want to leave the site. It's nice and cosy and I'm used to it. It's just that some new blood needs to be pumped into the veins of this community soon. ]
NStatic
In Specifications and More on Specifications, Wesner Moise talks about some of the features in his upcoming tool NStatic, which is a static analysis tool for .NET.
I've been following Wesner for a couple of years now, being especially interested in the tool, since it's a tool I've been wanting to write myself for ages, but have never had the time to invest in such a grand project. He's written some very inspiring posts and his blog is well recommended in any case.

Great stuff, Wesner, I'm loving it... even though that as a person who enjoys a good user interface, I think there's a long way ahead of you... and I'm more than willing to offer my assistance, if you'd like it! :)
More Posts