Wednesday, December 3, 2008

Watch out with Assembly.LoadFile in ASP.NET

Today I ran into a very annoying problem in Visual Web Developer 2008 SP1. When I tried to compile my web solution, I got this warning and sometimes even error in the Error List:

Unable to update auto-refresh reference 'Assembly.dll'. Cannot copy assembly 'Assembly.dll' to file 'X:\PathToWebProjectDirectory\Bin\Assembly.dll'.  Unable to add 'X:\PathToExternalLibrary\Assembly.dll' to the Web site.  Unable to add file 'Bin\Assembly.dll'.  The process cannot access the file because it is being used by another process.

Of course, paths and file names will be different in your case. If you would search this problem on the internet, then you will find several forum topics about this issue and eventually some support articles: KB843370 and KB313512.

Although I followed these instructions, the problem was still not resolved. Then I looked into something mentioned in some of the forums postings; to check which application was holding the handles to the file, causing it not to be updated. With the Sysinternals Process Explorer I could identify that the ASP.NET Developement Server (Webdev.Webserver.EXE) was holding the handle.

By that time I realized that my own code loads that specific assembly to extract some resources. I used the Assembly.LoadFile method to load this assembly. This will cause the file-lock on the assembly making it impossible for Visual Studio to AutoUpdate the file, because the built-in ASP.NET Development Server is blocking the assembly.

So why does this not happen with other assemblies in the ASP.NET Development Server and only with my code? The reason for this can be found in the way how ASP.NET makes a cache of all the assemblies it loads. These copies are placed in a folder managed by ASP.NET. These files will be locked, but as they are copies, the locks cause no harm.

I found a solution in changing from the Assembly.LoadFile method to the Assembly.Load method. Note that you can call the Assembly.Load method multiple times, but it will physically load the assembly only once. Even though I pass only the assembly name as the string argument, ASP.NET finds its cached copy of the assembly and loads that .dll instead of the one in the Bin folder of my project. Now Visual Studio can overwrite the assembly in the Bin folder without a hassle, and I'm happy too. :-)

Tuesday, November 25, 2008

Create a CssStyleCollection instance programmatically

Update 2011-07-12: Refer to this answer on Stackoverflow for a more elegant solution.

The CssStyleCollection class is a very useful class in ASP.NET. It manages CSS nicely in a programmatic way. However, if you would like to create an instance of this class in your own code, you will find it rather impossible. The class is sealed, so there is no way to inherit it. Moreover, the constructors are private, so you cannot create a new object!

I've seen many questions about how to create an instance of this class in online forums when I searched for it myself today. The solution is to delve into the internals of the class with Reflection. In that way it is possible to call the two private constructors of the class.

You can use the code below:

using System.Reflection;
using System.Web.UI;

namespace Tools
{
public class CssStyleTools
{
/// <summary>
/// Creates an instance of the CssStyleCollection class by reflection.
/// </summary>
/// <returns>A new instance of the CssStyleCollection class.</returns>
public static CssStyleCollection Create()
{
return (CssStyleCollection)typeof(CssStyleCollection).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0].Invoke(null);
}

/// <summary>
/// Creates an instance of the CssStyleCollection class by reflection and stores view state in the provided state bag.
/// </summary>
/// <param name="state">The storage object for the state.</param>
/// <returns>A new instance of the CssStyleCollection class.</returns>
public static CssStyleCollection Create(StateBag state)
{
return (CssStyleCollection)typeof(CssStyleCollection).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[1].Invoke( new object[]{ state });
}
}
}

It is as simple as calling the following code:

CssStyleCollection css = CssStyleTools.Create();

Feel free to comment if it was any use to you.

Tuesday, August 12, 2008

Learn from your tracks

Why would you have a file on your system where status messages can be dumped? Because it is there to warn you. But what if that alarm bell is ringing, but you don't hear it? Problems will arise...

That's why you should check the log files for your applications from time to time. Or actually, make it a regular thing.

Know your tools and platforms, check in what ways there is logging.

For web development, these logs are interesting:
  • Windows Event Log - for ASP.NET exceptions
  • IIS Server Log
  • PHP Log
So, check what your creations are doing, and learn from the mistakes they make.

Tuesday, June 17, 2008

Using using's class alias declaration

One big annoyance I had for a long time, is that generic types can create such a long and cryptic declaration in your code. But today I discovered a hidden feature of the using declaration that makes coding so much easier.

using is not only useful for importing namespaces. You can use it to declare an alias (shortcut, abbreviaton) for a class name too.

It is very simple, here is an example:

using S = System.String;

If you use the type S in your code, then it will refer to the type System.String. Note that you have to fully qualify the name to the class.

Lets have a look at a more complex declaration:

using ComplexType = System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<int,object>;

With this declaration you save a lot of space in your code. The next example shows this, one statement uses the alias type and the other statement does not:

// Using the using class alias declaration.
ComplexType ct1 = new ComplexType();

// Using the regular declaration.
Dictionary<string,Dictionary<int,object>> ct2 = new Dictionary<string,Dictionary<int,object>>();


I can guess which one you like. ;-)

However, of course there are some drawbacks. They are the same as namespace import using statements.
  1. The using class alias declaration is only valid in the file where it is declared.
  2. You must specify the using class alias declaration before using it in the code.
Although, I think it is quite easy to overcome these, as you are already familiar using namespace import using statements.

For more information read the MSDN article using Directive (C#).

Tuesday, May 20, 2008

ADO.NET Connection Pooling

Today I discovered something fundamentally in ADO.NET that changed my view on creating database connections completely.

In my days of Delphi, PHP and Java, connecting to databases was very straightforward. I got very used to opening a database connection, keeping a reference of that connection and close it regarding the situation.

For PHP, this would mean close it as soon as possible. HTTP is stateless, and therefore I got used to close my connections at the end of every HTTP response.

With ASP.NET, this seems to be the same situation. The ADO.NET API actually provides the same similar method set, and you can find this pattern in many ASP.NET web page examples on the net.

For my current project, which is getting bigger and bigger in code base, code is moved to a library - so not as embedded code in aspx pages, code-behind files, or files in the App_Code folder. So all code is bundled together at one central spot.

However, this is not the case for many database related tasks. A lot of these are spread over separated classes. They all require a database connection, and create one as they need.

Now I bet you already knew that creating a database connection is a resource intensive task. Therefore, you would tend to avoid this as much as possible. From my past experience with other programming languages, I was familiar with the use of a Singleton database connection class. This only instance of the connection class would provide a centralized way to manage your connections, or even reduce it to only one connection.

I planned the design of this class for my ASP.NET website today, and with it, I ran into a problem. Even though I would only have one open connection, this connection would remain open even at times when it was not needed at all. At night, all the users would be sound asleep, but this class would still be putting coals on the fire. Therefore, I'd like to close the connection after a specific idle time.

While searching for this feature in ADO.NET, I ran into connection pooling instead. I couldn't find anything useful about this idle feature, but connection pooling gave me the answer.

Connection pooling, nicely described by William Vaughn in his blog, keeps connections open in the background. It is developed for a scenario where a lot of connections are opened and closed within a short period of time. Just like that is with the processing of ASP.NET web pages. Now the nice thing is, this feature is already enabled by default, and efficiently manages the connections in your ASP.NET pages.

This connection pooling eliminates the need for a centralized connection class pattern. It's "cheap" to open connections with ADO.NET, and might be even more efficient rather than a centralized solution. Imagine a situation with the centralized connection class, where you would have to pipe all your database needs over one single connection. You might have to wait for one operation to finish, before the other can start. Furthermore, you might be keeping a connection open even when you are not using it, a waste of resources.

Therefore my conclusion is, make happily new connections all over the place, close them as soon as possible, and use the same connection string. The connection pooling feature of ADO.NET will do the rest of the magic.

Saturday, May 3, 2008

My first working day...

...at this brand new weblog!

With this first post, I'll start off with my day to day findings during professional or semi-professional or non-professional working hours.

Since my current occupation is IT Engineer, this blog will be stuffed with things related to the world that is known as Information Technology. More specifically: software and web development.

Although my Dutch roots, I'll keep this weblog English only. To make it more easy for you, I'll label all my posts, so you can easily filter on your points of interest.

I hope you'll find it interesting to read and if it might have been helpful in any sense to you, please don't hesitate to place a comment! :-)

Bart Verkoeijen