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