Click here to Skip to main content
Click here to Skip to main content

Resource File to JavaScript Object

, 23 Feb 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

Introduction

This is an ASP.NET control that can be dragged to a webpage or user control. It registers a JavaScript block to the page, which contains an object that represents the contents of a resx (resource) file (key and value). This is useful to get resource strings from JavaScript code (client side).

Background

It is known that getting resource strings in client-side JavaScript is not straightforward. This control makes it easy to share the same server side resource files (resx files) in client side code.

Using the Code

This web control will write all the entries in the specified resx file to a JavaScript (client side) object. So please make sure that the resx file entries don't contain sensitive data and the number of the entries in the resx file is not too large.

The code contains two classes, ResourcesToJavaScriptBase and GlobalResourcesToJavaScript. ResourcesToJavaScriptBase acts as an abstract base class that contains the logic of the idea. GlobalResourcesToJavaScript is a concrete class that specializes the logic to handle global resources (in the App_GlobalResources folder).

Note: If the resource key contains a dot (.), it will be replaced by an underscore (_). Example: textBox1.Text will be converted to textBox1_Text in the JavaScript object.

ResourcesToJavaScriptBase
/// <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('.', '_');
    }
}
GlobalResourcesToJavaScript
/// <summary>
/// Represents a class that can be used to render
/// a JavaScript object that contains resource keys and values
/// of a specific global resX file dependant on the CurrentUI culture.
/// </summary>
public class GlobalResourcesToJavaScript : ResourcesToJavaScriptBase
{
    /// <summary>
    /// The name of the Global ResX file (ex: "Resource1"
    ///       if the ResX file is "Resource1.resx")
    /// </summary>
    public string GlobalResXFileName
    {
        get;
        set;
    }
 
    private string _javaScriptObjectName;
    /// <summary>
    /// Sets and Gets the generated JavaScript object name.
    /// if not set it will return the normalized GlobalResXFileName.
    /// </summary>
    public override string JavaScriptObjectName
    {
        set
        {
            _javaScriptObjectName = value;
        }
        get
        {
            if (!string.IsNullOrEmpty(_javaScriptObjectName) && 
                    _javaScriptObjectName.Trim() != string.Empty)
            {
                return NormalizeVariableName(_javaScriptObjectName);
            }
            return NormalizeVariableName(GlobalResXFileName);
        }
    }
 
    protected override string GetResourceValue(string key)
    {
        string value = HttpContext.GetGlobalResourceObject
			(GlobalResXFileName, key) as string;
        return value == null ? string.Empty : value;
    }
 
    protected override string GetResXFilePath()
    {
        return Page.MapPath(Path.Combine("~//App_GlobalResources", 
               GlobalResXFileName + ".resx"));
    }
 
    protected override void ValidateBeforeRender(System.Web.UI.HtmlTextWriter writer)
    {
        if (string.IsNullOrEmpty(GlobalResXFileName) || 
                 GlobalResXFileName.Trim() == string.Empty)
        {
            writer.Write("GlobalResourcesToJavaScript: " + 
              this.ClientID + ": Please specify GlobalResXFileName");
            return;
        }
        base.ValidateBeforeRender(writer);
    }
}

All we need to do is to add an instance of GlobalResourcesToJavaScript to a web page or user control and set the property GlobalResXFileName to the file title of the required resx file.

We also may set the property JavaScriptObjectName to the name we need to call the generated JavaScript object:

<ResourcesToJavaScript:GlobalResourcesToJavaScript 
    ID="GlobalResourceToJavaScript1" runat="server" 
    GlobalResXFileName="Resource1" JavaScriptObjectName="Resources">
</ResourcesToJavaScript:GlobalResourcesToJavaScript>

The generated JavaScript will be something like:

<script type="text/javascript"> 
  var Resources = { Entry1:'Entry 1 text' , Entry2:'Entry 2 text' , 
                    Entry3:'Entry 3 text' };
</script>

And this can be easily used from any JavaScript code like:

alert(Resources.Entry2);

History

  • 19th February, 2011: Initial post
  • 20th February, 2011: Article updated

License

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

Share

About the Author

Adel Refaat
LINK Development
Egypt Egypt
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
SuggestionHandling single quotes Pinmembermatthewmarkmiller2-Sep-12 14:11 
GeneralGoo job PinmemberSunasara Imdadhusen1-Mar-11 0:27 
GeneralRe: Goo job PinmemberAdel Kamel1-Mar-11 9:27 
GeneralMy vote of 5 PinmemberStart Shining27-Feb-11 17:32 
GeneralRe: My vote of 5 PinmemberAdel Kamel27-Feb-11 19:25 
GeneralMy vote of 5 Pinmemberjustinonday23-Feb-11 20:07 
GeneralRe: My vote of 5 PinmemberAdel Kamel25-Feb-11 22:05 
GeneralExcellent.........!!!!!!!!!!!! Pinmemberjustinonday23-Feb-11 20:07 
GeneralMy vote of 5 PinmemberMonjurul Habib23-Feb-11 17:48 
GeneralRe: My vote of 5 PinmemberAdel Kamel25-Feb-11 22:06 
Generalthanks for sharing PinmemberPranay Rana21-Feb-11 2:43 
GeneralMy vote of 5 PinmvpSandeep Mewara20-Feb-11 1:21 
GeneralRe: My vote of 5 PinmemberAdel Kamel20-Feb-11 19:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 23 Feb 2011
Article Copyright 2011 by Adel Refaat
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid