Tuesday, December 05, 2006

In one of my articles I have written about using Immediate Window for debugging purposes - how we can use this Window to debug an application without starting it. Basically you can use the Window, to start a debugging process on any of your methods just by invoking it in Immediate Window:

new MyNamespace.MyType().MyMethod()

or for static methods just

MyNamespace.MyType.MyMethod()

There are however other useful features that make this window even more powerful.

One of them is evaluation of commands. Take for example:

System.Guid.NewGuid()
{04653f8d-58d3-4254-adc8-fb6d95457b49}

Which presents you with a new Guid instance as a string. Nice feature to have since I'm no longer able to find the Generate Guid window in my Visual Studio 2005. This window was very useful when I was working with Visual Studio 2003.

The above is simply a static method call. Lets see what else can we do. The immediate window can be used as a simple (or very advanced when you think about it) calculator. Take for example:

5*5
25

What we get in return is... of course the result of this operation. Still this is also a method call underneath. We can go very far with this, as far as the .NET classes allows us to. If we need an advanced calculator we can use some of the Math's methods:

System.Math.Sqrt(4) + 3.2
5.2

Those are still only simple method calls. The interesting part begins with multi-line statements!

The immediate window allows commands to span multiple lines and include variables. With those you can do almost anything you could do in the normal code:

int x = 2;
2
int y = 3;
3
x + y
5

If you wonder how far you can go with Immediate Window, just consider this example:

System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("someconnectionstring");
System.Data.SqlClient.SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM SomeTable";
connection.Open();
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
reader[0];

Not that you will use the window for such commands, but it is nice to know what it can really do :-)

BTW: I have noticed that sometimes Visual Studio hides the Immediate Window from me. While doing so it also removes the one place in the menu that I know of that can be used to show the window: Debug->Windows->Immediate. If your Visual Studio also knows better, the shortcut Ctrl+Alt+I will help you.

kick it on DotNetKicks.com

Tuesday, December 05, 2006 9:29:12 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, November 23, 2006

Today I have recieved a comment on my article on Optimizing Rendered Page Size, that it is not possible to override the LoadPageStateFromPersistenceMediummethod of a Page class because it is marked as internal in ASP.NET 2.0. Strange thing was that I have made just that in one of the projects I have been working on with ASP.NET 2.0! So I went for some searching.

First thing I have checked the code to see if it really compiles with the override - it did. There is even a support from Intelisense for overriding this method. Next I want to see if the is LoadPageStateFromPersistenceMediummethod really internal. Using reflector I have been able to confirm this. It really is "protected internal virtual". So the question is: how am I able to override it?

The reason we are able to override such a method is that "protected internal" is an OR relationship which means that such a member is accessible in the types that derive from our type AND in all types defined in the assembly. This should make it clear why we are able to override this method.

What may be less clear is why overriding "protected internal" requires sometimes "protected override" instead of "protected internal override". If you read once more the definition, it clearly states that protected internal is accessible to sub-types and the assembly. So if you want to override a method in the same assembly you would use "protected internal override". If on the other hand you want to override this method in other assemblies you must not use the "internal" access modifier because it would make the method visible to every type in your assembly - which would in fact change the visibiliti of the method. This would of course result in an error from the compiler. In this case you would get the CS0507 error.

I hope this sheds some light on the issue.

kick it on DotNetKicks.com

Thursday, November 23, 2006 2:15:34 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 

Following my last article on IComparable vs IComparer interfaces I now present a common pattern that I have found to be very effective in terms of code usability.

In order to make working with IComparer implementing classes more natural and intelisense friendly I usually create the inner classes of the main class and expose the objects as as static properties or methods. The following example demonstrates:

public class Person
{
  int age;
  string name;
  public static IComparer<Person> GetPersonAgeComparer()
  {
    return new PersonAgeComparer();
  }
  public static IComparer<Person> GetPersonNameComparer()
  {
    return new PersonNameComparer();
  }
  private class PersonAgeComparer : IComparer<Person>
  {
    #region IComparer<Person> Members
    public int Compare(Person x, Person y)
    {
      return x.age.CompareTo(y.age);
    }
    #endregion
  }
  private class PersonNameComparer : IComparer<Person>
  {
    #region IComparer<Person> Members
    public int Compare(Person x, Person y)
    {
      return x.name.CompareTo(y.name);
    }
    #endregion
  }
}

Now when you need to sort a collection of Person objects you just get the right IComparer from the Person's static Get*Comparer methods. Notice that the IComparer classes are defined as private so the only way to create them is through the factory - like static method. Making the classes private is nice a way to prevent Intelisense from unnecessary displaying them when what we really need is the concrete object. Notice the use of generic interface, which is new to the .NET Framework 2.0. You could also use the partial classes feature to put the comparers in a separate file if necessary.

kick it on DotNetKicks.com

Thursday, November 23, 2006 1:25:33 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, November 22, 2006

In .NET some of the collection types such as Array, ArrayList, List<T> expose the Sort method that allows you to sort the collection. In order for those classes to sort the collection, there has to be a way for them to somehow compare objects with each other. The most basic Sort method usually does not require any arguments other than the collection itself in case of the static Array.Sort. In this case how does the framework know how to compare our objects? Is person1 greater than person2? Or maybe they are equal?

Enter the IComparable interface. By implementing this interface, the objects of the type become, as the name suggest, comparable, so now it is possible to compare person1 to person2 using a simple person1.CompareTo(person2) call. With this each Sort method can easily handle sorting. An example implementation of sort method is included in the MSDN documentation.

So what is wrong there? If you take a Int32 objects, a String object, the IComparable interface on those is pretty straightforward and self explaining. It is plain even to a non-technical person that 1 < 3 and "abc" = "abc". But what about a more complex types such as a custom Person type that represents a person in the real world.

What does it mean for one persons to be greater (or equal for that matter) than the other? It does not mean anything without a context, a criteria by which we compare the two. So for example if were to compare the age of both persons, we would be able to say if who is older (greater) or younger (lesser). We could compare their names, their salary or whatever, but we need to know the criteria before we start.

Suppose that we have a class definition of Person as follows:

public class Person : IComparable
{
  int age;
  string name;

What does it mean for an object of this class to be comparable to each other? Is the name used? Or maybe the age? The fact that we don't know! The only way to know is to check the documentation or the implementation of the CompareTo method. First one goes against the rule I like to follow that states that the code should be self documenting. In this case it isn't. The second option breaks the rule of encapsulation - that is, we have to know the implementation of an object to work with it. Fortunately there is another way to compare and sort objects.

Enter the IComparer interface. This interface allows you to compare two objects in a similar way the IComparable interface does. The difference here is that it IComparer allows for much greater expressiveness. An implementation of IComparer is always a class which does have a name. This name explains (or at least it should) exactly what it does. For example:

public class PersonAgeComparer : IComparer

Makes it obvious to everyone what will be the criteria for the comparison without breaking the encapsulation. This makes your code easier to understand and much more self documenting. I strongly discourage everyone from using the IComparable interface on classes where it is not explicit what would be compared, even if it will be the only comparison made.

kick it on DotNetKicks.com

Wednesday, November 22, 2006 7:48:06 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, November 09, 2006

The standard procedure when working with ASP.NET Web Projects looks more or less like this:

1) Open/Create a solution in Visual Studio
2) Add/Change some of the pages/code in the solution
3) Press F5 to build and run the project to see the effect of the changes

This procedure has its pros and cons. The main advantage is that we get a debugger support from the IDE, so in case of an exception, we have the possibility to see what and where went wrong. We can also step through the code and see what is being done step by step. Those are only the few of many good things the Visual Studio gives you. 

So what are the drawbacks of this standard procedure? Take for example a page which requires you to login before you can use it. Using the Visual Studio to run the browser you have to login every time you start the debug session. You can somehow work around this problem by creating a persistent cookie (remember me checkbox) so that you will not have to login every time. But what if you have to login using different user name and password? Providing logout button returns you to the original problem. The bigger problem is however with multi-step, wizard-like operations. If you have a 5 steps in your Wizard and something goes wrong on the last step, you have to close the browser to stop debugging (ASP.NET does not support the edit and continue feature with the standard Web Project). Then after making the required changes you have to start the wizard all over again.
Keep in mind that those are only simple examples to illustrate the problems and benefits of the standard approach. They are in no way complete.

Now, We know that there are problems and there are benefits of the "standard way" but there is another way that I'm sure most ASP.NET developers coming from backgrounds such as PHP know about and use a lot. This solution was the only possible way to test and debug your web applications if you had no debugger support from your IDE - like was the case few years ago and I'm not sure if it is still the case. Basically what you do is run your own browser and navigate to the page that Visual Studio would otherwise navigate to using the browser it has started. Now you can browse through the pages and test whatever you want and in case something goes wrong, you can just make the changes in the Visual Studio and recompile. It is possible since the IDE is not in the debugging state while you do this. (The scope of the changes may cause the running application to reload causing you to relogin, but this will not always be the case)

What we don't get with the alternative way of working with our pages is the debugger support, so now if something goes wrong we will get the error page instead of the break in the debugger. Fortunately you can always attach Visual Studio to a running process hosting ASP.NET and debug the application as usual. After you have found the error you can safely stop the debugger and you browse window will not be closed. Also you will not suffer from the startup time of required fro Visual Studio to start the browser and the debugger. This way instead of the edit and continue you can work with a save and refresh style.

I'm not saying that the second approach is better or worse. I'm only pointing out that in some cases there is a faster way to do things, especially when you are getting irritated by the Internet Explorer's address bar always remembering the wrong addresses :-).

kick it on DotNetKicks.com

Thursday, November 09, 2006 8:56:04 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Wednesday, November 01, 2006

There is a refactoring feature in Visual Studio 2005 that lets you generate method stubs for methods that don't exists yet. I have described this feature in my article on how implementing MembershipProvider can help to understand the Test Driven Development (TDD) rule of writing your tests first. Basicaly the feature I'm talking about generates a stub for a method and puts "throw new Excelption("The method or operation is not implemented.")".

As powerful and helpful as this feature is, there is a problem with it! It throws an Exception and not a more proper NotImplementedException as would be expected. We can change that!

The snippet responsible for generating method stubs is located in the Visual Studio installation folder. By default it is something like: "c:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Refactoring\MethodStub.snippet". Changing the original value of:

 <Function>SimpleTypeName(global::System.Exception)</Function>

to

<Function>SimpleTypeName(global::System.NotImplementedException)</Function>

While searching for the solution to method stub problem I have also found that there is a "PropertyStub.snippet" file which should be used to generate property stubs. However I have been unable to find a way to invoke this snippet (it is not the same as "prop" snippet"). I have made a search on google and found some discussion on Microsoft's site that property stubs are not supported because it is hard to inferr something from their usage. Strangely enough there are tools such as Resharper that allow you to generate such stubs and why would there be a snippet file?

kick it on DotNetKicks.com

Wednesday, November 01, 2006 4:12:51 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 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 [6]  | 

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]  |