AppCodeCompiler.cs 23 KB

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