Click here to Skip to main content
15,887,596 members
Articles / Web Development / ASP.NET
Tip/Trick

Create a Dynamic JavaScript File for Global Resorce File Creation in JS Format Using ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.29/5 (4 votes)
3 Jan 2014CPOL 25.3K   6   1
Global Resorce File Creation in json Format using ASP.NET

Introduction

This is my first tip on CodeProject.

In this tip, I discuss how to create dynamic JavaScript file in json format for Global Resource Files (.resx) in ASP.NET. (Sample code is given For ASP.NET MVC but you can also utilize in classic ASP.NET applications.)

Using the Code

Let's start..............

First, create 1 Resource file in our Application Name: "Resource.resx" in App_GlobalResources folder.

Create the following method in any controller. (You can also use HomeController).

C#
public JavaScriptResult GlobalResourceJSCreate()
{ 
     return ResourceSerialiser.GetResourceScript(Resource.ResourceManager);
} 

Where Resource is my Resource.resx file in App_GlobalResources Directory we created. Now we need ResourceSerialiser Class for GetResourceScript method to execute.

C#
namespace ProjectName
{ 
    /// <summary>
    /// Utility class that allows serialisation of .NET resource files (.resx)
    /// into different formats
    /// </summary>
    public static class ResourceSerialiser
    {
        public static JavaScriptResult GetResourceScript(ResourceManager resourceManager)
        {
            string cacheName = string.Format
            ("ResourceJavaScripter.{0}", CultureInfo.CurrentCulture.Name);

            JavaScriptResult value = HttpRuntime.Cache.Get(cacheName) as JavaScriptResult;

            if (value == null)
            {
                JavaScriptResult javaScriptResult = CreateResourceScript(resourceManager);
                HttpContext.Current.Cache.Insert(cacheName, javaScriptResult);
                return javaScriptResult;
            }

            return value;
        }

        static JavaScriptResult CreateResourceScript(ResourceManager resourceManager)
        {
            ResourceSet defaultSet = resourceManager.GetResourceSet
            	(CultureInfo.GetCultureInfo("en"), true, true);
            ResourceSet resourceSet = resourceManager.GetResourceSet
            	(CultureInfo.CurrentCulture, true, true);

            var resourceBaseName = resourceManager.BaseName;
            var jsonObjectName = resourceBaseName.Substring(resourceBaseName.LastIndexOf(".") + 1);

            StringBuilder sb = new StringBuilder();
            sb.Append(jsonObjectName);
            sb.Append("={");
            foreach (DictionaryEntry dictionaryEntry in resourceSet)
                if (dictionaryEntry.Value is string)
                {
                    string value = resourceSet.GetString
                    ((string)dictionaryEntry.Key) ?? (string)dictionaryEntry.Value;
                    sb.AppendFormat("\"{0}\":\
                    "{1}\",", dictionaryEntry.Key, EncodeValue(value)); 
                }

            string script = sb.ToString();
            if (!string.IsNullOrEmpty(script)) 
                script = script.Remove(script.Length - 1);

            script += "};"; 

            JavaScriptResult result = new JavaScriptResult { Script = script };
            return result;
        } 

        static string EncodeValue(string value)
        {
            value = (value).Replace("\"", "\\\"").Replace('{', '[').Replace('}', ']');
            value = value.Trim();
            value = System.Text.RegularExpressions.Regex.Replace(value, @"\s", " ");
            return value;
        }
    }
}

Now add the below line to the RegisterRoutes method located in the Global.asax.cs file in our application.

This creates a JS file in the root directory.

JavaScript
routes.MapRoute("JSFileName", "JSFileName.js", 
new { controller = "Home", action = "GlobalResourceJSCreate" });   

E.g.:

C#
public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  routes.MapRoute("JSFileName", "JSFileName.js", 
  new { controller = "Home", action = "GlobalResourceJSCreate" });
  routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", 
            action = "Index", id = UrlParameter.Optional } // Parameter defaults
                 );
}

Now we need to add Url to our master page so we can use Global Resource File key value combination in JS file as below:

JavaScript
<script src="<%= ConfigurationManager.AppSettings["AppUrl"] 
%>/JSFileName.js" type="text/javascript"></script> 

In our JS file, we can access as below:

JavaScript
var str = Resources.Resource.lblFormulaName;

Where <code>lblFormulaName is Name in "Resource.resx" file and above statement returns Value "Formula Name".

License

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


Written By
Software Developer at Infosys ltd.
India India
Kiran is from India. He started his programming career with C and C++. After programming C/C++ for 2 years during his graduation he discovered his favorite programming language C#. He is working as software engineer at ITMC soft india pvt ltd. He is using Javascript, Jquery, HTML5, Asp.Net(Classic),Asp.Net MVC to develop applications or programs.

Comments and Discussions

 
SuggestionNice tip, but didn't work for me... Pin
Karim B.27-Aug-14 5:24
Karim B.27-Aug-14 5:24 

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

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