AppCodeCompiler.cs 23 KB

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