2
0

AppResourcesAssemblyBuilder.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. namespace System.Web.Compilation
  43. {
  44. class AppResourcesAssemblyBuilder
  45. {
  46. CompilationSection config;
  47. CompilerInfo ci;
  48. CodeDomProvider _provider;
  49. string baseAssemblyPath;
  50. string baseAssemblyDirectory;
  51. string canonicAssemblyName;
  52. Assembly mainAssembly;
  53. AppResourcesCompiler appResourcesCompiler;
  54. public CodeDomProvider Provider {
  55. get {
  56. if (_provider == null)
  57. _provider = ci.CreateProvider ();
  58. else
  59. return _provider;
  60. if (_provider == null)
  61. throw new ApplicationException ("Failed to instantiate the default compiler.");
  62. return _provider;
  63. }
  64. }
  65. public Assembly MainAssembly {
  66. get { return mainAssembly; }
  67. }
  68. public AppResourcesAssemblyBuilder (string canonicAssemblyName, string baseAssemblyPath, AppResourcesCompiler appres)
  69. {
  70. this.appResourcesCompiler = appres;
  71. this.baseAssemblyPath = baseAssemblyPath;
  72. this.baseAssemblyDirectory = Path.GetDirectoryName (baseAssemblyPath);
  73. this.canonicAssemblyName = canonicAssemblyName;
  74. config = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
  75. if (config == null || !CodeDomProvider.IsDefinedLanguage (config.DefaultLanguage))
  76. throw new ApplicationException ("Could not get the default compiler.");
  77. ci = CodeDomProvider.GetCompilerInfo (config.DefaultLanguage);
  78. if (ci == null || !ci.IsCodeDomProviderTypeValid)
  79. throw new ApplicationException ("Failed to obtain the default compiler information.");
  80. }
  81. public void Build ()
  82. {
  83. Build (null);
  84. }
  85. public void Build (CodeCompileUnit unit)
  86. {
  87. Dictionary <string, List <string>> cultures = appResourcesCompiler.CultureFiles;
  88. List <string> defaultCultureFiles = appResourcesCompiler.DefaultCultureFiles;
  89. if (defaultCultureFiles != null)
  90. BuildDefaultAssembly (defaultCultureFiles, unit);
  91. foreach (KeyValuePair <string, List <string>> kvp in cultures)
  92. BuildSatelliteAssembly (kvp.Key, kvp.Value);
  93. }
  94. void BuildDefaultAssembly (List <string> files, CodeCompileUnit unit)
  95. {
  96. AssemblyBuilder abuilder = new AssemblyBuilder (Provider);
  97. if (unit != null)
  98. abuilder.AddCodeCompileUnit (unit);
  99. CompilerParameters cp = ci.CreateDefaultCompilerParameters ();
  100. cp.OutputAssembly = baseAssemblyPath;
  101. cp.GenerateExecutable = false;
  102. cp.TreatWarningsAsErrors = true;
  103. cp.IncludeDebugInformation = config.Debug;
  104. foreach (string f in files)
  105. cp.EmbeddedResources.Add (f);
  106. CompilerResults results = abuilder.BuildAssembly (cp);
  107. if (results == null)
  108. return;
  109. if (results.NativeCompilerReturnValue == 0) {
  110. mainAssembly = results.CompiledAssembly;
  111. BuildManager.TopLevelAssemblies.Add (mainAssembly);
  112. } else {
  113. if (HttpContext.Current.IsCustomErrorEnabled)
  114. throw new ApplicationException ("An error occurred while compiling global resources.");
  115. throw new CompilationException (null, results.Errors, null);
  116. }
  117. HttpRuntime.WritePreservationFile (mainAssembly, canonicAssemblyName);
  118. HttpRuntime.EnableAssemblyMapping (true);
  119. }
  120. void BuildSatelliteAssembly (string cultureName, List <string> files)
  121. {
  122. string assemblyPath = BuildAssemblyPath (cultureName);
  123. var info = new ProcessStartInfo ();
  124. var al = new Process ();
  125. string arguments = SetAlPath (info);
  126. var sb = new StringBuilder (arguments);
  127. sb.Append ("/c:\"" + cultureName + "\" ");
  128. sb.Append ("/t:lib ");
  129. sb.Append ("/out:\"" + assemblyPath + "\" ");
  130. if (mainAssembly != null)
  131. sb.Append ("/template:\"" + mainAssembly.Location + "\" ");
  132. string responseFilePath = assemblyPath + ".response";
  133. using (FileStream fs = File.OpenWrite (responseFilePath)) {
  134. using (StreamWriter sw = new StreamWriter (fs)) {
  135. foreach (string f in files)
  136. sw.WriteLine ("/embed:\"" + f + "\" ");
  137. }
  138. }
  139. sb.Append ("@\"" + responseFilePath + "\"");
  140. info.Arguments = sb.ToString ();
  141. info.CreateNoWindow = true;
  142. info.UseShellExecute = false;
  143. info.RedirectStandardOutput = true;
  144. info.RedirectStandardError = true;
  145. al.StartInfo = info;
  146. var alOutput = new StringCollection ();
  147. var alMutex = new Mutex ();
  148. DataReceivedEventHandler outputHandler = (object sender, DataReceivedEventArgs args) => {
  149. if (args.Data != null) {
  150. alMutex.WaitOne ();
  151. alOutput.Add (args.Data);
  152. alMutex.ReleaseMutex ();
  153. }
  154. };
  155. al.ErrorDataReceived += outputHandler;
  156. al.OutputDataReceived += outputHandler;
  157. // TODO: consider using asynchronous processes
  158. try {
  159. al.Start ();
  160. } catch (Exception ex) {
  161. throw new HttpException (String.Format ("Error running {0}", al.StartInfo.FileName), ex);
  162. }
  163. Exception alException = null;
  164. int exitCode = 0;
  165. try {
  166. al.BeginOutputReadLine ();
  167. al.BeginErrorReadLine ();
  168. al.WaitForExit ();
  169. exitCode = al.ExitCode;
  170. } catch (Exception ex) {
  171. alException = ex;
  172. } finally {
  173. al.CancelErrorRead ();
  174. al.CancelOutputRead ();
  175. al.Close ();
  176. }
  177. if (exitCode != 0 || alException != null) {
  178. // TODO: consider adding a new type of compilation exception,
  179. // tailored for al
  180. CompilerErrorCollection errors = null;
  181. if (alOutput.Count != 0) {
  182. foreach (string line in alOutput) {
  183. if (!line.StartsWith ("ALINK: error ", StringComparison.Ordinal))
  184. continue;
  185. if (errors == null)
  186. errors = new CompilerErrorCollection ();
  187. int colon = line.IndexOf (':', 13);
  188. string errorNumber = colon != -1 ? line.Substring (13, colon - 13) : "Unknown";
  189. string errorText = colon != -1 ? line.Substring (colon + 1) : line.Substring (13);
  190. errors.Add (new CompilerError (Path.GetFileName (assemblyPath), 0, 0, errorNumber, errorText));
  191. }
  192. }
  193. throw new CompilationException (Path.GetFileName (assemblyPath), errors, null);
  194. }
  195. }
  196. string SetAlPath (ProcessStartInfo info)
  197. {
  198. if (HttpRuntime.RunningOnWindows) {
  199. string alPath;
  200. string monoPath;
  201. PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
  202. MethodInfo get_gac = gac.GetGetMethod (true);
  203. string p = Path.GetDirectoryName ((string) get_gac.Invoke (null, null));
  204. monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (p)), "bin\\mono.bat");
  205. if (!File.Exists (monoPath)) {
  206. monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (p)), "bin\\mono.exe");
  207. if (!File.Exists (monoPath)) {
  208. monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (Path.GetDirectoryName (p))), "mono\\mono\\mini\\mono.exe");
  209. if (!File.Exists (monoPath))
  210. throw new FileNotFoundException ("Windows mono path not found: " + monoPath);
  211. }
  212. }
  213. alPath = Path.Combine (p, "2.0\\al.exe");
  214. if (!File.Exists (alPath)) {
  215. alPath = Path.Combine(Path.GetDirectoryName (p), "lib\\net_2_0\\al.exe");
  216. if (!File.Exists (alPath))
  217. throw new FileNotFoundException ("Windows al path not found: " + alPath);
  218. }
  219. info.FileName = monoPath;
  220. return alPath;
  221. } else {
  222. info.FileName = "al2";
  223. return String.Empty;
  224. }
  225. }
  226. string BuildAssemblyPath (string cultureName)
  227. {
  228. string baseDir = Path.Combine (baseAssemblyDirectory, cultureName);
  229. if (!Directory.Exists (baseDir))
  230. Directory.CreateDirectory (baseDir);
  231. string baseFileName = Path.GetFileNameWithoutExtension (baseAssemblyPath);
  232. string fileName = String.Concat (baseFileName, ".resources.dll");
  233. fileName = Path.Combine (baseDir, fileName);
  234. return fileName;
  235. }
  236. CodeCompileUnit GenerateAssemblyInfo (string cultureName)
  237. {
  238. CodeAttributeArgument[] args = new CodeAttributeArgument [1];
  239. args [0] = new CodeAttributeArgument (new CodePrimitiveExpression (cultureName));
  240. CodeCompileUnit unit = new CodeCompileUnit ();
  241. unit.AssemblyCustomAttributes.Add (
  242. new CodeAttributeDeclaration (
  243. new CodeTypeReference ("System.Reflection.AssemblyCultureAttribute"),
  244. args));
  245. args = new CodeAttributeArgument [2];
  246. args [0] = new CodeAttributeArgument (new CodePrimitiveExpression ("ASP.NET"));
  247. args [1] = new CodeAttributeArgument (new CodePrimitiveExpression (Environment.Version.ToString ()));
  248. unit.AssemblyCustomAttributes.Add (
  249. new CodeAttributeDeclaration (
  250. new CodeTypeReference ("System.CodeDom.Compiler.GeneratedCodeAttribute"),
  251. args));
  252. return unit;
  253. }
  254. }
  255. }