1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
|
//
// System.Web.Compilation.AppResourceAseemblyBuilder
//
// Authors:
// Marek Habersack <grendel@twistedcode.net>
//
// (C) 2007-2009 Novell, Inc (http://novell.com/)
// (C) 2011 Xamarin, Inc (http://xamarin.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.Util;
namespace System.Web.Compilation
{
class AppResourcesAssemblyBuilder
{
#if NET_4_5
static string framework_version = "4.5";
static string profile_path = "net_4_5";
#elif NET_4_0
static string framework_version = "4.0";
static string profile_path = "net_4_0";
#else
static string framework_version = "2.0";
static string profile_path = "net_2_0";
#endif
CompilationSection config;
CompilerInfo ci;
CodeDomProvider _provider;
string baseAssemblyPath;
string baseAssemblyDirectory;
string canonicAssemblyName;
Assembly mainAssembly;
AppResourcesCompiler appResourcesCompiler;
public CodeDomProvider Provider {
get {
if (_provider == null)
_provider = ci.CreateProvider ();
else
return _provider;
if (_provider == null)
throw new ApplicationException ("Failed to instantiate the default compiler.");
return _provider;
}
}
public Assembly MainAssembly {
get { return mainAssembly; }
}
public AppResourcesAssemblyBuilder (string canonicAssemblyName, string baseAssemblyPath, AppResourcesCompiler appres)
{
this.appResourcesCompiler = appres;
this.baseAssemblyPath = baseAssemblyPath;
this.baseAssemblyDirectory = Path.GetDirectoryName (baseAssemblyPath);
this.canonicAssemblyName = canonicAssemblyName;
config = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
if (config == null || !CodeDomProvider.IsDefinedLanguage (config.DefaultLanguage))
throw new ApplicationException ("Could not get the default compiler.");
ci = CodeDomProvider.GetCompilerInfo (config.DefaultLanguage);
if (ci == null || !ci.IsCodeDomProviderTypeValid)
throw new ApplicationException ("Failed to obtain the default compiler information.");
}
public void Build ()
{
Build (null);
}
public void Build (CodeCompileUnit unit)
{
Dictionary <string, List <string>> cultures = appResourcesCompiler.CultureFiles;
List <string> defaultCultureFiles = appResourcesCompiler.DefaultCultureFiles;
if (defaultCultureFiles != null)
BuildDefaultAssembly (defaultCultureFiles, unit);
foreach (KeyValuePair <string, List <string>> kvp in cultures)
BuildSatelliteAssembly (kvp.Key, kvp.Value);
}
void BuildDefaultAssembly (List <string> files, CodeCompileUnit unit)
{
AssemblyBuilder abuilder = new AssemblyBuilder (Provider);
if (unit != null)
abuilder.AddCodeCompileUnit (unit);
CompilerParameters cp = ci.CreateDefaultCompilerParameters ();
cp.OutputAssembly = baseAssemblyPath;
cp.GenerateExecutable = false;
cp.TreatWarningsAsErrors = true;
cp.IncludeDebugInformation = config.Debug;
foreach (string f in files)
cp.EmbeddedResources.Add (f);
CompilerResults results = abuilder.BuildAssembly (cp);
if (results == null)
return;
if (results.NativeCompilerReturnValue == 0) {
mainAssembly = results.CompiledAssembly;
BuildManager.TopLevelAssemblies.Add (mainAssembly);
} else {
if (HttpContext.Current.IsCustomErrorEnabled)
throw new ApplicationException ("An error occurred while compiling global resources.");
throw new CompilationException (null, results.Errors, null);
}
HttpRuntime.WritePreservationFile (mainAssembly, canonicAssemblyName);
HttpRuntime.EnableAssemblyMapping (true);
}
void BuildSatelliteAssembly (string cultureName, List <string> files)
{
string assemblyPath = BuildAssemblyPath (cultureName);
var info = new ProcessStartInfo ();
var al = new Process ();
string arguments = SetAlPath (info);
var sb = new StringBuilder (arguments);
sb.Append ("/c:\"" + cultureName + "\" ");
sb.Append ("/t:lib ");
sb.Append ("/out:\"" + assemblyPath + "\" ");
if (mainAssembly != null)
sb.Append ("/template:\"" + mainAssembly.Location + "\" ");
string responseFilePath = assemblyPath + ".response";
using (FileStream fs = File.OpenWrite (responseFilePath)) {
using (StreamWriter sw = new StreamWriter (fs)) {
foreach (string f in files)
sw.WriteLine ("/embed:\"" + f + "\" ");
}
}
sb.Append ("@\"" + responseFilePath + "\"");
info.Arguments = sb.ToString ();
info.CreateNoWindow = true;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
al.StartInfo = info;
var alOutput = new StringCollection ();
var alMutex = new Mutex ();
DataReceivedEventHandler outputHandler = (object sender, DataReceivedEventArgs args) => {
if (args.Data != null) {
alMutex.WaitOne ();
alOutput.Add (args.Data);
alMutex.ReleaseMutex ();
}
};
al.ErrorDataReceived += outputHandler;
al.OutputDataReceived += outputHandler;
// TODO: consider using asynchronous processes
try {
al.Start ();
} catch (Exception ex) {
throw new HttpException (String.Format ("Error running {0}", al.StartInfo.FileName), ex);
}
Exception alException = null;
int exitCode = 0;
try {
al.BeginOutputReadLine ();
al.BeginErrorReadLine ();
al.WaitForExit ();
exitCode = al.ExitCode;
} catch (Exception ex) {
alException = ex;
} finally {
al.CancelErrorRead ();
al.CancelOutputRead ();
al.Close ();
}
if (exitCode != 0 || alException != null) {
// TODO: consider adding a new type of compilation exception,
// tailored for al
CompilerErrorCollection errors = null;
if (alOutput.Count != 0) {
foreach (string line in alOutput) {
if (!line.StartsWith ("ALINK: error ", StringComparison.Ordinal))
continue;
if (errors == null)
errors = new CompilerErrorCollection ();
int colon = line.IndexOf (':', 13);
string errorNumber = colon != -1 ? line.Substring (13, colon - 13) : "Unknown";
string errorText = colon != -1 ? line.Substring (colon + 1) : line.Substring (13);
errors.Add (new CompilerError (Path.GetFileName (assemblyPath), 0, 0, errorNumber, errorText));
}
}
throw new CompilationException (Path.GetFileName (assemblyPath), errors, null);
}
}
string SetAlPath (ProcessStartInfo info)
{
if (RuntimeHelpers.RunningOnWindows) {
string alPath;
string monoPath;
PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
MethodInfo get_gac = gac.GetGetMethod (true);
string p = Path.GetDirectoryName ((string) get_gac.Invoke (null, null));
monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (p)), "bin\\mono.bat");
if (!File.Exists (monoPath)) {
monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (p)), "bin\\mono.exe");
if (!File.Exists (monoPath)) {
monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (Path.GetDirectoryName (p))), "mono\\mono\\mini\\mono.exe");
if (!File.Exists (monoPath))
throw new FileNotFoundException ("Windows mono path not found: " + monoPath);
}
}
alPath = Path.Combine (p, framework_version + "\\al.exe");
if (!File.Exists (alPath)) {
alPath = Path.Combine (Path.GetDirectoryName (p), "lib\\" + profile_path + "\\al.exe");
if (!File.Exists (alPath))
throw new FileNotFoundException ("Windows al path not found: " + alPath);
}
info.FileName = monoPath;
return alPath + " ";
} else {
#if NET_4_0
info.FileName = "al";
#else
info.FileName = "al2";
#endif
return String.Empty;
}
}
string BuildAssemblyPath (string cultureName)
{
string baseDir = Path.Combine (baseAssemblyDirectory, cultureName);
if (!Directory.Exists (baseDir))
Directory.CreateDirectory (baseDir);
string baseFileName = Path.GetFileNameWithoutExtension (baseAssemblyPath);
string fileName = String.Concat (baseFileName, ".resources.dll");
fileName = Path.Combine (baseDir, fileName);
return fileName;
}
CodeCompileUnit GenerateAssemblyInfo (string cultureName)
{
CodeAttributeArgument[] args = new CodeAttributeArgument [1];
args [0] = new CodeAttributeArgument (new CodePrimitiveExpression (cultureName));
CodeCompileUnit unit = new CodeCompileUnit ();
unit.AssemblyCustomAttributes.Add (
new CodeAttributeDeclaration (
new CodeTypeReference ("System.Reflection.AssemblyCultureAttribute"),
args));
args = new CodeAttributeArgument [2];
args [0] = new CodeAttributeArgument (new CodePrimitiveExpression ("ASP.NET"));
args [1] = new CodeAttributeArgument (new CodePrimitiveExpression (Environment.Version.ToString ()));
unit.AssemblyCustomAttributes.Add (
new CodeAttributeDeclaration (
new CodeTypeReference ("System.CodeDom.Compiler.GeneratedCodeAttribute"),
args));
return unit;
}
}
}
|