Custom HttpHandler in SharePoint for getting dynamic javascript code
By Anatoly Mironov
Sometimes I want to add some dynamic javascript code. E.g. I had an idea to get javascript code for localization dynamically. Kirk Evan provides a very clean approach to add ASP.NET HttpHandler to SharePoint. This is just a little lab: Create a SharePoint empty project. I call it Jerkelle. Create a class called Resx2JsHandler and implement the IHttpHandler interface Add the mapped folder Layouts and create Jerkelle.ashx file Here is the project. I probably will publish it on my github account: The Jerkelle.ashx file is very simple, it references to the code file (Resx2JsHandler.cs):
<%@ Assembly Name="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Jerkelle, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1140e8620a44557a" %>
<%@ WebHandler Language="C#" Class="Jerkelle.Resx2JsHandler" %>
```The code file is nothing advanced neither, for this little lab:
using System.Web;
namespace Jerkelle { public class Resx2JsHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = “text/plain”; context.Response.Write(“Hello HttpHandler from the site “); }
public bool IsReusable
{
get { return false; }
}
}
}
[![](https://sharepointkunskap.files.wordpress.com/2012/02/jerkelle-003.png "jerkelle-003")](https://sharepointkunskap.files.wordpress.com/2012/02/jerkelle-003.png) So now it is time to deploy! Then when we hit the ashx in the address bar we'll get the nice message: "Hello HttpHandler from the site". Isn't it beautiful? [![](https://sharepointkunskap.files.wordpress.com/2012/02/jerkelle-001.png "jerkelle-001")](https://sharepointkunskap.files.wordpress.com/2012/02/jerkelle-001.png) Allright, so far so good. But the intention of this lab is to create a dynamic javascript file. Well, it doesn't need to be dynamic for now. Let's convert it to a javascript source file. In order to quickly test, let's write a simple alert:
using System.Web;
namespace Jerkelle { public class Resx2JsHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = “application/x-javascript”; context.Response.Write(”alert(‘Hello from ashx’);”); }
public bool IsReusable
{
get { return false; }
}
}
}
Now we can run this by adding it to the page as a script. Or just let's add it with a little script ([like we did with jQuery](/2011/05/17/ladda-jquery-dynamiskt-till-din-sida/)):
var script = document.createElement(“script”); script.setAttribute(“type”,“text/javascript”); script.setAttribute(“src”,"/_layouts/jerkelle.ashx"); document.body.appendChild(script);
public class Resx2JsHandler : IHttpHandler { public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { var res = context.Request.QueryString[“res”]; var js = GetJavascript(res); context.Response.ContentType = “application/x-javascript”; context.Response.Write(js); }
private static string GetJavascript(string res)
{
var result = string.Empty;
if (res == null)
{
return result;
}
var ci = SPContext.Current != null
? new CultureInfo((int) SPContext.Current.Web.Language)
: CultureInfo.CurrentCulture;
var name = ci.Name;
var fileName = string.Format("\\\\Resources\\\\{0}.{1}.resx", res, name);
var path = SPUtility.GetGenericSetupPath(fileName);
var text = GetContent(path);
var json = ConvertToJson(text);
result = string.Format("{0} = {1};\\n", res, json);
return result;
}
private static string ConvertToJson(string text)
{
var json = string.Empty;
var doc = new XmlDocument();
doc.LoadXml(text);
var elements = doc.SelectNodes("/root/data");
if (elements == null)
{
return json;
}
var pairs = new List();
foreach(XmlNode e in elements)
{
var name = e.Attributes\[0\].Value;
var value = e.FirstChild.InnerText.Trim().Replace("\\"", "'");
value = Regex.Replace(value, "\\r?\\n", "");
var pair = string.Format("\\t\\"{0}\\" : \\"{1}\\"", name, value);
pairs.Add(pair);
}
var s = string.Join(",\\n", pairs.ToArray());
json = string.Format("{{\\n{0}}}", s);
return json;
}
private static string GetContent(string path)
{
var content = string.Empty;
SPSecurity.RunWithElevatedPrivileges(() =>
{
content = System.IO.File.ReadAllText(path);
});
return content;
}
}
User **res** query string to get a localization file: [![](https://sharepointkunskap.files.wordpress.com/2012/02/jerkelle-005.png "jerkelle-005")](https://sharepointkunskap.files.wordpress.com/2012/02/jerkelle-005.png)
##### ScriptResx.ashx
EDIT: [Later I discovered ScriptResx.ashx: there is already such an httphandler, with its shortcomings but, it is already implemented](/2012/02/13/scriptresx-ashx-in-sharepoint/ "See my post about the built-in ScriptResx.ashx httphandler").