public AddCodeCompileUnit ( System.Web.Compilation.BuildProvider buildProvider, CodeCompileUnit compileUnit ) : void | ||
buildProvider | System.Web.Compilation.BuildProvider | |
compileUnit | CodeCompileUnit | |
return | void |
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { CodeCompileUnit unit = new CodeCompileUnit(); CodeNamespace proxyCode = new CodeNamespace(); unit.Namespaces.Add(proxyCode); var description = ServiceDescription.Read(OpenReader()); var discCollection = new DiscoveryClientDocumentCollection() { { VirtualPath, description } }; var webref = new WebReferenceCollection() { new WebReference(discCollection, proxyCode) }; var options = new WebReferenceOptions(); options.Style = ServiceDescriptionImportStyle.Client; ServiceDescriptionImporter.GenerateWebReferences(webref, assemblyBuilder.CodeDomProvider, unit, options); assemblyBuilder.AddCodeCompileUnit(unit); }
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) { 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")); }
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); }
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); } } }
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 myAb) { XmlDocument carXmlDoc = new XmlDocument(); using (Stream passedFile = OpenStream()) { carXmlDoc.Load(passedFile); } XmlNode mainNode = carXmlDoc.SelectSingleNode("/car"); string selectionMainNode = mainNode.Attributes["name"].Value; XmlNode colorNode = carXmlDoc.SelectSingleNode("/car/color"); string selectionColorNode = colorNode.InnerText; XmlNode doorNode = carXmlDoc.SelectSingleNode("/car/door"); string selectionDoorNode = doorNode.InnerText; XmlNode speedNode = carXmlDoc.SelectSingleNode("/car/speed"); string selectionSpeedNode = speedNode.InnerText; CodeCompileUnit ccu = new CodeCompileUnit(); CodeNamespace cn = new CodeNamespace(); CodeMemberProperty cmp1 = new CodeMemberProperty(); CodeMemberProperty cmp2 = new CodeMemberProperty(); CodeMemberMethod cmm1 = new CodeMemberMethod(); cn.Imports.Add(new CodeNamespaceImport("System")); cmp1.Name = "Color"; cmp1.Type = new CodeTypeReference(typeof(string)); cmp1.Attributes = MemberAttributes.Public; cmp1.GetStatements.Add(new CodeSnippetExpression("return \"" + selectionColorNode + "\"")); cmp2.Name = "Doors"; cmp2.Type = new CodeTypeReference(typeof(int)); cmp2.Attributes = MemberAttributes.Public; cmp2.GetStatements.Add(new CodeSnippetExpression("return " + selectionDoorNode)); cmm1.Name = "Go"; cmm1.ReturnType = new CodeTypeReference(typeof(int)); cmm1.Attributes = MemberAttributes.Public; cmm1.Statements.Add(new CodeSnippetExpression("return " + selectionSpeedNode)); CodeTypeDeclaration ctd = new CodeTypeDeclaration(selectionMainNode); ctd.Members.Add(cmp1); ctd.Members.Add(cmp2); ctd.Members.Add(cmm1); cn.Types.Add(ctd); ccu.Namespaces.Add(cn); myAb.AddCodeCompileUnit(this, ccu); }
protected virtual void GenerateCode(AssemblyBuilder assemblyBuilder, TParser parser, BaseCompiler compiler) { CodeCompileUnit unit = _compiler.CompileUnit; if (unit == null) { throw new HttpException("Unable to generate source code."); } assemblyBuilder.AddCodeCompileUnit(this, unit); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { Utility.WriteTrace("Invoking BuildProvider"); DataService.LoadProviders(); ICodeLanguage language = new CSharpCodeLanguage(); DirectoryInfo di = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath + "\\App_Code"); FileInfo[] fi = di.GetFiles("*.vb"); if(fi.Length > 0) language = new VBCodeLanguage(); StringBuilder code = new StringBuilder(language.DefaultUsingStatements); TurboCompiler tc = new TurboCompiler(); // loop over the providers, and generate code for each foreach(DataProvider provider in DataService.Providers) { Utility.WriteTrace(String.Format("Creating code for {0}", provider.Name)); string[] tableList = DataService.GetTableNames(provider.Name); string[] viewList = DataService.GetViewNames(provider.Name); foreach(string tbl in tableList) { TurboTemplate tt = CodeService.BuildClassTemplate(tbl, language, provider); tc.AddTemplate(tt); if(provider.GenerateODSControllers) { TurboTemplate tODS = CodeService.BuildODSTemplate(tbl, language, provider); tc.AddTemplate(tODS); } } foreach(string view in viewList) { TurboTemplate tt = CodeService.BuildViewTemplate(view, language, provider); tc.AddTemplate(tt); } tc.AddTemplate(CodeService.BuildSPTemplate(language, provider)); } if(DataService.Providers.Count > 0) tc.AddTemplate(CodeService.BuildStructsTemplate(language, DataService.Provider)); foreach(TurboTemplate tt in tc.Templates) tt.AddUsingBlock = false; tc.Run(); foreach(TurboTemplate tt in tc.Templates) code.Append(tt.FinalCode); assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(code.ToString())); }
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); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { try { assemblyBuilder.AddCodeCompileUnit(this, this.GetGeneratedCode()); assemblyBuilder.GenerateTypeFactory(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { this.host.DefaultNamespace, this.host.DefaultClassName })); } catch (Exception ex) { Log.Error("GenerateCode(): ", ex); } }
private void GenerateStronglyTypedClass(AssemblyBuilder assemblyBuilder, IResourceReader reader) { IDictionary resourceList; string[] strArray; using (reader) { resourceList = this.GetResourceList(reader); } CodeDomProvider codeDomProvider = assemblyBuilder.CodeDomProvider; CodeCompileUnit compileUnit = StronglyTypedResourceBuilder.Create(resourceList, this._typeName, this._ns, codeDomProvider, false, out strArray); assemblyBuilder.AddCodeCompileUnit(this, compileUnit); }
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) { // look at the assembly builder to see which language we should use in the App_Code directory EntityCodeGenerator generator = null; if (assemblyBuilder.CodeDomProvider.FileExtension.ToLowerInvariant() == "cs") { generator = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode); } else { generator = new EntityCodeGenerator(LanguageOption.GenerateVBCode); } // generate the code for our CSDL file IList<EdmSchemaError> errors = null; using (XmlReader input = XmlReader.Create(VirtualPathProvider.OpenFile(base.VirtualPath))) { using (StringWriter output = new StringWriter(CultureInfo.InvariantCulture)) { // Read from input and generate into output, put errors in a class member var entityFrameworkVersion = GetEntityFrameworkVersion(BuildManager.TargetFramework.Version); errors = generator.GenerateCode(input, output, entityFrameworkVersion); if (errors.Count == 0) { output.Flush(); assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(output.ToString())); } } } // if there are errors, package this data into XmlExceptions and throw this // if we are in VS, the ASP .NET stack will place this information in the error pane // if we are in the ASP .NET runtime, it will use this information to build the error page if (errors != null && errors.Count > 0) { XmlException inner = null; XmlException outer = null; foreach (EdmSchemaError error in errors) { outer = new XmlException(error.Message, inner, error.Line, error.Column); inner = outer; } throw outer; } BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath); }
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 unit = new CodeCompileUnit (); CodeNamespace dataSetCode = new CodeNamespace(null); unit.Namespaces.Add (dataSetCode); string path = HttpContext.Current.Request.MapPath (VirtualPath); TextReader tr = new StreamReader (path); CodeDomProvider provider = assemblyBuilder.CodeDomProvider; if (provider == null) throw new HttpException ("Assembly builder has no code provider"); System.Data.Design.TypedDataSetGenerator.Generate (tr.ReadToEnd (), unit, dataSetCode, provider); assemblyBuilder.AddCodeCompileUnit (unit); }
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); }
void BuildDefaultAssembly(List <string> files, CodeCompileUnit unit) { AssemblyBuilder abuilder = new AssemblyBuilder(Provider); if (unit != null) { abuilder.AddCodeCompileUnit(unit); } CompilerParameters cp = ci.CreateDefaultCompilerParameters(); cp.OutputAssembly = baseAssemblyPath; cp.GenerateExecutable = false; cp.TreatWarningsAsErrors = true; cp.IncludeDebugInformation = config.Debug; foreach (string f in files) { cp.EmbeddedResources.Add(f); } CompilerResults results = abuilder.BuildAssembly(cp); if (results == null) { return; } if (results.NativeCompilerReturnValue == 0) { mainAssembly = results.CompiledAssembly; BuildManager.TopLevelAssemblies.Add(mainAssembly); } else { if (HttpContext.Current.IsCustomErrorEnabled) { throw new ApplicationException("An error occurred while compiling global resources."); } throw new CompilationException(null, results.Errors, null); } HttpRuntime.WritePreservationFile(mainAssembly, canonicAssemblyName); HttpRuntime.EnableAssemblyMapping(true); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Get the namespace that we will use string ns = Util.GetNamespaceFromVirtualPath(VirtualPathObject); ServiceDescription sd; // Load the wsdl file using (Stream stream = VirtualPathObject.OpenFile()) { try { sd = ServiceDescription.Read(stream); } catch (InvalidOperationException e) { // It can throw an InvalidOperationException, with the relevant // XmlException as the inner exception. If so, throw that instead. XmlException xmlException = e.InnerException as XmlException; if (xmlException != null) { throw xmlException; } throw; } } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); #if !FEATURE_PAL importer.CodeGenerator = assemblyBuilder.CodeDomProvider; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; #endif // !FEATURE_PAL importer.ServiceDescriptions.Add(sd); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(ns); codeCompileUnit.Namespaces.Add(codeNamespace); // Create the code compile unit importer.Import(codeNamespace, codeCompileUnit); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { #if !FEATURE_PAL // FEATURE_PAL does not support System.Configuration.Design CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); // Process the .settings file and generate a CodeCompileUnit from it using (Stream stream = VirtualPathProvider.OpenFile(VirtualPath)) { using (TextReader reader = new StreamReader(stream)) { SettingsSingleFileGenerator.Generate( reader, codeCompileUnit, assemblyBuilder.CodeDomProvider, TypeAttributes.Public); } } // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); #else // !FEATURE_PAL throw new NotImplementedException("System.Configuration.Design - ROTORTODO"); #endif // !FEATURE_PAL }
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) { // Get the namespace that we will use string ns = Util.GetNamespaceFromVirtualPath(VirtualPathObject); ServiceDescription sd; // Load the wsdl file using (Stream stream = VirtualPathObject.OpenFile()) { try { sd = ServiceDescription.Read(stream); } catch (InvalidOperationException e) { // It can throw an InvalidOperationException, with the relevant // XmlException as the inner exception. If so, throw that instead. XmlException xmlException = e.InnerException as XmlException; if (xmlException != null) throw xmlException; throw; } } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); #if !FEATURE_PAL importer.CodeGenerator = assemblyBuilder.CodeDomProvider; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; #endif // !FEATURE_PAL importer.ServiceDescriptions.Add(sd); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(ns); codeCompileUnit.Namespaces.Add(codeNamespace); // Create the code compile unit importer.Import(codeNamespace, codeCompileUnit); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { #if !FEATURE_PAL // FEATURE_PAL does not support System.Configuration.Design CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); // Process the .settings file and generate a CodeCompileUnit from it using (Stream stream = VirtualPathProvider.OpenFile(VirtualPath)) { using (TextReader reader = new StreamReader(stream)) { SettingsSingleFileGenerator.Generate( reader, codeCompileUnit, assemblyBuilder.CodeDomProvider, TypeAttributes.Public); } } // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); #else // !FEATURE_PAL throw new NotImplementedException("System.Configuration.Design - ROTORTODO"); #endif // !FEATURE_PAL }
/// <summary> /// 此方法已被重写以产生代码 /// </summary> /// <param name="assemblyBuilder">程序集构建器</param> public override void GenerateCode( AssemblyBuilder assemblyBuilder ) { if ( _type == null ) { _type = CreateDocumentProviderType(); } var @namespace = new CodeNamespace( "HTML" ); @namespace.Types.Add( _type ); var unit = new CodeCompileUnit(); unit.Namespaces.Add( @namespace ); assemblyBuilder.AddCodeCompileUnit( this, unit ); AddReferences( assemblyBuilder ); }
private void GenerateStronglyTypedClass(AssemblyBuilder assemblyBuilder, IResourceReader reader) { // Copy the resources into an IDictionary IDictionary resourceList; using (reader) { resourceList = GetResourceList(reader); } // Generate a strongly typed class from the resources CodeDomProvider provider = assemblyBuilder.CodeDomProvider; string[] unmatchable; CodeCompileUnit ccu = StronglyTypedResourceBuilder.Create( resourceList, _typeName, _ns, provider, false /*internalClass*/, out unmatchable); // Ignore the unmatchable items. We just won't generate code for them, // but they'll still be usable via the ResourceManager (VSWhidbey 248226) // We decided to cut support for My.Resources (VSWhidbey 358088) #if OLD // generate a My.Resources.* override (VSWhidbey 251554) CodeNamespace ns = new CodeNamespace(); ns.Name = "My." + _ns; CodeTypeDeclaration type = new CodeTypeDeclaration(); type.Name = _typeName; CodeTypeReference baseType = new CodeTypeReference(_ns + "." + _typeName); // Need to use a global reference to avoid a conflict, since the classes have the same name baseType.Options = CodeTypeReferenceOptions.GlobalReference; type.BaseTypes.Add(baseType); ns.Types.Add(type); ccu.Namespaces.Add(ns); #endif // Add the code compile unit to the compilation assemblyBuilder.AddCodeCompileUnit(this, ccu); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { CodeCompileUnit unit = new CodeCompileUnit(); CodeNamespace dataSetCode = new CodeNamespace(null); unit.Namespaces.Add(dataSetCode); string path = HttpContext.Current.Request.MapPath(VirtualPath); TextReader tr = new StreamReader(path); CodeDomProvider provider = assemblyBuilder.CodeDomProvider; if (provider == null) { throw new HttpException("Assembly builder has no code provider"); } System.Data.Design.TypedDataSetGenerator.Generate(tr.ReadToEnd(), unit, dataSetCode, provider); assemblyBuilder.AddCodeCompileUnit(unit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Go through all the svcmap files in the directory VirtualDirectory vdir = GetVirtualDirectory(VirtualPath); foreach (VirtualFile child in vdir.Files) { string extension = IO.Path.GetExtension(child.VirtualPath); if (extension.Equals(SvcMapExtension, StringComparison.OrdinalIgnoreCase)) { // .svcmap file found // NOTE: the WebReferences code requires a physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); CodeCompileUnit codeUnit = GenerateCodeFromServiceMapFile(physicalPath); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeUnit); } else if (extension.Equals(DataSvcMapExtension, StringComparison.OrdinalIgnoreCase)) { // In .NET FX 3.5, the ADO.NET Data Service build provider was included as part of the // WCF build provider. In .NET FX 4.0, it is a separate build provider. However, under certain // circumstances (i.e. design time/Visual Studio), we may call the 4.0 version of the build provider // when we actually want the web site to target .NET FX 3.5, and in that case, we have to emulate the // old behavior. if (BuildManager.TargetFramework.Version.Major < 4) { // NOTE: the WebReferences code requires a physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); GenerateCodeFromDataServiceMapFile(physicalPath, assemblyBuilder); } } } }
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(); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { ServiceDescription description; string namespaceFromVirtualPath = Util.GetNamespaceFromVirtualPath(base.VirtualPathObject); Stream stream = base.VirtualPathObject.OpenFile(); try { description = ServiceDescription.Read(stream); } catch (InvalidOperationException exception) { XmlException innerException = exception.InnerException as XmlException; if (innerException != null) { throw innerException; } throw; } finally { if (stream != null) { stream.Dispose(); } } ServiceDescriptionImporter importer = new ServiceDescriptionImporter { CodeGenerator = assemblyBuilder.CodeDomProvider, CodeGenerationOptions = CodeGenerationOptions.GenerateOldAsync | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties }; importer.ServiceDescriptions.Add(description); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace namespace2 = new CodeNamespace(namespaceFromVirtualPath); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { ServiceDescription description; string namespaceFromVirtualPath = Util.GetNamespaceFromVirtualPath(base.VirtualPathObject); Stream stream = base.VirtualPathObject.OpenFile(); try { description = ServiceDescription.Read(stream); } catch (InvalidOperationException exception) { XmlException innerException = exception.InnerException as XmlException; if (innerException != null) { throw innerException; } throw; } finally { if (stream != null) { stream.Dispose(); } } ServiceDescriptionImporter importer = new ServiceDescriptionImporter { CodeGenerator = assemblyBuilder.CodeDomProvider, CodeGenerationOptions = CodeGenerationOptions.GenerateOldAsync | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties }; importer.ServiceDescriptions.Add(description); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace namespace2 = new CodeNamespace(namespaceFromVirtualPath); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { if (assemblyBuilder == null) { throw new ArgumentNullException("assemblyBuilder"); } // get name and namespace from the filename string ns = string.Empty; string name = VirtualPathUtility.GetFileName(VirtualPath); int i = name.LastIndexOf('.'); if (i > 0) { name = name.Substring(0, i); // discard extension i = name.LastIndexOf('.'); // and split into namespace and class if (i > 0) { name = name.Substring(i + 1); ns = name.Substring(0, i); } } // load as XML XmlDocument doc = new XmlDocument(); using (Stream s = OpenStream(VirtualPath)) { doc.Load(s); } // compile the channel CodeCompileUnit ccu = new CodeCompileUnit(); RssCodeGenerator.GenerateCodeDomTree(doc.OuterXml, string.Empty, ns, name, ccu, true); assemblyBuilder.AddCodeCompileUnit(this, 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(); }
private void GenerateStronglyTypedClass(AssemblyBuilder assemblyBuilder, IResourceReader reader) { // Copy the resources into an IDictionary IDictionary resourceList; using (reader) { resourceList = GetResourceList(reader); } // Generate a strongly typed class from the resources CodeDomProvider provider = assemblyBuilder.CodeDomProvider; string[] unmatchable; CodeCompileUnit ccu = StronglyTypedResourceBuilder.Create( resourceList, _typeName, _ns, provider, false /*internalClass*/, out unmatchable); // Ignore the unmatchable items. We just won't generate code for them, // but they'll still be usable via the ResourceManager (VSWhidbey 248226) // We decided to cut support for My.Resources (VSWhidbey 358088) #if OLD // generate a My.Resources.* override (VSWhidbey 251554) CodeNamespace ns = new CodeNamespace(); ns.Name = "My." + _ns; CodeTypeDeclaration type = new CodeTypeDeclaration(); type.Name = _typeName; CodeTypeReference baseType = new CodeTypeReference(_ns + "." + _typeName); // Need to use a global reference to avoid a conflict, since the classes have the same name baseType.Options = CodeTypeReferenceOptions.GlobalReference; type.BaseTypes.Add(baseType); ns.Types.Add(type); ccu.Namespaces.Add(ns); #endif // Add the code compile unit to the compilation assemblyBuilder.AddCodeCompileUnit(this, ccu); }
//////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // 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) { this.EnsureCodeCompileUnit(); assemblyBuilder.AddCodeCompileUnit(this, this._snippetCompileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Only attempt to get the Indigo provider once if (!s_triedToGetWebRefType) { s_indigoWebRefProviderType = BuildManager.GetType(IndigoWebRefProviderTypeName, false /*throwOnError*/); s_triedToGetWebRefType = true; } // If we have an Indigo provider, instantiate it and forward the GenerateCode call to it if (s_indigoWebRefProviderType != null) { BuildProvider buildProvider = (BuildProvider)HttpRuntime.CreateNonPublicInstance(s_indigoWebRefProviderType); buildProvider.SetVirtualPath(VirtualPathObject); buildProvider.GenerateCode(assemblyBuilder); } // e.g "/MyApp/Application_WebReferences" VirtualPath rootWebRefDirVirtualPath = HttpRuntime.WebRefDirectoryVirtualPath; // e.g "/MyApp/Application_WebReferences/Foo/Bar" string currentWebRefDirVirtualPath = _vdir.VirtualPath; Debug.Assert(StringUtil.StringStartsWithIgnoreCase( currentWebRefDirVirtualPath, rootWebRefDirVirtualPath.VirtualPathString)); string ns; if (rootWebRefDirVirtualPath.VirtualPathString.Length == currentWebRefDirVirtualPath.Length) { // If it's the root WebReferences dir, use the empty namespace ns = String.Empty; } else { // e.g. "Foo/Bar" Debug.Assert(rootWebRefDirVirtualPath.HasTrailingSlash); currentWebRefDirVirtualPath = UrlPath.RemoveSlashFromPathIfNeeded(currentWebRefDirVirtualPath); currentWebRefDirVirtualPath = currentWebRefDirVirtualPath.Substring( rootWebRefDirVirtualPath.VirtualPathString.Length); // Split it into chunks separated by '/' string[] chunks = currentWebRefDirVirtualPath.Split('/'); // Turn all the relevant chunks into valid namespace chunks for (int i = 0; i < chunks.Length; i++) { chunks[i] = Util.MakeValidTypeNameFromString(chunks[i]); } // Put the relevant chunks back together to form the namespace ns = String.Join(".", chunks); } #if !FEATURE_PAL // FEATURE_PAL does not support System.Web.Services CodeNamespace codeNamespace = new CodeNamespace(ns); // for each discomap file, read all references and add them to the WebReferenceCollection WebReferenceCollection webs = new WebReferenceCollection(); bool hasDiscomap = false; // Go through all the discomap in the directory foreach (VirtualFile child in _vdir.Files) { string extension = UrlPath.GetExtension(child.VirtualPath); extension = extension.ToLower(CultureInfo.InvariantCulture); if (extension == ".discomap") { // NOTE: the WebReferences code requires physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); DiscoveryClientProtocol client = new DiscoveryClientProtocol(); client.AllowAutoRedirect = true; client.Credentials = CredentialCache.DefaultCredentials; client.ReadAll(physicalPath); WebReference webRefTemp = new WebReference(client.Documents, codeNamespace); // string fileName = System.IO.Path.ChangeExtension(UrlPath.GetFileName(child.VirtualPath), null); string appSetttingUrlKey = ns + "." + fileName; WebReference web = new WebReference(client.Documents, codeNamespace, webRefTemp.ProtocolName, appSetttingUrlKey, null); webs.Add(web); hasDiscomap = true; } } // If we didn't find any discomap files, we have nothing to generate if (!hasDiscomap) { return; } CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNamespace); //public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { WebReferenceOptions options = new WebReferenceOptions(); options.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; options.Style = ServiceDescriptionImportStyle.Client; options.Verbose = true; StringCollection shareWarnings = ServiceDescriptionImporter.GenerateWebReferences(webs, assemblyBuilder.CodeDomProvider, codeCompileUnit, options); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); #else // !FEATURE_PAL return; #endif // !FEATURE_PAL }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { string str2; if (!s_triedToGetWebRefType) { s_indigoWebRefProviderType = BuildManager.GetType("System.Web.Compilation.WCFBuildProvider", false); s_triedToGetWebRefType = true; } if (s_indigoWebRefProviderType != null) { BuildProvider provider = (BuildProvider)HttpRuntime.CreateNonPublicInstance(s_indigoWebRefProviderType); provider.SetVirtualPath(base.VirtualPathObject); provider.GenerateCode(assemblyBuilder); } VirtualPath webRefDirectoryVirtualPath = HttpRuntime.WebRefDirectoryVirtualPath; string virtualPath = this._vdir.VirtualPath; if (webRefDirectoryVirtualPath.VirtualPathString.Length == virtualPath.Length) { str2 = string.Empty; } else { string[] strArray = UrlPath.RemoveSlashFromPathIfNeeded(virtualPath).Substring(webRefDirectoryVirtualPath.VirtualPathString.Length).Split(new char[] { '/' }); for (int i = 0; i < strArray.Length; i++) { strArray[i] = Util.MakeValidTypeNameFromString(strArray[i]); } str2 = string.Join(".", strArray); } CodeNamespace proxyCode = new CodeNamespace(str2); WebReferenceCollection webReferences = new WebReferenceCollection(); bool flag = false; foreach (VirtualFile file in this._vdir.Files) { if (UrlPath.GetExtension(file.VirtualPath).ToLower(CultureInfo.InvariantCulture) == ".discomap") { string topLevelFilename = HostingEnvironment.MapPath(file.VirtualPath); DiscoveryClientProtocol protocol = new DiscoveryClientProtocol { AllowAutoRedirect = true, Credentials = CredentialCache.DefaultCredentials }; protocol.ReadAll(topLevelFilename); WebReference reference = new WebReference(protocol.Documents, proxyCode); string str5 = Path.ChangeExtension(UrlPath.GetFileName(file.VirtualPath), null); string appSettingUrlKey = str2 + "." + str5; WebReference webReference = new WebReference(protocol.Documents, proxyCode, reference.ProtocolName, appSettingUrlKey, null); webReferences.Add(webReference); flag = true; } } if (flag) { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(proxyCode); WebReferenceOptions options = new WebReferenceOptions { CodeGenerationOptions = CodeGenerationOptions.GenerateOldAsync | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties, Style = ServiceDescriptionImportStyle.Client, Verbose = true }; ServiceDescriptionImporter.GenerateWebReferences(webReferences, assemblyBuilder.CodeDomProvider, codeCompileUnit, options); assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); } }
public override void GenerateCode (AssemblyBuilder assemblyBuilder) { CodeCompileUnit unit = new CodeCompileUnit (); CodeNamespace proxyCode = new CodeNamespace (); unit.Namespaces.Add (proxyCode); var description = ServiceDescription.Read (OpenReader ()); var discCollection = new DiscoveryClientDocumentCollection () { {VirtualPath, description} }; var webref = new WebReferenceCollection () { new WebReference (discCollection, proxyCode) }; var options = new WebReferenceOptions (); options.Style = ServiceDescriptionImportStyle.Client; ServiceDescriptionImporter.GenerateWebReferences (webref, assemblyBuilder.CodeDomProvider, unit, options); assemblyBuilder.AddCodeCompileUnit (unit); }
// Build and add the assembly to the BuildManager's // CodeAssemblies collection public void Build (string[] binAssemblies) { Type compilerProvider = null; CompilerInfo compilerInfo = null, cit; string extension, language, cpfile = null; List<string> knownfiles = new List<string>(); List<string> unknownfiles = new List<string>(); // First make sure all the files are in the same // language bool known = false; foreach (string f in files) { known = true; language = null; extension = Path.GetExtension (f); if (String.IsNullOrEmpty (extension) || !CodeDomProvider.IsDefinedExtension (extension)) known = false; if (known) { language = CodeDomProvider.GetLanguageFromExtension(extension); if (!CodeDomProvider.IsDefinedLanguage (language)) known = false; } if (!known || language == null) { unknownfiles.Add (f); continue; } cit = CodeDomProvider.GetCompilerInfo (language); if (cit == null || !cit.IsCodeDomProviderTypeValid) continue; if (compilerProvider == null) { cpfile = f; compilerProvider = cit.CodeDomProviderType; compilerInfo = cit; } else if (compilerProvider != cit.CodeDomProviderType) throw new HttpException ( String.Format ( "Files {0} and {1} are in different languages - they cannot be compiled into the same assembly", Path.GetFileName (cpfile), Path.GetFileName (f))); knownfiles.Add (f); } CodeDomProvider provider = null; CompilationSection compilationSection = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection; if (compilerInfo == null) { if (!CodeDomProvider.IsDefinedLanguage (compilationSection.DefaultLanguage)) throw new HttpException ("Failed to retrieve default source language"); compilerInfo = CodeDomProvider.GetCompilerInfo (compilationSection.DefaultLanguage); if (compilerInfo == null || !compilerInfo.IsCodeDomProviderTypeValid) throw new HttpException ("Internal error while initializing application"); } provider = compilerInfo.CreateProvider (); if (provider == null) throw new HttpException ("A code provider error occurred while initializing application."); AssemblyBuilder abuilder = new AssemblyBuilder (provider); foreach (string file in knownfiles) abuilder.AddCodeFile (file); foreach (CodeCompileUnit unit in units) abuilder.AddCodeCompileUnit (unit); BuildProvider bprovider; CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters (); parameters.IncludeDebugInformation = compilationSection.Debug; if (binAssemblies != null && binAssemblies.Length > 0) parameters.ReferencedAssemblies.AddRange (binAssemblies); if (compilationSection != null) { foreach (AssemblyInfo ai in compilationSection.Assemblies) if (ai.Assembly != "*") { try { parameters.ReferencedAssemblies.Add ( AssemblyPathResolver.GetAssemblyPath (ai.Assembly)); } catch (Exception ex) { throw new HttpException ( String.Format ("Could not find assembly {0}.", ai.Assembly), ex); } } BuildProviderCollection buildProviders = compilationSection.BuildProviders; foreach (string file in unknownfiles) { bprovider = GetBuildProviderFor (file, buildProviders); if (bprovider == null) continue; bprovider.GenerateCode (abuilder); } } if (knownfiles.Count == 0 && unknownfiles.Count == 0 && units.Count == 0) return; outputAssemblyName = (string)FileUtils.CreateTemporaryFile ( AppDomain.CurrentDomain.SetupInformation.DynamicBase, name, "dll", OnCreateTemporaryAssemblyFile); parameters.OutputAssembly = outputAssemblyName; foreach (Assembly a in BuildManager.TopLevelAssemblies) parameters.ReferencedAssemblies.Add (a.Location); CompilerResults results = abuilder.BuildAssembly (parameters); if (results == null) return; if (results.NativeCompilerReturnValue == 0) { BuildManager.CodeAssemblies.Add (results.CompiledAssembly); BuildManager.TopLevelAssemblies.Add (results.CompiledAssembly); HttpRuntime.WritePreservationFile (results.CompiledAssembly, name); } else { if (HttpContext.Current.IsCustomErrorEnabled) throw new HttpException ("An error occurred while initializing application."); throw new CompilationException (null, results.Errors, null); } }
//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) { BaseCodeDomTreeGenerator codeDomGen = CreateCodeDomTreeGenerator (this.Parser); codeDomGen.GeneratedTypeName = this.GeneratedTypeName; codeDomGen.GeneratedTypeNamespace = this.GeneratedTypeNamespace; codeDomGen.GeneratedTypeFullName = this.GeneratedTypeFullName; CodeCompileUnit compileUnit = new CodeCompileUnit (); codeDomGen.BuildCodeDomTree (compileUnit); assemblyBuilder.AddCodeCompileUnit (this, compileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Go through all the svcmap files in the directory VirtualDirectory vdir = GetVirtualDirectory(VirtualPath); foreach (VirtualFile child in vdir.Files) { string extension = IO.Path.GetExtension(child.VirtualPath); if (extension.Equals(SvcMapExtension, StringComparison.OrdinalIgnoreCase)) { // .svcmap file found // NOTE: the WebReferences code requires a physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); CodeCompileUnit codeUnit = GenerateCodeFromServiceMapFile(physicalPath); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeUnit); } else if (extension.Equals(DataSvcMapExtension, StringComparison.OrdinalIgnoreCase)) { // In .NET FX 3.5, the ADO.NET Data Service build provider was included as part of the // WCF build provider. In .NET FX 4.0, it is a separate build provider. However, under certain // circumstances (i.e. design time/Visual Studio), we may call the 4.0 version of the build provider // when we actually want the web site to target .NET FX 3.5, and in that case, we have to emulate the // old behavior. if (BuildManager.TargetFramework.Version.Major < 4) { // NOTE: the WebReferences code requires a physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); GenerateCodeFromDataServiceMapFile(physicalPath, assemblyBuilder); } } } }
//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); }
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 GenerateExpressionRootFactory(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider, string activityNamespace, string activityName) { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); // namespace <%= activityNamespace %> // { // public class <%= activityName %>_ExpressionRootFactory : System.ServiceModel.Activities.WorkflowService // { // public static System.Activities.XamlIntegration.ICompiledExpressionRoot CreateExpressionRoot(System.Activities.Activity activity) // { // return new <%= activityNamespace %>.<%= activityName %>(activity); // } // } // } CodeNamespace codeNamespace = new CodeNamespace(activityNamespace); CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(activityName + ExpressionRootFactorySuffix); codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(WorkflowService))); CodeMemberMethod codeMemberMethod = new CodeMemberMethod(); codeMemberMethod.Name = CreateExpressionRootMethodName; codeMemberMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; codeMemberMethod.ReturnType = new CodeTypeReference(typeof(ICompiledExpressionRoot)); codeMemberMethod.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(typeof(Activity)), ActivityParameterName)); CodeTypeReference typeRef = new CodeTypeReference(activityNamespace + "." + activityName); CodeObjectCreateExpression expr = new CodeObjectCreateExpression(typeRef, new CodeArgumentReferenceExpression(ActivityParameterName)); codeMemberMethod.Statements.Add(new CodeMethodReturnStatement(expr)); codeTypeDeclaration.Members.Add(codeMemberMethod); codeNamespace.Types.Add(codeTypeDeclaration); codeCompileUnit.Namespaces.Add(codeNamespace); assemblyBuilder.AddCodeCompileUnit(buildProvider, codeCompileUnit); }
void BuildDefaultAssembly (List <string> files, CodeCompileUnit unit) { AssemblyBuilder abuilder = new AssemblyBuilder (Provider); if (unit != null) abuilder.AddCodeCompileUnit (unit); CompilerParameters cp = ci.CreateDefaultCompilerParameters (); cp.OutputAssembly = baseAssemblyPath; cp.GenerateExecutable = false; cp.TreatWarningsAsErrors = true; cp.IncludeDebugInformation = config.Debug; foreach (string f in files) cp.EmbeddedResources.Add (f); CompilerResults results = abuilder.BuildAssembly (cp); if (results == null) return; if (results.NativeCompilerReturnValue == 0) { mainAssembly = results.CompiledAssembly; BuildManager.TopLevelAssemblies.Add (mainAssembly); } else { if (HttpContext.Current.IsCustomErrorEnabled) throw new ApplicationException ("An error occurred while compiling global resources."); throw new CompilationException (null, results.Errors, null); } HttpRuntime.WritePreservationFile (mainAssembly, canonicAssemblyName); HttpRuntime.EnableAssemblyMapping (true); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Only attempt to get the Indigo provider once if (!s_triedToGetWebRefType) { s_indigoWebRefProviderType = BuildManager.GetType(IndigoWebRefProviderTypeName, false /*throwOnError*/); s_triedToGetWebRefType = true; } // If we have an Indigo provider, instantiate it and forward the GenerateCode call to it if (s_indigoWebRefProviderType != null) { BuildProvider buildProvider = (BuildProvider)HttpRuntime.CreateNonPublicInstance(s_indigoWebRefProviderType); buildProvider.SetVirtualPath(VirtualPathObject); buildProvider.GenerateCode(assemblyBuilder); } // e.g "/MyApp/Application_WebReferences" VirtualPath rootWebRefDirVirtualPath = HttpRuntime.WebRefDirectoryVirtualPath; // e.g "/MyApp/Application_WebReferences/Foo/Bar" string currentWebRefDirVirtualPath = _vdir.VirtualPath; Debug.Assert(StringUtil.StringStartsWithIgnoreCase( currentWebRefDirVirtualPath, rootWebRefDirVirtualPath.VirtualPathString)); string ns; if (rootWebRefDirVirtualPath.VirtualPathString.Length == currentWebRefDirVirtualPath.Length) { // If it's the root WebReferences dir, use the empty namespace ns = String.Empty; } else { // e.g. "Foo/Bar" Debug.Assert(rootWebRefDirVirtualPath.HasTrailingSlash); currentWebRefDirVirtualPath = UrlPath.RemoveSlashFromPathIfNeeded(currentWebRefDirVirtualPath); currentWebRefDirVirtualPath = currentWebRefDirVirtualPath.Substring( rootWebRefDirVirtualPath.VirtualPathString.Length); // Split it into chunks separated by '/' string[] chunks = currentWebRefDirVirtualPath.Split('/'); // Turn all the relevant chunks into valid namespace chunks for (int i=0; i<chunks.Length; i++) { chunks[i] = Util.MakeValidTypeNameFromString(chunks[i]); } // Put the relevant chunks back together to form the namespace ns = String.Join(".", chunks); } #if !FEATURE_PAL // FEATURE_PAL does not support System.Web.Services CodeNamespace codeNamespace = new CodeNamespace(ns); // for each discomap file, read all references and add them to the WebReferenceCollection WebReferenceCollection webs = new WebReferenceCollection(); bool hasDiscomap = false; // Go through all the discomap in the directory foreach (VirtualFile child in _vdir.Files) { string extension = UrlPath.GetExtension(child.VirtualPath); extension = extension.ToLower(CultureInfo.InvariantCulture); if (extension == ".discomap") { // NOTE: the WebReferences code requires physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); DiscoveryClientProtocol client = new DiscoveryClientProtocol(); client.AllowAutoRedirect = true; client.Credentials = CredentialCache.DefaultCredentials; client.ReadAll(physicalPath); WebReference webRefTemp = new WebReference(client.Documents, codeNamespace); // string fileName = System.IO.Path.ChangeExtension(UrlPath.GetFileName(child.VirtualPath), null); string appSetttingUrlKey = ns + "." + fileName; WebReference web = new WebReference(client.Documents, codeNamespace, webRefTemp.ProtocolName, appSetttingUrlKey, null); webs.Add(web); hasDiscomap = true; } } // If we didn't find any discomap files, we have nothing to generate if (!hasDiscomap) return; CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNamespace); //public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { WebReferenceOptions options = new WebReferenceOptions(); options.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; options.Style = ServiceDescriptionImportStyle.Client; options.Verbose = true; StringCollection shareWarnings = ServiceDescriptionImporter.GenerateWebReferences(webs, assemblyBuilder.CodeDomProvider, codeCompileUnit, options); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); #else // !FEATURE_PAL return; #endif // !FEATURE_PAL }
// Build and add the assembly to the BuildManager's // CodeAssemblies collection public void Build(string[] binAssemblies) { Type compilerProvider = null; CompilerInfo compilerInfo = null, cit; string extension, language, cpfile = null; List <string> knownfiles = new List <string>(); List <string> unknownfiles = new List <string>(); // First make sure all the files are in the same // language bool known = false; foreach (string f in files) { known = true; language = null; extension = Path.GetExtension(f); if (String.IsNullOrEmpty(extension) || !CodeDomProvider.IsDefinedExtension(extension)) { known = false; } if (known) { language = CodeDomProvider.GetLanguageFromExtension(extension); if (!CodeDomProvider.IsDefinedLanguage(language)) { known = false; } } if (!known || language == null) { unknownfiles.Add(f); continue; } cit = CodeDomProvider.GetCompilerInfo(language); if (cit == null || !cit.IsCodeDomProviderTypeValid) { continue; } if (compilerProvider == null) { cpfile = f; compilerProvider = cit.CodeDomProviderType; compilerInfo = cit; } else if (compilerProvider != cit.CodeDomProviderType) { throw new HttpException( String.Format( "Files {0} and {1} are in different languages - they cannot be compiled into the same assembly", Path.GetFileName(cpfile), Path.GetFileName(f))); } knownfiles.Add(f); } CodeDomProvider provider = null; CompilationSection compilationSection = WebConfigurationManager.GetWebApplicationSection("system.web/compilation") as CompilationSection; if (compilerInfo == null) { if (!CodeDomProvider.IsDefinedLanguage(compilationSection.DefaultLanguage)) { throw new HttpException("Failed to retrieve default source language"); } compilerInfo = CodeDomProvider.GetCompilerInfo(compilationSection.DefaultLanguage); if (compilerInfo == null || !compilerInfo.IsCodeDomProviderTypeValid) { throw new HttpException("Internal error while initializing application"); } } provider = compilerInfo.CreateProvider(); if (provider == null) { throw new HttpException("A code provider error occurred while initializing application."); } AssemblyBuilder abuilder = new AssemblyBuilder(provider); foreach (string file in knownfiles) { abuilder.AddCodeFile(file); } foreach (CodeCompileUnit unit in units) { abuilder.AddCodeCompileUnit(unit); } BuildProvider bprovider; CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters(); parameters.IncludeDebugInformation = compilationSection.Debug; if (binAssemblies != null && binAssemblies.Length > 0) { StringCollection parmRefAsm = parameters.ReferencedAssemblies; foreach (string binAsm in binAssemblies) { if (parmRefAsm.Contains(binAsm)) { continue; } parmRefAsm.Add(binAsm); } } if (compilationSection != null) { foreach (AssemblyInfo ai in compilationSection.Assemblies) { if (ai.Assembly != "*") { try { parameters.ReferencedAssemblies.Add( AssemblyPathResolver.GetAssemblyPath(ai.Assembly)); } catch (Exception ex) { throw new HttpException( String.Format("Could not find assembly {0}.", ai.Assembly), ex); } } } BuildProviderCollection buildProviders = compilationSection.BuildProviders; foreach (string file in unknownfiles) { bprovider = GetBuildProviderFor(file, buildProviders); if (bprovider == null) { continue; } bprovider.GenerateCode(abuilder); } } if (knownfiles.Count == 0 && unknownfiles.Count == 0 && units.Count == 0) { return; } outputAssemblyName = (string)FileUtils.CreateTemporaryFile( AppDomain.CurrentDomain.SetupInformation.DynamicBase, name, "dll", OnCreateTemporaryAssemblyFile); parameters.OutputAssembly = outputAssemblyName; foreach (Assembly a in BuildManager.TopLevelAssemblies) { parameters.ReferencedAssemblies.Add(a.Location); } CompilerResults results = abuilder.BuildAssembly(parameters); if (results == null) { return; } if (results.NativeCompilerReturnValue == 0) { BuildManager.CodeAssemblies.Add(results.CompiledAssembly); BuildManager.TopLevelAssemblies.Add(results.CompiledAssembly); HttpRuntime.WritePreservationFile(results.CompiledAssembly, name); } else { if (HttpContext.Current.IsCustomErrorEnabled) { throw new HttpException("An error occurred while initializing application."); } throw new CompilationException(null, results.Errors, null); } }
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 }
//////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // 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); }
/* * Line 12: namespace Hao.Kung.Samples { Line 13: using System; Line 14: using System.Net; Line 15: using System.Web.Services; Line 16: using System.Collections; Line 17: using System.Xml.Serialization; Line 18: using System.Web.Services; Line 19: Line 20: Line 21: [WebService(Name="http://tempuri.org/")] Line 22: [WebServiceBinding(ConformsTo=System.Web.Services.WsiProfiles.BasicProfile1_1)] Line 23: public partial class MSNSearch { Line 24: Line 25: public MSNSearch() { Line 26: this.VirtualPath = "/atlas/BCL/msn.asbx"; this.BridgeXml = <contents of MSN.asbx> Line 27: } Line 28: [System.Web.Script.Services.ScriptService()] Line 29: [System.Web.Services.WebMethodAttribute()] Line 30: [System.Xml.Serialization.XmlIncludeAttribute(typeof(MSN.SearchRequest))] Line 31: public object Search(System.Collections.IDictionary args) { Line 32: return this.Invoke(new System.Web.Services.BridgeRequest("Search", args)); Line 33: } Line 34: */ public override void GenerateCode(AssemblyBuilder assemBuilder) { CodeNamespace ns = new CodeNamespace(Service.Namespace); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Net")); ns.Imports.Add(new CodeNamespaceImport("System.Web.Services")); ns.Imports.Add(new CodeNamespaceImport("System.Collections")); ns.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization")); ns.Imports.Add(new CodeNamespaceImport("Microsoft.Web.Preview.Services")); ns.Imports.Add(new CodeNamespaceImport("System.Web.Script.Services")); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); CodeTypeDeclaration classType = new CodeTypeDeclaration(Service.Classname); classType.BaseTypes.Add(typeof(BridgeHandler)); classType.IsPartial = true; ns.Types.Add(classType); classType.CustomAttributes.Add(new CodeAttributeDeclaration("ScriptService")); classType.CustomAttributes.Add(new CodeAttributeDeclaration("WebService", new CodeAttributeArgument("Name", new CodePrimitiveExpression("http://tempuri.org/")))); classType.CustomAttributes.Add(new CodeAttributeDeclaration("WebServiceBinding", new CodeAttributeArgument("ConformsTo", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(WsiProfiles)), "BasicProfile1_1")))); /** * public ClassName() { * VirtualPath = <the virtual path> * } */ CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "VirtualPath"), new CodePrimitiveExpression(VirtualPath))); constructor.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "BridgeXml"), new CodePrimitiveExpression(_bridgeXml))); classType.Members.Add(constructor); ServiceInfo serviceInfo = Service.ServiceInfo; foreach (BridgeMethodInfo methodInfo in serviceInfo.Methods.Values) { classType.Members.Add(GenerateWebMethodCode(methodInfo.Name, methodInfo.XmlIncludes, methodInfo.GetEnabled, methodInfo.ResponseFormat, false)); } // Skip the proxy method code generation for REST if (!string.Equals(serviceInfo.ServiceClass, "Microsoft.Web.Preview.Services.BridgeRestProxy")) classType.Members.Add(GenerateProxyMethodCode()); // BridgeMethod hook classType.Members.Add(GenerateWebMethodCode("__invokeBridge", null, false, ResponseFormat.Json, true)); assemBuilder.AddCodeCompileUnit(this, unit); if (!string.IsNullOrEmpty(Service.PartialClassFile)) { using (TextReader reader = OpenReader(Service.PartialClassFile)) { CodeSnippetCompileUnit snippet = new CodeSnippetCompileUnit(reader.ReadToEnd()); if (HttpContext.Current != null) { snippet.LinePragma = new CodeLinePragma(HttpContext.Current.Request.MapPath(Service.PartialClassFile), 1); } assemBuilder.AddCodeCompileUnit(this, snippet); } } }
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); }
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 }