BuildManager.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. //
  2. // System.Web.Compilation.BuildManager
  3. //
  4. // Authors:
  5. // Chris Toshok ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Marek Habersack ([email protected])
  8. //
  9. // (C) 2006-2009 Novell, Inc (http://www.novell.com)
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.CodeDom;
  33. using System.CodeDom.Compiler;
  34. using System.Collections;
  35. using System.Collections.Generic;
  36. using System.Collections.Specialized;
  37. using System.ComponentModel;
  38. using System.IO;
  39. using System.Reflection;
  40. using System.Text;
  41. using System.Threading;
  42. using System.Xml;
  43. using System.Web;
  44. using System.Web.Caching;
  45. using System.Web.Configuration;
  46. using System.Web.Hosting;
  47. using System.Web.Util;
  48. #if NET_4_0
  49. using System.Runtime.Versioning;
  50. #endif
  51. namespace System.Web.Compilation
  52. {
  53. public sealed class BuildManager
  54. {
  55. internal const string FAKE_VIRTUAL_PATH_PREFIX = "/@@MonoFakeVirtualPath@@";
  56. const string BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX = "@@Build_Manager@@";
  57. static int BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH = BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX.Length;
  58. static readonly object bigCompilationLock = new object ();
  59. static readonly object virtualPathsToIgnoreLock = new object ();
  60. static readonly char[] virtualPathsToIgnoreSplitChars = {','};
  61. static EventHandlerList events = new EventHandlerList ();
  62. static object buildManagerRemoveEntryEvent = new object ();
  63. static bool hosted;
  64. static Dictionary <string, bool> virtualPathsToIgnore;
  65. static bool virtualPathsToIgnoreChecked;
  66. static bool haveVirtualPathsToIgnore;
  67. static List <Assembly> AppCode_Assemblies = new List<Assembly>();
  68. static List <Assembly> TopLevel_Assemblies = new List<Assembly>();
  69. static Dictionary <Type, CodeDomProvider> codeDomProviders;
  70. static Dictionary <string, BuildManagerCacheItem> buildCache;
  71. static List <Assembly> referencedAssemblies;
  72. static List <Assembly> configReferencedAssemblies;
  73. static bool getReferencedAssembliesInvoked;
  74. static int buildCount;
  75. static bool is_precompiled;
  76. static bool toplevelsCompiled;
  77. #if NET_4_0
  78. static bool? batchCompilationEnabled;
  79. static FrameworkName targetFramework;
  80. static bool preStartMethodsDone;
  81. #endif
  82. //static bool updatable; unused
  83. static Dictionary<string, PreCompilationData> precompiled;
  84. // This is here _only_ for the purpose of unit tests!
  85. internal static bool suppressDebugModeMessages;
  86. #if SYSTEMCORE_DEP
  87. static ReaderWriterLockSlim buildCacheLock;
  88. #else
  89. static ReaderWriterLock buildCacheLock;
  90. #endif
  91. static ulong recursionDepth;
  92. internal static bool IsPrecompiled {
  93. get { return is_precompiled; }
  94. }
  95. internal static event BuildManagerRemoveEntryEventHandler RemoveEntry {
  96. add { events.AddHandler (buildManagerRemoveEntryEvent, value); }
  97. remove { events.RemoveHandler (buildManagerRemoveEntryEvent, value); }
  98. }
  99. #if NET_4_0
  100. public static bool? BatchCompilationEnabled {
  101. get { return batchCompilationEnabled; }
  102. set {
  103. if (preStartMethodsDone)
  104. throw new InvalidOperationException ("This method cannot be called after the application's pre-start initialization stage.");
  105. batchCompilationEnabled = value;
  106. }
  107. }
  108. public static FrameworkName TargetFramework {
  109. get {
  110. if (targetFramework == null) {
  111. CompilationSection cs = CompilationConfig;
  112. string framework;
  113. if (cs == null)
  114. framework = null;
  115. else
  116. framework = cs.TargetFramework;
  117. if (String.IsNullOrEmpty (framework))
  118. targetFramework = new FrameworkName (".NETFramework,Version=v4.0");
  119. else
  120. targetFramework = new FrameworkName (framework);
  121. }
  122. return targetFramework;
  123. }
  124. }
  125. #endif
  126. internal static bool BatchMode {
  127. get {
  128. #if NET_4_0
  129. if (batchCompilationEnabled != null)
  130. return (bool)batchCompilationEnabled;
  131. #endif
  132. if (!hosted)
  133. return false; // Fix for bug #380985
  134. CompilationSection cs = CompilationConfig;
  135. if (cs == null)
  136. return true;
  137. return cs.Batch;
  138. }
  139. }
  140. // Assemblies built from the App_Code directory
  141. public static IList CodeAssemblies {
  142. get { return AppCode_Assemblies; }
  143. }
  144. internal static CompilationSection CompilationConfig {
  145. get { return WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection; }
  146. }
  147. internal static bool HaveResources {
  148. get; set;
  149. }
  150. internal static IList TopLevelAssemblies {
  151. get { return TopLevel_Assemblies; }
  152. }
  153. static BuildManager ()
  154. {
  155. hosted = (AppDomain.CurrentDomain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
  156. buildCache = new Dictionary <string, BuildManagerCacheItem> (RuntimeHelpers.StringEqualityComparerCulture);
  157. #if SYSTEMCORE_DEP
  158. buildCacheLock = new ReaderWriterLockSlim ();
  159. #else
  160. buildCacheLock = new ReaderWriterLock ();
  161. #endif
  162. referencedAssemblies = new List <Assembly> ();
  163. recursionDepth = 0;
  164. string appPath = HttpRuntime.AppDomainAppPath;
  165. string precomp_name = null;
  166. is_precompiled = String.IsNullOrEmpty (appPath) ? false : File.Exists ((precomp_name = Path.Combine (appPath, "PrecompiledApp.config")));
  167. if (is_precompiled)
  168. is_precompiled = LoadPrecompilationInfo (precomp_name);
  169. }
  170. // Deal with precompiled sites deployed in a different virtual path
  171. static void FixVirtualPaths ()
  172. {
  173. if (precompiled == null)
  174. return;
  175. string [] parts;
  176. int skip = -1;
  177. foreach (string vpath in precompiled.Keys) {
  178. parts = vpath.Split ('/');
  179. for (int i = 0; i < parts.Length; i++) {
  180. if (String.IsNullOrEmpty (parts [i]))
  181. continue;
  182. // The path must be rooted, otherwise PhysicalPath returned
  183. // below will be relative to the current request path and
  184. // File.Exists will return a false negative. See bug #546053
  185. string test_path = "/" + String.Join ("/", parts, i, parts.Length - i);
  186. VirtualPath result = GetAbsoluteVirtualPath (test_path);
  187. if (result != null && File.Exists (result.PhysicalPath)) {
  188. skip = i - 1;
  189. break;
  190. }
  191. }
  192. }
  193. string app_vpath = HttpRuntime.AppDomainAppVirtualPath;
  194. if (skip == -1 || (skip == 0 && app_vpath == "/"))
  195. return;
  196. if (!app_vpath.EndsWith ("/"))
  197. app_vpath = app_vpath + "/";
  198. Dictionary<string, PreCompilationData> copy = new Dictionary<string, PreCompilationData> (precompiled);
  199. precompiled.Clear ();
  200. foreach (KeyValuePair<string,PreCompilationData> entry in copy) {
  201. parts = entry.Key.Split ('/');
  202. string new_path;
  203. if (String.IsNullOrEmpty (parts [0]))
  204. new_path = app_vpath + String.Join ("/", parts, skip + 1, parts.Length - skip - 1);
  205. else
  206. new_path = app_vpath + String.Join ("/", parts, skip, parts.Length - skip);
  207. entry.Value.VirtualPath = new_path;
  208. precompiled.Add (new_path, entry.Value);
  209. }
  210. }
  211. static bool LoadPrecompilationInfo (string precomp_config)
  212. {
  213. using (XmlTextReader reader = new XmlTextReader (precomp_config)) {
  214. reader.MoveToContent ();
  215. if (reader.Name != "precompiledApp")
  216. return false;
  217. /* unused
  218. if (reader.HasAttributes)
  219. while (reader.MoveToNextAttribute ())
  220. if (reader.Name == "updatable") {
  221. updatable = (reader.Value == "true");
  222. break;
  223. }
  224. */
  225. }
  226. string [] compiled = Directory.GetFiles (HttpRuntime.BinDirectory, "*.compiled");
  227. foreach (string str in compiled)
  228. LoadCompiled (str);
  229. FixVirtualPaths ();
  230. return true;
  231. }
  232. static void LoadCompiled (string filename)
  233. {
  234. using (XmlTextReader reader = new XmlTextReader (filename)) {
  235. reader.MoveToContent ();
  236. if (reader.Name == "preserve" && reader.HasAttributes) {
  237. reader.MoveToNextAttribute ();
  238. string val = reader.Value;
  239. // 1 -> app_code subfolder - add the assembly to CodeAssemblies
  240. // 2 -> ashx
  241. // 3 -> ascx, aspx
  242. // 6 -> app_code - add the assembly to CodeAssemblies
  243. // 8 -> global.asax
  244. // 9 -> App_GlobalResources - set the assembly for HttpContext
  245. if (reader.Name == "resultType" && (val == "2" || val == "3" || val == "8"))
  246. LoadPageData (reader, true);
  247. else if (val == "1" || val == "6") {
  248. PreCompilationData pd = LoadPageData (reader, false);
  249. CodeAssemblies.Add (Assembly.Load (pd.AssemblyFileName));
  250. } else if (val == "9") {
  251. PreCompilationData pd = LoadPageData (reader, false);
  252. HttpContext.AppGlobalResourcesAssembly = Assembly.Load (pd.AssemblyFileName);
  253. }
  254. }
  255. }
  256. }
  257. class PreCompilationData {
  258. public string VirtualPath;
  259. public string AssemblyFileName;
  260. public string TypeName;
  261. public Type Type;
  262. }
  263. static PreCompilationData LoadPageData (XmlTextReader reader, bool store)
  264. {
  265. PreCompilationData pc_data = new PreCompilationData ();
  266. while (reader.MoveToNextAttribute ()) {
  267. string name = reader.Name;
  268. if (name == "virtualPath")
  269. pc_data.VirtualPath = VirtualPathUtility.RemoveTrailingSlash (reader.Value);
  270. else if (name == "assembly")
  271. pc_data.AssemblyFileName = reader.Value;
  272. else if (name == "type")
  273. pc_data.TypeName = reader.Value;
  274. }
  275. if (store) {
  276. if (precompiled == null)
  277. precompiled = new Dictionary<string, PreCompilationData> (RuntimeHelpers.StringEqualityComparerCulture);
  278. precompiled.Add (pc_data.VirtualPath, pc_data);
  279. }
  280. return pc_data;
  281. }
  282. static void AddAssembly (Assembly asm, List <Assembly> al)
  283. {
  284. if (al.Contains (asm))
  285. return;
  286. al.Add (asm);
  287. }
  288. static void AddPathToIgnore (string vp)
  289. {
  290. if (virtualPathsToIgnore == null)
  291. virtualPathsToIgnore = new Dictionary <string, bool> (RuntimeHelpers.StringEqualityComparerCulture);
  292. VirtualPath path = GetAbsoluteVirtualPath (vp);
  293. string vpAbsolute = path.Absolute;
  294. if (!virtualPathsToIgnore.ContainsKey (vpAbsolute)) {
  295. virtualPathsToIgnore.Add (vpAbsolute, true);
  296. haveVirtualPathsToIgnore = true;
  297. }
  298. string vpRelative = path.AppRelative;
  299. if (!virtualPathsToIgnore.ContainsKey (vpRelative)) {
  300. virtualPathsToIgnore.Add (vpRelative, true);
  301. haveVirtualPathsToIgnore = true;
  302. }
  303. if (!virtualPathsToIgnore.ContainsKey (vp)) {
  304. virtualPathsToIgnore.Add (vp, true);
  305. haveVirtualPathsToIgnore = true;
  306. }
  307. }
  308. internal static void AddToReferencedAssemblies (Assembly asm)
  309. {
  310. // should not be used
  311. }
  312. static void AssertVirtualPathExists (VirtualPath virtualPath)
  313. {
  314. string realpath;
  315. bool dothrow = false;
  316. if (virtualPath.IsFake) {
  317. realpath = virtualPath.PhysicalPath;
  318. if (!File.Exists (realpath) && !Directory.Exists (realpath))
  319. dothrow = true;
  320. } else {
  321. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  322. string vpAbsolute = virtualPath.Absolute;
  323. if (!vpp.FileExists (vpAbsolute) && !vpp.DirectoryExists (vpAbsolute))
  324. dothrow = true;
  325. }
  326. if (dothrow)
  327. throw new HttpException (404, "The file '" + virtualPath + "' does not exist.", virtualPath.Absolute);
  328. }
  329. static void Build (VirtualPath vp)
  330. {
  331. AssertVirtualPathExists (vp);
  332. CompilationSection cs = CompilationConfig;
  333. lock (bigCompilationLock) {
  334. bool entryExists;
  335. if (HasCachedItemNoLock (vp.Absolute, out entryExists))
  336. return;
  337. if (recursionDepth == 0)
  338. referencedAssemblies.Clear ();
  339. recursionDepth++;
  340. try {
  341. BuildInner (vp, cs != null ? cs.Debug : false);
  342. if (entryExists && recursionDepth <= 1)
  343. // We count only update builds - first time a file
  344. // (or a batch) is built doesn't count.
  345. buildCount++;
  346. } finally {
  347. // See http://support.microsoft.com/kb/319947
  348. if (buildCount > cs.NumRecompilesBeforeAppRestart)
  349. HttpRuntime.UnloadAppDomain ();
  350. recursionDepth--;
  351. }
  352. }
  353. }
  354. // This method assumes it is being called with the big compilation lock held
  355. static void BuildInner (VirtualPath vp, bool debug)
  356. {
  357. var builder = new BuildManagerDirectoryBuilder (vp);
  358. bool recursive = recursionDepth > 1;
  359. List <BuildProviderGroup> builderGroups = builder.Build (IsSingleBuild (vp, recursive));
  360. if (builderGroups == null)
  361. return;
  362. string vpabsolute = vp.Absolute;
  363. int buildHash = (vpabsolute.GetHashCode () | (int)DateTime.Now.Ticks) + (int)recursionDepth;
  364. string assemblyBaseName;
  365. AssemblyBuilder abuilder;
  366. CompilerType ct;
  367. int attempts;
  368. bool singleBuild, needMainVpBuild;
  369. CompilationException compilationError;
  370. // Each group becomes a separate assembly.
  371. foreach (BuildProviderGroup group in builderGroups) {
  372. needMainVpBuild = false;
  373. compilationError = null;
  374. assemblyBaseName = null;
  375. if (group.Count == 1) {
  376. if (recursive || !group.Master)
  377. assemblyBaseName = String.Format ("{0}_{1}.{2:x}.", group.NamePrefix, VirtualPathUtility.GetFileName (group [0].VirtualPath), buildHash);
  378. singleBuild = true;
  379. } else
  380. singleBuild = false;
  381. if (assemblyBaseName == null)
  382. assemblyBaseName = group.NamePrefix + "_";
  383. ct = group.CompilerType;
  384. attempts = 3;
  385. while (attempts > 0) {
  386. abuilder = new AssemblyBuilder (vp, CreateDomProvider (ct), assemblyBaseName);
  387. abuilder.CompilerOptions = ct.CompilerParameters;
  388. abuilder.AddAssemblyReference (GetReferencedAssemblies () as List <Assembly>);
  389. try {
  390. GenerateAssembly (abuilder, group, vp, debug);
  391. attempts = 0;
  392. } catch (CompilationException ex) {
  393. attempts--;
  394. if (singleBuild)
  395. throw new HttpException ("Single file build failed.", ex);
  396. if (attempts == 0) {
  397. needMainVpBuild = true;
  398. compilationError = ex;
  399. break;
  400. }
  401. CompilerResults results = ex.Results;
  402. if (results == null)
  403. throw new HttpException ("No results returned from failed compilation.", ex);
  404. else
  405. RemoveFailedAssemblies (vpabsolute, ex, abuilder, group, results, debug);
  406. }
  407. }
  408. if (needMainVpBuild) {
  409. // One last attempt - try to build just the requested path
  410. // if it's not built yet or just return without throwing the
  411. // exception if it has already been built.
  412. if (HasCachedItemNoLock (vpabsolute)) {
  413. if (debug)
  414. DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
  415. compilationError, vpabsolute);
  416. return;
  417. };
  418. // This will trigger a recursive build of the requested vp,
  419. // which means only the vp alone will be built (or not);
  420. Build (vp);
  421. if (HasCachedItemNoLock (vpabsolute)) {
  422. if (debug)
  423. DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
  424. compilationError, vpabsolute);
  425. return;
  426. }
  427. // In theory this code is unreachable. If the recursive
  428. // build of the main vp failed, then it should have thrown
  429. // the build exception.
  430. throw new HttpException ("Requested virtual path build failed.", compilationError);
  431. }
  432. }
  433. }
  434. static CodeDomProvider CreateDomProvider (CompilerType ct)
  435. {
  436. if (codeDomProviders == null)
  437. codeDomProviders = new Dictionary <Type, CodeDomProvider> ();
  438. Type type = ct.CodeDomProviderType;
  439. if (type == null) {
  440. CompilationSection cs = CompilationConfig;
  441. CompilerType tmp = GetDefaultCompilerTypeForLanguage (cs.DefaultLanguage, cs);
  442. if (tmp != null)
  443. type = tmp.CodeDomProviderType;
  444. }
  445. if (type == null)
  446. return null;
  447. CodeDomProvider ret;
  448. if (codeDomProviders.TryGetValue (type, out ret))
  449. return ret;
  450. ret = Activator.CreateInstance (type) as CodeDomProvider;
  451. if (ret == null)
  452. return null;
  453. codeDomProviders.Add (type, ret);
  454. return ret;
  455. }
  456. #if NET_4_0
  457. internal static void CallPreStartMethods ()
  458. {
  459. if (preStartMethodsDone)
  460. return;
  461. MethodInfo mi = null;
  462. try {
  463. List <MethodInfo> methods = LoadPreStartMethodsFromAssemblies (GetReferencedAssemblies () as List <Assembly>);
  464. if (methods == null || methods.Count == 0)
  465. return;
  466. foreach (MethodInfo m in methods) {
  467. mi = m;
  468. m.Invoke (null, null);
  469. }
  470. } catch (Exception ex) {
  471. throw new HttpException (
  472. String.Format ("The pre-application start initialization method {0} on type {1} threw an exception with the following error message: {2}",
  473. mi != null ? mi.Name : "UNKNOWN",
  474. mi != null ? mi.DeclaringType.FullName : "UNKNOWN",
  475. ex.Message),
  476. ex
  477. );
  478. } finally {
  479. preStartMethodsDone = true;
  480. }
  481. }
  482. static List <MethodInfo> LoadPreStartMethodsFromAssemblies (List <Assembly> assemblies)
  483. {
  484. if (assemblies == null || assemblies.Count == 0)
  485. return null;
  486. var ret = new List <MethodInfo> ();
  487. object[] attributes;
  488. Type type;
  489. PreApplicationStartMethodAttribute attr;
  490. foreach (Assembly asm in assemblies) {
  491. try {
  492. attributes = asm.GetCustomAttributes (typeof (PreApplicationStartMethodAttribute), false);
  493. if (attributes == null || attributes.Length == 0)
  494. continue;
  495. attr = attributes [0] as PreApplicationStartMethodAttribute;
  496. type = attr.Type;
  497. if (type == null)
  498. continue;
  499. } catch {
  500. continue;
  501. }
  502. MethodInfo mi;
  503. Exception error = null;
  504. try {
  505. if (type.IsPublic)
  506. mi = type.GetMethod (attr.MethodName, BindingFlags.Static | BindingFlags.Public, null, new Type[] {}, null);
  507. else
  508. mi = null;
  509. } catch (Exception ex) {
  510. error = ex;
  511. mi = null;
  512. }
  513. if (mi == null)
  514. throw new HttpException (
  515. String.Format (
  516. "The method specified by the PreApplicationStartMethodAttribute on assembly '{0}' cannot be resolved. Type: '{1}', MethodName: '{2}'. Verify that the type is public and the method is public and static (Shared in Visual Basic).",
  517. asm.FullName,
  518. type.FullName,
  519. attr.MethodName),
  520. error
  521. );
  522. ret.Add (mi);
  523. }
  524. return ret;
  525. }
  526. public static Type GetGlobalAsaxType ()
  527. {
  528. Type ret = HttpApplicationFactory.AppType;
  529. if (!preStartMethodsDone)
  530. throw new InvalidOperationException ("This method cannot be called during the application's pre-start initialization stage.");
  531. return ret;
  532. }
  533. public static Stream CreateCachedFile (string fileName)
  534. {
  535. if (fileName != null && (fileName == String.Empty || fileName.IndexOf (Path.DirectorySeparatorChar) != -1))
  536. throw new ArgumentException ("Value does not fall within the expected range.");
  537. string path = Path.Combine (HttpRuntime.CodegenDir, fileName);
  538. return new FileStream (path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
  539. }
  540. public static Stream ReadCachedFile (string fileName)
  541. {
  542. if (fileName != null && (fileName == String.Empty || fileName.IndexOf (Path.DirectorySeparatorChar) != -1))
  543. throw new ArgumentException ("Value does not fall within the expected range.");
  544. string path = Path.Combine (HttpRuntime.CodegenDir, fileName);
  545. if (!File.Exists (path))
  546. return null;
  547. return new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.None);
  548. }
  549. [MonoDocumentationNote ("Fully implemented but no info on application pre-init stage is available yet.")]
  550. public static void AddReferencedAssembly (Assembly assembly)
  551. {
  552. if (assembly == null)
  553. throw new ArgumentNullException ("assembly");
  554. Type ret = HttpApplicationFactory.AppType;
  555. if (preStartMethodsDone)
  556. throw new InvalidOperationException ("This method cannot be called after the application's pre-start initialization stage.");
  557. if (configReferencedAssemblies == null)
  558. configReferencedAssemblies = new List <Assembly> ();
  559. if (!configReferencedAssemblies.Contains (assembly))
  560. configReferencedAssemblies.Add (assembly);
  561. }
  562. [MonoTODO ("A no-op until we use IWebObjectFactory internally. Always returns null.")]
  563. public static IWebObjectFactory GetObjectFactory (string virtualPath, bool throwIfNotFound)
  564. {
  565. return null;
  566. }
  567. #endif
  568. public static object CreateInstanceFromVirtualPath (string virtualPath, Type requiredBaseType)
  569. {
  570. return CreateInstanceFromVirtualPath (GetAbsoluteVirtualPath (virtualPath), requiredBaseType);
  571. }
  572. internal static object CreateInstanceFromVirtualPath (VirtualPath virtualPath, Type requiredBaseType)
  573. {
  574. if (requiredBaseType == null)
  575. throw new NullReferenceException (); // This is what MS does, but
  576. // from somewhere else.
  577. Type type = GetCompiledType (virtualPath);
  578. if (type == null)
  579. return null;
  580. if (!requiredBaseType.IsAssignableFrom (type))
  581. throw new HttpException (500,
  582. String.Format ("Type '{0}' does not inherit from '{1}'.", type.FullName, requiredBaseType.FullName));
  583. return Activator.CreateInstance (type, null);
  584. }
  585. static void DescribeCompilationError (string format, CompilationException ex, params object[] parms)
  586. {
  587. StringBuilder sb = new StringBuilder ();
  588. string newline = Environment.NewLine;
  589. if (parms != null)
  590. sb.AppendFormat (format + newline, parms);
  591. else
  592. sb.Append (format + newline);
  593. CompilerResults results = ex != null ? ex.Results : null;
  594. if (results == null)
  595. sb.Append ("No compiler error information present." + newline);
  596. else {
  597. sb.Append ("Compiler errors:" + newline);
  598. foreach (CompilerError error in results.Errors)
  599. sb.Append (" " + error.ToString () + newline);
  600. }
  601. if (ex != null) {
  602. sb.Append (newline + "Exception thrown:" + newline);
  603. sb.Append (ex.ToString ());
  604. }
  605. ShowDebugModeMessage (sb.ToString ());
  606. }
  607. static BuildProvider FindBuildProviderForPhysicalPath (string path, BuildProviderGroup group, HttpRequest req)
  608. {
  609. if (req == null || String.IsNullOrEmpty (path))
  610. return null;
  611. foreach (BuildProvider bp in group) {
  612. if (String.Compare (path, req.MapPath (bp.VirtualPath), RuntimeHelpers.StringComparison) == 0)
  613. return bp;
  614. }
  615. return null;
  616. }
  617. static void GenerateAssembly (AssemblyBuilder abuilder, BuildProviderGroup group, VirtualPath vp, bool debug)
  618. {
  619. IDictionary <string, bool> deps;
  620. BuildManagerCacheItem bmci;
  621. string bvp, vpabsolute = vp.Absolute;
  622. StringBuilder sb;
  623. string newline;
  624. int failedCount = 0;
  625. if (debug) {
  626. newline = Environment.NewLine;
  627. sb = new StringBuilder ("Code generation for certain virtual paths in a batch failed. Those files have been removed from the batch." + newline);
  628. sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
  629. } else {
  630. newline = null;
  631. sb = null;
  632. }
  633. List <BuildProvider> failedBuildProviders = null;
  634. StringComparison stringComparison = RuntimeHelpers.StringComparison;
  635. foreach (BuildProvider bp in group) {
  636. bvp = bp.VirtualPath;
  637. if (HasCachedItemNoLock (bvp))
  638. continue;
  639. try {
  640. bp.GenerateCode (abuilder);
  641. } catch (Exception ex) {
  642. if (String.Compare (bvp, vpabsolute, stringComparison) == 0) {
  643. if (ex is CompilationException || ex is ParseException)
  644. throw;
  645. throw new HttpException ("Code generation failed.", ex);
  646. }
  647. if (failedBuildProviders == null)
  648. failedBuildProviders = new List <BuildProvider> ();
  649. failedBuildProviders.Add (bp);
  650. failedCount++;
  651. if (sb != null) {
  652. if (failedCount > 1)
  653. sb.Append (newline);
  654. sb.AppendFormat ("Failed file virtual path: {0}; Exception: {1}{2}{1}", bp.VirtualPath, newline, ex);
  655. }
  656. continue;
  657. }
  658. deps = bp.ExtractDependencies ();
  659. if (deps != null) {
  660. foreach (var dep in deps) {
  661. bmci = GetCachedItemNoLock (dep.Key);
  662. if (bmci == null || bmci.BuiltAssembly == null)
  663. continue;
  664. abuilder.AddAssemblyReference (bmci.BuiltAssembly);
  665. }
  666. }
  667. }
  668. if (sb != null && failedCount > 0)
  669. ShowDebugModeMessage (sb.ToString ());
  670. if (failedBuildProviders != null) {
  671. foreach (BuildProvider bp in failedBuildProviders)
  672. group.Remove (bp);
  673. }
  674. foreach (Assembly asm in referencedAssemblies) {
  675. if (asm == null)
  676. continue;
  677. abuilder.AddAssemblyReference (asm);
  678. }
  679. CompilerResults results = abuilder.BuildAssembly (vp);
  680. // No results is not an error - it is possible that the assembly builder contained only .asmx and
  681. // .ashx files which had no body, just the directive. In such case, no code unit or code file is added
  682. // to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
  683. // to be added to the cache.
  684. Assembly compiledAssembly = results != null ? results.CompiledAssembly : null;
  685. bool locked = false;
  686. try {
  687. #if SYSTEMCORE_DEP
  688. buildCacheLock.EnterWriteLock ();
  689. #else
  690. buildCacheLock.AcquireWriterLock (-1);
  691. #endif
  692. locked = true;
  693. if (compiledAssembly != null)
  694. referencedAssemblies.Add (compiledAssembly);
  695. foreach (BuildProvider bp in group) {
  696. if (HasCachedItemNoLock (bp.VirtualPath))
  697. continue;
  698. StoreInCache (bp, compiledAssembly, results);
  699. }
  700. } finally {
  701. if (locked) {
  702. #if SYSTEMCORE_DEP
  703. buildCacheLock.ExitWriteLock ();
  704. #else
  705. buildCacheLock.ReleaseWriterLock ();
  706. #endif
  707. }
  708. }
  709. }
  710. static VirtualPath GetAbsoluteVirtualPath (string virtualPath)
  711. {
  712. string vp;
  713. if (!VirtualPathUtility.IsRooted (virtualPath)) {
  714. HttpContext ctx = HttpContext.Current;
  715. HttpRequest req = ctx != null ? ctx.Request : null;
  716. if (req != null) {
  717. string fileDir = req.FilePath;
  718. if (!String.IsNullOrEmpty (fileDir) && String.Compare (fileDir, "/", StringComparison.Ordinal) != 0)
  719. fileDir = VirtualPathUtility.GetDirectory (fileDir);
  720. else
  721. fileDir = "/";
  722. vp = VirtualPathUtility.Combine (fileDir, virtualPath);
  723. } else
  724. throw new HttpException ("No context, cannot map paths.");
  725. } else
  726. vp = virtualPath;
  727. return new VirtualPath (vp);
  728. }
  729. [MonoTODO ("Not implemented, always returns null")]
  730. public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath)
  731. {
  732. return null; // null is ok here until we store the dependency set in the Cache.
  733. }
  734. #if NET_4_0
  735. [MonoTODO ("Not implemented, always returns null")]
  736. public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath, bool ensureIsUpToDate)
  737. {
  738. return null; // null is ok here until we store the dependency set in the Cache.
  739. }
  740. #endif
  741. static BuildManagerCacheItem GetCachedItem (string vp)
  742. {
  743. bool locked = false;
  744. try {
  745. #if SYSTEMCORE_DEP
  746. buildCacheLock.EnterReadLock ();
  747. #else
  748. buildCacheLock.AcquireReaderLock (-1);
  749. #endif
  750. locked = true;
  751. return GetCachedItemNoLock (vp);
  752. } finally {
  753. if (locked) {
  754. #if SYSTEMCORE_DEP
  755. buildCacheLock.ExitReadLock ();
  756. #else
  757. buildCacheLock.ReleaseReaderLock ();
  758. #endif
  759. }
  760. }
  761. }
  762. static BuildManagerCacheItem GetCachedItemNoLock (string vp)
  763. {
  764. BuildManagerCacheItem ret;
  765. if (buildCache.TryGetValue (vp, out ret))
  766. return ret;
  767. return null;
  768. }
  769. internal static Type GetCodeDomProviderType (BuildProvider provider)
  770. {
  771. CompilerType codeCompilerType;
  772. Type codeDomProviderType = null;
  773. codeCompilerType = provider.CodeCompilerType;
  774. if (codeCompilerType != null)
  775. codeDomProviderType = codeCompilerType.CodeDomProviderType;
  776. if (codeDomProviderType == null)
  777. throw new HttpException (String.Concat ("Provider '", provider, " 'fails to specify the compiler type."));
  778. return codeDomProviderType;
  779. }
  780. static Type GetPrecompiledType (string virtualPath)
  781. {
  782. PreCompilationData pc_data;
  783. if (precompiled != null && precompiled.TryGetValue (virtualPath, out pc_data)) {
  784. if (pc_data.Type == null) {
  785. pc_data.Type = Type.GetType (pc_data.TypeName + ", " + pc_data.AssemblyFileName, true);
  786. }
  787. return pc_data.Type;
  788. }
  789. return null;
  790. }
  791. internal static Type GetPrecompiledApplicationType ()
  792. {
  793. if (!is_precompiled)
  794. return null;
  795. Type apptype = GetPrecompiledType (VirtualPathUtility.Combine (HttpRuntime.AppDomainAppVirtualPath, "Global.asax"));
  796. if (apptype == null)
  797. apptype = GetPrecompiledType (VirtualPathUtility.Combine (HttpRuntime.AppDomainAppVirtualPath , "global.asax"));
  798. return apptype;
  799. }
  800. public static Assembly GetCompiledAssembly (string virtualPath)
  801. {
  802. return GetCompiledAssembly (GetAbsoluteVirtualPath (virtualPath));
  803. }
  804. internal static Assembly GetCompiledAssembly (VirtualPath virtualPath)
  805. {
  806. string vpabsolute = virtualPath.Absolute;
  807. if (is_precompiled) {
  808. Type type = GetPrecompiledType (vpabsolute);
  809. if (type != null)
  810. return type.Assembly;
  811. }
  812. BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
  813. if (bmci != null)
  814. return bmci.BuiltAssembly;
  815. Build (virtualPath);
  816. bmci = GetCachedItem (vpabsolute);
  817. if (bmci != null)
  818. return bmci.BuiltAssembly;
  819. return null;
  820. }
  821. public static Type GetCompiledType (string virtualPath)
  822. {
  823. return GetCompiledType (GetAbsoluteVirtualPath (virtualPath));
  824. }
  825. internal static Type GetCompiledType (VirtualPath virtualPath)
  826. {
  827. string vpabsolute = virtualPath.Absolute;
  828. if (is_precompiled) {
  829. Type type = GetPrecompiledType (vpabsolute);
  830. if (type != null)
  831. return type;
  832. }
  833. BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
  834. if (bmci != null) {
  835. ReferenceAssemblyInCompilation (bmci);
  836. return bmci.Type;
  837. }
  838. Build (virtualPath);
  839. bmci = GetCachedItem (vpabsolute);
  840. if (bmci != null) {
  841. ReferenceAssemblyInCompilation (bmci);
  842. return bmci.Type;
  843. }
  844. return null;
  845. }
  846. public static string GetCompiledCustomString (string virtualPath)
  847. {
  848. return GetCompiledCustomString (GetAbsoluteVirtualPath (virtualPath));
  849. }
  850. internal static string GetCompiledCustomString (VirtualPath virtualPath)
  851. {
  852. string vpabsolute = virtualPath.Absolute;
  853. BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
  854. if (bmci != null)
  855. return bmci.CompiledCustomString;
  856. Build (virtualPath);
  857. bmci = GetCachedItem (vpabsolute);
  858. if (bmci != null)
  859. return bmci.CompiledCustomString;
  860. return null;
  861. }
  862. internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection)
  863. {
  864. return GetDefaultCompilerTypeForLanguage (language, configSection, true);
  865. }
  866. internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection, bool throwOnMissing)
  867. {
  868. // MS throws when accesing a Hashtable, we do here.
  869. if (language == null || language.Length == 0)
  870. throw new ArgumentNullException ("language");
  871. CompilationSection config;
  872. if (configSection == null)
  873. config = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
  874. else
  875. config = configSection;
  876. Compiler compiler = config.Compilers.Get (language);
  877. CompilerParameters p;
  878. Type type;
  879. if (compiler != null) {
  880. type = HttpApplication.LoadType (compiler.Type, true);
  881. p = new CompilerParameters ();
  882. p.CompilerOptions = compiler.CompilerOptions;
  883. p.WarningLevel = compiler.WarningLevel;
  884. SetCommonParameters (config, p, type, language);
  885. return new CompilerType (type, p);
  886. }
  887. if (CodeDomProvider.IsDefinedLanguage (language)) {
  888. CompilerInfo info = CodeDomProvider.GetCompilerInfo (language);
  889. p = info.CreateDefaultCompilerParameters ();
  890. type = info.CodeDomProviderType;
  891. SetCommonParameters (config, p, type, language);
  892. return new CompilerType (type, p);
  893. }
  894. if (throwOnMissing)
  895. throw new HttpException (String.Concat ("No compiler for language '", language, "'."));
  896. return null;
  897. }
  898. public static ICollection GetReferencedAssemblies ()
  899. {
  900. if (getReferencedAssembliesInvoked)
  901. return configReferencedAssemblies;
  902. getReferencedAssembliesInvoked = true;
  903. if (configReferencedAssemblies == null)
  904. configReferencedAssemblies = new List <Assembly> ();
  905. CompilationSection compConfig = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
  906. if (compConfig == null)
  907. return configReferencedAssemblies;
  908. bool addAssembliesInBin = false;
  909. foreach (AssemblyInfo info in compConfig.Assemblies) {
  910. if (info.Assembly == "*")
  911. addAssembliesInBin = is_precompiled ? false : true;
  912. else
  913. LoadAssembly (info, configReferencedAssemblies);
  914. }
  915. foreach (Assembly topLevelAssembly in TopLevelAssemblies)
  916. configReferencedAssemblies.Add (topLevelAssembly);
  917. foreach (string assLocation in WebConfigurationManager.ExtraAssemblies)
  918. LoadAssembly (assLocation, configReferencedAssemblies);
  919. // Precompiled sites unconditionally load all assemblies from bin/ (fix for
  920. // bug #502016)
  921. if (is_precompiled || addAssembliesInBin) {
  922. foreach (string s in HttpApplication.BinDirectoryAssemblies) {
  923. try {
  924. LoadAssembly (s, configReferencedAssemblies);
  925. } catch (BadImageFormatException) {
  926. // ignore silently
  927. }
  928. }
  929. }
  930. return configReferencedAssemblies;
  931. }
  932. // The 2 GetType() overloads work on the global.asax, App_GlobalResources, App_WebReferences or App_Browsers
  933. public static Type GetType (string typeName, bool throwOnError)
  934. {
  935. return GetType (typeName, throwOnError, false);
  936. }
  937. public static Type GetType (string typeName, bool throwOnError, bool ignoreCase)
  938. {
  939. Type ret = null;
  940. try {
  941. foreach (Assembly asm in TopLevel_Assemblies) {
  942. ret = asm.GetType (typeName, throwOnError, ignoreCase);
  943. if (ret != null)
  944. break;
  945. }
  946. } catch (Exception ex) {
  947. throw new HttpException ("Failed to find the specified type.", ex);
  948. }
  949. return ret;
  950. }
  951. public static ICollection GetVirtualPathDependencies (string virtualPath)
  952. {
  953. return GetVirtualPathDependencies (virtualPath, null);
  954. }
  955. internal static ICollection GetVirtualPathDependencies (string virtualPath, BuildProvider bprovider)
  956. {
  957. BuildProvider provider = bprovider;
  958. if (provider == null) {
  959. CompilationSection cs = CompilationConfig;
  960. if (cs == null)
  961. return null;
  962. provider = BuildManagerDirectoryBuilder.GetBuildProvider (virtualPath, cs.BuildProviders);
  963. }
  964. if (provider == null)
  965. return null;
  966. IDictionary <string, bool> deps = provider.ExtractDependencies ();
  967. if (deps == null)
  968. return null;
  969. return (ICollection)deps.Keys;
  970. }
  971. internal static bool HasCachedItemNoLock (string vp, out bool entryExists)
  972. {
  973. BuildManagerCacheItem item;
  974. if (buildCache.TryGetValue (vp, out item)) {
  975. entryExists = true;
  976. return item != null;
  977. }
  978. entryExists = false;
  979. return false;
  980. }
  981. internal static bool HasCachedItemNoLock (string vp)
  982. {
  983. bool dummy;
  984. return HasCachedItemNoLock (vp, out dummy);
  985. }
  986. internal static bool IgnoreVirtualPath (string virtualPath)
  987. {
  988. if (!virtualPathsToIgnoreChecked) {
  989. lock (virtualPathsToIgnoreLock) {
  990. if (!virtualPathsToIgnoreChecked)
  991. LoadVirtualPathsToIgnore ();
  992. virtualPathsToIgnoreChecked = true;
  993. }
  994. }
  995. if (!haveVirtualPathsToIgnore)
  996. return false;
  997. if (virtualPathsToIgnore.ContainsKey (virtualPath))
  998. return true;
  999. return false;
  1000. }
  1001. static bool IsSingleBuild (VirtualPath vp, bool recursive)
  1002. {
  1003. if (String.Compare (vp.AppRelative, "~/global.asax", StringComparison.OrdinalIgnoreCase) == 0)
  1004. return true;
  1005. if (!BatchMode)
  1006. return true;
  1007. return recursive;
  1008. }
  1009. static void LoadAssembly (string path, List <Assembly> al)
  1010. {
  1011. AddAssembly (Assembly.LoadFrom (path), al);
  1012. }
  1013. static void LoadAssembly (AssemblyInfo info, List <Assembly> al)
  1014. {
  1015. AddAssembly (Assembly.Load (info.Assembly), al);
  1016. }
  1017. static void LoadVirtualPathsToIgnore ()
  1018. {
  1019. NameValueCollection appSettings = WebConfigurationManager.AppSettings;
  1020. if (appSettings == null)
  1021. return;
  1022. string pathsFromConfig = appSettings ["MonoAspnetBatchCompileIgnorePaths"];
  1023. string pathsFromFile = appSettings ["MonoAspnetBatchCompileIgnoreFromFile"];
  1024. if (!String.IsNullOrEmpty (pathsFromConfig)) {
  1025. string[] paths = pathsFromConfig.Split (virtualPathsToIgnoreSplitChars);
  1026. string path;
  1027. foreach (string p in paths) {
  1028. path = p.Trim ();
  1029. if (path.Length == 0)
  1030. continue;
  1031. AddPathToIgnore (path);
  1032. }
  1033. }
  1034. if (!String.IsNullOrEmpty (pathsFromFile)) {
  1035. string realpath;
  1036. HttpContext ctx = HttpContext.Current;
  1037. HttpRequest req = ctx != null ? ctx.Request : null;
  1038. if (req == null)
  1039. throw new HttpException ("Missing context, cannot continue.");
  1040. realpath = req.MapPath (pathsFromFile);
  1041. if (!File.Exists (realpath))
  1042. return;
  1043. string[] paths = File.ReadAllLines (realpath);
  1044. if (paths == null || paths.Length == 0)
  1045. return;
  1046. string path;
  1047. foreach (string p in paths) {
  1048. path = p.Trim ();
  1049. if (path.Length == 0)
  1050. continue;
  1051. AddPathToIgnore (path);
  1052. }
  1053. }
  1054. }
  1055. static void OnEntryRemoved (string vp)
  1056. {
  1057. BuildManagerRemoveEntryEventHandler eh = events [buildManagerRemoveEntryEvent] as BuildManagerRemoveEntryEventHandler;
  1058. if (eh != null)
  1059. eh (new BuildManagerRemoveEntryEventArgs (vp, HttpContext.Current));
  1060. }
  1061. static void OnVirtualPathChanged (string key, object value, CacheItemRemovedReason removedReason)
  1062. {
  1063. string virtualPath;
  1064. if (StrUtils.StartsWith (key, BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX))
  1065. virtualPath = key.Substring (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH);
  1066. else
  1067. return;
  1068. bool locked = false;
  1069. try {
  1070. #if SYSTEMCORE_DEP
  1071. buildCacheLock.EnterWriteLock ();
  1072. #else
  1073. buildCacheLock.AcquireWriterLock (-1);
  1074. #endif
  1075. locked = true;
  1076. if (HasCachedItemNoLock (virtualPath)) {
  1077. buildCache [virtualPath] = null;
  1078. OnEntryRemoved (virtualPath);
  1079. }
  1080. } finally {
  1081. if (locked) {
  1082. #if SYSTEMCORE_DEP
  1083. buildCacheLock.ExitWriteLock ();
  1084. #else
  1085. buildCacheLock.ReleaseWriterLock ();
  1086. #endif
  1087. }
  1088. }
  1089. }
  1090. static void ReferenceAssemblyInCompilation (BuildManagerCacheItem bmci)
  1091. {
  1092. if (recursionDepth == 0 || referencedAssemblies.Contains (bmci.BuiltAssembly))
  1093. return;
  1094. referencedAssemblies.Add (bmci.BuiltAssembly);
  1095. }
  1096. static void RemoveFailedAssemblies (string requestedVirtualPath, CompilationException ex, AssemblyBuilder abuilder,
  1097. BuildProviderGroup group, CompilerResults results, bool debug)
  1098. {
  1099. StringBuilder sb;
  1100. string newline;
  1101. if (debug) {
  1102. newline = Environment.NewLine;
  1103. sb = new StringBuilder ("Compilation of certain files in a batch failed. Another attempt to compile the batch will be made." + newline);
  1104. sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
  1105. } else {
  1106. newline = null;
  1107. sb = null;
  1108. }
  1109. var failedBuildProviders = new List <BuildProvider> ();
  1110. BuildProvider bp;
  1111. HttpContext ctx = HttpContext.Current;
  1112. HttpRequest req = ctx != null ? ctx.Request : null;
  1113. bool rethrow = false;
  1114. foreach (CompilerError error in results.Errors) {
  1115. if (error.IsWarning)
  1116. continue;
  1117. bp = abuilder.GetBuildProviderForPhysicalFilePath (error.FileName);
  1118. if (bp == null) {
  1119. bp = FindBuildProviderForPhysicalPath (error.FileName, group, req);
  1120. if (bp == null)
  1121. continue;
  1122. }
  1123. if (String.Compare (bp.VirtualPath, requestedVirtualPath, StringComparison.Ordinal) == 0)
  1124. rethrow = true;
  1125. if (!failedBuildProviders.Contains (bp)) {
  1126. failedBuildProviders.Add (bp);
  1127. if (sb != null)
  1128. sb.AppendFormat ("\t{0}{1}", bp.VirtualPath, newline);
  1129. }
  1130. if (sb != null)
  1131. sb.AppendFormat ("\t\t{0}{1}", error, newline);
  1132. }
  1133. foreach (BuildProvider fbp in failedBuildProviders)
  1134. group.Remove (fbp);
  1135. if (sb != null) {
  1136. sb.AppendFormat ("{0}The following exception has been thrown for the file(s) listed above:{0}{1}",
  1137. newline, ex.ToString ());
  1138. ShowDebugModeMessage (sb.ToString ());
  1139. sb = null;
  1140. }
  1141. if (rethrow)
  1142. throw new HttpException ("Compilation failed.", ex);
  1143. }
  1144. static void SetCommonParameters (CompilationSection config, CompilerParameters p, Type compilerType, string language)
  1145. {
  1146. p.IncludeDebugInformation = config.Debug;
  1147. MonoSettingsSection mss = WebConfigurationManager.GetSection ("system.web/monoSettings") as MonoSettingsSection;
  1148. if (mss == null || !mss.UseCompilersCompatibility)
  1149. return;
  1150. Compiler compiler = mss.CompilersCompatibility.Get (language);
  1151. if (compiler == null)
  1152. return;
  1153. Type type = HttpApplication.LoadType (compiler.Type, false);
  1154. if (type != compilerType)
  1155. return;
  1156. p.CompilerOptions = String.Concat (p.CompilerOptions, " ", compiler.CompilerOptions);
  1157. }
  1158. static void ShowDebugModeMessage (string msg)
  1159. {
  1160. if (suppressDebugModeMessages)
  1161. return;
  1162. Console.WriteLine ();
  1163. Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
  1164. Console.WriteLine (msg);
  1165. Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
  1166. Console.WriteLine ();
  1167. }
  1168. static void StoreInCache (BuildProvider bp, Assembly compiledAssembly, CompilerResults results)
  1169. {
  1170. string virtualPath = bp.VirtualPath;
  1171. var item = new BuildManagerCacheItem (compiledAssembly, bp, results);
  1172. if (buildCache.ContainsKey (virtualPath))
  1173. buildCache [virtualPath] = item;
  1174. else
  1175. buildCache.Add (virtualPath, item);
  1176. HttpContext ctx = HttpContext.Current;
  1177. HttpRequest req = ctx != null ? ctx.Request : null;
  1178. CacheDependency dep;
  1179. if (req != null) {
  1180. IDictionary <string, bool> deps = bp.ExtractDependencies ();
  1181. var files = new List <string> ();
  1182. string physicalPath;
  1183. physicalPath = req.MapPath (virtualPath);
  1184. if (File.Exists (physicalPath))
  1185. files.Add (physicalPath);
  1186. if (deps != null && deps.Count > 0) {
  1187. foreach (var d in deps) {
  1188. physicalPath = req.MapPath (d.Key);
  1189. if (!File.Exists (physicalPath))
  1190. continue;
  1191. if (!files.Contains (physicalPath))
  1192. files.Add (physicalPath);
  1193. }
  1194. }
  1195. dep = new CacheDependency (files.ToArray ());
  1196. } else
  1197. dep = null;
  1198. HttpRuntime.InternalCache.Add (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX + virtualPath,
  1199. true,
  1200. dep,
  1201. Cache.NoAbsoluteExpiration,
  1202. Cache.NoSlidingExpiration,
  1203. CacheItemPriority.High,
  1204. new CacheItemRemovedCallback (OnVirtualPathChanged));
  1205. }
  1206. }
  1207. }