AddAssemblyReference() public method

public AddAssemblyReference ( Assembly a ) : void
a Assembly
return void
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     assemblyBuilder.AddAssemblyReference(typeof(SimpleWeb).Assembly);
     assemblyBuilder.AddAssemblyReference(typeof(SimpleTemplateBase).Assembly);
     assemblyBuilder.AddCodeCompileUnit(this, GeneratedCode);
     assemblyBuilder.GenerateTypeFactory(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", Host.DefaultNamespace, "Foot"));
 }
Ejemplo n.º 2
0
    /// <summary>
    /// 添加依赖项
    /// </summary>
    /// <param name="assemblyBuilder"></param>
    protected virtual void AddReferences( AssemblyBuilder assemblyBuilder )
    {
      var buildTypeAssembly = GetType().Assembly;
      var domProviderTypeAssembly = GetDomProviderType().Assembly;


      assemblyBuilder.AddAssemblyReference( buildTypeAssembly );
      if ( buildTypeAssembly != domProviderTypeAssembly )
        assemblyBuilder.AddAssemblyReference( domProviderTypeAssembly );
    }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            if (this._generatedCode == null)
            {
                this._generatedCode = GenerateCode();
            }

            assemblyBuilder.AddAssemblyReference(typeof(SimpleWeb).Assembly);
            assemblyBuilder.AddAssemblyReference(typeof(SimpleTemplateBase).Assembly);
            assemblyBuilder.AddCodeCompileUnit(this, this._generatedCode);
            assemblyBuilder.GenerateTypeFactory(this._typeName);
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            CodeCompileUnit codeCompileUnit = _parser.GetCodeModel();

            // Bail if we have nothing we need to compile
            if (codeCompileUnit == null)
            {
                return;
            }

            assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);

            // Add all the assemblies
            if (_parser.AssemblyDependencies != null)
            {
                foreach (Assembly assembly in _parser.AssemblyDependencies)
                {
                    assemblyBuilder.AddAssemblyReference(assembly, codeCompileUnit);
                }
            }

            // NOTE: we can't actually generate the fast factory because it would give
            // a really bad error if the user specifies a classname which doesn't match
            // the actual class they define.  A bit unfortunate, but not that big a deal...

            // tell the host to generate a fast factory for this type (if any)
            //string generatedTypeName = _parser.GeneratedTypeName;
            //if (generatedTypeName != null)
            //    assemblyBuilder.GenerateTypeFactory(generatedTypeName);
        }
Ejemplo n.º 5
0
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            if (!_codeGenerated)
            {
                GenerateCode();
            }

            TParser parser = Parse();

            OverrideAssemblyPrefix(parser, assemblyBuilder);

            string codeBehindSource = GetCodeBehindSource(parser);

            if (codeBehindSource != null)
            {
                assemblyBuilder.AddCodeFile(codeBehindSource, this, true);
            }

            List <string> refasms = GetReferencedAssemblies(parser);

            if (refasms != null && refasms.Count > 0)
            {
                foreach (string loc in refasms)
                {
                    assemblyBuilder.AddAssemblyReference(loc);
                }
            }

            GenerateCode(assemblyBuilder, parser, _compiler);
        }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     if (this.Parser.RequiresCompilation)
     {
         BaseCodeDomTreeGenerator generator = this.CreateCodeDomTreeGenerator(this._parser);
         CodeCompileUnit ccu = generator.GetCodeDomTree(assemblyBuilder.CodeDomProvider, assemblyBuilder.StringResourceBuilder, base.VirtualPathObject);
         if (ccu != null)
         {
             if (this._parser.AssemblyDependencies != null)
             {
                 foreach (Assembly assembly in (IEnumerable) this._parser.AssemblyDependencies)
                 {
                     assemblyBuilder.AddAssemblyReference(assembly, ccu);
                 }
             }
             assemblyBuilder.AddCodeCompileUnit(this, ccu);
         }
         this._instantiatableFullTypeName = generator.GetInstantiatableFullTypeName();
         if (this._instantiatableFullTypeName != null)
         {
             assemblyBuilder.GenerateTypeFactory(this._instantiatableFullTypeName);
         }
         this._intermediateFullTypeName = generator.GetIntermediateFullTypeName();
     }
 }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     if (this.Parser.RequiresCompilation)
     {
         BaseCodeDomTreeGenerator generator = this.CreateCodeDomTreeGenerator(this._parser);
         CodeCompileUnit          ccu       = generator.GetCodeDomTree(assemblyBuilder.CodeDomProvider, assemblyBuilder.StringResourceBuilder, base.VirtualPathObject);
         if (ccu != null)
         {
             if (this._parser.AssemblyDependencies != null)
             {
                 foreach (Assembly assembly in (IEnumerable)this._parser.AssemblyDependencies)
                 {
                     assemblyBuilder.AddAssemblyReference(assembly, ccu);
                 }
             }
             assemblyBuilder.AddCodeCompileUnit(this, ccu);
         }
         this._instantiatableFullTypeName = generator.GetInstantiatableFullTypeName();
         if (this._instantiatableFullTypeName != null)
         {
             assemblyBuilder.GenerateTypeFactory(this._instantiatableFullTypeName);
         }
         this._intermediateFullTypeName = generator.GetIntermediateFullTypeName();
     }
 }
    public override void GenerateCode(AssemblyBuilder assemblyBuilder) {

        CodeCompileUnit codeCompileUnit = _parser.GetCodeModel();

        // Bail if we have nothing we need to compile
        if (codeCompileUnit == null)
            return;

        assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);

        // Add all the assemblies
        if (_parser.AssemblyDependencies != null) {
            foreach (Assembly assembly in _parser.AssemblyDependencies) {
                assemblyBuilder.AddAssemblyReference(assembly, codeCompileUnit);
            }
        }

        // NOTE: we can't actually generate the fast factory because it would give
        // a really bad error if the user specifies a classname which doesn't match
        // the actual class they define.  A bit unfortunate, but not that big a deal...

        // tell the host to generate a fast factory for this type (if any)
        //string generatedTypeName = _parser.GeneratedTypeName;
        //if (generatedTypeName != null)
        //    assemblyBuilder.GenerateTypeFactory(generatedTypeName);
    }
    public override void GenerateCode(AssemblyBuilder assemblyBuilder)  {
#if !FEATURE_PAL // FEATURE_PAL does not support System.Data.Design
        // Get the namespace that we will use
        string ns = Util.GetNamespaceFromVirtualPath(VirtualPathObject);

        // We need to use XmlDocument to parse the xsd file is order to open it with the
        // correct encoding (VSWhidbey 566286)
        XmlDocument doc = new XmlDocument();
        using (Stream stream = OpenStream()) {
            doc.Load(stream);
        }
        String content = doc.OuterXml;

        // Generate a CodeCompileUnit from the dataset
        CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

        CodeNamespace codeNamespace = new CodeNamespace(ns);
        codeCompileUnit.Namespaces.Add(codeNamespace);

        // Devdiv 18365, Dev10 bug 444516 
        // Call a different Generate method if compiler version is v3.5 or above
        bool isVer35OrAbove = CompilationUtil.IsCompilerVersion35OrAbove(assemblyBuilder.CodeDomProvider.GetType());

        if (isVer35OrAbove) {
            TypedDataSetGenerator.GenerateOption generateOptions = TypedDataSetGenerator.GenerateOption.None;
            generateOptions |= TypedDataSetGenerator.GenerateOption.HierarchicalUpdate;
            generateOptions |= TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets;
            Hashtable customDBProviders = null;
            TypedDataSetGenerator.Generate(content, codeCompileUnit, codeNamespace, assemblyBuilder.CodeDomProvider, customDBProviders, generateOptions);
        }
        else {
            TypedDataSetGenerator.Generate(content, codeCompileUnit, codeNamespace, assemblyBuilder.CodeDomProvider);
        }

        // Add all the assembly references needed by the generated code
        if (TypedDataSetGenerator.ReferencedAssemblies != null) {
            var isVer35 = CompilationUtil.IsCompilerVersion35(assemblyBuilder.CodeDomProvider.GetType());
            foreach (Assembly a in TypedDataSetGenerator.ReferencedAssemblies) {
                
                if (isVer35) {
                    var aName = a.GetName();
                    if (aName.Name == "System.Data.DataSetExtensions") {
                        // Dev10 Bug 861688 - We need to specify v3.5 version so that the build system knows to use the v3.5 version
                        // because the loaded assembly here is always v4.0
                        aName.Version = new Version(3, 5, 0, 0);
                        CompilationSection.RecordAssembly(aName.FullName, a);
                    }
                }
                assemblyBuilder.AddAssemblyReference(a);
            }
        }
        

        // Add the CodeCompileUnit to the compilation
        assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);
#else // !FEATURE_PAL 
        throw new NotImplementedException("System.Data.Design - ROTORTODO");
#endif // !FEATURE_PAL 
    }
Ejemplo n.º 10
0
        /// <summary>
        /// Generate code for one .datasvcmap file
        /// </summary>
        /// <param name="mapFilePath">The physical path to the data service map file</param>
        private void GenerateCodeFromDataServiceMapFile(string mapFilePath, AssemblyBuilder assemblyBuilder)
        {
            try
            {
                assemblyBuilder.AddAssemblyReference(typeof(System.Data.Services.Client.DataServiceContext).Assembly);

                DataSvcMapFileLoader loader  = new DataSvcMapFileLoader(mapFilePath);
                DataSvcMapFile       mapFile = loader.LoadMapFile() as DataSvcMapFile;

                if (mapFile.MetadataList[0].ErrorInLoading != null)
                {
                    throw mapFile.MetadataList[0].ErrorInLoading;
                }

                string edmxContent = mapFile.MetadataList[0].Content;

                System.Data.Services.Design.EntityClassGenerator generator = new System.Data.Services.Design.EntityClassGenerator(LanguageOption.GenerateCSharpCode);

                // the EntityClassGenerator works on streams/writers, does not return a CodeDom
                // object, so we use CreateCodeFile instead of compile units.
                using (TextWriter writer = assemblyBuilder.CreateCodeFile(this))
                {
                    // Note: currently GenerateCode never actually returns values
                    // for the error case (even though it returns an IList of error
                    // objects). Instead it throws on error. This may need some tweaking
                    // later on.
#if DEBUG
                    object errors =
#endif
                    generator.GenerateCode(
                        XmlReader.Create(new StringReader(edmxContent)),
                        writer,
                        GetGeneratedNamespace());

#if DEBUG
                    Debug.Assert(
                        errors == null ||
                        !(errors is ICollection) ||
                        ((ICollection)errors).Count == 0,
                        "Errors reported through the return value. Expected an exception");
#endif
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                errorMessage = String.Format(CultureInfo.CurrentCulture, "{0}: {1}", IO.Path.GetFileName(mapFilePath), errorMessage);
                throw new InvalidOperationException(errorMessage, ex);
            }
        }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     CodeCompileUnit codeModel = this._parser.GetCodeModel();
     if (codeModel != null)
     {
         assemblyBuilder.AddCodeCompileUnit(this, codeModel);
         if (this._parser.AssemblyDependencies != null)
         {
             foreach (Assembly assembly in this._parser.AssemblyDependencies)
             {
                 assemblyBuilder.AddAssemblyReference(assembly, codeModel);
             }
         }
     }
 }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            CodeCompileUnit codeModel = this._parser.GetCodeModel();

            if (codeModel != null)
            {
                assemblyBuilder.AddCodeCompileUnit(this, codeModel);
                if (this._parser.AssemblyDependencies != null)
                {
                    foreach (Assembly assembly in this._parser.AssemblyDependencies)
                    {
                        assemblyBuilder.AddAssemblyReference(assembly, codeModel);
                    }
                }
            }
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            string      namespaceFromVirtualPath = Util.GetNamespaceFromVirtualPath(base.VirtualPathObject);
            XmlDocument document = new XmlDocument();

            using (Stream stream = base.OpenStream())
            {
                document.Load(stream);
            }
            string          outerXml    = document.OuterXml;
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace   namespace2  = new CodeNamespace(namespaceFromVirtualPath);

            compileUnit.Namespaces.Add(namespace2);
            if (CompilationUtil.IsCompilerVersion35OrAbove(assemblyBuilder.CodeDomProvider.GetType()))
            {
                TypedDataSetGenerator.GenerateOption none = TypedDataSetGenerator.GenerateOption.None;
                none |= TypedDataSetGenerator.GenerateOption.HierarchicalUpdate;
                none |= TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets;
                Hashtable customDBProviders = null;
                TypedDataSetGenerator.Generate(outerXml, compileUnit, namespace2, assemblyBuilder.CodeDomProvider, customDBProviders, none);
            }
            else
            {
                TypedDataSetGenerator.Generate(outerXml, compileUnit, namespace2, assemblyBuilder.CodeDomProvider);
            }
            if (TypedDataSetGenerator.ReferencedAssemblies != null)
            {
                bool flag2 = CompilationUtil.IsCompilerVersion35(assemblyBuilder.CodeDomProvider.GetType());
                foreach (Assembly assembly in TypedDataSetGenerator.ReferencedAssemblies)
                {
                    if (flag2)
                    {
                        AssemblyName name = assembly.GetName();
                        if (name.Name == "System.Data.DataSetExtensions")
                        {
                            name.Version = new Version(3, 5, 0, 0);
                            CompilationSection.RecordAssembly(name.FullName, assembly);
                        }
                    }
                    assemblyBuilder.AddAssemblyReference(assembly);
                }
            }
            assemblyBuilder.AddCodeCompileUnit(this, compileUnit);
        }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     string namespaceFromVirtualPath = Util.GetNamespaceFromVirtualPath(base.VirtualPathObject);
     XmlDocument document = new XmlDocument();
     using (Stream stream = base.OpenStream())
     {
         document.Load(stream);
     }
     string outerXml = document.OuterXml;
     CodeCompileUnit compileUnit = new CodeCompileUnit();
     CodeNamespace namespace2 = new CodeNamespace(namespaceFromVirtualPath);
     compileUnit.Namespaces.Add(namespace2);
     if (CompilationUtil.IsCompilerVersion35OrAbove(assemblyBuilder.CodeDomProvider.GetType()))
     {
         TypedDataSetGenerator.GenerateOption none = TypedDataSetGenerator.GenerateOption.None;
         none |= TypedDataSetGenerator.GenerateOption.HierarchicalUpdate;
         none |= TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets;
         Hashtable customDBProviders = null;
         TypedDataSetGenerator.Generate(outerXml, compileUnit, namespace2, assemblyBuilder.CodeDomProvider, customDBProviders, none);
     }
     else
     {
         TypedDataSetGenerator.Generate(outerXml, compileUnit, namespace2, assemblyBuilder.CodeDomProvider);
     }
     if (TypedDataSetGenerator.ReferencedAssemblies != null)
     {
         bool flag2 = CompilationUtil.IsCompilerVersion35(assemblyBuilder.CodeDomProvider.GetType());
         foreach (Assembly assembly in TypedDataSetGenerator.ReferencedAssemblies)
         {
             if (flag2)
             {
                 AssemblyName name = assembly.GetName();
                 if (name.Name == "System.Data.DataSetExtensions")
                 {
                     name.Version = new Version(3, 5, 0, 0);
                     CompilationSection.RecordAssembly(name.FullName, assembly);
                 }
             }
             assemblyBuilder.AddAssemblyReference(assembly);
         }
     }
     assemblyBuilder.AddCodeCompileUnit(this, compileUnit);
 }
Ejemplo n.º 15
0
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            // Don't generate any code for no-compile pages
            if (!Parser.RequiresCompilation)
            {
                return;
            }

            BaseCodeDomTreeGenerator treeGenerator = CreateCodeDomTreeGenerator(_parser);

            CodeCompileUnit ccu = treeGenerator.GetCodeDomTree(assemblyBuilder.CodeDomProvider,
                                                               assemblyBuilder.StringResourceBuilder, VirtualPathObject);

            if (ccu != null)
            {
                // Add all the assemblies
                if (_parser.AssemblyDependencies != null)
                {
                    foreach (Assembly assembly in _parser.AssemblyDependencies)
                    {
                        assemblyBuilder.AddAssemblyReference(assembly, ccu);
                    }
                }

                assemblyBuilder.AddCodeCompileUnit(this, ccu);
            }

            // Get the name of the generated type that can be instantiated.  It may be null
            // in updatable compilation scenarios.
            _instantiatableFullTypeName = treeGenerator.GetInstantiatableFullTypeName();

            // tell the assembly builder to generate a fast factory for this type
            if (_instantiatableFullTypeName != null)
            {
                assemblyBuilder.GenerateTypeFactory(_instantiatableFullTypeName);
            }

            _intermediateFullTypeName = treeGenerator.GetIntermediateFullTypeName();
        }
Ejemplo n.º 16
0
            /// <summary>
            /// Add the assembly references to the assembly builder depending on whether the databinding is enabled or not.
            /// </summary>
            /// <param name="assemblyBuilder">instance of assemblyBuilder where we need to add assembly references.</param>
            /// <param name="enableDataBinding">indicates whether databinding is enabled or not.</param>
            internal static void AddAssemblyReferences(AssemblyBuilder assemblyBuilder, bool useDataServiceCollection)
            {
                assemblyBuilder.AddAssemblyReference(typeof(System.Data.Services.Client.DataServiceContext).Assembly);

                if (useDataServiceCollection)
                {
                    // TODO: SQLBUDT 707098 - Use the helper method which returns the FrameworkName instance as defined in System.Runtime.Versioning namespace.
                    // When generating data binding code for .Net framework 3.5, we need to load the right version of windows base here.
                    // 3.5 Framework version: WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
                    // In 4.0, ObservableCollection<> class was moved into System.dll. Hence no need to do anything.
                    if (BuildManager.TargetFramework.Version.Major < 4)
                    {
                        assemblyBuilder.AddAssemblyReference(System.Reflection.Assembly.Load("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
                    }
                }
            }
Ejemplo n.º 17
0
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
#if !FEATURE_PAL // FEATURE_PAL does not support System.Data.Design
            // Get the namespace that we will use
            string ns = Util.GetNamespaceFromVirtualPath(VirtualPathObject);

            // We need to use XmlDocument to parse the xsd file is order to open it with the
            // correct encoding (VSWhidbey 566286)
            XmlDocument doc = new XmlDocument();
            using (Stream stream = OpenStream()) {
                doc.Load(stream);
            }
            String content = doc.OuterXml;

            // Generate a CodeCompileUnit from the dataset
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            CodeNamespace codeNamespace = new CodeNamespace(ns);
            codeCompileUnit.Namespaces.Add(codeNamespace);

            // Devdiv 18365, Dev10

            bool isVer35OrAbove = CompilationUtil.IsCompilerVersion35OrAbove(assemblyBuilder.CodeDomProvider.GetType());

            if (isVer35OrAbove)
            {
                TypedDataSetGenerator.GenerateOption generateOptions = TypedDataSetGenerator.GenerateOption.None;
                generateOptions |= TypedDataSetGenerator.GenerateOption.HierarchicalUpdate;
                generateOptions |= TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets;
                Hashtable customDBProviders = null;
                TypedDataSetGenerator.Generate(content, codeCompileUnit, codeNamespace, assemblyBuilder.CodeDomProvider, customDBProviders, generateOptions);
            }
            else
            {
                TypedDataSetGenerator.Generate(content, codeCompileUnit, codeNamespace, assemblyBuilder.CodeDomProvider);
            }

            // Add all the assembly references needed by the generated code
            if (TypedDataSetGenerator.ReferencedAssemblies != null)
            {
                var isVer35 = CompilationUtil.IsCompilerVersion35(assemblyBuilder.CodeDomProvider.GetType());
                foreach (Assembly a in TypedDataSetGenerator.ReferencedAssemblies)
                {
                    if (isVer35)
                    {
                        var aName = a.GetName();
                        if (aName.Name == "System.Data.DataSetExtensions")
                        {
                            // Dev10

                            aName.Version = new Version(3, 5, 0, 0);
                            CompilationSection.RecordAssembly(aName.FullName, a);
                        }
                    }
                    assemblyBuilder.AddAssemblyReference(a);
                }
            }


            // Add the CodeCompileUnit to the compilation
            assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);
#else // !FEATURE_PAL
            throw new NotImplementedException("System.Data.Design - ROTORTODO");
#endif // !FEATURE_PAL
        }
Ejemplo n.º 18
0
		static void GenerateAssembly (AssemblyBuilder abuilder, BuildProviderGroup group, VirtualPath vp, bool debug)
		{
			IDictionary <string, bool> deps;
			BuildManagerCacheItem bmci;
			string bvp, vpabsolute = vp.Absolute;
			StringBuilder sb;
			string newline;
			int failedCount = 0;
			
			if (debug) {
				newline = Environment.NewLine;
				sb = new StringBuilder ("Code generation for certain virtual paths in a batch failed. Those files have been removed from the batch." + newline);
				sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
			} else {
				newline = null;
				sb = null;
			}
			
			List <BuildProvider> failedBuildProviders = null;
			StringComparison stringComparison = RuntimeHelpers.StringComparison;
			foreach (BuildProvider bp in group) {
				bvp = bp.VirtualPath;
				if (HasCachedItemNoLock (bvp))
					continue;
				
				try {
					bp.GenerateCode (abuilder);
				} catch (Exception ex) {
					if (String.Compare (bvp, vpabsolute, stringComparison) == 0) {
						if (ex is CompilationException || ex is ParseException)
							throw;
						
						throw new HttpException ("Code generation failed.", ex);
					}
					
					if (failedBuildProviders == null)
						failedBuildProviders = new List <BuildProvider> ();
					failedBuildProviders.Add (bp);
					failedCount++;
					if (sb != null) {
						if (failedCount > 1)
							sb.Append (newline);
						
						sb.AppendFormat ("Failed file virtual path: {0}; Exception: {1}{2}{1}", bp.VirtualPath, newline, ex);
					}
					continue;
				}
				
				deps = bp.ExtractDependencies ();
				if (deps != null) {
					foreach (var dep in deps) {
						bmci = GetCachedItemNoLock (dep.Key);
						if (bmci == null || bmci.BuiltAssembly == null)
							continue;
						abuilder.AddAssemblyReference (bmci.BuiltAssembly);
					}
				}
			}

			if (sb != null && failedCount > 0)
				ShowDebugModeMessage (sb.ToString ());
			
			if (failedBuildProviders != null) {
				foreach (BuildProvider bp in failedBuildProviders)
					group.Remove (bp);
			}
			
			foreach (Assembly asm in referencedAssemblies) {
				if (asm == null)
					continue;
				
				abuilder.AddAssemblyReference (asm);
			}
			
			CompilerResults results  = abuilder.BuildAssembly (vp);
			
			// No results is not an error - it is possible that the assembly builder contained only .asmx and
			// .ashx files which had no body, just the directive. In such case, no code unit or code file is added
			// to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
			// to be added to the cache.
			Assembly compiledAssembly = results != null ? results.CompiledAssembly : null;
			try {
				buildCacheLock.EnterWriteLock ();
				if (compiledAssembly != null)
					referencedAssemblies.Add (compiledAssembly);
				
				foreach (BuildProvider bp in group) {
					if (HasCachedItemNoLock (bp.VirtualPath))
						continue;
					
					StoreInCache (bp, compiledAssembly, results);
				}
			} finally {
				buildCacheLock.ExitWriteLock ();
			}
		}
Ejemplo n.º 19
0
		// This method assumes it is being called with the big compilation lock held
		static void BuildInner (VirtualPath vp, bool debug)
		{
			var builder = new BuildManagerDirectoryBuilder (vp);
			bool recursive = recursionDepth > 1;
			List <BuildProviderGroup> builderGroups = builder.Build (IsSingleBuild (vp, recursive));
			if (builderGroups == null)
				return;

			string vpabsolute = vp.Absolute;
			int buildHash = (vpabsolute.GetHashCode () | (int)DateTime.Now.Ticks) + (int)recursionDepth;
			string assemblyBaseName;
			AssemblyBuilder abuilder;
			CompilerType ct;
			int attempts;
			bool singleBuild, needMainVpBuild;
			CompilationException compilationError;
			
			// Each group becomes a separate assembly.
			foreach (BuildProviderGroup group in builderGroups) {
				needMainVpBuild = false;
				compilationError = null;
				assemblyBaseName = null;
				
				if (group.Count == 1) {
					if (recursive || !group.Master)
						assemblyBaseName = String.Format ("{0}_{1}.{2:x}.", group.NamePrefix, VirtualPathUtility.GetFileName (group [0].VirtualPath), buildHash);
					singleBuild = true;
				} else
					singleBuild = false;
				
				if (assemblyBaseName == null)
					assemblyBaseName = group.NamePrefix + "_";
				
				ct = group.CompilerType;
				attempts = 3;
				while (attempts > 0) {
					abuilder = new AssemblyBuilder (vp, CreateDomProvider (ct), assemblyBaseName);
					abuilder.CompilerOptions = ct.CompilerParameters;
					abuilder.AddAssemblyReference (GetReferencedAssemblies () as List <Assembly>);
					try {
						GenerateAssembly (abuilder, group, vp, debug);
						attempts = 0;
					} catch (CompilationException ex) {
						attempts--;
						if (singleBuild)
							throw new HttpException ("Single file build failed.", ex);
						
						if (attempts == 0) {
							needMainVpBuild = true;
							compilationError = ex;
							break;
						}
						
						CompilerResults results = ex.Results;
						if (results == null)
							throw new HttpException ("No results returned from failed compilation.", ex);
						else
							RemoveFailedAssemblies (vpabsolute, ex, abuilder, group, results, debug);
					}
				}

				if (needMainVpBuild) {
					// One last attempt - try to build just the requested path
					// if it's not built yet or just return without throwing the
					// exception if it has already been built. 
					if (HasCachedItemNoLock (vpabsolute)) {
						if (debug)
							DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
										  compilationError, vpabsolute);
						return;
					};

					// This will trigger a recursive build of the requested vp,
					// which means only the vp alone will be built (or not); 
					Build (vp);
					if (HasCachedItemNoLock (vpabsolute)) {
						if (debug)
							DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
										  compilationError, vpabsolute);
						return;
					}

					// In theory this code is unreachable. If the recursive
					// build of the main vp failed, then it should have thrown
					// the build exception.
					throw new HttpException ("Requested virtual path build failed.", compilationError);
				}
			}
		}
Ejemplo n.º 20
0
		Assembly GetAssemblyFromSource (string vpath)
		{			
			vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
			string realPath = MapPath (vpath, false);
			if (!File.Exists (realPath))
				ThrowParseException ("File " + vpath + " not found");

			AddSourceDependency (vpath);
			
			CompilerResults result;
			string tmp;
			CompilerParameters parameters;
			CodeDomProvider provider = BaseCompiler.CreateProvider (HttpContext.Current, language, out parameters, out tmp);
			if (provider == null)
				throw new HttpException ("Cannot find provider for language '" + language + "'.");
			
			AssemblyBuilder abuilder = new AssemblyBuilder (provider);
			abuilder.CompilerOptions = parameters;
			abuilder.AddAssemblyReference (BuildManager.GetReferencedAssemblies () as List <Assembly>);
			abuilder.AddCodeFile (realPath);
			result = abuilder.BuildAssembly (new VirtualPath (vpath));

			if (result.NativeCompilerReturnValue != 0) {
				using (StreamReader reader = new StreamReader (realPath)) {
					throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
				}
			}

			AddAssembly (result.CompiledAssembly, true);
			return result.CompiledAssembly;
		}		
 internal void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     base.ProcessBrowserFiles(true, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
     base.ProcessCustomBrowserFiles(true, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
     CodeCompileUnit ccu = new CodeCompileUnit();
     ArrayList list = new ArrayList();
     for (int i = 0; i < base.CustomTreeNames.Count; i++)
     {
         list.Add((BrowserDefinition) ((BrowserTree) base.CustomTreeList[i])[base.CustomTreeNames[i]]);
     }
     CodeNamespace namespace2 = new CodeNamespace("ASP");
     namespace2.Imports.Add(new CodeNamespaceImport("System"));
     namespace2.Imports.Add(new CodeNamespaceImport("System.Web"));
     namespace2.Imports.Add(new CodeNamespaceImport("System.Web.Configuration"));
     namespace2.Imports.Add(new CodeNamespaceImport("System.Reflection"));
     ccu.Namespaces.Add(namespace2);
     Type browserCapabilitiesFactoryBaseType = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType();
     CodeTypeDeclaration declaration = new CodeTypeDeclaration {
         Attributes = MemberAttributes.Private,
         IsClass = true,
         Name = this.TypeName
     };
     declaration.BaseTypes.Add(new CodeTypeReference(browserCapabilitiesFactoryBaseType));
     namespace2.Types.Add(declaration);
     BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase;
     BrowserDefinition bd = null;
     CodeMemberMethod method = new CodeMemberMethod {
         Attributes = MemberAttributes.Public | MemberAttributes.Override,
         ReturnType = new CodeTypeReference(typeof(void)),
         Name = "ConfigureCustomCapabilities"
     };
     CodeParameterDeclarationExpression expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
     method.Parameters.Add(expression);
     expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
     method.Parameters.Add(expression);
     declaration.Members.Add(method);
     for (int j = 0; j < list.Count; j++)
     {
         base.GenerateSingleProcessCall((BrowserDefinition) list[j], method);
     }
     foreach (DictionaryEntry entry in this._browserOverrides)
     {
         object key = entry.Key;
         BrowserDefinition definition2 = (BrowserDefinition) base.BrowserTree[GetFirstItemFromKey(this._browserOverrides, key)];
         string parentName = definition2.ParentName;
         if (!TargetFrameworkUtil.HasMethod(browserCapabilitiesFactoryBaseType, parentName + "ProcessBrowsers", bindingAttr) || !TargetFrameworkUtil.HasMethod(browserCapabilitiesFactoryBaseType, parentName + "ProcessGateways", bindingAttr))
         {
             string parentID = definition2.ParentID;
             if (definition2 != null)
             {
                 throw new ConfigurationErrorsException(System.Web.SR.GetString("Browser_parentID_Not_Found", new object[] { parentID }), definition2.XmlNode);
             }
             throw new ConfigurationErrorsException(System.Web.SR.GetString("Browser_parentID_Not_Found", new object[] { parentID }));
         }
         bool flag = true;
         if (definition2 is GatewayDefinition)
         {
             flag = false;
         }
         string str3 = parentName + (flag ? "ProcessBrowsers" : "ProcessGateways");
         CodeMemberMethod method2 = new CodeMemberMethod {
             Name = str3,
             ReturnType = new CodeTypeReference(typeof(void)),
             Attributes = MemberAttributes.Family | MemberAttributes.Override
         };
         if (flag)
         {
             expression = new CodeParameterDeclarationExpression(typeof(bool), "ignoreApplicationBrowsers");
             method2.Parameters.Add(expression);
         }
         expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
         method2.Parameters.Add(expression);
         expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
         method2.Parameters.Add(expression);
         declaration.Members.Add(method2);
         ArrayList list2 = (ArrayList) this._browserOverrides[key];
         CodeStatementCollection stmts = method2.Statements;
         bool flag2 = false;
         foreach (string str4 in list2)
         {
             bd = (BrowserDefinition) base.BrowserTree[str4];
             if ((bd is GatewayDefinition) || bd.IsRefID)
             {
                 base.GenerateSingleProcessCall(bd, method2);
             }
             else
             {
                 if (!flag2)
                 {
                     CodeConditionStatement statement = new CodeConditionStatement {
                         Condition = new CodeVariableReferenceExpression("ignoreApplicationBrowsers")
                     };
                     method2.Statements.Add(statement);
                     stmts = statement.FalseStatements;
                     flag2 = true;
                 }
                 stmts = base.GenerateTrackedSingleProcessCall(stmts, bd, method2);
                 if (this._baseInstance == null)
                 {
                     if (MultiTargetingUtil.IsTargetFramework40OrAbove || (browserCapabilitiesFactoryBaseType.Assembly == BrowserCapabilitiesCompiler.AspBrowserCapsFactoryAssembly))
                     {
                         this._baseInstance = (BrowserCapabilitiesFactoryBase) Activator.CreateInstance(browserCapabilitiesFactoryBaseType);
                     }
                     else
                     {
                         this._baseInstance = new BrowserCapabilitiesFactory35();
                     }
                 }
                 int third = (int) ((Triplet) this._baseInstance.InternalGetBrowserElements()[parentName]).Third;
                 base.AddBrowserToCollectionRecursive(bd, third + 1);
             }
         }
     }
     foreach (DictionaryEntry entry2 in this._defaultBrowserOverrides)
     {
         object obj3 = entry2.Key;
         BrowserDefinition definition3 = (BrowserDefinition) base.DefaultTree[GetFirstItemFromKey(this._defaultBrowserOverrides, obj3)];
         string str5 = definition3.ParentName;
         if (browserCapabilitiesFactoryBaseType.GetMethod("Default" + str5 + "ProcessBrowsers", bindingAttr) == null)
         {
             string str6 = definition3.ParentID;
             if (definition3 != null)
             {
                 throw new ConfigurationErrorsException(System.Web.SR.GetString("DefaultBrowser_parentID_Not_Found", new object[] { str6 }), definition3.XmlNode);
             }
         }
         string str7 = "Default" + str5 + "ProcessBrowsers";
         CodeMemberMethod method3 = new CodeMemberMethod {
             Name = str7,
             ReturnType = new CodeTypeReference(typeof(void)),
             Attributes = MemberAttributes.Family | MemberAttributes.Override
         };
         expression = new CodeParameterDeclarationExpression(typeof(bool), "ignoreApplicationBrowsers");
         method3.Parameters.Add(expression);
         expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
         method3.Parameters.Add(expression);
         expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
         method3.Parameters.Add(expression);
         declaration.Members.Add(method3);
         ArrayList list3 = (ArrayList) this._defaultBrowserOverrides[obj3];
         CodeConditionStatement statement2 = new CodeConditionStatement {
             Condition = new CodeVariableReferenceExpression("ignoreApplicationBrowsers")
         };
         method3.Statements.Add(statement2);
         CodeStatementCollection falseStatements = statement2.FalseStatements;
         foreach (string str8 in list3)
         {
             bd = (BrowserDefinition) base.DefaultTree[str8];
             if (bd.IsRefID)
             {
                 base.GenerateSingleProcessCall(bd, method3, "Default");
             }
             else
             {
                 falseStatements = base.GenerateTrackedSingleProcessCall(falseStatements, bd, method3, "Default");
             }
         }
     }
     foreach (DictionaryEntry entry3 in base.BrowserTree)
     {
         bd = entry3.Value as BrowserDefinition;
         base.GenerateProcessMethod(bd, declaration);
     }
     for (int k = 0; k < list.Count; k++)
     {
         foreach (DictionaryEntry entry4 in (BrowserTree) base.CustomTreeList[k])
         {
             bd = entry4.Value as BrowserDefinition;
             base.GenerateProcessMethod(bd, declaration);
         }
     }
     foreach (DictionaryEntry entry5 in base.DefaultTree)
     {
         bd = entry5.Value as BrowserDefinition;
         base.GenerateProcessMethod(bd, declaration, "Default");
     }
     base.GenerateOverrideMatchedHeaders(declaration);
     base.GenerateOverrideBrowserElements(declaration);
     Assembly a = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType().Assembly;
     assemblyBuilder.AddAssemblyReference(a, ccu);
     assemblyBuilder.AddCodeCompileUnit(this._buildProvider, ccu);
 }
        void GenerateCodeCore(AssemblyBuilder assemblyBuilder)
        {
            if (assemblyBuilder == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assemblyBuilder");
            }

            CodeCompileUnit codeCompileUnit = parser.GetCodeModel();

            // Bail if we have nothing we need to compile
            //
            if (codeCompileUnit == null)
                return;

            // Add the code unit and then add all the assemblies 
            //
            assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);
            if (parser.AssemblyDependencies != null)
            {
                foreach (Assembly assembly in parser.AssemblyDependencies)
                {
                    assemblyBuilder.AddAssemblyReference(assembly);
                }
            }
        }
        //generate the code from the parsed BrowserDefinitionTree
        //compile it, and install it in the gac
        internal void GenerateCode(AssemblyBuilder assemblyBuilder) {
            
            ProcessBrowserFiles(true /*useVirtualPath*/, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
            ProcessCustomBrowserFiles(true /*useVirtualPath*/, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
            
            CodeCompileUnit ccu = new CodeCompileUnit();

            Debug.Assert(BrowserTree != null);
            ArrayList customTreeRoots = new ArrayList();
            for (int i = 0; i < CustomTreeNames.Count; i++) {
                customTreeRoots.Add((BrowserDefinition)(((BrowserTree)CustomTreeList[i])[CustomTreeNames[i]]));
            }

            // namespace ASP
            CodeNamespace cnamespace = new CodeNamespace(BaseCodeDomTreeGenerator.defaultNamespace);
            //GEN: using System;
            cnamespace.Imports.Add(new CodeNamespaceImport("System"));
            //GEN: using System.Web;
            cnamespace.Imports.Add(new CodeNamespaceImport("System.Web"));
            //GEN: using System.Web.Configuration;
            cnamespace.Imports.Add(new CodeNamespaceImport("System.Web.Configuration"));
            //GEN: using System.Reflection;
            cnamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            //GEN: class BrowserCapabilitiesFactory
            ccu.Namespaces.Add(cnamespace);

            Type baseType = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType();

            CodeTypeDeclaration factoryType = new CodeTypeDeclaration();
            factoryType.Attributes = MemberAttributes.Private;
            factoryType.IsClass = true;
            factoryType.Name = TypeName;
            factoryType.BaseTypes.Add(new CodeTypeReference(baseType));
            cnamespace.Types.Add(factoryType);

            BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic;

            BrowserDefinition bd = null;
            //GEN: protected override object ConfigureBrowserCapabilities(NameValueCollection headers, HttpBrowserCapabilities browserCaps)
            CodeMemberMethod method = new CodeMemberMethod();
            method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(void));
            method.Name = "ConfigureCustomCapabilities";
            CodeParameterDeclarationExpression cpde = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
            method.Parameters.Add(cpde);
            cpde = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
            method.Parameters.Add(cpde);
            factoryType.Members.Add(method);

            for (int i = 0; i < customTreeRoots.Count; i++) {
                GenerateSingleProcessCall((BrowserDefinition)customTreeRoots[i], method);
            }
            
            foreach (DictionaryEntry entry in _browserOverrides) {
                object key = entry.Key;
                BrowserDefinition firstBrowserDefinition = (BrowserDefinition)BrowserTree[GetFirstItemFromKey(_browserOverrides, key)];
                
                string parentName = firstBrowserDefinition.ParentName;
                
                //



                if ((!TargetFrameworkUtil.HasMethod(baseType, parentName + "ProcessBrowsers", flags)) ||
                    (!TargetFrameworkUtil.HasMethod(baseType, parentName + "ProcessGateways", flags))) {
                    String parentID = firstBrowserDefinition.ParentID;

                    if (firstBrowserDefinition != null) {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Browser_parentID_Not_Found, parentID), firstBrowserDefinition.XmlNode);
                    } else {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Browser_parentID_Not_Found, parentID));
                    }
                }
               
                bool isBrowserDefinition = true;
                if (firstBrowserDefinition is GatewayDefinition) {
                    isBrowserDefinition = false;
                }

                //GenerateMethodsToOverrideBrowsers
                //Gen: protected override void Xxx_ProcessChildBrowsers(bool ignoreApplicationBrowsers, MNameValueCollection headers, HttpBrowserCapabilities browserCaps) ;

                string methodName = parentName + (isBrowserDefinition ? "ProcessBrowsers" : "ProcessGateways");
                CodeMemberMethod cmm = new CodeMemberMethod();
                cmm.Name = methodName;
                cmm.ReturnType = new CodeTypeReference(typeof(void));
                cmm.Attributes = MemberAttributes.Family | MemberAttributes.Override;

                if (isBrowserDefinition) {
                    cpde = new CodeParameterDeclarationExpression(typeof(bool), BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);
                    cmm.Parameters.Add(cpde);
                }
                cpde = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
                cmm.Parameters.Add(cpde);
                cpde = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), browserCapsVariable);
                cmm.Parameters.Add(cpde);

                factoryType.Members.Add(cmm);

                ArrayList overrides = (ArrayList)_browserOverrides[key];
                CodeStatementCollection statements = cmm.Statements;

                bool ignoreApplicationBrowsersVarRefGenerated = false;
                
                foreach (string browserID in overrides) {
                    bd = (BrowserDefinition)BrowserTree[browserID];
                    if (bd is GatewayDefinition || bd.IsRefID) {
                        GenerateSingleProcessCall(bd, cmm);
                    }
                    else {
                        if (!ignoreApplicationBrowsersVarRefGenerated) {
                            Debug.Assert(isBrowserDefinition);

                            // Gen: if (ignoreApplicationBrowsers) {
                            //      }
                            //      else {
                            //          ...
                            //      }
                            CodeConditionStatement istatement = new CodeConditionStatement();

                            istatement.Condition = new CodeVariableReferenceExpression(BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);

                            cmm.Statements.Add(istatement);
                            statements = istatement.FalseStatements;

                            ignoreApplicationBrowsersVarRefGenerated = true;
                        }
                        statements = GenerateTrackedSingleProcessCall(statements, bd, cmm);
                        if (_baseInstance == null) {
                            // If we are targeting 4.0 or using the ASP.BrowserCapsFactory assembly generated by
                            // aspnet_regbrowsers.exe, we can simply just instantiate the type.
                            // If not, then we need to use the type BrowserCapabilitiesFactory35 that contains code
                            // from the 2.0 version of BrowserCapabilitiesFactory. This is because "baseType" is the 4.0 type
                            // that contains the new 4.0 definitions.
                            // (Dev10 bug 795509)
                            if (MultiTargetingUtil.IsTargetFramework40OrAbove || 
                                baseType.Assembly == BrowserCapabilitiesCompiler.AspBrowserCapsFactoryAssembly) {
                                _baseInstance = (BrowserCapabilitiesFactoryBase)Activator.CreateInstance(baseType);
                            }
                            else {
                                _baseInstance = new BrowserCapabilitiesFactory35();
                            }
                        }
                        int parentDepth = (int)((Triplet)_baseInstance.InternalGetBrowserElements()[parentName]).Third;
                        AddBrowserToCollectionRecursive(bd, parentDepth + 1);
                    }
                }

            }

            foreach (DictionaryEntry entry in _defaultBrowserOverrides) {
                object key = entry.Key;

                BrowserDefinition firstDefaultBrowserDefinition = (BrowserDefinition)DefaultTree[GetFirstItemFromKey(_defaultBrowserOverrides, key)];
                string parentName = firstDefaultBrowserDefinition.ParentName;

                if (baseType.GetMethod("Default" + parentName + "ProcessBrowsers", flags) == null) {
                    String parentID = firstDefaultBrowserDefinition.ParentID;
                    if (firstDefaultBrowserDefinition != null) {
                        throw new ConfigurationErrorsException(SR.GetString(SR.DefaultBrowser_parentID_Not_Found, parentID), firstDefaultBrowserDefinition.XmlNode);
                    }
                }

                string methodName = "Default" + parentName + "ProcessBrowsers";
                CodeMemberMethod cmm = new CodeMemberMethod();
                cmm.Name = methodName;
                cmm.ReturnType = new CodeTypeReference(typeof(void));
                cmm.Attributes = MemberAttributes.Family | MemberAttributes.Override;
                cpde = new CodeParameterDeclarationExpression(typeof(bool), BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);
                cmm.Parameters.Add(cpde);
                cpde = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
                cmm.Parameters.Add(cpde);
                cpde = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), browserCapsVariable);
                cmm.Parameters.Add(cpde);
                factoryType.Members.Add(cmm);

                ArrayList overrides = (ArrayList)_defaultBrowserOverrides[key];

                CodeConditionStatement istatement = new CodeConditionStatement();
                istatement.Condition = new CodeVariableReferenceExpression(BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);

                cmm.Statements.Add(istatement);
                CodeStatementCollection statements = istatement.FalseStatements;

                foreach(string browserID in overrides) {
                    bd = (BrowserDefinition)DefaultTree[browserID];
                    Debug.Assert(!(bd is GatewayDefinition));

                    if(bd.IsRefID) {
                        GenerateSingleProcessCall(bd, cmm, "Default");
                    }
                    else {
                        statements = GenerateTrackedSingleProcessCall(statements, bd, cmm, "Default");
                    }
                }
            }

            // Generate process method for the browser elements
            foreach (DictionaryEntry entry in BrowserTree) {
                bd = entry.Value as BrowserDefinition;
                Debug.Assert(bd != null);
                GenerateProcessMethod(bd, factoryType);
            }

            for (int i = 0; i < customTreeRoots.Count; i++) {
                foreach (DictionaryEntry entry in (BrowserTree)CustomTreeList[i]) {
                    bd = entry.Value as BrowserDefinition;
                    Debug.Assert(bd != null);
                    GenerateProcessMethod(bd, factoryType);
                }
            }

            // Generate process method for the default browser elements
            foreach (DictionaryEntry entry in DefaultTree) {
                bd = entry.Value as BrowserDefinition;
                Debug.Assert(bd != null);
                GenerateProcessMethod(bd, factoryType, "Default");
            }
            GenerateOverrideMatchedHeaders(factoryType);
            GenerateOverrideBrowserElements(factoryType);

            Assembly assembly = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType().Assembly;
            assemblyBuilder.AddAssemblyReference(assembly, ccu);
            assemblyBuilder.AddCodeCompileUnit(_buildProvider, ccu);
        }
        //generate the code from the parsed BrowserDefinitionTree
        //compile it, and install it in the gac
        internal void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            ProcessBrowserFiles(true /*useVirtualPath*/, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
            ProcessCustomBrowserFiles(true /*useVirtualPath*/, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);

            CodeCompileUnit ccu = new CodeCompileUnit();

            Debug.Assert(BrowserTree != null);
            ArrayList customTreeRoots = new ArrayList();

            for (int i = 0; i < CustomTreeNames.Count; i++)
            {
                customTreeRoots.Add((BrowserDefinition)(((BrowserTree)CustomTreeList[i])[CustomTreeNames[i]]));
            }

            // namespace ASP
            CodeNamespace cnamespace = new CodeNamespace(BaseCodeDomTreeGenerator.defaultNamespace);

            //GEN: using System;
            cnamespace.Imports.Add(new CodeNamespaceImport("System"));
            //GEN: using System.Web;
            cnamespace.Imports.Add(new CodeNamespaceImport("System.Web"));
            //GEN: using System.Web.Configuration;
            cnamespace.Imports.Add(new CodeNamespaceImport("System.Web.Configuration"));
            //GEN: using System.Reflection;
            cnamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            //GEN: class BrowserCapabilitiesFactory
            ccu.Namespaces.Add(cnamespace);

            Type baseType = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType();

            CodeTypeDeclaration factoryType = new CodeTypeDeclaration();

            factoryType.Attributes = MemberAttributes.Private;
            factoryType.IsClass    = true;
            factoryType.Name       = TypeName;
            factoryType.BaseTypes.Add(new CodeTypeReference(baseType));
            cnamespace.Types.Add(factoryType);

            BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic;

            BrowserDefinition bd = null;
            //GEN: protected override object ConfigureBrowserCapabilities(NameValueCollection headers, HttpBrowserCapabilities browserCaps)
            CodeMemberMethod method = new CodeMemberMethod();

            method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(void));
            method.Name       = "ConfigureCustomCapabilities";
            CodeParameterDeclarationExpression cpde = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");

            method.Parameters.Add(cpde);
            cpde = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
            method.Parameters.Add(cpde);
            factoryType.Members.Add(method);

            for (int i = 0; i < customTreeRoots.Count; i++)
            {
                GenerateSingleProcessCall((BrowserDefinition)customTreeRoots[i], method);
            }

            foreach (DictionaryEntry entry in _browserOverrides)
            {
                object            key = entry.Key;
                BrowserDefinition firstBrowserDefinition = (BrowserDefinition)BrowserTree[GetFirstItemFromKey(_browserOverrides, key)];

                string parentName = firstBrowserDefinition.ParentName;

                //



                if ((!TargetFrameworkUtil.HasMethod(baseType, parentName + "ProcessBrowsers", flags)) ||
                    (!TargetFrameworkUtil.HasMethod(baseType, parentName + "ProcessGateways", flags)))
                {
                    String parentID = firstBrowserDefinition.ParentID;

                    if (firstBrowserDefinition != null)
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Browser_parentID_Not_Found, parentID), firstBrowserDefinition.XmlNode);
                    }
                    else
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Browser_parentID_Not_Found, parentID));
                    }
                }

                bool isBrowserDefinition = true;
                if (firstBrowserDefinition is GatewayDefinition)
                {
                    isBrowserDefinition = false;
                }

                //GenerateMethodsToOverrideBrowsers
                //Gen: protected override void Xxx_ProcessChildBrowsers(bool ignoreApplicationBrowsers, MNameValueCollection headers, HttpBrowserCapabilities browserCaps) ;

                string           methodName = parentName + (isBrowserDefinition ? "ProcessBrowsers" : "ProcessGateways");
                CodeMemberMethod cmm        = new CodeMemberMethod();
                cmm.Name       = methodName;
                cmm.ReturnType = new CodeTypeReference(typeof(void));
                cmm.Attributes = MemberAttributes.Family | MemberAttributes.Override;

                if (isBrowserDefinition)
                {
                    cpde = new CodeParameterDeclarationExpression(typeof(bool), BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);
                    cmm.Parameters.Add(cpde);
                }
                cpde = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
                cmm.Parameters.Add(cpde);
                cpde = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), browserCapsVariable);
                cmm.Parameters.Add(cpde);

                factoryType.Members.Add(cmm);

                ArrayList overrides = (ArrayList)_browserOverrides[key];
                CodeStatementCollection statements = cmm.Statements;

                bool ignoreApplicationBrowsersVarRefGenerated = false;

                foreach (string browserID in overrides)
                {
                    bd = (BrowserDefinition)BrowserTree[browserID];
                    if (bd is GatewayDefinition || bd.IsRefID)
                    {
                        GenerateSingleProcessCall(bd, cmm);
                    }
                    else
                    {
                        if (!ignoreApplicationBrowsersVarRefGenerated)
                        {
                            Debug.Assert(isBrowserDefinition);

                            // Gen: if (ignoreApplicationBrowsers) {
                            //      }
                            //      else {
                            //          ...
                            //      }
                            CodeConditionStatement istatement = new CodeConditionStatement();

                            istatement.Condition = new CodeVariableReferenceExpression(BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);

                            cmm.Statements.Add(istatement);
                            statements = istatement.FalseStatements;

                            ignoreApplicationBrowsersVarRefGenerated = true;
                        }
                        statements = GenerateTrackedSingleProcessCall(statements, bd, cmm);
                        if (_baseInstance == null)
                        {
                            // If we are targeting 4.0 or using the ASP.BrowserCapsFactory assembly generated by
                            // aspnet_regbrowsers.exe, we can simply just instantiate the type.
                            // If not, then we need to use the type BrowserCapabilitiesFactory35 that contains code
                            // from the 2.0 version of BrowserCapabilitiesFactory. This is because "baseType" is the 4.0 type
                            // that contains the new 4.0 definitions.
                            // (Dev10 bug 795509)
                            if (MultiTargetingUtil.IsTargetFramework40OrAbove ||
                                baseType.Assembly == BrowserCapabilitiesCompiler.AspBrowserCapsFactoryAssembly)
                            {
                                _baseInstance = (BrowserCapabilitiesFactoryBase)Activator.CreateInstance(baseType);
                            }
                            else
                            {
                                _baseInstance = new BrowserCapabilitiesFactory35();
                            }
                        }
                        int parentDepth = (int)((Triplet)_baseInstance.InternalGetBrowserElements()[parentName]).Third;
                        AddBrowserToCollectionRecursive(bd, parentDepth + 1);
                    }
                }
            }

            foreach (DictionaryEntry entry in _defaultBrowserOverrides)
            {
                object key = entry.Key;

                BrowserDefinition firstDefaultBrowserDefinition = (BrowserDefinition)DefaultTree[GetFirstItemFromKey(_defaultBrowserOverrides, key)];
                string            parentName = firstDefaultBrowserDefinition.ParentName;

                if (baseType.GetMethod("Default" + parentName + "ProcessBrowsers", flags) == null)
                {
                    String parentID = firstDefaultBrowserDefinition.ParentID;
                    if (firstDefaultBrowserDefinition != null)
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.DefaultBrowser_parentID_Not_Found, parentID), firstDefaultBrowserDefinition.XmlNode);
                    }
                }

                string           methodName = "Default" + parentName + "ProcessBrowsers";
                CodeMemberMethod cmm        = new CodeMemberMethod();
                cmm.Name       = methodName;
                cmm.ReturnType = new CodeTypeReference(typeof(void));
                cmm.Attributes = MemberAttributes.Family | MemberAttributes.Override;
                cpde           = new CodeParameterDeclarationExpression(typeof(bool), BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);
                cmm.Parameters.Add(cpde);
                cpde = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
                cmm.Parameters.Add(cpde);
                cpde = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), browserCapsVariable);
                cmm.Parameters.Add(cpde);
                factoryType.Members.Add(cmm);

                ArrayList overrides = (ArrayList)_defaultBrowserOverrides[key];

                CodeConditionStatement istatement = new CodeConditionStatement();
                istatement.Condition = new CodeVariableReferenceExpression(BrowserCapabilitiesCodeGenerator.IgnoreApplicationBrowserVariableName);

                cmm.Statements.Add(istatement);
                CodeStatementCollection statements = istatement.FalseStatements;

                foreach (string browserID in overrides)
                {
                    bd = (BrowserDefinition)DefaultTree[browserID];
                    Debug.Assert(!(bd is GatewayDefinition));

                    if (bd.IsRefID)
                    {
                        GenerateSingleProcessCall(bd, cmm, "Default");
                    }
                    else
                    {
                        statements = GenerateTrackedSingleProcessCall(statements, bd, cmm, "Default");
                    }
                }
            }

            // Generate process method for the browser elements
            foreach (DictionaryEntry entry in BrowserTree)
            {
                bd = entry.Value as BrowserDefinition;
                Debug.Assert(bd != null);
                GenerateProcessMethod(bd, factoryType);
            }

            for (int i = 0; i < customTreeRoots.Count; i++)
            {
                foreach (DictionaryEntry entry in (BrowserTree)CustomTreeList[i])
                {
                    bd = entry.Value as BrowserDefinition;
                    Debug.Assert(bd != null);
                    GenerateProcessMethod(bd, factoryType);
                }
            }

            // Generate process method for the default browser elements
            foreach (DictionaryEntry entry in DefaultTree)
            {
                bd = entry.Value as BrowserDefinition;
                Debug.Assert(bd != null);
                GenerateProcessMethod(bd, factoryType, "Default");
            }
            GenerateOverrideMatchedHeaders(factoryType);
            GenerateOverrideBrowserElements(factoryType);

            Assembly assembly = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType().Assembly;

            assemblyBuilder.AddAssemblyReference(assembly, ccu);
            assemblyBuilder.AddCodeCompileUnit(_buildProvider, ccu);
        }
    public override void GenerateCode(AssemblyBuilder assemblyBuilder) {

        // Don't generate any code for no-compile pages
        if (!Parser.RequiresCompilation)
            return;

        BaseCodeDomTreeGenerator treeGenerator = CreateCodeDomTreeGenerator(_parser);

        CodeCompileUnit ccu = treeGenerator.GetCodeDomTree(assemblyBuilder.CodeDomProvider,
            assemblyBuilder.StringResourceBuilder, VirtualPathObject);

        if (ccu != null) {
            // Add all the assemblies
            if (_parser.AssemblyDependencies != null) {
                foreach (Assembly assembly in _parser.AssemblyDependencies) {
                    assemblyBuilder.AddAssemblyReference(assembly, ccu);
                }
            }

            assemblyBuilder.AddCodeCompileUnit(this, ccu);
        }

        // Get the name of the generated type that can be instantiated.  It may be null
        // in updatable compilation scenarios.
        _instantiatableFullTypeName = treeGenerator.GetInstantiatableFullTypeName();

        // tell the assembly builder to generate a fast factory for this type
        if (_instantiatableFullTypeName != null)
            assemblyBuilder.GenerateTypeFactory(_instantiatableFullTypeName);

        _intermediateFullTypeName = treeGenerator.GetIntermediateFullTypeName();
    }
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////

        // BuildProvider implementation

        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            Hashtable       properties  = ProfileBase.GetPropertiesForCompilation();
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            Hashtable       groups      = new Hashtable();
            Type            baseType    = Type.GetType(ProfileBase.InheritsFromTypeString, false);

            // namespace ASP {
            //
            CodeNamespace ns = new CodeNamespace();

            // ns.Name = BaseCodeDomTreeGenerator.defaultNamespace;

            //GEN: using System;
            ns.Imports.Add(new CodeNamespaceImport("System"));
            //GEN: using System.Web;
            ns.Imports.Add(new CodeNamespaceImport("System.Web"));
            //GEN: using System.Web.Profile;
            ns.Imports.Add(new CodeNamespaceImport("System.Web.Profile"));

            // class Profile :  System.Web.Security.ProfileBase {
            //
            CodeTypeDeclaration type = new CodeTypeDeclaration();

            type.Name = ProfileTypeName;
            if (baseType != null)
            {
                type.BaseTypes.Add(new CodeTypeReference(baseType));
                assemblyBuilder.AddAssemblyReference(baseType.Assembly, compileUnit);
            }
            else
            {
                type.BaseTypes.Add(new CodeTypeReference(ProfileBase.InheritsFromTypeString));
                ProfileSection config = MTConfigUtil.GetProfileAppConfig();
                if (config != null)
                {
                    PropertyInformation prop = config.ElementInformation.Properties["inherits"];
                    if (prop != null && prop.Source != null && prop.LineNumber > 0)
                    {
                        type.LinePragma = new CodeLinePragma(HttpRuntime.GetSafePath(prop.Source), prop.LineNumber);
                    }
                }
            }
            // tell the assemblyBuilder to generate a fast factory for this type
            assemblyBuilder.GenerateTypeFactory(/*ns.Name + "." + */ ProfileTypeName);

            foreach (DictionaryEntry de in properties)
            {
                ProfileNameTypeStruct property = (ProfileNameTypeStruct)de.Value;
                if (property.PropertyType != null)
                {
                    assemblyBuilder.AddAssemblyReference(property.PropertyType.Assembly, compileUnit);
                }
                int pos = property.Name.IndexOf('.');
                if (pos < 0)
                {
                    // public string Color { get { return (string) GetProperty("Color"); } set { SetProperty("Color", value); } }
                    CreateCodeForProperty(assemblyBuilder, type, property);
                }
                else
                {
                    string grpName = property.Name.Substring(0, pos);
                    if (!assemblyBuilder.CodeDomProvider.IsValidIdentifier(grpName))
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Profile_bad_group, grpName), property.FileName, property.LineNumber);
                    }
                    if (groups[grpName] == null)
                    {
                        groups.Add(grpName, property.Name);
                    }
                    else
                    {
                        groups[grpName] = ((string)groups[grpName]) + ";" + property.Name;
                    }
                }
            }

            foreach (DictionaryEntry de in groups)
            {
                // public ProfileGroupFooClass Foo { get { return ProfileGroupSomething; }}
                //
                // public class ProfileGroupFoo : ProfileGroup {
                //      Properties
                // }
                AddPropertyGroup(assemblyBuilder, (string)de.Key, (string)de.Value, properties, type, ns);
            }


            // public ASP.Profile GetProfileForUser(string username) {
            //      return (ASP.Profile) this.GetUserProfile(username);
            // }
            AddCodeForGetProfileForUser(type);

            // }
            //
            ns.Types.Add(type);
            compileUnit.Namespaces.Add(ns);

            assemblyBuilder.AddCodeCompileUnit(this, compileUnit);
        }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     Hashtable propertiesForCompilation = ProfileBase.GetPropertiesForCompilation();
     CodeCompileUnit ccu = new CodeCompileUnit();
     Hashtable hashtable2 = new Hashtable();
     Type type = Type.GetType(ProfileBase.InheritsFromTypeString, false);
     CodeNamespace ns = new CodeNamespace();
     ns.Imports.Add(new CodeNamespaceImport("System"));
     ns.Imports.Add(new CodeNamespaceImport("System.Web"));
     ns.Imports.Add(new CodeNamespaceImport("System.Web.Profile"));
     CodeTypeDeclaration declaration = new CodeTypeDeclaration {
         Name = "ProfileCommon"
     };
     if (type != null)
     {
         declaration.BaseTypes.Add(new CodeTypeReference(type));
         assemblyBuilder.AddAssemblyReference(type.Assembly, ccu);
     }
     else
     {
         declaration.BaseTypes.Add(new CodeTypeReference(ProfileBase.InheritsFromTypeString));
         ProfileSection profileAppConfig = MTConfigUtil.GetProfileAppConfig();
         if (profileAppConfig != null)
         {
             PropertyInformation information = profileAppConfig.ElementInformation.Properties["inherits"];
             if (((information != null) && (information.Source != null)) && (information.LineNumber > 0))
             {
                 declaration.LinePragma = new CodeLinePragma(HttpRuntime.GetSafePath(information.Source), information.LineNumber);
             }
         }
     }
     assemblyBuilder.GenerateTypeFactory("ProfileCommon");
     foreach (DictionaryEntry entry in propertiesForCompilation)
     {
         ProfileNameTypeStruct property = (ProfileNameTypeStruct) entry.Value;
         if (property.PropertyType != null)
         {
             assemblyBuilder.AddAssemblyReference(property.PropertyType.Assembly, ccu);
         }
         int index = property.Name.IndexOf('.');
         if (index < 0)
         {
             this.CreateCodeForProperty(assemblyBuilder, declaration, property);
         }
         else
         {
             string str = property.Name.Substring(0, index);
             if (!assemblyBuilder.CodeDomProvider.IsValidIdentifier(str))
             {
                 throw new ConfigurationErrorsException(System.Web.SR.GetString("Profile_bad_group", new object[] { str }), property.FileName, property.LineNumber);
             }
             if (hashtable2[str] == null)
             {
                 hashtable2.Add(str, property.Name);
             }
             else
             {
                 hashtable2[str] = ((string) hashtable2[str]) + ";" + property.Name;
             }
         }
     }
     foreach (DictionaryEntry entry2 in hashtable2)
     {
         this.AddPropertyGroup(assemblyBuilder, (string) entry2.Key, (string) entry2.Value, propertiesForCompilation, declaration, ns);
     }
     this.AddCodeForGetProfileForUser(declaration);
     ns.Types.Add(declaration);
     ccu.Namespaces.Add(ns);
     assemblyBuilder.AddCodeCompileUnit(this, ccu);
 }
        /// <summary>
        /// Generate code for one .datasvcmap file
        /// </summary>
        /// <param name="mapFilePath">The physical path to the data service map file</param>
        private void GenerateCodeFromDataServiceMapFile(string mapFilePath, AssemblyBuilder assemblyBuilder)
        {
            try
            {
                assemblyBuilder.AddAssemblyReference(typeof(System.Data.Services.Client.DataServiceContext).Assembly);

                DataSvcMapFileLoader loader = new DataSvcMapFileLoader(mapFilePath);
                DataSvcMapFile mapFile = loader.LoadMapFile() as DataSvcMapFile;

                if (mapFile.MetadataList[0].ErrorInLoading != null)
                {
                    throw mapFile.MetadataList[0].ErrorInLoading;
                }

                string edmxContent = mapFile.MetadataList[0].Content;

                System.Data.Services.Design.EntityClassGenerator generator = new System.Data.Services.Design.EntityClassGenerator(LanguageOption.GenerateCSharpCode);

                // the EntityClassGenerator works on streams/writers, does not return a CodeDom
                // object, so we use CreateCodeFile instead of compile units.
                using (TextWriter writer = assemblyBuilder.CreateCodeFile(this))
                {

                    // Note: currently GenerateCode never actually returns values
                    // for the error case (even though it returns an IList of error
                    // objects). Instead it throws on error. This may need some tweaking 
                    // later on.
#if DEBUG
                object errors = 
#endif
                    generator.GenerateCode(
                        XmlReader.Create(new StringReader(edmxContent)),
                        writer,
                        GetGeneratedNamespace());

#if DEBUG
                Debug.Assert(
                    errors == null ||
                    !(errors is ICollection) ||
                    ((ICollection)errors).Count == 0,
                    "Errors reported through the return value. Expected an exception");
#endif
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                errorMessage = String.Format(CultureInfo.CurrentCulture, "{0}: {1}", IO.Path.GetFileName(mapFilePath), errorMessage);
                throw new InvalidOperationException(errorMessage, ex);
            }
        }
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////

        // BuildProvider implementation

        public override void GenerateCode(AssemblyBuilder assemblyBuilder) {
            Hashtable           properties   = ProfileBase.GetPropertiesForCompilation();
            CodeCompileUnit     compileUnit  = new CodeCompileUnit();
            Hashtable           groups       = new Hashtable();
            Type                baseType     = Type.GetType(ProfileBase.InheritsFromTypeString, false);

            // namespace ASP {
            //
            CodeNamespace ns = new CodeNamespace();
            // ns.Name = BaseCodeDomTreeGenerator.defaultNamespace;

            //GEN: using System;
            ns.Imports.Add(new CodeNamespaceImport("System"));
            //GEN: using System.Web;
            ns.Imports.Add(new CodeNamespaceImport("System.Web"));
            //GEN: using System.Web.Profile;
            ns.Imports.Add(new CodeNamespaceImport("System.Web.Profile"));

            // class Profile :  System.Web.Security.ProfileBase {
            //
            CodeTypeDeclaration type = new CodeTypeDeclaration();
            type.Name = ProfileTypeName;
            if (baseType != null) {
                type.BaseTypes.Add(new CodeTypeReference(baseType));
                assemblyBuilder.AddAssemblyReference(baseType.Assembly, compileUnit);
            } else {
                type.BaseTypes.Add(new CodeTypeReference(ProfileBase.InheritsFromTypeString));
                ProfileSection config = MTConfigUtil.GetProfileAppConfig();
                if (config != null) {
                    PropertyInformation prop = config.ElementInformation.Properties["inherits"];
                    if (prop != null && prop.Source != null && prop.LineNumber > 0)
                        type.LinePragma = new CodeLinePragma(HttpRuntime.GetSafePath(prop.Source), prop.LineNumber);
                }
            }
            // tell the assemblyBuilder to generate a fast factory for this type
            assemblyBuilder.GenerateTypeFactory(/*ns.Name + "." + */ ProfileTypeName);

            foreach(DictionaryEntry de in properties)
            {
                ProfileNameTypeStruct property = (ProfileNameTypeStruct)de.Value;
                if (property.PropertyType != null)
                    assemblyBuilder.AddAssemblyReference(property.PropertyType.Assembly, compileUnit);
                int pos = property.Name.IndexOf('.');
                if (pos < 0) {
                    // public string Color { get { return (string) GetProperty("Color"); } set { SetProperty("Color", value); } }
                    CreateCodeForProperty(assemblyBuilder, type, property);
                } else {
                    string grpName = property.Name.Substring(0, pos);
                    if (!assemblyBuilder.CodeDomProvider.IsValidIdentifier(grpName))
                        throw new ConfigurationErrorsException(SR.GetString(SR.Profile_bad_group, grpName), property.FileName, property.LineNumber);
                    if (groups[grpName] == null) {
                        groups.Add(grpName, property.Name);
                    } else {
                        groups[grpName] = ((string)groups[grpName]) + ";" + property.Name;
                    }
                }
            }

            foreach(DictionaryEntry de in groups) {
                // public ProfileGroupFooClass Foo { get { return ProfileGroupSomething; }}
                //
                // public class ProfileGroupFoo : ProfileGroup {
                //      Properties
                // }
                AddPropertyGroup(assemblyBuilder, (string) de.Key, (string) de.Value, properties, type, ns);
            }


            // public ASP.Profile GetProfileForUser(string username) {
            //      return (ASP.Profile) this.GetUserProfile(username);
            // }
            AddCodeForGetProfileForUser(type);

            // }
            //
            ns.Types.Add(type);
            compileUnit.Namespaces.Add(ns);

            assemblyBuilder.AddCodeCompileUnit(this, compileUnit);
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            try
            {
                this.EnsureDirective();

                if (String.IsNullOrEmpty(this.serviceTypeName))
                {
                    return;
                }

                Assembly tempAssembly = null;
                if (!String.IsNullOrEmpty(this.sourceText))
                {
                    // generate a code snippet for any inline source
                    CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(this.sourceText);
                    unit.LinePragma = new CodeLinePragma(base.VirtualPath, this.lineNumber);

                    // add known assembly references
                    foreach (Assembly assembly in this.ReferencedAssemblies)
                    {
                        assemblyBuilder.AddAssemblyReference(assembly);
                        if (!String.IsNullOrEmpty(assembly.Location) &&
                            !unit.ReferencedAssemblies.Contains(assembly.Location))
                        {
                            unit.ReferencedAssemblies.Add(assembly.Location);
                        }
                    }

                    // compile once so we can reflect and build proxy, etc.
                    assemblyBuilder.AddCodeCompileUnit(this, unit);
                    CompilerResults results = assemblyBuilder.CodeDomProvider.CompileAssemblyFromDom(new CompilerParameters(), unit);
                    if (results.Errors.HasErrors)
                    {
                        CompilerError error = results.Errors[0];
                        throw new HttpParseException(error.ErrorText, null, error.FileName, "", error.Line);
                    }
                    tempAssembly = results.CompiledAssembly;
                }

                Type serviceType = this.GetTypeToCache(this.serviceTypeName, tempAssembly);
                this.GenerateServiceProxyCode(assemblyBuilder, serviceType);
            }
            catch (HttpParseException ex)
            {
                Console.Error.WriteLine(ex);
                throw;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw new HttpParseException("GenerateCode: "+ex.Message, ex, base.VirtualPath, this.sourceText, this.lineNumber);
            }
        }
        internal void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            base.ProcessBrowserFiles(true, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
            base.ProcessCustomBrowserFiles(true, BrowserCapabilitiesCompiler.AppBrowsersVirtualDir.VirtualPathString);
            CodeCompileUnit ccu  = new CodeCompileUnit();
            ArrayList       list = new ArrayList();

            for (int i = 0; i < base.CustomTreeNames.Count; i++)
            {
                list.Add((BrowserDefinition)((BrowserTree)base.CustomTreeList[i])[base.CustomTreeNames[i]]);
            }
            CodeNamespace namespace2 = new CodeNamespace("ASP");

            namespace2.Imports.Add(new CodeNamespaceImport("System"));
            namespace2.Imports.Add(new CodeNamespaceImport("System.Web"));
            namespace2.Imports.Add(new CodeNamespaceImport("System.Web.Configuration"));
            namespace2.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            ccu.Namespaces.Add(namespace2);
            Type browserCapabilitiesFactoryBaseType = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType();
            CodeTypeDeclaration declaration         = new CodeTypeDeclaration {
                Attributes = MemberAttributes.Private,
                IsClass    = true,
                Name       = this.TypeName
            };

            declaration.BaseTypes.Add(new CodeTypeReference(browserCapabilitiesFactoryBaseType));
            namespace2.Types.Add(declaration);
            BindingFlags      bindingAttr = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase;
            BrowserDefinition bd          = null;
            CodeMemberMethod  method      = new CodeMemberMethod {
                Attributes = MemberAttributes.Public | MemberAttributes.Override,
                ReturnType = new CodeTypeReference(typeof(void)),
                Name       = "ConfigureCustomCapabilities"
            };
            CodeParameterDeclarationExpression expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");

            method.Parameters.Add(expression);
            expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
            method.Parameters.Add(expression);
            declaration.Members.Add(method);
            for (int j = 0; j < list.Count; j++)
            {
                base.GenerateSingleProcessCall((BrowserDefinition)list[j], method);
            }
            foreach (DictionaryEntry entry in this._browserOverrides)
            {
                object            key         = entry.Key;
                BrowserDefinition definition2 = (BrowserDefinition)base.BrowserTree[GetFirstItemFromKey(this._browserOverrides, key)];
                string            parentName  = definition2.ParentName;
                if (!TargetFrameworkUtil.HasMethod(browserCapabilitiesFactoryBaseType, parentName + "ProcessBrowsers", bindingAttr) || !TargetFrameworkUtil.HasMethod(browserCapabilitiesFactoryBaseType, parentName + "ProcessGateways", bindingAttr))
                {
                    string parentID = definition2.ParentID;
                    if (definition2 != null)
                    {
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("Browser_parentID_Not_Found", new object[] { parentID }), definition2.XmlNode);
                    }
                    throw new ConfigurationErrorsException(System.Web.SR.GetString("Browser_parentID_Not_Found", new object[] { parentID }));
                }
                bool flag = true;
                if (definition2 is GatewayDefinition)
                {
                    flag = false;
                }
                string           str3    = parentName + (flag ? "ProcessBrowsers" : "ProcessGateways");
                CodeMemberMethod method2 = new CodeMemberMethod {
                    Name       = str3,
                    ReturnType = new CodeTypeReference(typeof(void)),
                    Attributes = MemberAttributes.Family | MemberAttributes.Override
                };
                if (flag)
                {
                    expression = new CodeParameterDeclarationExpression(typeof(bool), "ignoreApplicationBrowsers");
                    method2.Parameters.Add(expression);
                }
                expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
                method2.Parameters.Add(expression);
                expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
                method2.Parameters.Add(expression);
                declaration.Members.Add(method2);
                ArrayList list2 = (ArrayList)this._browserOverrides[key];
                CodeStatementCollection stmts = method2.Statements;
                bool flag2 = false;
                foreach (string str4 in list2)
                {
                    bd = (BrowserDefinition)base.BrowserTree[str4];
                    if ((bd is GatewayDefinition) || bd.IsRefID)
                    {
                        base.GenerateSingleProcessCall(bd, method2);
                    }
                    else
                    {
                        if (!flag2)
                        {
                            CodeConditionStatement statement = new CodeConditionStatement {
                                Condition = new CodeVariableReferenceExpression("ignoreApplicationBrowsers")
                            };
                            method2.Statements.Add(statement);
                            stmts = statement.FalseStatements;
                            flag2 = true;
                        }
                        stmts = base.GenerateTrackedSingleProcessCall(stmts, bd, method2);
                        if (this._baseInstance == null)
                        {
                            if (MultiTargetingUtil.IsTargetFramework40OrAbove || (browserCapabilitiesFactoryBaseType.Assembly == BrowserCapabilitiesCompiler.AspBrowserCapsFactoryAssembly))
                            {
                                this._baseInstance = (BrowserCapabilitiesFactoryBase)Activator.CreateInstance(browserCapabilitiesFactoryBaseType);
                            }
                            else
                            {
                                this._baseInstance = new BrowserCapabilitiesFactory35();
                            }
                        }
                        int third = (int)((Triplet)this._baseInstance.InternalGetBrowserElements()[parentName]).Third;
                        base.AddBrowserToCollectionRecursive(bd, third + 1);
                    }
                }
            }
            foreach (DictionaryEntry entry2 in this._defaultBrowserOverrides)
            {
                object            obj3        = entry2.Key;
                BrowserDefinition definition3 = (BrowserDefinition)base.DefaultTree[GetFirstItemFromKey(this._defaultBrowserOverrides, obj3)];
                string            str5        = definition3.ParentName;
                if (browserCapabilitiesFactoryBaseType.GetMethod("Default" + str5 + "ProcessBrowsers", bindingAttr) == null)
                {
                    string str6 = definition3.ParentID;
                    if (definition3 != null)
                    {
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("DefaultBrowser_parentID_Not_Found", new object[] { str6 }), definition3.XmlNode);
                    }
                }
                string           str7    = "Default" + str5 + "ProcessBrowsers";
                CodeMemberMethod method3 = new CodeMemberMethod {
                    Name       = str7,
                    ReturnType = new CodeTypeReference(typeof(void)),
                    Attributes = MemberAttributes.Family | MemberAttributes.Override
                };
                expression = new CodeParameterDeclarationExpression(typeof(bool), "ignoreApplicationBrowsers");
                method3.Parameters.Add(expression);
                expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
                method3.Parameters.Add(expression);
                expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
                method3.Parameters.Add(expression);
                declaration.Members.Add(method3);
                ArrayList list3 = (ArrayList)this._defaultBrowserOverrides[obj3];
                CodeConditionStatement statement2 = new CodeConditionStatement {
                    Condition = new CodeVariableReferenceExpression("ignoreApplicationBrowsers")
                };
                method3.Statements.Add(statement2);
                CodeStatementCollection falseStatements = statement2.FalseStatements;
                foreach (string str8 in list3)
                {
                    bd = (BrowserDefinition)base.DefaultTree[str8];
                    if (bd.IsRefID)
                    {
                        base.GenerateSingleProcessCall(bd, method3, "Default");
                    }
                    else
                    {
                        falseStatements = base.GenerateTrackedSingleProcessCall(falseStatements, bd, method3, "Default");
                    }
                }
            }
            foreach (DictionaryEntry entry3 in base.BrowserTree)
            {
                bd = entry3.Value as BrowserDefinition;
                base.GenerateProcessMethod(bd, declaration);
            }
            for (int k = 0; k < list.Count; k++)
            {
                foreach (DictionaryEntry entry4 in (BrowserTree)base.CustomTreeList[k])
                {
                    bd = entry4.Value as BrowserDefinition;
                    base.GenerateProcessMethod(bd, declaration);
                }
            }
            foreach (DictionaryEntry entry5 in base.DefaultTree)
            {
                bd = entry5.Value as BrowserDefinition;
                base.GenerateProcessMethod(bd, declaration, "Default");
            }
            base.GenerateOverrideMatchedHeaders(declaration);
            base.GenerateOverrideBrowserElements(declaration);
            Assembly a = BrowserCapabilitiesCompiler.GetBrowserCapabilitiesFactoryBaseType().Assembly;

            assemblyBuilder.AddAssemblyReference(a, ccu);
            assemblyBuilder.AddCodeCompileUnit(this._buildProvider, ccu);
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            Hashtable       propertiesForCompilation = ProfileBase.GetPropertiesForCompilation();
            CodeCompileUnit ccu        = new CodeCompileUnit();
            Hashtable       hashtable2 = new Hashtable();
            Type            type       = Type.GetType(ProfileBase.InheritsFromTypeString, false);
            CodeNamespace   ns         = new CodeNamespace();

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Web"));
            ns.Imports.Add(new CodeNamespaceImport("System.Web.Profile"));
            CodeTypeDeclaration declaration = new CodeTypeDeclaration {
                Name = "ProfileCommon"
            };

            if (type != null)
            {
                declaration.BaseTypes.Add(new CodeTypeReference(type));
                assemblyBuilder.AddAssemblyReference(type.Assembly, ccu);
            }
            else
            {
                declaration.BaseTypes.Add(new CodeTypeReference(ProfileBase.InheritsFromTypeString));
                ProfileSection profileAppConfig = MTConfigUtil.GetProfileAppConfig();
                if (profileAppConfig != null)
                {
                    PropertyInformation information = profileAppConfig.ElementInformation.Properties["inherits"];
                    if (((information != null) && (information.Source != null)) && (information.LineNumber > 0))
                    {
                        declaration.LinePragma = new CodeLinePragma(HttpRuntime.GetSafePath(information.Source), information.LineNumber);
                    }
                }
            }
            assemblyBuilder.GenerateTypeFactory("ProfileCommon");
            foreach (DictionaryEntry entry in propertiesForCompilation)
            {
                ProfileNameTypeStruct property = (ProfileNameTypeStruct)entry.Value;
                if (property.PropertyType != null)
                {
                    assemblyBuilder.AddAssemblyReference(property.PropertyType.Assembly, ccu);
                }
                int index = property.Name.IndexOf('.');
                if (index < 0)
                {
                    this.CreateCodeForProperty(assemblyBuilder, declaration, property);
                }
                else
                {
                    string str = property.Name.Substring(0, index);
                    if (!assemblyBuilder.CodeDomProvider.IsValidIdentifier(str))
                    {
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("Profile_bad_group", new object[] { str }), property.FileName, property.LineNumber);
                    }
                    if (hashtable2[str] == null)
                    {
                        hashtable2.Add(str, property.Name);
                    }
                    else
                    {
                        hashtable2[str] = ((string)hashtable2[str]) + ";" + property.Name;
                    }
                }
            }
            foreach (DictionaryEntry entry2 in hashtable2)
            {
                this.AddPropertyGroup(assemblyBuilder, (string)entry2.Key, (string)entry2.Value, propertiesForCompilation, declaration, ns);
            }
            this.AddCodeForGetProfileForUser(declaration);
            ns.Types.Add(declaration);
            ccu.Namespaces.Add(ns);
            assemblyBuilder.AddCodeCompileUnit(this, ccu);
        }