AppCodeCompiler.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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.Configuration;
  34. using System.Collections;
  35. using System.Collections.Generic;
  36. using System.Globalization;
  37. using System.IO;
  38. using System.Reflection;
  39. using System.Web;
  40. using System.Web.Configuration;
  41. using System.Web.Profile;
  42. using System.Web.Util;
  43. namespace System.Web.Compilation
  44. {
  45. internal class AppCodeAssembly
  46. {
  47. private List<string> files;
  48. private List<CodeCompileUnit> units;
  49. private string name;
  50. private string path;
  51. private bool validAssembly;
  52. private string outputAssemblyName;
  53. public string OutputAssemblyName
  54. {
  55. get {
  56. return outputAssemblyName;
  57. }
  58. }
  59. public bool IsValid
  60. {
  61. get { return validAssembly; }
  62. }
  63. public string SourcePath
  64. {
  65. get { return path; }
  66. }
  67. // temporary
  68. public string Name
  69. {
  70. get { return name; }
  71. }
  72. public List<string> Files
  73. {
  74. get { return files; }
  75. }
  76. // temporary
  77. public AppCodeAssembly (string name, string path)
  78. {
  79. this.files = new List<string> ();
  80. this.units = new List<CodeCompileUnit> ();
  81. this.validAssembly = true;
  82. this.name = name;
  83. this.path = path;
  84. }
  85. public void AddFile (string path)
  86. {
  87. files.Add (path);
  88. }
  89. public void AddUnit (CodeCompileUnit unit)
  90. {
  91. units.Add (unit);
  92. }
  93. object OnCreateTemporaryAssemblyFile (string path)
  94. {
  95. FileStream f = new FileStream (path, FileMode.CreateNew);
  96. f.Close ();
  97. return path;
  98. }
  99. // Build and add the assembly to the BuildManager's
  100. // CodeAssemblies collection
  101. public void Build (string[] binAssemblies)
  102. {
  103. Type compilerProvider = null;
  104. CompilerInfo compilerInfo = null, cit;
  105. string extension, language, cpfile = null;
  106. List<string> knownfiles = new List<string>();
  107. List<string> unknownfiles = new List<string>();
  108. // First make sure all the files are in the same
  109. // language
  110. bool known;
  111. foreach (string f in files) {
  112. known = true;
  113. language = null;
  114. extension = Path.GetExtension (f);
  115. if (!CodeDomProvider.IsDefinedExtension (extension))
  116. known = false;
  117. if (known) {
  118. language = CodeDomProvider.GetLanguageFromExtension(extension);
  119. if (!CodeDomProvider.IsDefinedLanguage (language))
  120. known = false;
  121. }
  122. if (!known || language == null) {
  123. unknownfiles.Add (f);
  124. continue;
  125. }
  126. cit = CodeDomProvider.GetCompilerInfo (language);
  127. if (cit == null || !cit.IsCodeDomProviderTypeValid)
  128. continue;
  129. if (compilerProvider == null) {
  130. cpfile = f;
  131. compilerProvider = cit.CodeDomProviderType;
  132. compilerInfo = cit;
  133. } else if (compilerProvider != cit.CodeDomProviderType)
  134. throw new HttpException (
  135. String.Format (
  136. "Files {0} and {1} are in different languages - they cannot be compiled into the same assembly",
  137. Path.GetFileName (cpfile),
  138. Path.GetFileName (f)));
  139. knownfiles.Add (f);
  140. }
  141. CodeDomProvider provider = null;
  142. if (compilerInfo == null) {
  143. CompilationSection config = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
  144. if (config == null || !CodeDomProvider.IsDefinedLanguage (config.DefaultLanguage))
  145. throw new HttpException ("Failed to retrieve default source language");
  146. compilerInfo = CodeDomProvider.GetCompilerInfo (config.DefaultLanguage);
  147. if (compilerInfo == null || !compilerInfo.IsCodeDomProviderTypeValid)
  148. throw new HttpException ("Internal error while initializing application");
  149. provider = compilerInfo.CreateProvider ();
  150. if (provider == null)
  151. throw new HttpException ("A code provider error occurred while initializing application.");
  152. }
  153. provider = compilerInfo.CreateProvider ();
  154. if (provider == null)
  155. throw new HttpException ("A code provider error occurred while initializing application.");
  156. AssemblyBuilder abuilder = new AssemblyBuilder (provider);
  157. foreach (string file in knownfiles)
  158. abuilder.AddCodeFile (file);
  159. foreach (CodeCompileUnit unit in units)
  160. abuilder.AddCodeCompileUnit (unit);
  161. BuildProvider bprovider;
  162. CompilationSection compilationSection = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
  163. CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters ();
  164. if (binAssemblies != null && binAssemblies.Length > 0)
  165. parameters.ReferencedAssemblies.AddRange (binAssemblies);
  166. if (compilationSection != null) {
  167. AssemblyName asmName;
  168. foreach (AssemblyInfo ai in compilationSection.Assemblies)
  169. if (ai.Assembly != "*") {
  170. try {
  171. asmName = new AssemblyName (ai.Assembly);
  172. parameters.ReferencedAssemblies.Add (asmName.Name);
  173. } catch (Exception ex) {
  174. throw new HttpException (
  175. String.Format ("Could not find assembly {0}.", ai.Assembly),
  176. ex);
  177. }
  178. }
  179. BuildProviderCollection buildProviders = compilationSection.BuildProviders;
  180. foreach (string file in unknownfiles) {
  181. bprovider = GetBuildProviderFor (file, buildProviders);
  182. if (bprovider == null)
  183. continue;
  184. bprovider.GenerateCode (abuilder);
  185. }
  186. }
  187. outputAssemblyName = (string)FileUtils.CreateTemporaryFile (
  188. AppDomain.CurrentDomain.SetupInformation.DynamicBase,
  189. name, "dll", OnCreateTemporaryAssemblyFile);
  190. parameters.OutputAssembly = outputAssemblyName;
  191. CompilerResults results = abuilder.BuildAssembly (parameters);
  192. if (results.Errors.Count == 0) {
  193. BuildManager.CodeAssemblies.Add (results.PathToAssembly);
  194. BuildManager.TopLevelAssemblies.Add (results.CompiledAssembly);
  195. } else {
  196. if (HttpContext.Current.IsCustomErrorEnabled)
  197. throw new HttpException ("An error occurred while initializing application.");
  198. throw new CompilationException (null, results.Errors, null);
  199. }
  200. }
  201. private BuildProvider GetBuildProviderFor (string file, BuildProviderCollection buildProviders)
  202. {
  203. if (file == null || file.Length == 0 || buildProviders == null || buildProviders.Count == 0)
  204. return null;
  205. BuildProvider ret = buildProviders.GetProviderForExtension (Path.GetExtension (file));
  206. if (ret != null && IsCorrectBuilderType (ret)) {
  207. ret.SetVirtualPath (VirtualPathUtility.ToAppRelative (file));
  208. return ret;
  209. }
  210. return null;
  211. }
  212. private bool IsCorrectBuilderType (BuildProvider bp)
  213. {
  214. if (bp == null)
  215. return false;
  216. Type type;
  217. object[] attrs;
  218. type = bp.GetType ();
  219. attrs = type.GetCustomAttributes (true);
  220. if (attrs == null)
  221. return false;
  222. BuildProviderAppliesToAttribute bpAppliesTo;
  223. bool attributeFound = false;
  224. foreach (object attr in attrs) {
  225. bpAppliesTo = attr as BuildProviderAppliesToAttribute;
  226. if (bpAppliesTo == null)
  227. continue;
  228. attributeFound = true;
  229. if ((bpAppliesTo.AppliesTo & BuildProviderAppliesTo.All) == BuildProviderAppliesTo.All ||
  230. (bpAppliesTo.AppliesTo & BuildProviderAppliesTo.Code) == BuildProviderAppliesTo.Code)
  231. return true;
  232. }
  233. if (attributeFound)
  234. return false;
  235. return true;
  236. }
  237. }
  238. internal class AppCodeCompiler
  239. {
  240. static private bool _alreadyCompiled;
  241. internal static string DefaultAppCodeAssemblyName;
  242. // A dictionary that contains an entry per an assembly that will
  243. // be produced by compiling App_Code. There's one main assembly
  244. // and an optional number of assemblies as defined by the
  245. // codeSubDirectories sub-element of the compilation element in
  246. // the system.web section of the app's config file.
  247. // Each entry's value is an AppCodeAssembly instance.
  248. //
  249. // Assemblies are named as follows:
  250. //
  251. // 1. main assembly: App_Code.{HASH}
  252. // 2. subdir assemblies: App_SubCode_{DirName}.{HASH}
  253. //
  254. // If any of the assemblies contains files that would be
  255. // compiled with different compilers, a System.Web.HttpException
  256. // is thrown.
  257. //
  258. // Files for which there is no explicit builder are ignored
  259. // silently
  260. //
  261. // Files for which exist BuildProviders but which have no
  262. // unambiguous language assigned to them (e.g. .wsdl files), are
  263. // built using the default website compiler.
  264. private List<AppCodeAssembly> assemblies;
  265. string _bindir;
  266. public AppCodeCompiler ()
  267. {
  268. assemblies = new List<AppCodeAssembly>();
  269. }
  270. bool ProcessAppCodeDir (string appCode, AppCodeAssembly defasm)
  271. {
  272. // First process the codeSubDirectories
  273. CompilationSection cs = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  274. if (cs != null) {
  275. string aname;
  276. for (int i = 0; i < cs.CodeSubDirectories.Count; i++) {
  277. aname = String.Format ("App_SubCode_{0}", cs.CodeSubDirectories[i].DirectoryName);
  278. assemblies.Add (new AppCodeAssembly (
  279. aname,
  280. Path.Combine (appCode, cs.CodeSubDirectories[i].DirectoryName)));
  281. }
  282. }
  283. return CollectFiles (appCode, defasm);
  284. }
  285. CodeTypeReference GetProfilePropertyType (string type)
  286. {
  287. if (String.IsNullOrEmpty (type))
  288. throw new ArgumentException ("String size cannot be 0", "type");
  289. return new CodeTypeReference (type);
  290. }
  291. Type GetTypeFromBin (string typeName)
  292. {
  293. string bindir = BinDir;
  294. if (!Directory.Exists (bindir))
  295. return null;
  296. string [] binDlls = Directory.GetFiles (bindir, "*.dll");
  297. Type ret = null;
  298. foreach (string dll in binDlls) {
  299. try {
  300. Assembly asm = Assembly.LoadFrom (dll);
  301. ret = asm.GetType (typeName, false);
  302. if (ret != null)
  303. break;
  304. } catch (Exception) {
  305. continue;
  306. }
  307. }
  308. return ret;
  309. }
  310. string FindProviderTypeName (ProfileSection ps, string providerName)
  311. {
  312. if (ps.Providers == null || ps.Providers.Count == 0)
  313. return null;
  314. ProviderSettings pset = ps.Providers [providerName];
  315. if (pset == null)
  316. return null;
  317. return pset.Type;
  318. }
  319. void GetProfileProviderAttribute (ProfileSection ps, CodeAttributeDeclarationCollection collection,
  320. string providerName)
  321. {
  322. string providerTypeName;
  323. if (String.IsNullOrEmpty (providerName))
  324. providerTypeName = FindProviderTypeName (ps, ps.DefaultProvider);
  325. else
  326. providerTypeName = FindProviderTypeName (ps, providerName);
  327. if (providerTypeName == null)
  328. throw new HttpException (String.Format ("Profile provider type not found: {0}",
  329. providerTypeName));
  330. Type type = Type.GetType (providerTypeName, false);
  331. if (type == null) {
  332. type = GetTypeFromBin (providerTypeName);
  333. if (type == null)
  334. throw new HttpException (String.Format ("Profile provider type not found: {0}",
  335. providerTypeName));
  336. }
  337. collection.Add (
  338. new CodeAttributeDeclaration (
  339. "ProfileProvider",
  340. new CodeAttributeArgument (
  341. new CodePrimitiveExpression (providerTypeName)
  342. )
  343. )
  344. );
  345. }
  346. void GetProfileSettingsSerializeAsAttribute (ProfileSection ps, CodeAttributeDeclarationCollection collection,
  347. SerializationMode mode)
  348. {
  349. string parameter = String.Format ("SettingsSerializeAs.{0}", mode.ToString ());
  350. collection.Add (
  351. new CodeAttributeDeclaration (
  352. "SettingsSerializeAs",
  353. new CodeAttributeArgument (
  354. new CodeSnippetExpression (parameter)
  355. )
  356. )
  357. );
  358. }
  359. void AddProfileClassProperty (ProfileSection ps, CodeTypeDeclaration profileClass, ProfilePropertySettings pset)
  360. {
  361. string name = pset.Name;
  362. if (String.IsNullOrEmpty (name))
  363. throw new HttpException ("Profile property 'Name' attribute cannot be null.");
  364. CodeMemberProperty property = new CodeMemberProperty ();
  365. string typeName = pset.Type;
  366. if (typeName == "string")
  367. typeName = "System.String";
  368. property.Name = name;
  369. property.Type = GetProfilePropertyType (typeName);
  370. property.Attributes = MemberAttributes.Public;
  371. CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();
  372. GetProfileProviderAttribute (ps, collection, pset.Provider);
  373. GetProfileSettingsSerializeAsAttribute (ps, collection, pset.SerializeAs);
  374. property.CustomAttributes = collection;
  375. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  376. CodeCastExpression cast = new CodeCastExpression ();
  377. ret.Expression = cast;
  378. CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
  379. new CodeThisReferenceExpression (),
  380. "GetPropertyValue");
  381. CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
  382. mref,
  383. new CodeExpression[] { new CodePrimitiveExpression (name) }
  384. );
  385. cast.TargetType = new CodeTypeReference (typeName);
  386. cast.Expression = minvoke;
  387. property.GetStatements.Add (ret);
  388. if (!pset.ReadOnly) {
  389. mref = new CodeMethodReferenceExpression (
  390. new CodeThisReferenceExpression (),
  391. "SetPropertyValue");
  392. minvoke = new CodeMethodInvokeExpression (
  393. mref,
  394. new CodeExpression[] { new CodePrimitiveExpression (name), new CodeSnippetExpression ("value") }
  395. );
  396. property.SetStatements.Add (minvoke);
  397. }
  398. profileClass.Members.Add (property);
  399. }
  400. void AddProfileClassGroupProperty (string groupName, string memberName, CodeTypeDeclaration profileClass)
  401. {
  402. CodeMemberProperty property = new CodeMemberProperty ();
  403. property.Name = memberName;
  404. property.Type = new CodeTypeReference (groupName);
  405. property.Attributes = MemberAttributes.Public;
  406. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  407. CodeCastExpression cast = new CodeCastExpression ();
  408. ret.Expression = cast;
  409. CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
  410. new CodeThisReferenceExpression (),
  411. "GetProfileGroup");
  412. CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
  413. mref,
  414. new CodeExpression[] { new CodePrimitiveExpression (memberName) }
  415. );
  416. cast.TargetType = new CodeTypeReference (groupName);
  417. cast.Expression = minvoke;
  418. property.GetStatements.Add (ret);
  419. profileClass.Members.Add (property);
  420. }
  421. void BuildProfileClass (ProfileSection ps, string className, ProfilePropertySettingsCollection psc,
  422. CodeNamespace ns, string baseClass, SortedList <string, string> groupProperties)
  423. {
  424. CodeTypeDeclaration profileClass = new CodeTypeDeclaration (className);
  425. profileClass.BaseTypes.Add (new CodeTypeReference (baseClass));
  426. profileClass.TypeAttributes = TypeAttributes.Public;
  427. ns.Types.Add (profileClass);
  428. foreach (ProfilePropertySettings pset in psc)
  429. AddProfileClassProperty (ps, profileClass, pset);
  430. if (groupProperties != null && groupProperties.Count > 0)
  431. foreach (KeyValuePair <string, string> group in groupProperties)
  432. AddProfileClassGroupProperty (group.Key, group.Value, profileClass);
  433. }
  434. string MakeGroupName (string name)
  435. {
  436. return String.Format ("ProfileGroup{0}", name);
  437. }
  438. // FIXME: there should be some validation of syntactic correctness of the member/class name
  439. // for the groups/properties. For now it's left to the compiler to report errors.
  440. //
  441. // CodeGenerator.IsValidLanguageIndependentIdentifier (id) - use that
  442. //
  443. bool ProcessCustomProfile (ProfileSection ps, AppCodeAssembly defasm)
  444. {
  445. CodeCompileUnit unit = new CodeCompileUnit ();
  446. CodeNamespace ns = new CodeNamespace (null);
  447. unit.Namespaces.Add (ns);
  448. defasm.AddUnit (unit);
  449. ns.Imports.Add (new CodeNamespaceImport ("System"));
  450. ns.Imports.Add (new CodeNamespaceImport ("System.Configuration"));
  451. ns.Imports.Add (new CodeNamespaceImport ("System.Web"));
  452. ns.Imports.Add (new CodeNamespaceImport ("System.Web.Profile"));
  453. RootProfilePropertySettingsCollection props = ps.PropertySettings;
  454. if (props == null || props.Count == 0)
  455. return true;
  456. SortedList<string, string> groupProperties = new SortedList<string, string> ();
  457. string groupName;
  458. foreach (ProfileGroupSettings pgs in props.GroupSettings) {
  459. groupName = MakeGroupName (pgs.Name);
  460. groupProperties.Add (groupName, pgs.Name);
  461. BuildProfileClass (ps, groupName, pgs.PropertySettings, ns,
  462. "System.Web.Profile.ProfileGroupBase", null);
  463. }
  464. string baseType = ps.Inherits;
  465. if (String.IsNullOrEmpty (baseType))
  466. baseType = "System.Web.Profile.ProfileBase";
  467. BuildProfileClass (ps, "ProfileCommon", props, ns, baseType, groupProperties);
  468. return true;
  469. }
  470. void PutCustomProfileInContext (HttpContext context, string assemblyName)
  471. {
  472. Type type = Type.GetType (String.Format ("ProfileCommon, {0}",
  473. Path.GetFileNameWithoutExtension (assemblyName)));
  474. ProfileBase pb = Activator.CreateInstance (type) as ProfileBase;
  475. if (pb != null)
  476. context.Profile = pb;
  477. }
  478. public void Compile ()
  479. {
  480. if (_alreadyCompiled)
  481. return;
  482. _alreadyCompiled = false;
  483. string appCode = Path.Combine (HttpRuntime.AppDomainAppPath, "App_Code");
  484. ProfileSection ps = WebConfigurationManager.GetSection ("system.web/profile") as ProfileSection;
  485. bool haveAppCodeDir = Directory.Exists (appCode);
  486. bool haveCustomProfile = ps != null ? ps.PropertySettings.Count > 0 : false;
  487. if (!haveAppCodeDir && !haveCustomProfile)
  488. return;
  489. AppCodeAssembly defasm = new AppCodeAssembly ("App_Code", appCode);
  490. assemblies.Add (defasm);
  491. bool haveCode = false;
  492. if (haveAppCodeDir)
  493. haveCode = ProcessAppCodeDir (appCode, defasm);
  494. if (haveCustomProfile)
  495. if (ProcessCustomProfile (ps, defasm))
  496. haveCode = true;
  497. if (!haveCode)
  498. return;
  499. string bindir = BinDir;
  500. string[] binAssemblies = null;
  501. if (Directory.Exists (bindir))
  502. binAssemblies = Directory.GetFiles (bindir, "*.dll");
  503. foreach (AppCodeAssembly aca in assemblies)
  504. aca.Build (binAssemblies);
  505. DefaultAppCodeAssemblyName = Path.GetFileNameWithoutExtension (defasm.OutputAssemblyName);
  506. }
  507. private bool CollectFiles (string dir, AppCodeAssembly aca)
  508. {
  509. bool haveFiles = false;
  510. AppCodeAssembly curaca = aca;
  511. foreach (string f in Directory.GetFiles (dir)) {
  512. aca.AddFile (f);
  513. haveFiles = true;
  514. }
  515. foreach (string d in Directory.GetDirectories (dir)) {
  516. foreach (AppCodeAssembly a in assemblies)
  517. if (a.SourcePath == d) {
  518. curaca = a;
  519. break;
  520. }
  521. CollectFiles (d, curaca);
  522. curaca = aca;
  523. }
  524. return haveFiles;
  525. }
  526. private string BinDir {
  527. get {
  528. if (_bindir != null)
  529. return _bindir;
  530. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  531. _bindir = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  532. return _bindir;
  533. }
  534. }
  535. }
  536. }
  537. #endif