|
Wow, resource files are useful in web apps
Jeff Key January 16, 2002 Visual Studio.NET makes it very easy to use resource files, so why not take advantage of them? You can store just about anything in them, including strings, images and persisted objects, but the most useful for web apps is strings. I was originally using them for error message management, but realized that they could offer more, especially in a text-intensive application where having packaged units might be beneficial. Another advantage is their read-only nature; people (ie. clients) can’t modify the contents unless you provide them with an application that writes satellite assemblies.
Availability
Using in web apps In my specific case, I found that my error messages were long enough to make my code look messy and decreased the readability. Simply putting the error messages into a local resource file (compiled with the assembly) made the code much easier to follow. You can add a resource file via the "Add Item…" item in the Solution Explorer. When you open the file, you’re presented with VS.NET’s XML editor, as the resx format is a simple XML document. The columns presented are Name, Value, Comment, Type and MimeType. When using strings, you only need to be concerned with the Name and Value columns. Reading from the resourceAs with everything .NET, there are a number of different ways to get at the resources. The ResourceManager class offers the simplest way. The most useful constructor takes an assembly and the root name to pick the resources from. For example, if you have a resource in your application ("MyApplication") with the name of "res.resx", you would create an instance with the following:
ResourceManager rm = new ResourceManager("MyApplication.res",
Assembly.GetExecutingAssembly())
Once you have a reference to the ResourceManager, it’s just a matter of calling its GetString method.
string s = rm.GetString("TheKey");
This simple feature, in conjunction with the String class’s static Format method, makes for powerful string handling. Instead of:
throw new Exception("The file ‘" + filename + "’ cannot be deleted from the ‘"
+ dir + "’ directory because of the following error: " + ex.Message + ". Please
ensure that that file is not currently being used.")
I can put the following string (name = "FileDeleteError) into the resource file:
The file ‘{0}’ cannot be deleted from the ‘{1}’ directory because of the
following error: {2}. Please ensure that that file is not currently being used.
And reference it with the following:
throw new Exception(String.Format(rm.GetString("FileDeleteError", filename,
dir, ex.Message)));
Much nicer. Dynamically
loading and using satellite resource assemblies
Summary |