April 15, 2014

Access web.config settings from your JavaScript

When you create a set of interconnected web applications, or a mobile application that accesses a web service back-end, you have different service addresses that need to make their way into your JavaScript. Visual studio has XML transformations that apply to the app.config or web.config files, depending upon your build configuration, but that doesn't do you a lot of good if your client-side JavaScript is looking for the appropriate settings.
You can isolate those settings in a single JavaScript file, but that file needs to change when you deploy to the web or the cloud.
Here is a simple solution:
Create an IHTTPHandler that reads all the application settings from your web.config file and transforms them into a constant object (named appSettings) containing all the application settings. Add the reference to this "dynamic" JavaScript in your master page template.
As a HTTP Handler, it is fast, and because IsReusable is set, it is cached too.
    /// 
    /// Summary description for EnvironmentToJavascript1
    /// 
    /// 
    ///     Include a link to the dynamically generated script to the scripts section of the web page
    ///     
    /// 
public class AppSettings : IHttpHandler
    {
        /// 
        /// Create an "appSettings" namespace in a javascript file containing all the app settings from the web.config file
        /// 
        /// 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/javascript";
            context.Response.Write("var appSettings = {");
            foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            {
                context.Response.Write(string.Format("'{0}': '{1}',", key, ConfigurationManager.AppSettings[key]));
            }
            context.Response.Write("'loaded': true };");
        }

        /// 
        /// No dynamic values here, so feel free to cache the results. 
        /// If the web.config file changes, the app pool will also reset
        /// 
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }