public static void Initialize()
{
if (isInitialized)
return;
isInitialized = true;
isEnabled = false;
bundleKeyBySourceUrl = null;
bundleByKey = null;
#if !COREFX
MsieJsEngine jsEngine = null;
#endif
try
{
var setting = ConfigurationManager.AppSettings["ScriptBundling"];
var settings = JsonConvert.DeserializeObject<ScriptBundlingSettings>(
setting.TrimToNull() ?? "{}", JsonSettings.Tolerant);
if (settings == null ||
settings.Enabled != true)
return;
var bundles = ScriptBundles;
if (bundles == null ||
bundles.Count == 0)
{
return;
}
var bundleKeyBySourceUrlNew = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var bundleByKeyNew = new Dictionary<string, ConcatenatedScript>(StringComparer.OrdinalIgnoreCase);
bool minimize = settings.Minimize == true;
foreach (var pair in bundles)
{
var sourceFiles = pair.Value;
if (sourceFiles == null ||
sourceFiles.Length == 0)
continue;
var bundleKey = pair.Key;
var bundleName = "Bundle." + bundleKey;
var bundleParts = new List<Func<string>>();
foreach (var sourceFile in sourceFiles)
{
if (sourceFile.IsNullOrEmpty())
continue;
string sourceUrl = ExpandVersionVariable(sourceFile);
sourceUrl = VirtualPathUtility.ToAbsolute(sourceUrl);
if (sourceUrl.IsNullOrEmpty())
continue;
bundleKeyBySourceUrlNew[sourceUrl] = bundleKey;
bundleParts.Add(() =>
{
var sourcePath = HostingEnvironment.MapPath(sourceUrl);
if (!File.Exists(sourcePath))
return String.Format(errorLines, String.Format("File {0} is not found!", sourcePath));
if (minimize)
{
if (settings.UseMinJS == true)
{
var minPath = Path.ChangeExtension(sourcePath, ".min.js");
if (File.Exists(minPath))
{
sourcePath = minPath;
using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
return sr.ReadToEnd();
}
}
string code;
using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
code = sr.ReadToEnd();
#if COREFX
return code;
#else
try
{
return MinimizeWithUglifyJS(ref jsEngine, code);
}
catch (Exception ex)
{
ex.Log();
return code;
}
#endif
}
using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
return sr.ReadToEnd();
});
}
var bundle = new ConcatenatedScript(bundleParts);
DynamicScriptManager.Register(bundleName, bundle);
bundleByKeyNew[bundleKey] = bundle;
}
bundleKeyBySourceUrl = bundleKeyBySourceUrlNew;
bundleByKey = bundleByKeyNew;
isEnabled = true;
}
catch (Exception ex)
{
ex.Log();
}
finally
{
#if !COREFX
if (jsEngine != null)
jsEngine.Dispose();
#endif
}
}