Saturday, March 27, 2010

Accessing Global Resource Files from a Class Library in ASP.NET

If you add an App_GlobalResources Folder to your asp.net 2.0 web application you may want to access some of the values within it from a class library - such as a Business Logic Layer (BLL). Since there is unlikely to be a reference from your BLL to the main site, and even if there were, the designer class that shadows the resource file is declared with "Friend" keywords so that class would not be visible to the BLL. Therefore trying to call it using the Resources.[Filename].[key] syntax that works from anywhere within the site will not work. Instead you can simply create a wrapper like the following somwhere within your class library:

1 Imports System.Resources

2 Imports System.Web

3

4 Namespace Resources

5 Public Class ResourceWrapper

6

7 Public Shared Function Strings1(ByVal key As String) As String

8 Return HttpContext.GetGlobalResourceObject("Strings1", key)

9 End Function

10

11 Public Shared Function Strings2(ByVal key As String) As String

12 Return HttpContext.GetGlobalResourceObject("Strings2", key)

13 End Function

14

15 Public Shared Function Strings3(ByVal key As String) As String

16 Return HttpContext.GetGlobalResourceObject("Strings3", key)

17 End Function

18

19 End Class

20 End Namespace




Then you can retrieve values from the resource files from within your class library simply by passing in the key you want to retrieve:

Resources.ResourceWrapper.Strings1("SupportEmail")

This example assumes that you have created three .resx resource files inside the App_GlobalResources folder of an ASP.Net Web Application, and that you created them within Visual Studio (as opposed to a text editor for example), and that you named the files "Strings1.resx", "Strings2.resx" and "Strings3.resx", and that Strings1.resx contains the key "SupportEmail".



The Great thing about adding .resx files in this fashion is that you can actually edit the values in a text editor on the live site without having to recompile and republish your entire project. Having said that, adding new key value pairs in the text editor will not create the properties in the class that shadows it, and removing or renaming existig key value pairs could cause runtime errors so if you need to do anything other than change the value of an existing key, do so within visual studio and republish.

No comments:

Post a Comment