Putting Attributes to Use

Whether you know it or now, attributes are already part of your development life. Creating a web service using ASP.NET?  Attributes are used to define the methods that are exposed.  Make a call to a non-COM DLL?  Attributes are used to define the entry point for the DLL, as well as the parameters that are passed.  In fact, closer examination shows that attributes play a large part in many cool (the programmer’s code word for ‘advanced’) features. For this reason, as well as the possibility of putting them to use in your own environment, a deeper understanding of attributes is worth gaining (a writer’s code phrase for ‘topic’).

Why are Attributes Useful

One of the starting points for a discussion about the why and when of attributes is with objects. Not a surprising starting point, given the prevalence of objects within the .NET Framework. But before believing that objects are the be all and end all of programming, consider the effort that a developer goes through while creating a typical object oriented application.  The classes that are part of the hierarchy lay strewn about the workspace.  When the situation calls for it, the developer grabs one of the classes and inserts it into their project.  They then surround the class with the code necessary to integrate it into the application and perform all of the common functions.  To a certain extent, this code is basically the mortar that holds the various classes together.

But think about the problems associated with this development process.  The common functions alreadya mentioned include logging the method calls, validating that the inbound parameters are correct and ensuring that the caller is authorized to make the call.  Every time that a class is created, all of the supporting code needs to be included in each method. 

This problem results from the fact that the common functions don’t really follow the same flow as the class hierarchy.  A class hierarchy assumes that common functions move up and down the inheritance path.  In other words, a Person class shares methods with an Employee class which in turn shares methods with an HourlyEmployee class. However, the functions described in the previous paragraph apply across all of the classes in a model, not just those in the same inheritance path.  Which means that the necessary code might very well have to be implemented more than once.

Is there a solution within the object-oriented world?  Yes and no.  The solution requires that a couple of things come together.  First, all of the classes in the hierarchy would need to be derived from the same ancestor.  Then the procedures required by the common functions would need to be baked into the ancestor.  Finally, each of the methods that want to implement the common functions (which could very well be all of them) would call the procedures in the ancestor.  Do you find this beginning to sound like the gluing together of pieces that we’re trying to avoid in the first place?  Me too.

Separation of Concerns

The solution, at least at a conceptual level, revolves around separating concerns. When used in this context, a ‘concern’ is a set of related functions.  Going back to the examples mentioned in the previous section, the functions that log a method call would make up one concern. The validation of inbound parameters would be a second. By keeping the implementation of the concerns separate, a number of different benefits ensue.

First of all, keeping the concerns separate increases the level of abstraction for the entire application.  In general, the functionality required by the concern will be implemented in a single class.  So while in development, the methods can be implemented and tested without regard to the other elements of the application.

The second rationale for separation is also a justification for using an object-oriented architecture.  The level of coupling when a concern is maintained in a separate class is quite low.  Only the public interface is used by the various classes, meaning that the details of the implementation are hidden.  It also means that the details can be changed at the whim…er…judgment of the developer. 

To be completely up front, a concern does not have to be a set of functions that can be applied to multiple classes.  The functions in a single class can also be categorized as a concern.  The difference, as has already been noted, is that the method logging and parameter validation apply to different classes throughout the hierarchy.  For this reason, they are known as ‘cross-cutting concerns’.

One more thing before we get into how concerns are actually put together in .NET.  In many articles on this topic, the term ‘aspect’ is used to describe what we are calling a concern.  For the most part, ‘aspect’ and ‘concern’ can be used interchangeably.  And from this, the more commonly heard term ‘aspect oriented programming’ is derived. 

Creating Concerns in .NET

Actually, it’s not the creation of a concern that is the difficult part.  After all, a concern is just a collection of related functions.  In .NET (as well as in pretty much every object-oriented language), that is just a fancy term for a class.  The difficult part is in integrating the functionality provided by the concern into existing classes without impacting the class itself.  To accomplish this feat requires the use of Application Domains

In the .NET Framework, an application domain is a logical boundary that the common language runtime (CLR) creates within a single process.  The key to the application domain concept is one of isolation.  The CLR can load different .NET applications into different domains in a single process.  Each of the applications runs not only independently of one another, but cannot directly impact one another.  They don’t directly share memory.  They each have their own process stack.  They even can load and use different versions of the same assembly.  For all intents and purposes, the applications are isolated. 

It might not immediately be apparent why an application domain is required.  Even though application domains are isolated from one another, programs running in one can still invoke methods running in another.  This is accomplished through a technique not that dissimilar to .NET Remoting.  And since we take advantage of this remoting to implement a cross-cutting concern, understanding it is worth a few more words.


Figure 1 – Cross-Domain Method Invocation Flow

The diagram shown in Figure 1 shows the flow of a call between the client class and the receiving object.  The assumption built into the diagram is that the client and the recipient are in different application domains.  First, transparent proxy is created.  This proxy contains an interface identical to the recipient, so that the caller is kept in the dark about the ultimate location of the callee.  The transparent proxy calls the real proxy, whose job it is to marshal the parameters of the method across the application domain.  As it turns out, before the receiving object sees the call there are zero or more message sink classes that get called.  These classes can perform a variety of functions, as well shall see shortly.  The last sink in the chain is the stack builder sink. This sink takes the parameters and places them onto the stack before invoking the method in the receiving object.  By doing this, the recipient remains as oblivious to the mechanism used to make the call as the initiator is.

A review of this flow reveals that chain of message sinks.  These are classes that get called every time a cross-domain call is made.  And they would seem to be the perfect place to implement our cross-concern functionality. So the question becomes one of how do this message sinks get created and how do we tell the CLR to use them.

The answer is two-fold.  First, in order to indicate that an object should be created in a separate application domain, the recipient class needs to be inherited from ContextBoundObject.  So much for the easy part.  The second step is to create an attribute which is used to decorate the recipient class. 

Context Attributes

The attribute class which decorates the recipient class is one that we create ourselves.  It allows us to provide the message sinks which will ultimately implement the cross-cutting concern. The class itself must be derived from the ContextAttribute class.  The ContextAttribute class requires that two methods be implemented.  First, the IsContextOk function returns a Boolean value indicating whether the current application domain is acceptable for this instance of the class.  Since the purpose of our attribute is to force the object to be placed into a separate domain, this function should always return a true. 


Public Class TraceLogger

   Inherits ContextAttribute

   Public Overloads Function IsContextOK(ByVal ctx As Context, _

ByVal ctorMsg As IConstructionCallMessage) As Boolean _

Implements IContextAttribute.IsContextOK

      Return False

   End Function

End Class

The second function that is required by the ContextAttribute base class is one called GetPropertiesForNewContext.  The purpose of this method is to allow information about the new context.  It is in this method that we indicate the message sinks that are to be included in the method invocation.

Public Overl"

      End Get

    End Property

    Public Overloads Sub Freeze(ByVal NewContext As Context) _

      Implements IContextProperty.Freeze


    End Sub

End Class

I know it seems like a long journey, but we’re almost at the end.  The TraceLoggerObjectSink class used in the GetObjectSink method is where the cross-cutting concern function actually gets implemented.  In order to be included in the chain of message sinks, this class needs to implement the IMessageSink interface.  As well, at least one constructor in the class needs to accept the next message sink in the chain as a parameter. 

Public Class TraceLoggerObjectSink

    Implements IMessageSink

    Private fNextSink As IMessageSink

    Public Sub New(ByVal ims As IMessageSink)

        fNextSink = ims

    End Sub

End Class

The other two methods required by IMessageSink are SyncProcessMessage and AsyncProcessMessage.  These methods are called when the recipient method is invoked synchronously and asynchronously respective.  For simplicity, we’ll just focus on SyncProcessMessage. The diagram shown in Figure 2 illustrates how SyncProcessMessage comes into play.

Figure 2 – Process Flow within SyncProcessMessage

As part of the Message Sink chain, the SyncProcessMessage method of this class is called.  Within the method, any preprocessing of the request is performed.  The method then invokes the SyncProcessMessage method for the message sink provided in the constructor.  In its turn, each of the message sinks perform the same logic until the recipient object is called.  On the way back, the flow is reversed.  From the perspective of just this one sink, however, the flow is return through the same procedure.  So after the call to SyncProcessMessage, any post processing of the response is done and control allowed to pass back up the chain.

Public Overloads Function SyncProcessMessage(ByVal Message As IMessage) _

   As IMessage Implements IMessageSink.SyncProcessMessage

   Dim RetValue As IMessage


   RetValue = _NextSink.SyncProcessMessage(Message)

   PostProcess(Message, RetValue)

   Return RetValue

End Function

Within the PreProcess and PostProcess methods, any manner of processing can take place.  The actual name of the method, the parameter values and the return values are all available to be view and modified.  And it is in these methods that the cross-cutting concern functions, such as tracing, validation and authentication can be performed.


Is the use of a ContextBoundObject and cross-domain calls the best way to implement a cross-cutting concern.  Probably not.  The restriction that the class must be inherited from ContextBoundObject means that this technique is not suitable for every situation.  For example, if you wanted to implement method tracing for an object that was being used in COM+, you have a problem.  The COM+ class needs to inherit from System.EnterpriseServices and there is no way to have a single class inherit from multiple bases.  However for relatively straightforward situations, this technique is not only effective, but also useful.  After all, being able to add functionality without altering the underlying class is always a good way of improving programmer productivity and lowering the rate of defects.  Quite a noble goal in its own right.

Another O#er is blogging...

Stewart Zanolla

.NET 2.0 Whidbey Presentation in Toronto

On December 9th, myself and Dave Lloyd will present an in depth sneak peak of the next release of .NET: Visual Studio .NET 2.0 (code-named "Whidbey"). This should be a really fun presentation but seating is pretty limited. Adam Gallant from Microsoft is going to come by and also demo Longhorn and Avalon. He's getting daily builds so hopefully he'll show us some cool stuff that wasn't in the PDC build and is maybe even newer than some of the stuff they showed us at PDC. Hope to see some of you there.

NAntContrib "slingshot" vs. NAnt "solution"

I was trying to build the latest NAntContrib project so I could take advantage of their Slingshot task which automagically converts a visual studio solution (*.sln) and projects (*.csproj - not sure about *.vbproj) into a handy-dandy NAnt *.build file complete with all reference, source inclusions, dependencies, debug, release, and clean targets. Nice.

The only problem with this approach of course is that you need to run it daily if you don't want your NAnt builds to break when a new project or reference is added to your solution. Fortunately, NAntContrib exposes slingshot not only as a command line tool but also as a native NAnt task. The pain is that NAntContrib doesn't have a “stable release” but only a “nightly build”.....which of course is not built against the NAnt “stable release”. So I had to throw away my NAnt stable release that I've been using and opt for the latest nightly build for it too. After I got both to compile successfully I started to battle goofy slingshot issues like having to map web projects to my local hd path, avoiding spaces in my paths, and ReallyReallyReallyLongPaths.  I ended up doing a subst to map a directory to a drive letter to make it short. All this to create a build file that will get thrown away each and every night.

While browsing through the new things added to NAnt since the stable release I was accustomed too, I discovered a new task “Solution”. It compiles a whole solution - sln file. No generation of a build file. My build file literally goes from hundreds if not thousands of lines to this.

<target name="Debug">

<solution solutionfile="ObjectSharp.Framework.sln" configuration="Debug" />


This compiles our entire framework, with all 8 projects as referenced in the sln file, in the right order, with the same dependencies used by a developer while using the VS.NET IDE. What a concept: share the build files used by your build server and IDE so that there are no surprises or impedance mismatches. Such a great idea that MS is doing this with MSBuild in Whidbey. I wonder if MSBuild will have add on tasks like NAntContrib, like for Visual Source Safe, sending email, running NUnit, and executing SQL. I like my NAnt - not sure if I'll be able to break free with MSBuild.

MSDN Experimental Annotations Service uses RSS

I miss Win95 winhelp. In particular, I was sad to see in Win98 that HTML Help had not included the annotation feature, the ability to add your own notes to a help topic - any help topic. These were stored in a local .ann file next to the help file if memory serves.

During his PDC keynote, Eric Rudder mentioned and briefly showed some stuff they were doing with the Longhorn SDK to enable threaded annotations, kind of like discussions to a help topic. So I've stumbled on what promises to be a cool site: lab.msdn.microsoft.com. One of the play things is the MSDN Annotations Service. It requires the download of a small plug in for your browser.

It basically works like this...

You visit any page (in theory) on the msdn site (including the longhorn sdk) and you get an annotations window on the bottom. This allows you to add your own comments. Nice. The cool thing is, you get to see other users annotations as well. These annotations are not stored in a local .ann file, no they are stored on the Microsoft site.

Maybe you don't want other people to see your goofy code snippets. Fortunately you can subscribe to your own feeds - so long as they are exposed as an RSS, like say - this blog. If you want to make an entry to a page your visiting, simple paste in the URL to your blog entry (like so: http://longhorn.msdn.microsoft.com/lhsdk/ref/ns/microsoft.build.buildengine/c/target/target.aspx).

The annotation service allows you to subscribe to a feed. While you are looking at a given page - like the one above, if the subscribed feed contains an URL to that page, then presto it shows up as an annotation. Very cool.  The stipulation here is that in the RSS XML feed, the tag has to contain an anchor with that URL.

So does MS listen to your subscribed feeds? No, that's what the small utility plug in is for. It's done on the client.

Yet another creative use of RSS. I'm also told that the MS provided annotations also are scraped from newsgroups.

Using a DLL from Web Service

I had the distinct pleasure of trying to incorporate a non-COM compliant DLL into a web service yesterday.  Along with the issues associated with marshalling parameters (and which I'll mention in a separate blog entry), I also had to get the web service to find the DLL that needed to be loaded.  I would have thought that simply placing it into the bin directory under the virtual root would be sufficient.  Apparently not. Even after doing so, I still got a could not load DLL message

The correct answer is that the DLL needs to be someplace in the directories listed in PATH.  And by default, the bin directory is not in this list. 

For those who are unfamiliar with the process, the PATH is build from a combination of sources.  First, the System Path as defined in the System Environment Variables in the System administration applet is included.  Then the User path as defined in the same place is appended.  Finally the directories added to the PATH through Autoexec.bat are included. 

So if you plan on using a DLL in a web service, make sure that either the DLL is installed someplace along your PATH or your PATH is modified to include the web service's bin directory.

Loop optimization and .Net JIT Compiler

The other day, a colleague asked me a performance question involving loops and optimization.

The question was as follows:

When looping thru an array in a for loop, should the array's upper bound calculation (array.length) be placed in a separate variable prior to the start of a loop so that the expression does not get evaluated each time thru the loop.

For example:

int l = theArray.length;
for(int i = 0; i < l; i++){


for(int i = 0; i < theArray.length; i++){


On the surface, this seems to make perfect sense; however, I seemed to remember reading something that suggested that the optimal solution was actually the second, because the compiler already has an algorithm for dealing with this. 

After several minutes of debate, we decided to check the web, and found this interesting article  by Emmanuel Schanzer of Microsoft which suggests that “optimizations like this haven't been helpful for nearly 10 years: modern compilers are more than capable of performing this optimization for you. In fact, sometimes things like this can actually hurt performance.”

Although this sounds counter-intuitive, it really makes sense once you read the article and think about it.

The moral of this story?  Don't try to out think the compiler.

Sparkle to kill Flash? I think not.

Mary Jo Foley speculates that Avalon is a Macromedia “Flash Killer”.

So I guess that would mean MS is going to extract out the Avalon Graphics subsystem from Longhorn, including the WinFx/.NET Framework which is the API to it, all into a handy dandy ActiveX “Avalon Player“ control and we can all embed that in our web pages. That's cool. I guess that will also mean that MS will back port this to Windows 98, Windows ME, and Mac OS 9.x

Maybe that article should have been posted on slashdot.

C# vs. VB.NET Interfaces

Visual Basic has an interest syntax for implementing interface members.

Public Interface IAdd

Function Execute(ByVal i As Integer, ByVal j As Integer) As Integer

End Interface

Public Interface ISubtract

Function Execute(ByVal i As Integer, ByVal j As Integer) As Integer

End Interface

Public Class Calculator

Implements IAdd, ISubtract

Public Function Add(ByVal i As Integer, ByVal j As Integer) As Integer Implements IAdd.Execute

Return i + j

End Function

Public Function Subtract(ByVal i As Integer, ByVal j As Integer) As Integer Implements ISubtract.Execute

Return i - j

End Function

End Class

The key here is that the function names don't have to be the same as they are in the interface definition. I have two interfaces that both expose a Execute method. They are implemented separately as Add and Subtract. Thanks VB team for the “Implements“ keyword. C# is a different story - and up until a few days ago I didn't think you could do this at all in in C#. Here you go:

interface IAdd


int Execute(int i, int j);


interface ISubtract


int Execute(int i, int j);


public class Calculator: IAdd, ISubtract


#region IAdd Members

public int Execute(int i, int j)


return i + j;



ISubtract Members

int InterfacesCS.ISubtract.Execute(int i, int j)


return i - j;




I used the auto-magic interface template generator built into the VS.NET C# editor. After you type ISubtract on the class declaration, wait for a little tool tip that tells you to hit TAB for a default implementation template. You'll notice the fully qualified function name “InterfacesCS.ISubtract.Execute“ on the second declaration of “Execute”. The whipper snappers out there will also notice that the second method is not public. So it's private you might say. The class view and object browser would agree with you. Don't try putting “private” in front of the declaration. The compiler won't like that. Don't even think of trying to call it directly though. The only way to call this second method either internally to the class (why not it's private) or externally is by casting the reference to the interface, like so..

Calculator calc = new Calculator();

int result = ((ISubtract)calc).Execute(5,4);


If you really want to call the method directly without casting it, you'll have to create a wrapper method and expose it publicly or privately if that suits your needs.

public int Subtract(int i, int j)


return ((ISubtract)this).Execute(i, j);


Thanks to Alex Bershadski for pointing me to a few code snippets in the MS Press C# book about this. The book could really do a better job of identifying the limitations of C# in this regard. At least it can be done. Up until Tuesday, I didn't think it was possible.


Have you ever tried to update a Dataset and received this message?

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

Not a problem in a small DataSet. But if your Dataset is more complex sometimes it's not easy to see the problem right away.

There is a property on the DataSet called EnforceConstraints. When you set this to true the DataSet will try to enforce all the constraints in the DataSet (Not null columns, Foreign keys, unique keys) The problem with this exception is, it tells you very little. You know you have violated a constraint, but which one? The way to find out is to look at the row and column errors.

Below is a method that will attempt to apply contraints and write the errors out to the output window. I hope someone out there finds it useful.

Public Sub GetDataSetErrors(ByVal ds As System.Data.DataSet)


Public Shared Sub GetDataSetErrors(ByVal ds As System.Data.DataSet)



ds.EnforceConstraints =


Catch ex As Exception

Debug.WriteLine("DataSet errors: " & ds.DataSetName)


For Each table As DataTable In ds.Tables


Dim ErrorRows As DataRow()

ErrorRows = table.GetErrors()


For Each row As DataRow In ErrorRows

Debug.WriteLine("Table: " & table.TableName)

Debug.WriteLine(" Row Error: " & row.RowError)


Dim ErrorColumns As DataColumn()

ErrorColumns = row.GetColumnsInError()


For Each column As DataColumn In ErrorColumns

Debug.WriteLine("Column: " & column.ColumnName)

Debug.WriteLine(" Error: " & row.GetColumnError(column))








End Try


End Sub