2
0

AppCodeCompiler.cs 23 KB

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