Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
 
Add your own
alternative version

Declarative ASP.NET globalization

, 16 Apr 2004
An article on how to implement globalization support for ASP.NET pages through attributes and reflection
DeclarativeGlobalization_src.zip
GlobalizationModule
bin
Debug
GlobalizationModule.pdb
Release
GlobalizationModule.csproj.user
httppipeline.gif
obj
Debug
GlobalizationModule.pdb
Release
MyWebApp
bin
fi-FI
fr-FR
GlobalizationModule.pdb
MyWebApp.pdb
sv-SE
Controls
flags
Finland.gif
France.gif
Sweden.gif
UnitedKingdom.gif
Global.asax
MyWebApp.csproj.webinfo
MyWebApp.vsdisco
using System;
using System.Web;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Configuration;

namespace GlobalizationModule
{
	/// <summary>
	/// GlobalizationMod is an IHttpModule implementation. It does the
	/// leg work of processing the Localize attributes on a web page
	/// and putting the localized values into the controls.
	/// </summary>
	public class GlobalizationMod : IHttpModule
	{
		public GlobalizationMod()
		{}

        HttpApplication app_;
        System.Web.UI.Page page_;

        /// <summary>
        /// Init prepares to handle the PreRequestHandlerExecute event
        /// of the HttpApplication.
        /// </summary>
        public void Init(HttpApplication app)
        {
            app_ = app;
            app_.PreRequestHandlerExecute += new EventHandler(this.OnPreRequest);
        }

        public void Dispose()
        {
            app_.PreRequestHandlerExecute -= new EventHandler(this.OnPreRequest);
            page_.PreRender -= new EventHandler(this.OnPreRender);
        }

        /// <summary>
        /// PreRequest prepares to handle the PreRender event of the page.
        /// </summary>
        /// <param name="sender">HttpApplication</param>
        /// <param name="eventArgs"></param>
        public void OnPreRequest(object sender, EventArgs eventArgs)
        {
            // Get the IHttpHandler from the HttpApplication
            HttpContext ctx = ((HttpApplication)sender).Context;
            IHttpHandler handler = ctx.Handler;

            // Handle the PreRender event of the page
            if (handler is System.Web.UI.Page)
            {
                page_ = (System.Web.UI.Page)handler;
                page_.PreRender += new EventHandler(this.OnPreRender);
            }
        }

        // Remember user's page class
        private System.Web.UI.Page targetPage_;
        // Remember root attribute
        private LocalizeAttribute rootAttribute_;

        /// <summary>
        /// OnPreRender performs the localization logic.
        /// </summary>
        /// <param name="sender">Web page instance</param>
        /// <param name="eventArgs"></param>
        public void OnPreRender(object sender, EventArgs eventArgs)
        {
            // If current culture is the same as the web site's
            // default language, then we do nothing
            CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
            if (ConfigurationSettings.AppSettings["DefaultLanguage"] == currentCulture.Name)
                return;

            System.Web.UI.Page page = (System.Web.UI.Page)sender;

            
            // Localize the page if it has the Localize attribute
            object[] typeAttrs = page.GetType().GetCustomAttributes(typeof(LocalizeAttribute), true);
            if (typeAttrs != null && typeAttrs.Length > 0)
            {
                LocalizeObject(null, sender, (LocalizeAttribute)typeAttrs[0]);
            }            
        }

        /// <summary>
        /// Localize target based on attribute.
        /// </summary>
        /// <param name="fieldInfo">Reflection.FieldInfo with information about 'target'</param>
        /// <param name="target">Object to localize</param>
        /// <param name="attr">Localization attribute</param>
        protected void LocalizeObject(FieldInfo fieldInfo, object target, LocalizeAttribute attr)
        {
            if (attr.Mode == LocalizeAttribute.LocalizeMode.Fields)
            {
                //
                // Localize child objects of target
                //
                FieldInfo[] fields = null;
                Type targetType = null;

                if (target is System.Web.UI.Page)
                {   // Remember the web page class
                    targetPage_ = (System.Web.UI.Page)target;
                    // Remember root attribute
                    rootAttribute_ = attr;
                    targetType = target.GetType().BaseType;
                }
                else
                {
                    targetType = target.GetType();
                }

                //
                // Localize fields that have the Localize attribute
                //
                fields = targetType.GetFields(BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public);
                foreach (FieldInfo f in fields)
                {
                    // Get the child instance
                    object child = f.GetValue(target);
                    if (child != null)
                    {                     
                        // Localize this object if it has the Localize attribute
                        object[] typeAttrs = f.GetCustomAttributes(typeof(LocalizeAttribute), false);
                        if (typeAttrs != null && typeAttrs.Length > 0)
                        {
                            LocalizeObject(f, child, (LocalizeAttribute)typeAttrs[0]);
                        }
                    }
                }
            }
            else // attr.Mode != LocalizeAttribute.LocalizeMode.Fields
            {
                // If this attribute has no resource name specified,
                // use the root attribute's resource name as base resource name.
                if (attr.ResourceBaseName == null)
                    attr.ResourceBaseName = rootAttribute_.ResourceBaseName;

                // If this attribute has no resource name specified,
                // use the target object's name as resource name.
                if (attr.ResourceName == null)
                    attr.ResourceName = fieldInfo.Name;

                // The actual localization of the target is performed
                // by the attribute. Seems odd? Well, this way the developer
                // can implement his/her own localization logic by deriving a
                // class from LocalizeAttribute and overriding the Localize
                // method.
                attr.LocalizeObject(target, targetPage_);
            }
        }
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sami Vaaraniemi
Web Developer
Finland Finland
Sami Vaaraniemi has been working as a software developer since 1990, primarily on Microsoft technologies. After 12 years of Win32 API and C++ he switched to .NET. He currently works as an independent consultant and can be contacted through his website at www.capehill.net.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 17 Apr 2004
Article Copyright 2003 by Sami Vaaraniemi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid