Monday, October 23, 2006

For a long time now I have been wondering how to handle a situation in which there is an unhandled exception thrown from the event handling method of my events. Given the simple pattern for raising events in the form of:

private event EventHandler SomeEvent;
protected void OnSomeEvent()
{
   
if (SomeEvent != null)
   {
      SomeEvent();
   }
}

What happens when one of the handlers of SomeMethod throws exception? Keeping in mind the internal implementation of events that I have described here, I know that this exception will go outside the SomeEvent() call and even outside the OnSomeEvent() up the call stack. It is rather obvious. What is not so obvious is one should handle such a situation?

I have spend some time searchin the Internet for some kind of guideline or best practice but I have been unable to find one. I have talked with Krzysztof Cwalina about it and it seems that there is no good solution to the problem. You can put the event invocation in the try catch block but the only kind of exception you can catch there is really the Exception - since you don't know anything about what the handler may be. Krzysztof suggests that it may be good idea to document what kind of exception you expect from the event handlers but it it only a partial solution. Other solutions include terminating the application, allowing the exception to propagate or swallowing the exception - none of those seems right to me.

If any of you knows of any proven practice on how to handle this kind of situation I would really appreciate it if you point me in the right direction.

kick it on DotNetKicks.com

Monday, October 23, 2006 11:07:16 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [5]  | 

Events in the .NET Framework implement the Observer design pattern. What this means is that under the hood when one object (Observer) wants to be notified about some event that occured in another object (Subject), it has to register one of its methods in a special list of methods stored in the Subject. In .NET those methods are really delegates. When an event occurs what really happens? The Subject iterates through the collection of the delegates it stores and invokes them one at a time. It is a simple overview of how it works. It is not meant to be a complete description. Just keep in mind the in fact it is the Subject who holds the referrence to the Observer and not the other way around.

So, given the introduction you know that Subject knows about all the registered Observers - it holds a referrence. Sometimes the Observer also holds a referrence to a subject such as in a Form handling a Click event of a contained Button control. In this situation there is in fact a circullar referrence between the objects!

What does this mean and why it is important? The problem starts to appear when you have an object A with an event E. If this object has a long life cycle then every event you hook up to this object will cause its defining Observer not to be garbage collected. Take for example a Windows Forms application when the A object is passed between number of forms - maybe a wizard-like procedure - and each step attaches its own handlers to the E event. Long after the windows are closed, the object still lives and by doing so, it prevents the Forms from being collected by the GC (via the referrence the Subject has to the Observers). And that is not all to it! Imagine for example that you have your first form closed via Close method (which should call Dispose to release the unmanaged resources). After a while the E event is rised and it will be handled inside the Form which sa been closed long time ago. If in the handler you will try to use the resources that have already been released - exception will be thrown!

So given the problem there is a simple solution. Just remember to unhook the event handlers from Subject when they are no longer needed. When that is? It depends. Only you can tell. The sad thing is that the necessity of manually removing the event handler from the event is something to REMEMBER which is not always that easy and certainly it is a source of MANY unexpected "memory leaks" in the applications.

kick it on DotNetKicks.com

Monday, October 23, 2006 11:00:53 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

Events and event handlers were the part of the .NET from the beginning. They are used widely throughout the whole BCL (Base Class Library). As a developer I often define my own events using the simple syntax offered by the C# language:

public event EventHandler SomeEvent;

I also prefer to define a protected method that raises the event:

protected void OnSomeEvent()
{
   
if (SomeEvent != null)
   {
      SomeEvent(
this, EventArgs.Empty);
   }
}

Simple as it is, there is one catch to this kind of event declaration. What happens when you declare an event in such a way? "By default, when a class declares an event, the compiler allocates memory for a field to store the event information. If a class has many unused events, they needlessly take up memory" (MSDN). So if your type declares a lot of events then it will consume a lot of memory even if you do not hook up handlers for those events. In order to conserve memory ".NET Framework provides a construct called event properties (custom events in Visual Basic 2005)" (MSDN).

Defining events using the special - explicite - construct is similar to defining a property:

protected EventHandlerList events = new EventHandlerList();
static readonly object eventKey1 = new object();
static readonly object eventKey2 = new object();

public
event EventHandler Event1
{
   
add 
   { 
      events.AddHandler(eventKey1,
value); 
   }
   
remove 
   { 
      events.RemoveHandler(eventKey1,
value); 
   }
}
public event EventHandler Event2
{
   
add
   
{
      events.AddHandler(eventKey2,
value);
   }
   remove
   
{
      events.RemoveHandler(eventKey2,
value);
   }
}

Notice the use of the EventHandlerList class which is a "Provides a simple list of delegates" (MSDN) to store event handlers. Notice also that it is an instance field - one per object instance and the use of static key-objects to use with the EventHandlerList object. This way you end up with only one list field per object to store delegates and a total of N number of object instances where N is the number of events on your type.

Consider the amount of the memory which is saved in this way if you have a collection of thousands of objects of type that defines just a few events!

Unfortunately there is a performance hit when using this alternative syntax because of the additional step needed to retrieve the delagate from the list. Other then this I always declare my events using this syntax if I have more than 2 in one class.

As a side note. This syntax has been avaialble to the C# developers since the 1.1 (or 1.0) version of the .NET Framework. It was not possiblet to do it in VB.NET 2003. According to MSDN: "Event properties are not supported in Visual Basic 2005", but I think this may not be the case since in this same MSDN there is a sample of Visual Basic code:

Private Events As New System.ComponentModel.EventHandlerList

' Define the Click event to use the delegate store.
Public Custom Event Click As EventHandler
   AddHandler(ByVal value As EventHandler)
      Events.AddHandler(
"ClickEvent", value)
   End AddHandler
   RemoveHandler(ByVal value As EventHandler)
      Events.RemoveHandler(
"ClickEvent", value)
   End RemoveHandler
   
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
      
CType(Events("ClickEvent"), EventHandler).Invoke(sender, e)
   
End RaiseEvent
End
Event

Which does exactly the same thing and more! Since events in VB.NET are invoked using the RaiseEvent statement it is also possible to provide an implementation for this. You can use it to raise events asynchronously thanks to it and this pattern is also described in the MSDN.

kick it on DotNetKicks.com

Monday, October 23, 2006 10:49:29 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, October 19, 2006

Yep! Microsoft has done it again. They never fail at bringing you pain. This time it is the final release of their new browser - the Internet Explorer 7.

Since the beginning of my adventure with IE7 I have always had problems with it. At first I have paid two visits to my bank to change my online account password because for some reason i have been unable to log in with a message that the password was incorrect - thrid try and my account had been locked out. At first I thought that it is possible that I have forgotten it. The bank changed my password so I could log in again. But guess what? The new password which I have tested on the computer in the bank did not work at home! It took me a while to figure out that it was the new IE7 (BETA 1 I think) that was causing the problem! This was fixed.

Next there came the problems with "Navigation Cancelled" or other messages that prevent me from browsing sites. Strangely enough, refreshing such a page helps. Sometimes I had to refresh twice but mostly I can handle the problems.

Then came the final release! What a glorius day. I had a release candidate installed by the time I have downloaded the finall version, but I hoped that the setup procedure would handle this situation. This hope was against my previous experiences with Microsoft products which are generally hard to upgrade from the BETAs to finall releases. And then it came. The pain.

I have run the setup file. First validation of my copy of Windows - everything ok. (BTW: I was supprised that there was no validation before downloading). Then I've got a message telling me that I have to restart my system, because of the previous version has been installed. So I did. After a SECOND validation the installation procedure told me that it is downloading some updates for Internet Explorer 7. Hmmm. Updates already after few days? Ooo Ok.

Then the sceond restart came! What the hell? Two restarts are required to install a browser? Hmmm. Even Windows requires only ONE restart if I remember correctly.

After the restart I've been welcomed with a taksbar unlike my previous taksbar. IE7 has decided that I don't need my Quick Launch and my custom toolbar with shortcuts that I'm using for my software. Hmmm. So now IE knows better.

I'm afraid what else might be missing. One thing I have noticed is that IE also messed up my favourites toolbar...

Pain!

It maybe the time for

kick it on DotNetKicks.com

Thursday, October 19, 2006 9:31:51 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [4]  | 
 Wednesday, October 18, 2006

Some time ago I have been searching for a solution to a common problem you have dealing with inheritance in web services. The main problem is that if you have a base class: Employee and two sub-classes: Manager and PartTimeEmployee, and you have a WebMethod that returns Employee - then it will not work if you just try to return any of the sub-classes. What you will get is an InvalidOperationException in a form of:

"System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type Manager was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

Fortunately, the error message also provides an information about what should be done: "Use the XmlInclude or SoapInclude attribute". If you have dealt with web services in .NET you have probably encountered this kind of problem and know the solution which is to put the mentionet XmlInclude attribute on the base class - in this case the Employee and specify all the derived types in there as in the example:

[XmlInclude(typeof(Manager))]
[
XmlInclude(typeof(PartTimeEmployee))]
public class Employee
{

This solves the problem of the inheritance only in part. Generally you not always have control over the inheritance structure at the time of writing the Employee class so you cannot use the XmlInclude there. I have found the answer for this problem here. Basicaly what you can do is put the XmlInclude attribute on the web method returning the Employee type. At the time of writing this method, you should have a more complete knowledge about the possible subtypes of the Employee class than you had while creating the class itself. The solution is far from perfect but it is still better than nothing.

There is also an interesting discussion about the issuue on the same page where I have found the article - in the comments section.

kick it on DotNetKicks.com

Wednesday, October 18, 2006 3:50:51 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Wednesday, October 11, 2006

Every once in a while I make members of my types "internal" so that I can access them inside my assembly but other code (other assemblies) using my types would not have access to those members. The same holds true for all kinds of helper classes that are either designed specifically to handle some internal tasks or whose api is to complicated to be exposed as public. Internal visibility is also the default visibility the class has if not specified otherwise such as in:

class MyClass
{
   
//...
}

Which makes the class "internal" - that is C# compiler defaults to internal.

Suppose now that the project you are working on consists of multiple assemblies be it because every assembly holds types representing different layers or because of the deployement requirements that specify that assemblies should be more granular.

One of the reasons for restricing visibility of types has been mentioned earlier. But what to do in the simple scenario where one company needs to create multiple assemblies, hide some types from public and still be able to use its own "hidden" types across assemblies?

In the old days when I was learning C++ I have learned about "friend classes". Basically what that meant was that one class allowed  other - well known - class to access its otherwise private members. Until recently I thought that It was impossible to do such a thing in .NET, but then came the InternalsVisibleToAttribute...

Although not the same as "friend class" from C++, the InternalsVisibleToAttribute which is new to .NET 2.0 allows you to specify which assembly has access to internal members of the defining assembly. MSDN: "Specifies that all nonpublic types in an assembly are visible to another assembly."

MSDN documentations explains how to use the InternalsVisibleToAttribute, which basically means that to make your internal types available to some other assembly you will need to specify which assemblies should have been able to access the internal types using  an assembly level attribute as follows:

[assembly: InternalsVisibleTo("AssemblyName, PublicKey=123124.....")]

Where AssemblyName is the name of the friend assembly and the PublicKey is the whole public key (not the token) that assembly will be using.

kick it on DotNetKicks.com

Wednesday, October 11, 2006 8:43:25 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Tuesday, October 10, 2006

Today I have realized that often when I'm writing code I'm using some skeleton methods that will encapsulate some part of the functionality that I don't really want to write right now. So for example I have a main code with a call to a method that does nothing, because its internals have not been defined yet as in the following example:

public int Calculate()
{
   int x = 1;
   
int y = DoSomething(x);
   
return y + 1;
}
private int DoSomething(int x)
{
   
throw new NotImplementedException();
}

The important thing here is the use of the "throw new NotImplementedException();" since it will ensure that in the future, at runtime I will not forget to implement the "DoSomething" method. This is the way I really recommend you to do instead of returning 0 or null value, because then you WILL forget about it.

Fortunately Visual Studio 2005 comes with some refactoring tools that enable you to generate the "DoSomething" method when you wrtite the line "int y = DoSomething(x);" via smart tag. It will even have a default implementation which throws an exception although of type Exception - which I don't understand. There are however situations when you write the method yourself and for this I have created a simpliest code snippet ever. It outputs the "throw new NotImplementedException();" frament inside your method. To use it just type nimpl from "Not Implemented".

The snippet is available in the package with all my other snippets that I use on daily basis. You can read more on the code snippets in my other article: Visual Studio Code Snippets.

kick it on DotNetKicks.com

Tuesday, October 10, 2006 3:03:26 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, October 09, 2006

Since the version 1.1 of the .NET framework I have been mesuring the performance of my code using the same simple pattern. This basically was something like this:

DateTime begin = DateTime.Now;
DoSomething();
DateTime end = DateTime.Now;
TimeSpan duration = end - begin;

For long running tasks it was good enough, but if a task was very short, often the difference between the begin and end was 0.

Such as the following code:

private void DoSomething()
{
   
int a = 1;
   
for (long i = 0; i < 100; i++)
   {
      a = a + a - 1;
   }
}

Which's duration allways equals to 0 on my, not so fast, machine.

Of course this is a known "feature" of the DateTime now in that it is far from perfect for messuring short periods of time.

So how do you messure the performance of your code without calling some unmanaged functions? Is it at all possible? In 1.1 I do not think so, but fortunately .NET 2.0 comes with a new class called Stopwatch.

The Stopwatch type is defined in the System.Diagnostics namespace and "Provides a set of methods and properties that you can use to accurately measure elapsed time" (MSDN). The code above used the imperfect DateTime.Now can now be written as follows:

Stopwatch sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
TimeSpan duration = sw.Elapsed;

Beside the fact that the duration will be much more accurate, the Stopwatch offers you a cleaner API to messure your time.

kick it on DotNetKicks.com

Monday, October 09, 2006 8:53:28 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, October 05, 2006

So the Google Code Search has made it debut and everyone is happy. Searching for example code has never been easier. Is it all that the the search provides? Is C#, C++, PHP, Java and other languages code all there is? Someone found a WinZip Serial Number Algoritm, but there is one more thing you can do...

Every time there is a code there are comments. So maybe we should try searching for comments? Indeed this could be funny. Try some of the following searches and see the results :-)

The cite of the day: "/* This is crazy, but we are desparate at this point... */" :-)

I'm sure you can come out with more funny search ideas. I expect a wave of creative blog posts that exploit some of the funniest comments out there.

kick it on DotNetKicks.com

Thursday, October 05, 2006 8:53:07 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 

Debuted just recently the new tool for programmers the Google Code Search is here.

Google Code Search

Maybe it will end the problem of documentation not having enough examples?

A sample search for a "foreach" construct in C# looks promissing.

kick it on DotNetKicks.com

Thursday, October 05, 2006 8:36:13 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, October 04, 2006

Today I have recieved a request for a sample on how to use MyObjectDataSource control. So without delay I have prepared a very simple web project which allows you to see the ease of use of the my control.

ObjectDataSourceExample.zip (19.05 KB)

Sample is divided into 4 pages explaining how to use some of the features of the control. Descrption is added on each page.

Wednesday, October 04, 2006 6:38:47 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

If you are developing n-tier application sooner or later you will find yourself in a situation where you need to move data between the tiers. Be it from the lowest tier - i.e.: the data tier or data access layer (DAL) to a middle tier such as business logic layer (BLL) or the other way around. So how to accomplish this task?

Actually there are many problems with moving data between tiers, especially if you like a clean OOP with a full domain model. Suppose you have a domain object filled with all the necessary methods such as a Teacher who can Grade Students. Now with this logic you also have the data such as Name for both the Sudent and the Teacher. That is your BLL. Now you also have a DAL in which you would like to have a method such as GetTeacherById or SaveStudent. What should those methods return (or accept as a parameter)? The easy answer is - your BLL objects. This implies the referrence from the DAL to BLL - which is wrong since most people will tell you that every layer should only reference the layer below. I agree with this recommendation completly. If you think about a situation where you would like to have some kind of lazy load mechanism for properties of your BLL objects or a simple method call that gets the data from the database such as Teacher.GetGradedStudents, you would have to have a referrence from BLL to DAL.

So is it possible to at the same time have a referrence from DAL to BLL and from BLL to DAL? In .NET it is not possible as long as both are in separate projects. This situation is called a Circular Refference and Visual Studio will not allow you to do it if you try.

So how to solve this issue? Surely there has to be a solution... There are many solutions to the problem. Microsoft has its way described in their article on Designing Data Tier Components and Passing Data Through Tiers. It is a good overview of the problem, but Microsoft being Micorosft has its way of thinking. After all they are the ones that promote the DataSet/DataTable objects.

In short: what you need is an additional component which I will call a Data Transfer Object (DTO). The DTO will be refferenced by both BLL and DAL but will not reference neither BLL nor DAL. This way we have no circular refference problem. The DTO objects will represent only the data, with no behavior. A DataSet/DataTable is an example of such an object. So is the DataReader or an XmlDocument. You can use any of the mentioned objects to move data from your DAL up to BLL, but it gets a little more difficult to do it the other way. More over, if you are not using Typed DataSets, how would you know how to access the name property of the Teacher object? By using an Indexer and a string argument to represent the column name? How do you know what columns are there in the database? Why do you need this knowledge in the BLL? You do not need it! Even more! It is a violation of the rule that the layer should only know about the layer immediatly below, but the database which dictates the column names is not directly below BLL it is below DAL. So not typed DataSets do not shield you from the database and that is why I think they are wrong. A better solution would be to use a strongly typed objects defined in a separate project. So for example there will be a Teacher class in the DTO with a Name property but without a Grade method.

As an example I have prepared a sample solution with 3 projects: BLL, DAL and DTO. You can download the sample here: DTOExample.zip (7.29 KB).

Keep in mind that the example presents only the simpliest scenario where BLL objects know about DAL and how to save themselves. In a real application it will most likely not be the case.

kick it on DotNetKicks.com

Wednesday, October 04, 2006 4:55:01 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  |