using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
namespace MyWeb.Models
{
public class AppScriptsHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
static string[] debugClients = null;
static string[] DebugClients
{
get
{
if (debugClients == null)
{
var list = new List<string>();
string config =
ConfigurationManager.AppSettings["AppScriptsDebugClients"];
if (!string.IsNullOrEmpty(config))
{
foreach (string ip in config.Split(',', ';'))
{
//Replace to regular expression pattern
list.Add(ip.Replace("*", "[0-9]+").Replace(".", "\\."));
}
}
debugClients = list.ToArray();
}
return debugClients;
}
}
//Check if the ip address matches any pattern in DebugClients
static bool IsDebugClient(string ip)
{
foreach (string ipPattern in DebugClients)
{
if (Regex.IsMatch(ip, ipPattern))
return true;
}
return false;
}
public void ProcessRequest(HttpContext context)
{
string jsFile = Path.GetFileName(context.Request.Url.AbsolutePath).ToLower();
string jsPath = Path.Combine(
HostingEnvironment.MapPath("~/Scripts/mycode"), jsFile);
var resp = context.Response;
if (!jsFile.EndsWith(".js") || !File.Exists(jsPath))
{
resp.Write("//JavaScript not found: " + jsFile);
}
else
{
string js = File.ReadAllText(jsPath);
resp.ContentType = "text/javascript";
if (jsFile.EndsWith(".min.js") ||
IsDebugClient(context.Request.UserHostAddress))
{
//if already minified or from debug clients
resp.Write(js);
}
else
{
//return minified result
Minifier minifier = new Minifier();
resp.Write(minifier.MinifyJavaScript(js));
}
}
}
}
}