AppCodeCompiler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //
  2. // System.Web.Compilation.AppCodeCompiler: A compiler for the App_Code folder
  3. //
  4. // Authors:
  5. // Marek Habersack ([email protected])
  6. //
  7. // (C) 2006 Marek Habersack
  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. #if NET_2_0
  30. using System;
  31. using System.CodeDom;
  32. using System.CodeDom.Compiler;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.Globalization;
  36. using System.IO;
  37. using System.Web;
  38. using System.Web.Configuration;
  39. using System.Web.Util;
  40. namespace System.Web.Compilation
  41. {
  42. internal class AppCodeAssembly
  43. {
  44. private List<string> files;
  45. private string name;
  46. private string path;
  47. private bool validAssembly;
  48. public bool IsValid
  49. {
  50. get { return validAssembly; }
  51. }
  52. public string SourcePath
  53. {
  54. get { return path; }
  55. }
  56. // temporary
  57. public string Name
  58. {
  59. get { return name; }
  60. }
  61. public List<string> Files
  62. {
  63. get { return files; }
  64. }
  65. // temporary
  66. public AppCodeAssembly (string name, string path)
  67. {
  68. this.files = new List<string>();
  69. this.validAssembly = true;
  70. this.name = name;
  71. this.path = path;
  72. }
  73. public void AddFile (string path)
  74. {
  75. files.Add (path);
  76. }
  77. object OnCreateTemporaryAssemblyFile (string path)
  78. {
  79. FileStream f = new FileStream (path, FileMode.CreateNew);
  80. f.Close ();
  81. return path;
  82. }
  83. // Build and add the assembly to the BuildManager's
  84. // CodeAssemblies collection
  85. public void Build (string[] binAssemblies)
  86. {
  87. Type compilerProvider = null;
  88. CompilerInfo compilerInfo = null, cit;
  89. string extension, language, cpfile = null;
  90. List<string> knownfiles = new List<string>();
  91. List<string> unknownfiles = new List<string>();
  92. // First make sure all the files are in the same
  93. // language
  94. bool known;
  95. foreach (string f in files) {
  96. known = true;
  97. language = null;
  98. extension = Path.GetExtension (f);
  99. if (!CodeDomProvider.IsDefinedExtension (extension))
  100. known = false;
  101. if (known) {
  102. language = CodeDomProvider.GetLanguageFromExtension(extension);
  103. if (!CodeDomProvider.IsDefinedLanguage (language))
  104. known = false;
  105. }
  106. if (!known || language == null) {
  107. unknownfiles.Add (f);
  108. continue;
  109. }
  110. cit = CodeDomProvider.GetCompilerInfo (language);
  111. if (cit == null || !cit.IsCodeDomProviderTypeValid)
  112. continue;
  113. if (compilerProvider == null) {
  114. cpfile = f;
  115. compilerProvider = cit.CodeDomProviderType;
  116. compilerInfo = cit;
  117. } else if (compilerProvider != cit.CodeDomProviderType)
  118. throw new HttpException (
  119. String.Format (
  120. "Files {0} and {1} are in different languages - they cannot be compiled into the same assembly",
  121. Path.GetFileName (cpfile),
  122. Path.GetFileName (f)));
  123. knownfiles.Add (f);
  124. }
  125. CodeDomProvider provider = null;
  126. if (compilerInfo == null) {
  127. CompilationSection config = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
  128. if (config == null || !CodeDomProvider.IsDefinedLanguage (config.DefaultLanguage))
  129. throw new HttpException ("Failed to retrieve default source language");
  130. compilerInfo = CodeDomProvider.GetCompilerInfo (config.DefaultLanguage);
  131. if (compilerInfo == null || !compilerInfo.IsCodeDomProviderTypeValid)
  132. throw new HttpException ("Internal error while initializing application");
  133. provider = compilerInfo.CreateProvider ();
  134. if (provider == null)
  135. throw new HttpException ("A code provider error occurred while initializing application.");
  136. }
  137. provider = compilerInfo.CreateProvider ();
  138. if (provider == null)
  139. throw new HttpException ("A code provider error occurred while initializing application.");
  140. AssemblyBuilder abuilder = new AssemblyBuilder (provider);
  141. foreach (string file in knownfiles)
  142. abuilder.AddCodeFile (file);
  143. BuildProvider bprovider;
  144. CompilationSection compilationSection = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
  145. CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters ();
  146. if (binAssemblies != null && binAssemblies.Length > 0)
  147. parameters.ReferencedAssemblies.AddRange (binAssemblies);
  148. if (compilationSection != null) {
  149. foreach (AssemblyInfo ai in compilationSection.Assemblies)
  150. if (ai.Assembly != "*")
  151. parameters.ReferencedAssemblies.Add (ai.Assembly);
  152. BuildProviderCollection buildProviders = compilationSection.BuildProviders;
  153. foreach (string file in unknownfiles) {
  154. bprovider = GetBuildProviderFor (file, buildProviders);
  155. if (bprovider == null)
  156. continue;
  157. bprovider.GenerateCode (abuilder);
  158. }
  159. }
  160. string assemblyName = (string)FileUtils.CreateTemporaryFile (
  161. AppDomain.CurrentDomain.SetupInformation.DynamicBase,
  162. name, "dll", OnCreateTemporaryAssemblyFile);
  163. parameters.OutputAssembly = assemblyName;
  164. CompilerResults results = abuilder.BuildAssembly (parameters);
  165. if (results.Errors.Count == 0) {
  166. BuildManager.CodeAssemblies.Add (results.PathToAssembly);
  167. BuildManager.TopLevelAssemblies.Add (results.CompiledAssembly);
  168. } else {
  169. if (HttpContext.Current.IsCustomErrorEnabled)
  170. throw new HttpException ("An error occurred while initializing application.");
  171. throw new CompilationException (null, results.Errors, null);
  172. }
  173. }
  174. private BuildProvider GetBuildProviderFor (string file, BuildProviderCollection buildProviders)
  175. {
  176. if (file == null || file.Length == 0 || buildProviders == null || buildProviders.Count == 0)
  177. return null;
  178. BuildProvider ret = buildProviders.GetProviderForExtension (Path.GetExtension (file));
  179. if (ret != null && IsCorrectBuilderType (ret)) {
  180. ret.SetVirtualPath (VirtualPathUtility.ToAppRelative (file));
  181. return ret;
  182. }
  183. return null;
  184. }
  185. private bool IsCorrectBuilderType (BuildProvider bp)
  186. {
  187. if (bp == null)
  188. return false;
  189. Type type;
  190. object[] attrs;
  191. type = bp.GetType ();
  192. attrs = type.GetCustomAttributes (true);
  193. if (attrs == null)
  194. return false;
  195. BuildProviderAppliesToAttribute bpAppliesTo;
  196. bool attributeFound = false;
  197. foreach (object attr in attrs) {
  198. bpAppliesTo = attr as BuildProviderAppliesToAttribute;
  199. if (bpAppliesTo == null)
  200. continue;
  201. attributeFound = true;
  202. if ((bpAppliesTo.AppliesTo & BuildProviderAppliesTo.All) == BuildProviderAppliesTo.All ||
  203. (bpAppliesTo.AppliesTo & BuildProviderAppliesTo.Code) == BuildProviderAppliesTo.Code)
  204. return true;
  205. }
  206. if (attributeFound)
  207. return false;
  208. return true;
  209. }
  210. }
  211. internal class AppCodeCompiler
  212. {
  213. // A dictionary that contains an entry per an assembly that will
  214. // be produced by compiling App_Code. There's one main assembly
  215. // and an optional number of assemblies as defined by the
  216. // codeSubDirectories sub-element of the compilation element in
  217. // the system.web section of the app's config file.
  218. // Each entry's value is an AppCodeAssembly instance.
  219. //
  220. // Assemblies are named as follows:
  221. //
  222. // 1. main assembly: App_Code.{HASH}
  223. // 2. subdir assemblies: App_SubCode_{DirName}.{HASH}
  224. //
  225. // If any of the assemblies contains files that would be
  226. // compiled with different compilers, a System.Web.HttpException
  227. // is thrown.
  228. //
  229. // Files for which there is no explicit builder are ignored
  230. // silently
  231. //
  232. // Files for which exist BuildProviders but which have no
  233. // unambiguous language assigned to them (e.g. .wsdl files), are
  234. // built using the default website compiler.
  235. private List<AppCodeAssembly> assemblies;
  236. public AppCodeCompiler ()
  237. {
  238. assemblies = new List<AppCodeAssembly>();
  239. }
  240. public void Compile ()
  241. {
  242. string appCode = Path.Combine (HttpRuntime.AppDomainAppPath, "App_Code");
  243. if (!Directory.Exists (appCode))
  244. return;
  245. // First process the codeSubDirectories
  246. CompilationSection cs = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  247. if (cs != null) {
  248. string aname;
  249. for (int i = 0; i < cs.CodeSubDirectories.Count; i++) {
  250. aname = String.Format ("App_SubCode_{0}", cs.CodeSubDirectories[i].DirectoryName);
  251. assemblies.Add (new AppCodeAssembly (
  252. aname,
  253. Path.Combine (appCode, cs.CodeSubDirectories[i].DirectoryName)));
  254. }
  255. }
  256. AppCodeAssembly defasm = new AppCodeAssembly ("App_Code", appCode);
  257. assemblies.Add (defasm);
  258. if (!CollectFiles (appCode, defasm))
  259. return;
  260. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  261. string bindir = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  262. string[] binAssemblies = null;
  263. if (Directory.Exists (bindir))
  264. binAssemblies = Directory.GetFiles (bindir, "*.dll");
  265. foreach (AppCodeAssembly aca in assemblies)
  266. aca.Build (binAssemblies);
  267. }
  268. private bool CollectFiles (string dir, AppCodeAssembly aca)
  269. {
  270. bool haveFiles = false;
  271. AppCodeAssembly curaca = aca;
  272. foreach (string f in Directory.GetFiles (dir)) {
  273. aca.AddFile (f);
  274. haveFiles = true;
  275. }
  276. foreach (string d in Directory.GetDirectories (dir)) {
  277. foreach (AppCodeAssembly a in assemblies)
  278. if (a.SourcePath == d) {
  279. curaca = a;
  280. break;
  281. }
  282. CollectFiles (d, curaca);
  283. curaca = aca;
  284. }
  285. return haveFiles;
  286. }
  287. }
  288. }
  289. #endif