Skip to content

Instantly share code, notes, and snippets.

@doeringp
Last active July 12, 2016 10:36
Show Gist options
  • Save doeringp/3de42fa1fc100a3b2d3faaedd2835af6 to your computer and use it in GitHub Desktop.
Save doeringp/3de42fa1fc100a3b2d3faaedd2835af6 to your computer and use it in GitHub Desktop.
Make RESX files available at client-side for JavaScript.
using System;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
namespace AspNetWebFormsApp
{
/// <summary>
/// This page generates a JavaScript file from a certain resource file within the App_GlobalResources folder.
/// The keys are available from JavaScript with the window.Resources global variable.
/// </summary>
public partial class Resources : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// TODO: Set your resource class key here.
const string classKey = "MyResourceFileClassKey";
WriteAsJson(GetResources(classKey));
}
private static IEnumerable<DictionaryEntry> GetResources(string classKey)
{
string baseName = $"Resources.{classKey}";
var resourceManager = new ResourceManager(baseName, Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
return resourceSet.Cast<DictionaryEntry>();
}
private void WriteAsJson(IEnumerable<DictionaryEntry> resourceSet)
{
Response.Clear();
Response.ContentType = "text/javascript; charset=utf-8";
Response.Write("window.Resources = {\n");
foreach (DictionaryEntry entry in resourceSet)
{
string key = Escape((string) entry.Key);
string value = Escape((string) entry.Value);
Response.Write($"'{key}': '{value}',\n");
}
Response.Write("}");
Response.End();
}
private string Escape(string s)
{
return s.Replace("'", @"\'").Replace("\r", "").Replace("\n", @"\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment