Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
3 Jan 2014 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).

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.

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.

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

E.g.:

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:

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

In our JS file, we can access as below:

var str = Resources.Resource.lblFormulaName;

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here