2 // System.Web.Compilation.AppCodeCompiler: A compiler for the App_Code folder
5 // Marek Habersack (grendello@gmail.com)
7 // (C) 2006 Marek Habersack
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
33 using System.CodeDom.Compiler;
34 using System.Configuration;
35 using System.Collections;
36 using System.Collections.Generic;
37 using System.Globalization;
39 using System.Reflection;
41 using System.Web.Configuration;
42 using System.Web.Profile;
43 using System.Web.Util;
45 namespace System.Web.Compilation
47 class AssemblyPathResolver
49 static Dictionary <string, string> assemblyCache;
51 static AssemblyPathResolver ()
53 assemblyCache = new Dictionary <string, string> ();
56 public static string GetAssemblyPath (string assemblyName)
58 lock (assemblyCache) {
59 if (assemblyCache.ContainsKey (assemblyName))
60 return assemblyCache [assemblyName];
63 Exception error = null;
64 if (assemblyName.IndexOf (',') != -1) {
66 asm = Assembly.Load (assemblyName);
67 } catch (Exception e) {
74 asm = Assembly.LoadWithPartialName (assemblyName);
75 } catch (Exception e) {
81 throw new HttpException (String.Format ("Unable to find assembly {0}", assemblyName), error);
83 assemblyCache.Add (assemblyName, asm.Location);
89 internal class AppCodeAssembly
91 private List<string> files;
92 private List<CodeCompileUnit> units;
96 private bool validAssembly;
97 private string outputAssemblyName;
99 public string OutputAssemblyName
102 return outputAssemblyName;
108 get { return validAssembly; }
111 public string SourcePath
122 public List<string> Files
124 get { return files; }
128 public AppCodeAssembly (string name, string path)
130 this.files = new List<string> ();
131 this.units = new List<CodeCompileUnit> ();
132 this.validAssembly = true;
137 public void AddFile (string path)
142 public void AddUnit (CodeCompileUnit unit)
147 object OnCreateTemporaryAssemblyFile (string path)
149 FileStream f = new FileStream (path, FileMode.CreateNew);
154 // Build and add the assembly to the BuildManager's
155 // CodeAssemblies collection
156 public void Build (string[] binAssemblies)
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>();
164 // First make sure all the files are in the same
167 foreach (string f in files) {
171 extension = Path.GetExtension (f);
172 if (String.IsNullOrEmpty (extension) || !CodeDomProvider.IsDefinedExtension (extension))
175 language = CodeDomProvider.GetLanguageFromExtension(extension);
176 if (!CodeDomProvider.IsDefinedLanguage (language))
179 if (!known || language == null) {
180 unknownfiles.Add (f);
184 cit = CodeDomProvider.GetCompilerInfo (language);
185 if (cit == null || !cit.IsCodeDomProviderTypeValid)
187 if (compilerProvider == null) {
189 compilerProvider = cit.CodeDomProviderType;
191 } else if (compilerProvider != cit.CodeDomProviderType)
192 throw new HttpException (
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)));
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");
210 provider = compilerInfo.CreateProvider ();
211 if (provider == null)
212 throw new HttpException ("A code provider error occurred while initializing application.");
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);
220 BuildProvider bprovider;
221 CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters ();
222 parameters.IncludeDebugInformation = compilationSection.Debug;
224 if (binAssemblies != null && binAssemblies.Length > 0)
225 parameters.ReferencedAssemblies.AddRange (binAssemblies);
227 if (compilationSection != null) {
228 foreach (AssemblyInfo ai in compilationSection.Assemblies)
229 if (ai.Assembly != "*") {
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),
240 BuildProviderCollection buildProviders = compilationSection.BuildProviders;
242 foreach (string file in unknownfiles) {
243 bprovider = GetBuildProviderFor (file, buildProviders);
244 if (bprovider == null)
246 bprovider.GenerateCode (abuilder);
250 if (knownfiles.Count == 0 && unknownfiles.Count == 0 && units.Count == 0)
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);
263 if (results.NativeCompilerReturnValue == 0) {
264 BuildManager.CodeAssemblies.Add (results.CompiledAssembly);
265 BuildManager.TopLevelAssemblies.Add (results.CompiledAssembly);
266 HttpRuntime.WritePreservationFile (results.CompiledAssembly, name);
268 if (HttpContext.Current.IsCustomErrorEnabled)
269 throw new HttpException ("An error occurred while initializing application.");
270 throw new CompilationException (null, results.Errors, null);
274 private string PhysicalToVirtual (string file)
276 return file.Replace (HttpRuntime.AppDomainAppPath, "/").Replace (Path.DirectorySeparatorChar, '/');
279 private BuildProvider GetBuildProviderFor (string file, BuildProviderCollection buildProviders)
281 if (file == null || file.Length == 0 || buildProviders == null || buildProviders.Count == 0)
284 BuildProvider ret = buildProviders.GetProviderForExtension (Path.GetExtension (file));
285 if (ret != null && IsCorrectBuilderType (ret)) {
286 ret.SetVirtualPath (PhysicalToVirtual (file));
293 private bool IsCorrectBuilderType (BuildProvider bp)
300 type = bp.GetType ();
301 attrs = type.GetCustomAttributes (true);
305 BuildProviderAppliesToAttribute bpAppliesTo;
306 bool attributeFound = false;
307 foreach (object attr in attrs) {
308 bpAppliesTo = attr as BuildProviderAppliesToAttribute;
309 if (bpAppliesTo == null)
311 attributeFound = true;
312 if ((bpAppliesTo.AppliesTo & BuildProviderAppliesTo.All) == BuildProviderAppliesTo.All ||
313 (bpAppliesTo.AppliesTo & BuildProviderAppliesTo.Code) == BuildProviderAppliesTo.Code)
324 internal class AppCodeCompiler
326 static private bool _alreadyCompiled;
327 internal static string DefaultAppCodeAssemblyName;
329 // A dictionary that contains an entry per an assembly that will
330 // be produced by compiling App_Code. There's one main assembly
331 // and an optional number of assemblies as defined by the
332 // codeSubDirectories sub-element of the compilation element in
333 // the system.web section of the app's config file.
334 // Each entry's value is an AppCodeAssembly instance.
336 // Assemblies are named as follows:
338 // 1. main assembly: App_Code.{HASH}
339 // 2. subdir assemblies: App_SubCode_{DirName}.{HASH}
341 // If any of the assemblies contains files that would be
342 // compiled with different compilers, a System.Web.HttpException
345 // Files for which there is no explicit builder are ignored
348 // Files for which exist BuildProviders but which have no
349 // unambiguous language assigned to them (e.g. .wsdl files), are
350 // built using the default website compiler.
351 private List<AppCodeAssembly> assemblies;
352 string providerTypeName = null;
354 public AppCodeCompiler ()
356 assemblies = new List<AppCodeAssembly>();
359 bool ProcessAppCodeDir (string appCode, AppCodeAssembly defasm)
361 // First process the codeSubDirectories
362 CompilationSection cs = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
366 for (int i = 0; i < cs.CodeSubDirectories.Count; i++) {
367 aname = String.Concat ("App_SubCode_", cs.CodeSubDirectories[i].DirectoryName);
368 assemblies.Add (new AppCodeAssembly (
370 Path.Combine (appCode, cs.CodeSubDirectories[i].DirectoryName)));
374 return CollectFiles (appCode, defasm);
377 CodeTypeReference GetProfilePropertyType (string type)
379 if (String.IsNullOrEmpty (type))
380 throw new ArgumentException ("String size cannot be 0", "type");
381 return new CodeTypeReference (type);
384 string FindProviderTypeName (ProfileSection ps, string providerName)
386 if (ps.Providers == null || ps.Providers.Count == 0)
389 ProviderSettings pset = ps.Providers [providerName];
395 void GetProfileProviderAttribute (ProfileSection ps, CodeAttributeDeclarationCollection collection,
398 if (String.IsNullOrEmpty (providerName))
399 providerTypeName = FindProviderTypeName (ps, ps.DefaultProvider);
401 providerTypeName = FindProviderTypeName (ps, providerName);
402 if (providerTypeName == null)
403 throw new HttpException (String.Format ("Profile provider type not defined: {0}",
407 new CodeAttributeDeclaration (
409 new CodeAttributeArgument (
410 new CodePrimitiveExpression (providerTypeName)
416 void GetProfileSettingsSerializeAsAttribute (ProfileSection ps, CodeAttributeDeclarationCollection collection,
417 SerializationMode mode)
419 string parameter = String.Concat ("SettingsSerializeAs.", mode.ToString ());
421 new CodeAttributeDeclaration (
422 "SettingsSerializeAs",
423 new CodeAttributeArgument (
424 new CodeSnippetExpression (parameter)
431 void AddProfileClassGetProfileMethod (CodeTypeDeclaration profileClass)
433 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
434 new CodeTypeReferenceExpression (typeof (System.Web.Profile.ProfileBase)),
436 CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
438 new CodeExpression[] { new CodeVariableReferenceExpression ("username") }
440 CodeCastExpression cast = new CodeCastExpression ();
441 cast.TargetType = new CodeTypeReference ("ProfileCommon");
442 cast.Expression = minvoke;
444 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
445 ret.Expression = cast;
447 CodeMemberMethod method = new CodeMemberMethod ();
448 method.Name = "GetProfile";
449 method.ReturnType = new CodeTypeReference ("ProfileCommon");
450 method.Parameters.Add (new CodeParameterDeclarationExpression("System.String", "username"));
451 method.Statements.Add (ret);
452 method.Attributes = MemberAttributes.Public;
454 profileClass.Members.Add (method);
457 void AddProfileClassProperty (ProfileSection ps, CodeTypeDeclaration profileClass, ProfilePropertySettings pset)
459 string name = pset.Name;
460 if (String.IsNullOrEmpty (name))
461 throw new HttpException ("Profile property 'Name' attribute cannot be null.");
462 CodeMemberProperty property = new CodeMemberProperty ();
463 string typeName = pset.Type;
464 if (typeName == "string")
465 typeName = "System.String";
466 property.Name = name;
467 property.Type = GetProfilePropertyType (typeName);
468 property.Attributes = MemberAttributes.Public;
470 CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();
471 GetProfileProviderAttribute (ps, collection, pset.Provider);
472 GetProfileSettingsSerializeAsAttribute (ps, collection, pset.SerializeAs);
474 property.CustomAttributes = collection;
475 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
476 CodeCastExpression cast = new CodeCastExpression ();
477 ret.Expression = cast;
479 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
480 new CodeThisReferenceExpression (),
482 CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
484 new CodeExpression[] { new CodePrimitiveExpression (name) }
486 cast.TargetType = new CodeTypeReference (typeName);
487 cast.Expression = minvoke;
488 property.GetStatements.Add (ret);
490 if (!pset.ReadOnly) {
491 mref = new CodeMethodReferenceExpression (
492 new CodeThisReferenceExpression (),
494 minvoke = new CodeMethodInvokeExpression (
496 new CodeExpression[] { new CodePrimitiveExpression (name), new CodeSnippetExpression ("value") }
498 property.SetStatements.Add (minvoke);
502 profileClass.Members.Add (property);
505 void AddProfileClassGroupProperty (string groupName, string memberName, CodeTypeDeclaration profileClass)
507 CodeMemberProperty property = new CodeMemberProperty ();
508 property.Name = memberName;
509 property.Type = new CodeTypeReference (groupName);
510 property.Attributes = MemberAttributes.Public;
512 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
513 CodeCastExpression cast = new CodeCastExpression ();
514 ret.Expression = cast;
516 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
517 new CodeThisReferenceExpression (),
519 CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
521 new CodeExpression[] { new CodePrimitiveExpression (memberName) }
523 cast.TargetType = new CodeTypeReference (groupName);
524 cast.Expression = minvoke;
525 property.GetStatements.Add (ret);
527 profileClass.Members.Add (property);
530 void BuildProfileClass (ProfileSection ps, string className, ProfilePropertySettingsCollection psc,
531 CodeNamespace ns, string baseClass, bool baseIsGlobal,
532 SortedList <string, string> groupProperties)
534 CodeTypeDeclaration profileClass = new CodeTypeDeclaration (className);
535 CodeTypeReference cref = new CodeTypeReference (baseClass);
537 cref.Options |= CodeTypeReferenceOptions.GlobalReference;
538 profileClass.BaseTypes.Add (cref);
539 profileClass.TypeAttributes = TypeAttributes.Public;
540 ns.Types.Add (profileClass);
542 foreach (ProfilePropertySettings pset in psc)
543 AddProfileClassProperty (ps, profileClass, pset);
544 if (groupProperties != null && groupProperties.Count > 0)
545 foreach (KeyValuePair <string, string> group in groupProperties)
546 AddProfileClassGroupProperty (group.Key, group.Value, profileClass);
547 AddProfileClassGetProfileMethod (profileClass);
550 string MakeGroupName (string name)
552 return String.Concat ("ProfileGroup", name);
555 // FIXME: there should be some validation of syntactic correctness of the member/class name
556 // for the groups/properties. For now it's left to the compiler to report errors.
558 // CodeGenerator.IsValidLanguageIndependentIdentifier (id) - use that
560 bool ProcessCustomProfile (ProfileSection ps, AppCodeAssembly defasm)
562 CodeCompileUnit unit = new CodeCompileUnit ();
563 CodeNamespace ns = new CodeNamespace (null);
564 unit.Namespaces.Add (ns);
565 defasm.AddUnit (unit);
567 ns.Imports.Add (new CodeNamespaceImport ("System"));
568 ns.Imports.Add (new CodeNamespaceImport ("System.Configuration"));
569 ns.Imports.Add (new CodeNamespaceImport ("System.Web"));
570 ns.Imports.Add (new CodeNamespaceImport ("System.Web.Profile"));
572 RootProfilePropertySettingsCollection props = ps.PropertySettings;
576 SortedList<string, string> groupProperties = new SortedList<string, string> ();
578 foreach (ProfileGroupSettings pgs in props.GroupSettings) {
579 groupName = MakeGroupName (pgs.Name);
580 groupProperties.Add (groupName, pgs.Name);
581 BuildProfileClass (ps, groupName, pgs.PropertySettings, ns,
582 "System.Web.Profile.ProfileGroupBase", true, null);
585 string baseType = ps.Inherits;
586 bool baseIsGlobal = false;
587 if (String.IsNullOrEmpty (baseType)) {
588 baseType = "System.Web.Profile.ProfileBase";
592 BuildProfileClass (ps, "ProfileCommon", props, ns, baseType, baseIsGlobal, groupProperties);
596 // void PutCustomProfileInContext (HttpContext context, string assemblyName)
598 // Type type = Type.GetType (String.Format ("ProfileCommon, {0}",
599 // Path.GetFileNameWithoutExtension (assemblyName)));
600 // ProfileBase pb = Activator.CreateInstance (type) as ProfileBase;
602 // context.Profile = pb;
605 public static bool HaveCustomProfile (ProfileSection ps)
607 if (ps == null || !ps.Enabled)
609 if (!String.IsNullOrEmpty (ps.Inherits) || (ps.PropertySettings != null && ps.PropertySettings.Count > 0))
615 public void Compile ()
617 if (_alreadyCompiled)
620 string appCode = Path.Combine (HttpRuntime.AppDomainAppPath, "App_Code");
621 ProfileSection ps = WebConfigurationManager.GetSection ("system.web/profile") as ProfileSection;
622 bool haveAppCodeDir = Directory.Exists (appCode);
623 bool haveCustomProfile = HaveCustomProfile (ps);
625 if (!haveAppCodeDir && !haveCustomProfile)
628 AppCodeAssembly defasm = new AppCodeAssembly ("App_Code", appCode);
629 assemblies.Add (defasm);
631 bool haveCode = false;
633 haveCode = ProcessAppCodeDir (appCode, defasm);
634 if (haveCustomProfile)
635 if (ProcessCustomProfile (ps, defasm))
641 HttpRuntime.EnableAssemblyMapping (true);
642 string[] binAssemblies = HttpApplication.BinDirectoryAssemblies;
644 foreach (AppCodeAssembly aca in assemblies)
645 aca.Build (binAssemblies);
646 _alreadyCompiled = true;
647 DefaultAppCodeAssemblyName = Path.GetFileNameWithoutExtension (defasm.OutputAssemblyName);
651 if (haveCustomProfile && providerTypeName != null) {
652 if (Type.GetType (providerTypeName, false) == null) {
653 foreach (Assembly asm in BuildManager.TopLevelAssemblies) {
657 if (asm.GetType (providerTypeName, false) != null)
663 if (HttpApplication.LoadTypeFromBin (providerTypeName) == null)
664 throw new HttpException (String.Format ("Profile provider type not found: {0}",
669 // Documented (sort of...) briefly in:
671 // http://quickstarts.asp.net/QuickStartv20/aspnet/doc/extensibility.aspx
672 // http://msdn2.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx
673 void RunAppInitialize ()
675 MethodInfo mi = null, tmi;
678 foreach (Assembly asm in BuildManager.CodeAssemblies) {
679 types = asm.GetExportedTypes ();
680 if (types == null || types.Length == 0)
683 foreach (Type type in types) {
684 tmi = type.GetMethod ("AppInitialize",
685 BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
693 throw new HttpException ("The static AppInitialize method found in more than one type in the App_Code directory.");
702 mi.Invoke (null, null);
705 private bool CollectFiles (string dir, AppCodeAssembly aca)
707 bool haveFiles = false;
709 AppCodeAssembly curaca = aca;
710 foreach (string f in Directory.GetFiles (dir)) {
715 foreach (string d in Directory.GetDirectories (dir)) {
716 foreach (AppCodeAssembly a in assemblies)
717 if (a.SourcePath == d) {
721 if (CollectFiles (d, curaca))