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);
260 if (results.NativeCompilerReturnValue == 0) {
261 BuildManager.CodeAssemblies.Add (results.CompiledAssembly);
262 BuildManager.TopLevelAssemblies.Add (results.CompiledAssembly);
263 HttpRuntime.WritePreservationFile (results.CompiledAssembly, name);
265 if (HttpContext.Current.IsCustomErrorEnabled)
266 throw new HttpException ("An error occurred while initializing application.");
267 throw new CompilationException (null, results.Errors, null);
271 private string PhysicalToVirtual (string file)
273 return file.Replace (HttpRuntime.AppDomainAppPath, "/").Replace (Path.DirectorySeparatorChar, '/');
276 private BuildProvider GetBuildProviderFor (string file, BuildProviderCollection buildProviders)
278 if (file == null || file.Length == 0 || buildProviders == null || buildProviders.Count == 0)
281 BuildProvider ret = buildProviders.GetProviderForExtension (Path.GetExtension (file));
282 if (ret != null && IsCorrectBuilderType (ret)) {
283 ret.SetVirtualPath (PhysicalToVirtual (file));
290 private bool IsCorrectBuilderType (BuildProvider bp)
297 type = bp.GetType ();
298 attrs = type.GetCustomAttributes (true);
302 BuildProviderAppliesToAttribute bpAppliesTo;
303 bool attributeFound = false;
304 foreach (object attr in attrs) {
305 bpAppliesTo = attr as BuildProviderAppliesToAttribute;
306 if (bpAppliesTo == null)
308 attributeFound = true;
309 if ((bpAppliesTo.AppliesTo & BuildProviderAppliesTo.All) == BuildProviderAppliesTo.All ||
310 (bpAppliesTo.AppliesTo & BuildProviderAppliesTo.Code) == BuildProviderAppliesTo.Code)
321 internal class AppCodeCompiler
323 static private bool _alreadyCompiled;
324 internal static string DefaultAppCodeAssemblyName;
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.
333 // Assemblies are named as follows:
335 // 1. main assembly: App_Code.{HASH}
336 // 2. subdir assemblies: App_SubCode_{DirName}.{HASH}
338 // If any of the assemblies contains files that would be
339 // compiled with different compilers, a System.Web.HttpException
342 // Files for which there is no explicit builder are ignored
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;
351 public AppCodeCompiler ()
353 assemblies = new List<AppCodeAssembly>();
356 bool ProcessAppCodeDir (string appCode, AppCodeAssembly defasm)
358 // First process the codeSubDirectories
359 CompilationSection cs = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
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 (
367 Path.Combine (appCode, cs.CodeSubDirectories[i].DirectoryName)));
371 return CollectFiles (appCode, defasm);
374 CodeTypeReference GetProfilePropertyType (string type)
376 if (String.IsNullOrEmpty (type))
377 throw new ArgumentException ("String size cannot be 0", "type");
378 return new CodeTypeReference (type);
381 string FindProviderTypeName (ProfileSection ps, string providerName)
383 if (ps.Providers == null || ps.Providers.Count == 0)
386 ProviderSettings pset = ps.Providers [providerName];
392 void GetProfileProviderAttribute (ProfileSection ps, CodeAttributeDeclarationCollection collection,
395 if (String.IsNullOrEmpty (providerName))
396 providerTypeName = FindProviderTypeName (ps, ps.DefaultProvider);
398 providerTypeName = FindProviderTypeName (ps, providerName);
399 if (providerTypeName == null)
400 throw new HttpException (String.Format ("Profile provider type not defined: {0}",
404 new CodeAttributeDeclaration (
406 new CodeAttributeArgument (
407 new CodePrimitiveExpression (providerTypeName)
413 void GetProfileSettingsSerializeAsAttribute (ProfileSection ps, CodeAttributeDeclarationCollection collection,
414 SerializationMode mode)
416 string parameter = String.Concat ("SettingsSerializeAs.", mode.ToString ());
418 new CodeAttributeDeclaration (
419 "SettingsSerializeAs",
420 new CodeAttributeArgument (
421 new CodeSnippetExpression (parameter)
428 void AddProfileClassGetProfileMethod (CodeTypeDeclaration profileClass)
430 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
431 new CodeTypeReferenceExpression (typeof (System.Web.Profile.ProfileBase)),
433 CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
435 new CodeExpression[] { new CodeVariableReferenceExpression ("username") }
437 CodeCastExpression cast = new CodeCastExpression ();
438 cast.TargetType = new CodeTypeReference ("ProfileCommon");
439 cast.Expression = minvoke;
441 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
442 ret.Expression = cast;
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;
451 profileClass.Members.Add (method);
454 void AddProfileClassProperty (ProfileSection ps, CodeTypeDeclaration profileClass, ProfilePropertySettings pset)
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;
467 CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();
468 GetProfileProviderAttribute (ps, collection, pset.Provider);
469 GetProfileSettingsSerializeAsAttribute (ps, collection, pset.SerializeAs);
471 property.CustomAttributes = collection;
472 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
473 CodeCastExpression cast = new CodeCastExpression ();
474 ret.Expression = cast;
476 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
477 new CodeThisReferenceExpression (),
479 CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
481 new CodeExpression[] { new CodePrimitiveExpression (name) }
483 cast.TargetType = new CodeTypeReference (typeName);
484 cast.Expression = minvoke;
485 property.GetStatements.Add (ret);
487 if (!pset.ReadOnly) {
488 mref = new CodeMethodReferenceExpression (
489 new CodeThisReferenceExpression (),
491 minvoke = new CodeMethodInvokeExpression (
493 new CodeExpression[] { new CodePrimitiveExpression (name), new CodeSnippetExpression ("value") }
495 property.SetStatements.Add (minvoke);
499 profileClass.Members.Add (property);
502 void AddProfileClassGroupProperty (string groupName, string memberName, CodeTypeDeclaration profileClass)
504 CodeMemberProperty property = new CodeMemberProperty ();
505 property.Name = memberName;
506 property.Type = new CodeTypeReference (groupName);
507 property.Attributes = MemberAttributes.Public;
509 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
510 CodeCastExpression cast = new CodeCastExpression ();
511 ret.Expression = cast;
513 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
514 new CodeThisReferenceExpression (),
516 CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
518 new CodeExpression[] { new CodePrimitiveExpression (memberName) }
520 cast.TargetType = new CodeTypeReference (groupName);
521 cast.Expression = minvoke;
522 property.GetStatements.Add (ret);
524 profileClass.Members.Add (property);
527 void BuildProfileClass (ProfileSection ps, string className, ProfilePropertySettingsCollection psc,
528 CodeNamespace ns, string baseClass, bool baseIsGlobal,
529 SortedList <string, string> groupProperties)
531 CodeTypeDeclaration profileClass = new CodeTypeDeclaration (className);
532 CodeTypeReference cref = new CodeTypeReference (baseClass);
534 cref.Options |= CodeTypeReferenceOptions.GlobalReference;
535 profileClass.BaseTypes.Add (cref);
536 profileClass.TypeAttributes = TypeAttributes.Public;
537 ns.Types.Add (profileClass);
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);
547 string MakeGroupName (string name)
549 return String.Concat ("ProfileGroup", name);
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.
555 // CodeGenerator.IsValidLanguageIndependentIdentifier (id) - use that
557 bool ProcessCustomProfile (ProfileSection ps, AppCodeAssembly defasm)
559 CodeCompileUnit unit = new CodeCompileUnit ();
560 CodeNamespace ns = new CodeNamespace (null);
561 unit.Namespaces.Add (ns);
562 defasm.AddUnit (unit);
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"));
569 RootProfilePropertySettingsCollection props = ps.PropertySettings;
573 SortedList<string, string> groupProperties = new SortedList<string, string> ();
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);
582 string baseType = ps.Inherits;
583 bool baseIsGlobal = false;
584 if (String.IsNullOrEmpty (baseType)) {
585 baseType = "System.Web.Profile.ProfileBase";
589 BuildProfileClass (ps, "ProfileCommon", props, ns, baseType, baseIsGlobal, groupProperties);
593 // void PutCustomProfileInContext (HttpContext context, string assemblyName)
595 // Type type = Type.GetType (String.Format ("ProfileCommon, {0}",
596 // Path.GetFileNameWithoutExtension (assemblyName)));
597 // ProfileBase pb = Activator.CreateInstance (type) as ProfileBase;
599 // context.Profile = pb;
602 public static bool HaveCustomProfile (ProfileSection ps)
604 if (ps == null || !ps.Enabled)
606 if (!String.IsNullOrEmpty (ps.Inherits) || (ps.PropertySettings != null && ps.PropertySettings.Count > 0))
612 public void Compile ()
614 if (_alreadyCompiled)
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);
622 if (!haveAppCodeDir && !haveCustomProfile)
625 AppCodeAssembly defasm = new AppCodeAssembly ("App_Code", appCode);
626 assemblies.Add (defasm);
628 bool haveCode = false;
630 haveCode = ProcessAppCodeDir (appCode, defasm);
631 if (haveCustomProfile)
632 if (ProcessCustomProfile (ps, defasm))
638 HttpRuntime.EnableAssemblyMapping (true);
639 string[] binAssemblies = HttpApplication.BinDirectoryAssemblies;
641 foreach (AppCodeAssembly aca in assemblies)
642 aca.Build (binAssemblies);
643 _alreadyCompiled = true;
644 DefaultAppCodeAssemblyName = Path.GetFileNameWithoutExtension (defasm.OutputAssemblyName);
646 if (haveCustomProfile && providerTypeName != null) {
647 if (Type.GetType (providerTypeName, false) == null) {
648 foreach (Assembly asm in BuildManager.TopLevelAssemblies) {
652 if (asm.GetType (providerTypeName, false) != null)
658 if (HttpApplication.LoadTypeFromBin (providerTypeName) == null)
659 throw new HttpException (String.Format ("Profile provider type not found: {0}",
664 private bool CollectFiles (string dir, AppCodeAssembly aca)
666 bool haveFiles = false;
668 AppCodeAssembly curaca = aca;
669 foreach (string f in Directory.GetFiles (dir)) {
674 foreach (string d in Directory.GetDirectories (dir)) {
675 foreach (AppCodeAssembly a in assemblies)
676 if (a.SourcePath == d) {
680 if (CollectFiles (d, curaca))