Click here to Skip to main content
15,896,118 members
Articles / Web Development / HTML

Resource File to JavaScript Object

Rate me:
Please Sign up or sign in to vote.
4.77/5 (14 votes)
23 Feb 2011CPOL1 min read 76.9K   751   25  
A web control that creates a JavaScript object representing a resx (resources) file and makes it available to be used from HTML and JavaScript code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections;
using System.IO;

namespace ResourcesToJavaScript
{
    /// <summary>
    /// Represents a class that can be used to render a javascript object that contains resource keys and values
    /// of a specific resX file dependant on the CurrentUI culture.
    /// </summary>
    public abstract class ResourcesToJavaScriptBase : Control
    {
        /// <summary>
        /// Gets the full resX file path.
        /// </summary>
        /// <returns></returns>
        protected abstract string GetResXFilePath();

        /// <summary>
        /// Sets and Gets the generated JavaScript object name.
        /// </summary>
        public abstract string JavaScriptObjectName
        {
            get;
            set;
        }

        /// <summary>
        /// Get the resource value of specific key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected abstract string GetResourceValue(string key);

        protected virtual void ValidateBeforeRender(System.Web.UI.HtmlTextWriter writer)
        {
            if (!File.Exists(GetResXFilePath()))
            {
                writer.Write("GlobalResourcesToJavaScript: " + this.ClientID + ": Can't find the file " + GetResXFilePath());
                return;
            }
            return;
        }
        protected override void OnLoad(EventArgs e)
        {
            if (!string.IsNullOrEmpty(JavaScriptObjectName) && File.Exists(GetResXFilePath()) &&
                !Page.ClientScript.IsClientScriptBlockRegistered(GetType(), JavaScriptObjectName))
            {
                StringBuilder script = new StringBuilder();
                script.Append("<script type=\"text/javascript\"> ");
                using (System.Resources.ResXResourceReader resourceReader = new System.Resources.ResXResourceReader(GetResXFilePath()))
                {

                    script.Append(" var " + JavaScriptObjectName + " = { ");
                    bool first = true;
                    foreach (DictionaryEntry entry in resourceReader)
                    {
                        if (first)
                            first = false;
                        else
                            script.Append(" , ");

                        script.Append(NormalizeVariableName(entry.Key as string));
                        script.Append(":");
                        script.Append("'" + GetResourceValue(entry.Key as string) + "'");
                    }
                    script.Append(" }; </script>");
                    Page.ClientScript.RegisterClientScriptBlock(GetType(), JavaScriptObjectName, script.ToString(), false);

                }
            }

            base.OnLoad(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            ValidateBeforeRender(writer);
            base.Render(writer);
        }

        /// <summary>
        /// Normalizes the variable names to be used as JavaScript variable names
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected static string NormalizeVariableName(string key)
        {
            return key.Replace('.', '_');
        }
    }

}

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)


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions