Thursday, July 9, 2009

State vs Status API guide

Today I had to make the choice whether I would use the word state or status in my program API, and I got confused. What is actually the difference?

This is not about states in the sense of the United States, but about the condition of something.

As an example, I will use the condition of the "something" called H2O, also known as water.

Luckily we as programmers are already familiar with the concept of a definition (class) and an instance (object). With state and status it's the same. State is a definition, and status is an instance of that definition.

So, H2O has several states, namely; Solid, Liquid and Gas. Solid is one state of the 3 states in which H2O can be. If we would query for the state of a H2O substance, then we would ask for its status. Like, Q: "What is the status of this 'water'?", A: "It's in a solid state, it's ice.".

In an API, you would have to stick to the right naming, because it can confuse the use of the API. Let me show you with an example in C#:

   enum H2OStates
{
Solid,
Liquid,
Gas
}

class H2O
{
public const H2OStates IceState = H2OStates.Solid;
public const H2OStates WaterState = H2OStates.Liquid;
public const H2OStates VaporState = H2OStates.Gas;

public H2OStates Status;
}


The confusion will probably occur with the definition of the H2O class. When you have a H2O object, something that comes to mind is to ask the question "What is the state of this H2O?". The property to return the state, should not be called State, but Status. Why? Because it could return any of the possible states, and not a single hard-coded state value of the H2O, like it is with the constants in the H2O class. Those constants should be named with State in stead of Status, because they always return the same static value, and not an item within a range of possible values.

But now I hear you ask, what about statuses? That's nothing more than a bunch of H2O instances with each having their Status property referring to a specific state.

Thursday, March 19, 2009

PHP's _SERVER["DOCUMENT_ROOT"] no good for filesystem path with virtual directories

One thing that can bring a serious headache is if you use the PHP variable $_SERVER["DOCUMENT_ROOT"] to open files in the file system and your site is placed in an Virtual Directory in IIS.

This server variable points to the root of the server and this is not necessarily the path the virtual directory points to.

Of course this solution could work in the right conditions; hosted on a web server and placed in a physical directory under this path. However, if you want to have a flexible application and avoid issues if it is placed in a virtual directory, then do not use this variable.

An alternative could be to use:
dirname(__FILE__)
This method with the provided constant will return the directory where the current script file (also for included files) is located. Then you can point to this path relatively if it is a well known location such as your application root. Another benefit is that this constant is always available, as the _SERVER[] constants are depending on the host.

So here's my advise: try to avoid using the $_SERVER["DOCUMENT_ROOT"] variable for paths and use physical paths instead.

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.