AppResourcesAssemblyBuilder.cs 10 KB

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