public override void GenerateCode(AssemblyBuilder assemblyBuilder) {

        CodeCompileUnit codeCompileUnit = _parser.GetCodeModel();

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

        assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);

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

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

        // tell the host to generate a fast factory for this type (if any)
        //string generatedTypeName = _parser.GeneratedTypeName;
        //if (generatedTypeName != null)
        //    assemblyBuilder.GenerateTypeFactory(generatedTypeName);
    }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
     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"));
 }
 private void CacheCompileErrors(AssemblyBuilder assemblyBuilder, CompilerResults results)
 {
     System.Web.Compilation.BuildProvider provider = null;
     foreach (CompilerError error in results.Errors)
     {
         if (!error.IsWarning)
         {
             System.Web.Compilation.BuildProvider buildProviderFromLinePragma = assemblyBuilder.GetBuildProviderFromLinePragma(error.FileName);
             if (((buildProviderFromLinePragma != null) && (buildProviderFromLinePragma is BaseTemplateBuildProvider)) && (buildProviderFromLinePragma != provider))
             {
                 provider = buildProviderFromLinePragma;
                 CompilerResults results2 = new CompilerResults(null);
                 foreach (string str in results.Output)
                 {
                     results2.Output.Add(str);
                 }
                 results2.PathToAssembly = results.PathToAssembly;
                 results2.NativeCompilerReturnValue = results.NativeCompilerReturnValue;
                 results2.Errors.Add(error);
                 HttpCompileException compileException = new HttpCompileException(results2, assemblyBuilder.GetGeneratedSourceFromBuildProvider(buildProviderFromLinePragma));
                 BuildResult result = new BuildResultCompileError(buildProviderFromLinePragma.VirtualPathObject, compileException);
                 buildProviderFromLinePragma.SetBuildResultDependencies(result);
                 BuildManager.CacheVPathBuildResult(buildProviderFromLinePragma.VirtualPathObject, result, this._utcStart);
             }
         }
     }
 }
 /// <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 (!IsCompiledFile)
     {
         base.GenerateCode(assemblyBuilder);
     }
 }
 public override void GenerateCode(AssemblyBuilder assemblyBuilder) {
     var context = new CompileExtensionContext {
         VirtualPath = this.VirtualPath,
         AssemblyBuilder =  new AspNetAssemblyBuilder(assemblyBuilder, this)
     };
     HostContainer.Resolve<IExtensionCompiler>().Compile(context);
 }
        public AssemblyBuilderWrapper(AssemblyBuilder builder) {
            if (builder == null) {
                throw new ArgumentNullException("builder");
            }

            InnerBuilder = builder;
        }
        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();
     }
 }
 private void AddPropertyGroup(AssemblyBuilder assemblyBuilder, string groupName, string propertyNames, Hashtable properties, CodeTypeDeclaration type, CodeNamespace ns)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Name = groupName,
         Attributes = MemberAttributes.Public,
         HasGet = true,
         Type = new CodeTypeReference("ProfileGroup" + groupName)
     };
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = { TargetObject = new CodeThisReferenceExpression(), MethodName = "GetProfileGroup" }
     };
     expression.Parameters.Add(new CodePrimitiveExpression(property.Name));
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(new CodeCastExpression(property.Type, expression));
     property.GetStatements.Add(statement);
     type.Members.Add(property);
     CodeTypeDeclaration declaration = new CodeTypeDeclaration {
         Name = "ProfileGroup" + groupName
     };
     declaration.BaseTypes.Add(new CodeTypeReference(typeof(ProfileGroupBase)));
     foreach (string str in propertyNames.Split(new char[] { ';' }))
     {
         this.CreateCodeForProperty(assemblyBuilder, declaration, (ProfileNameTypeStruct) properties[str]);
     }
     ns.Types.Add(declaration);
 }
    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 
    }
		protected override void OverrideAssemblyPrefix (TemplateParser parser, AssemblyBuilder assemblyBuilder)
		{
			if (parser == null || assemblyBuilder == null)
				return;

			string newPrefix = assemblyBuilder.OutputFilesPrefix + parser.ClassName + ".";
			assemblyBuilder.OutputFilesPrefix = newPrefix;
		}
Exemple #12
0
        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);
        }
Exemple #13
0
    /// <summary>
    /// 添加依赖项
    /// </summary>
    /// <param name="assemblyBuilder"></param>
    protected virtual void AddReferences( AssemblyBuilder assemblyBuilder )
    {
      var buildTypeAssembly = GetType().Assembly;
      var domProviderTypeAssembly = GetDomProviderType().Assembly;


      assemblyBuilder.AddAssemblyReference( buildTypeAssembly );
      if ( buildTypeAssembly != domProviderTypeAssembly )
        assemblyBuilder.AddAssemblyReference( domProviderTypeAssembly );
    }
		public void Compile ()
		{
			string refsPath = Path.Combine (HttpRuntime.AppDomainAppPath, ResourcesDirName);
			if (!Directory.Exists (refsPath))
				return;

			string[] files = Directory.GetFiles (refsPath, "*.wsdl", SearchOption.AllDirectories);
			if (files == null || files.Length == 0)
				return;

			CompilationSection cs = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
			if (cs == null)
				throw new HttpException ("Unable to determine default compilation language.");

			CompilerType ct = BuildManager.GetDefaultCompilerTypeForLanguage (cs.DefaultLanguage, cs);
			CodeDomProvider codeDomProvider = null;
			Exception codeDomException = null;
			
			try {
				codeDomProvider = Activator.CreateInstance (ct.CodeDomProviderType) as CodeDomProvider;
			} catch (Exception e) {
				codeDomException = e;
			}

			if (codeDomProvider == null)
				throw new HttpException ("Unable to instantiate default compilation language provider.", codeDomException);

			AssemblyBuilder ab = new AssemblyBuilder (codeDomProvider, "App_WebReferences_");
			ab.CompilerOptions = ct.CompilerParameters;
			
			VirtualPath vp;
			WsdlBuildProvider wbp;
			foreach (string file in files) {
				vp = VirtualPath.PhysicalToVirtual (file);
				if (vp == null)
					continue;
				
				wbp = new WsdlBuildProvider ();
				wbp.SetVirtualPath (vp);
				wbp.GenerateCode (ab);
			}

			CompilerResults results;
			try {
				results = ab.BuildAssembly ();
			} catch (CompilationException ex) {
				throw new HttpException ("Failed to compile web references.", ex);
			}

			if (results == null)
				return;
			
			Assembly asm = results.CompiledAssembly;
			BuildManager.TopLevelAssemblies.Add (asm);
		}
        public void GenerateCode(AssemblyBuilder assemblyBuilder, Stream xamlStream, BuildProvider buildProvider)
        {
            object serviceObject = WorkflowServiceHostFactory.LoadXaml(xamlStream);

            WorkflowService workflowService = serviceObject as WorkflowService;
            if (workflowService != null && workflowService.Body != null)
            {
                string activityName;
                if (this.TryGenerateSource(assemblyBuilder, buildProvider, workflowService, false, null, out activityName))
                {
                    this.generatedPrimaryTypeName = GeneratedNamespace + "." + activityName + ExpressionRootFactorySuffix;
                }

                // find all supported versions xamlx files, load and compile them
                IList<Tuple<string, Stream>> streams = null;

                string xamlVirtualFile = GetXamlVirtualPath(buildProvider);
                string xamlFileName = Path.GetFileNameWithoutExtension(VirtualPathUtility.GetFileName(xamlVirtualFile));
                WorkflowServiceHostFactory.GetSupportedVersionStreams(xamlFileName, out streams);
                if (streams != null)
                {
                    try
                    {
                        foreach (Tuple<string, Stream> stream in streams)
                        {
                            try
                            {
                                WorkflowService service = WorkflowServiceHostFactory.CreatetWorkflowService(stream.Item2, workflowService.Name);
                                if (service != null && service.Body != null)
                                {
                                    this.TryGenerateSource(assemblyBuilder, buildProvider, service, true, stream.Item1, out activityName);
                                }
                            }
                            catch (Exception e)
                            {
                                Exception newException;
                                if (Fx.IsFatal(e) || !WorkflowServiceHostFactory.TryWrapSupportedVersionException(stream.Item1, e, out newException))
                                {
                                    throw;
                                }

                                throw FxTrace.Exception.AsError(newException);
                            }
                        }
                    }
                    finally
                    {
                        foreach (Tuple<string, Stream> stream in streams)
                        {
                            stream.Item2.Dispose();
                        }
                    }
                }
            }            
        }        
 private void CacheAssemblyResults(AssemblyBuilder assemblyBuilder, CompilerResults results)
 {
     foreach (System.Web.Compilation.BuildProvider provider in assemblyBuilder.BuildProviders)
     {
         BuildResult buildResult = provider.GetBuildResult(results);
         if ((buildResult != null) && !BuildManager.CacheVPathBuildResult(provider.VirtualPathObject, buildResult, this._utcStart))
         {
             break;
         }
     }
 }
        /// <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));
                tc.AddTemplate(CodeService.BuildEnumTemplate(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);
        }
 private void GenerateResourceFile(AssemblyBuilder assemblyBuilder, IResourceReader reader)
 {
     string str;
     if (this._ns == null)
     {
         str = UrlPath.GetFileNameWithoutExtension(base.VirtualPath) + ".resources";
     }
     else if (this._cultureName == null)
     {
         str = this._ns + "." + this._typeName + ".resources";
     }
     else
     {
         str = this._ns + "." + this._typeName + "." + this._cultureName + ".resources";
     }
     str = str.ToLower(CultureInfo.InvariantCulture);
     Stream stream = null;
     try
     {
         try
         {
             try
             {
             }
             finally
             {
                 stream = assemblyBuilder.CreateEmbeddedResource(this, str);
             }
         }
         catch (ArgumentException)
         {
             throw new HttpException(System.Web.SR.GetString("Duplicate_Resource_File", new object[] { base.VirtualPath }));
         }
         using (stream)
         {
             using (ResourceWriter writer = new ResourceWriter(stream))
             {
                 writer.TypeNameConverter = new Func<Type, string>(TargetFrameworkUtil.TypeNameConverter);
                 foreach (DictionaryEntry entry in reader)
                 {
                     writer.AddResource((string) entry.Key, entry.Value);
                 }
             }
         }
     }
     finally
     {
         if (stream != null)
         {
             stream.Close();
         }
     }
 }
		/// <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);
            }
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            XamlType rootXamlType = GetRootXamlType();

            this.GetXamlBuildProviderExtension(rootXamlType);

            if (this.xamlBuildProviderExtension != null)
            {
                using (Stream xamlStream = base.OpenStream())
                {
                    this.xamlBuildProviderExtension.GenerateCode(assemblyBuilder, xamlStream, this);
                }
            }
        }        
 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)
		{
         
			base.GenerateCode (assemblyBuilder);

			SchematronParser schParser = (SchematronParser)this.Parser;
         
			IXsltProcessor proc = Processors.Xslt [schParser.ProcessorName];
         
			IXPathNavigable schemaDoc;

			using (TextReader textReader = OpenReader()) 
				schemaDoc = proc.ItemFactory.CreateNodeReadOnly (textReader, new XmlParsingOptions { BaseUri = this.PhysicalPath }); 
         
			Stream resourceStream;

			try {
				resourceStream = assemblyBuilder.CreateEmbeddedResource (this, this.ValidatorUri.AbsolutePath);
			} catch (ArgumentException) {
				throw CreateCompileException (String.Format (CultureInfo.InvariantCulture, "There is already another type generated with the name '{0}'.", this.GeneratedTypeFullName));
			}

			using (resourceStream) {  
				using (MemoryStream copyStream = new MemoryStream()) {
            
					try {
						using (XmlWriter writer = XmlWriter.Create(copyStream)) 
							proc.BuildSchematronValidatorStylesheet (schemaDoc, writer);
               
					} catch (ProcessorException ex) {
						throw CreateCompileException (ex);
					}
               
					copyStream.Position = 0;
					copyStream.WriteTo (resourceStream);

					// test compilation

					copyStream.Position = 0;
               
					try {
						proc.Compile (copyStream, new XsltCompileOptions { BaseUri = this.PhysicalPath });
					} catch (ProcessorException ex) {
						throw CreateCompileException (ex);
					}
				}
			}
		}
        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(DataSvcMapExtension, StringComparison.OrdinalIgnoreCase))
                {
                    // 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);
                }
            }
        }
Exemple #26
0
		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);
		}
        private void GenerateCodeFromDataServiceMapFile(string mapFilePath, AssemblyBuilder assemblyBuilder)
        {
            try
            {
                MapFileLoader loader = new MapFileLoader(mapFilePath);
                loader.LoadDataSvcMapFile();
                MapFileLoader.AddAssemblyReferences(assemblyBuilder, loader.UseDataServiceCollection);
                string edmxContent = loader.GetEdmxContent();
                System.Data.Services.Design.EntityClassGenerator generator = new System.Data.Services.Design.EntityClassGenerator(LanguageOption.GenerateCSharpCode);

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

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

#if DEBUG
                Debug.Assert(
                    errors == null ||
                    !(errors is ICollection) ||
                    ((ICollection)errors).Count == 0,
                    "Errors reported through the return value. Expected an exception");
#endif
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                errorMessage = String.Format(CultureInfo.CurrentCulture, "{0}: {1}", IO.Path.GetFileName(mapFilePath), errorMessage);
                throw new InvalidOperationException(errorMessage, ex);
            }
        }
    public override void GenerateCode(AssemblyBuilder assemblyBuilder)  {
#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)
        {
            base.GenerateCode(assemblyBuilder);

             // test compilation

             XsltPageParser pageParser = (XsltPageParser)this.Parser;

             IXsltProcessor proc = Processors.Xslt[pageParser.ProcessorName];

             using (Stream source = OpenStream(pageParser.XsltVirtualPath)) {

            try {
               proc.Compile(source, new XsltCompileOptions(baseUri: pageParser.XsltPhysicalUri));
            } catch (ProcessorException ex) {
               throw CreateCompileException(ex);
            }
             }
        }
    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);
    }
 /// <devdoc>
 ///     Asks this build provider to generate any code that it needs, using the various
 ///     methods on the passed in BuildProvider.
 /// </devdoc>
 public virtual void GenerateCode(AssemblyBuilder assemblyBuilder)
 {
 }
Exemple #32
0
        private void GenerateResourceFile(AssemblyBuilder assemblyBuilder, IResourceReader reader)
        {
            // Get the name of the generated .resource file
            string resourceFileName;

            if (_ns == null)
            {
                // In the case where we don't generate code, just name the resource file
                // after the virtual file
                resourceFileName = UrlPath.GetFileNameWithoutExtension(VirtualPath) + ".resources";
            }
            else if (_cultureName == null)
            {
                // Name the resource file after the generated class, since that's what the
                // generated class expects
                resourceFileName = _ns + "." + _typeName + ".resources";
            }
            else
            {
                // If it's a non-default resource, include the culture in the name
                resourceFileName = _ns + "." + _typeName + "." + _cultureName + ".resources";
            }

            // Make it lower case, since GetManifestResourceStream (which we use later on) is
            // case sensitive
            resourceFileName = resourceFileName.ToLower(CultureInfo.InvariantCulture);

            Stream outputStream = null;

            try {
                try {
                    try {
                    }
                    finally {
                        // Put the assignment in a finally block to avoid a ThreadAbortException from
                        // causing the created stream to not get assigned and become leaked (Dev10 bug 844463)
                        outputStream = assemblyBuilder.CreateEmbeddedResource(this, resourceFileName);
                    }
                }
                catch (ArgumentException) {
                    // This throws an ArgumentException if the resource file name was already added.
                    // Catch the situation, and give a better error message (VSWhidbey 87110)

                    throw new HttpException(SR.GetString(SR.Duplicate_Resource_File, VirtualPath));
                }

                // Create an output stream from the .resource file
                using (outputStream) {
                    using (ResourceWriter writer = new ResourceWriter(outputStream)) {
                        // Enable resource writer to be target-aware
                        writer.TypeNameConverter = System.Web.UI.TargetFrameworkUtil.TypeNameConverter;

                        // Copy the resources
                        foreach (DictionaryEntry de in reader)
                        {
                            writer.AddResource((string)de.Key, de.Value);
                        }
                    }
                }
            }
            finally {
                // Always close the stream to avoid a ThreadAbortException from causing the stream
                // to be leaked (Dev10 bug 844463)
                if (outputStream != null)
                {
                    outputStream.Close();
                }
            }
        }
        // Cache the various compile errors found during batching
        private void CacheCompileErrors(AssemblyBuilder assemblyBuilder, CompilerResults results)
        {
            BuildProvider previous = null;

            // Go through all the compile errors
            foreach (CompilerError error in results.Errors)
            {
                // Skip warnings
                if (error.IsWarning)
                {
                    continue;
                }

                // Try to map the error back to a BuildProvider.  If we can't, skip the error.
                BuildProvider buildProvider = assemblyBuilder.GetBuildProviderFromLinePragma(error.FileName);
                if (buildProvider == null)
                {
                    continue;
                }

                // Only cache the error for template controls.  Otherwise, for file types like
                // asmx/ashx, it's too likely that two of them define the same class.
                if (!(buildProvider is BaseTemplateBuildProvider))
                {
                    continue;
                }

                // If the error is for the same page as the previous one, ignore it
                if (buildProvider == previous)
                {
                    continue;
                }
                previous = buildProvider;

                // Create a new CompilerResults for this error
                CompilerResults newResults = new CompilerResults(null /*tempFiles*/);

                // Copy all the output to the new result.  Note that this will include all the
                // error lines, not just the ones for this BuildProvider.  But that's not a big deal,
                // and we can't easily filter the output here.
                foreach (string s in results.Output)
                {
                    newResults.Output.Add(s);
                }

                // Copy various other fields to the new CompilerResults object
                newResults.PathToAssembly            = results.PathToAssembly;
                newResults.NativeCompilerReturnValue = results.NativeCompilerReturnValue;

                // Add this error.  It will be the only one in the CompilerResults object.
                newResults.Errors.Add(error);

                // Create a new HttpCompileException & BuildResultCompileError to wrap this error
                HttpCompileException e = new HttpCompileException(newResults,
                                                                  assemblyBuilder.GetGeneratedSourceFromBuildProvider(buildProvider));
                BuildResult result = new BuildResultCompileError(buildProvider.VirtualPathObject, e);

                // Add the dependencies to the compile error build provider, so that
                // we will retry compilation when a dependency changes
                buildProvider.SetBuildResultDependencies(result);

                // Cache it
                BuildManager.CacheVPathBuildResult(buildProvider.VirtualPathObject, result, _utcStart);
            }
        }
        private bool CompileNonDependentBuildProviders(ICollection buildProviders)
        {
            // Key: CompilerType, Value: AssemblyBuilder
            IDictionary assemblyBuilders = new Hashtable();

            // List of InternalBuildProvider's that don't ask for a specific language
            ArrayList languageFreeBuildProviders = null;

            // AssemblyBuilder used for providers that don't need a specific language
            AssemblyBuilder defaultAssemblyBuilder = null;

            bool hasParserErrors = false;

            foreach (BuildProvider buildProvider in buildProviders)
            {
                if (IsBuildProviderSkipable(buildProvider))
                {
                    continue;
                }

                // Instruct the internal build providers to continue processing for more parse errors.
                if (!BuildManager.ThrowOnFirstParseError)
                {
                    InternalBuildProvider provider = buildProvider as InternalBuildProvider;
                    if (provider != null)
                    {
                        provider.ThrowOnFirstParseError = false;
                    }
                }

                CompilerType compilerType = null;

                // Get the language
                try {
                    compilerType = BuildProvider.GetCompilerTypeFromBuildProvider(
                        buildProvider);
                }
                catch (HttpParseException ex) {
                    // Ignore the error if we are in that mode.
                    if (_ignoreProvidersWithErrors)
                    {
                        continue;
                    }

                    hasParserErrors = true;

                    // Remember the first parse exception
                    if (_firstException == null)
                    {
                        _firstException = ex;
                    }

                    if (_parserErrors == null)
                    {
                        _parserErrors = new ParserErrorCollection();
                    }

                    _parserErrors.AddRange(ex.ParserErrors);

                    continue;
                }
                catch {
                    // Ignore the error if we are in that mode.
                    if (_ignoreProvidersWithErrors)
                    {
                        continue;
                    }

                    throw;
                }

                AssemblyBuilder assemblyBuilder = defaultAssemblyBuilder;
                ICollection     typeNames       = buildProvider.GetGeneratedTypeNames();

                // Is it asking for a specific language?
                if (compilerType == null)
                {
                    // If this provider doesn't need a specific language, and we haven't yet created
                    // a default builder that is capable of building this, just keep track of it
                    if (defaultAssemblyBuilder == null || defaultAssemblyBuilder.IsBatchFull ||
                        defaultAssemblyBuilder.ContainsTypeNames(typeNames))
                    {
                        if (languageFreeBuildProviders == null)
                        {
                            languageFreeBuildProviders = new ArrayList();
                        }

                        languageFreeBuildProviders.Add(buildProvider);
                        continue;
                    }
                }
                else
                {
                    // Check if we already have an assembly builder of the right type
                    assemblyBuilder = (AssemblyBuilder)assemblyBuilders[compilerType];
                }

                // Starts a new assemblyBuilder if the old one already contains another buildprovider
                // that uses the same type name
                if (assemblyBuilder == null || assemblyBuilder.IsBatchFull ||
                    assemblyBuilder.ContainsTypeNames(typeNames))
                {
                    // If the assemblyBuilder is full, compile it.
                    if (assemblyBuilder != null)
                    {
                        CompileAssemblyBuilder(assemblyBuilder);
                    }

                    AssemblyBuilder newBuilder = compilerType.CreateAssemblyBuilder(
                        _compConfig, _referencedAssemblies);

                    assemblyBuilders[compilerType] = newBuilder;

                    // Remember it as the default if we don't already have one,
                    // or if the default is already full, switch the default to the new one.
                    if (defaultAssemblyBuilder == null ||
                        defaultAssemblyBuilder == assemblyBuilder)
                    {
                        defaultAssemblyBuilder = newBuilder;
                    }

                    assemblyBuilder = newBuilder;
                }

                assemblyBuilder.AddTypeNames(typeNames);
                assemblyBuilder.AddBuildProvider(buildProvider);
            }

            // Don't try to compile providers, otherwise compile exceptions will be bubbled up,
            // and we lose the parse errors.
            if (hasParserErrors)
            {
                return(false);
            }

            // Handle all the left over language free providers
            if (languageFreeBuildProviders != null)
            {
                // Indicates whether the default assembly builder is not a language specific builder.
                bool newDefaultAssemblyBuilder = (defaultAssemblyBuilder == null);

                // Add language independent providers to the default assembly builder.
                foreach (BuildProvider languageFreeBuildProvider in languageFreeBuildProviders)
                {
                    ICollection typeNames = languageFreeBuildProvider.GetGeneratedTypeNames();

                    // If we don't have a default language assembly builder, get one or
                    // starts a new assemblyBuilder if the old one already contains another buildprovider
                    // that uses the same type name
                    if (defaultAssemblyBuilder == null || defaultAssemblyBuilder.IsBatchFull ||
                        defaultAssemblyBuilder.ContainsTypeNames(typeNames))
                    {
                        // If the default assemblyBuilder is full, compile it.
                        if (defaultAssemblyBuilder != null)
                        {
                            CompileAssemblyBuilder(defaultAssemblyBuilder);
                        }

                        defaultAssemblyBuilder = CompilerType.GetDefaultAssemblyBuilder(
                            _compConfig, _referencedAssemblies, _vdir.VirtualPathObject /*configPath*/,
                            null /*outputAssemblyName*/);

                        // the default assembly builder needs to be compiled separately.
                        newDefaultAssemblyBuilder = true;
                    }

                    defaultAssemblyBuilder.AddTypeNames(typeNames);
                    defaultAssemblyBuilder.AddBuildProvider(languageFreeBuildProvider);
                }

                // Only compile the default assembly builder if it's not part of language specific
                // assembly builder (which will be compiled separately)
                if (newDefaultAssemblyBuilder)
                {
                    // Compile the default assembly builder.
                    CompileAssemblyBuilder(defaultAssemblyBuilder);
                }
            }

            CompileAssemblyBuilderParallel(assemblyBuilders.Values);

            return(true);
        }
        private void ProcessBuildProviders()
        {
            CompilerType  compilerType = null;
            BuildProvider firstLanguageBuildProvider = null;

            // First, delete all the existing satellite assemblies of the assembly
            // we're about to build (VSWhidbey 87022) (only if it has a fixed name)
            if (OutputAssemblyName != null)
            {
                Debug.Assert(!CbmGenerateOnlyMode);
                StandardDiskBuildResultCache.RemoveSatelliteAssemblies(OutputAssemblyName);
            }

            // List of BuildProvider's that don't ask for a specific language
            ArrayList languageFreeBuildProviders = null;

            foreach (BuildProvider buildProvider in _buildProviders)
            {
                // If it's an InternalBuildProvider, give it the assembly references early on
                buildProvider.SetReferencedAssemblies(_referencedAssemblies);

                // Instruct the internal build providers to continue processing for more parse errors.
                if (!BuildManager.ThrowOnFirstParseError)
                {
                    InternalBuildProvider provider = buildProvider as InternalBuildProvider;
                    if (provider != null)
                    {
                        provider.ThrowOnFirstParseError = false;
                    }
                }

                // Get the language and culture
                CompilerType ctwp = BuildProvider.GetCompilerTypeFromBuildProvider(buildProvider);

                // Only look for a culture if we're supposed to (basically, in the resources directories)
                string cultureName = null;
                if (_supportLocalization)
                {
                    cultureName = buildProvider.GetCultureName();
                }

                // Is it asking for a specific language?
                if (ctwp != null)
                {
                    // If it specifies a language, it can't also have a culture
                    if (cultureName != null)
                    {
                        throw new HttpException(SR.GetString(SR.Both_culture_and_language, BuildProvider.GetDisplayName(buildProvider)));
                    }

                    // Do we already know the language we'll be using
                    if (compilerType != null)
                    {
                        // If it's different from the current one, fail
                        if (!ctwp.Equals(compilerType))
                        {
                            throw new HttpException(SR.GetString(SR.Inconsistent_language,
                                                                 BuildProvider.GetDisplayName(buildProvider),
                                                                 BuildProvider.GetDisplayName(firstLanguageBuildProvider)));
                        }
                    }
                    else
                    {
                        // Keep track of the build provider of error handling purpose
                        firstLanguageBuildProvider = buildProvider;

                        // Keep track of the language
                        compilerType     = ctwp;
                        _assemblyBuilder = compilerType.CreateAssemblyBuilder(
                            CompConfig, _referencedAssemblies, _generatedFilesDir, OutputAssemblyName);
                    }
                }
                else
                {
                    if (cultureName != null)
                    {
                        // Ignore the culture files in generate-only mode
                        if (CbmGenerateOnlyMode)
                        {
                            continue;
                        }

                        if (_satelliteAssemblyBuilders == null)
                        {
                            _satelliteAssemblyBuilders = new Hashtable(
                                StringComparer.OrdinalIgnoreCase);
                        }

                        // Check if we already have an assembly builder for this culture
                        AssemblyBuilder satelliteAssemblyBuilder =
                            (AssemblyBuilder)_satelliteAssemblyBuilders[cultureName];

                        // If not, create one and store it in the hashtable
                        if (satelliteAssemblyBuilder == null)
                        {
                            satelliteAssemblyBuilder = CompilerType.GetDefaultAssemblyBuilder(
                                CompConfig, _referencedAssemblies, _configPath, OutputAssemblyName);
                            satelliteAssemblyBuilder.CultureName    = cultureName;
                            _satelliteAssemblyBuilders[cultureName] = satelliteAssemblyBuilder;
                        }

                        satelliteAssemblyBuilder.AddBuildProvider(buildProvider);
                        continue;
                    }

                    if (_assemblyBuilder == null)
                    {
                        // If this provider doesn't need a specific language, and we don't know
                        // the language yet, just keep track of it
                        if (languageFreeBuildProviders == null)
                        {
                            languageFreeBuildProviders = new ArrayList();
                        }
                        languageFreeBuildProviders.Add(buildProvider);
                        continue;
                    }
                }

                _assemblyBuilder.AddBuildProvider(buildProvider);
            }

            // If we didn't get an AssemblyBuilder, use a default
            if (_assemblyBuilder == null && languageFreeBuildProviders != null)
            {
                _assemblyBuilder = CompilerType.GetDefaultAssemblyBuilder(
                    CompConfig, _referencedAssemblies, _configPath,
                    _generatedFilesDir, OutputAssemblyName);
            }

            // Add all the language free providers (if any) to the AssemblyBuilder
            if (_assemblyBuilder != null && languageFreeBuildProviders != null)
            {
                foreach (BuildProvider languageFreeBuildProvider in languageFreeBuildProviders)
                {
                    _assemblyBuilder.AddBuildProvider(languageFreeBuildProvider);
                }
            }
        }
Exemple #36
0
        public void Compile()
        {
            string refsPath = Path.Combine(HttpRuntime.AppDomainAppPath, ResourcesDirName);

            if (!Directory.Exists(refsPath))
            {
                return;
            }

            string[] files = Directory.GetFiles(refsPath, "*.wsdl", SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
            {
                return;
            }

            CompilationSection cs = WebConfigurationManager.GetWebApplicationSection("system.web/compilation") as CompilationSection;

            if (cs == null)
            {
                throw new HttpException("Unable to determine default compilation language.");
            }

            CompilerType    ct = BuildManager.GetDefaultCompilerTypeForLanguage(cs.DefaultLanguage, cs);
            CodeDomProvider codeDomProvider  = null;
            Exception       codeDomException = null;

            try
            {
                codeDomProvider = Activator.CreateInstance(ct.CodeDomProviderType) as CodeDomProvider;
            }
            catch (Exception e)
            {
                codeDomException = e;
            }

            if (codeDomProvider == null)
            {
                throw new HttpException("Unable to instantiate default compilation language provider.", codeDomException);
            }

            AssemblyBuilder ab = new AssemblyBuilder(codeDomProvider, "App_WebReferences_");

            ab.CompilerOptions = ct.CompilerParameters;

            VirtualPath       vp;
            WsdlBuildProvider wbp;

            foreach (string file in files)
            {
                vp = VirtualPath.PhysicalToVirtual(file);
                if (vp == null)
                {
                    continue;
                }

                wbp = new WsdlBuildProvider();
                wbp.SetVirtualPath(vp);
                wbp.GenerateCode(ab);
            }

            CompilerResults results;

            try
            {
                results = ab.BuildAssembly();
            }
            catch (CompilationException ex)
            {
                throw new HttpException("Failed to compile web references.", ex);
            }

            if (results == null)
            {
                return;
            }

            Assembly asm = results.CompiledAssembly;

            BuildManager.TopLevelAssemblies.Add(asm);
        }
Exemple #37
0
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
#if !FEATURE_PAL // FEATURE_PAL does not support System.Data.Design
            // Get the namespace that we will use
            string ns = Util.GetNamespaceFromVirtualPath(VirtualPathObject);

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

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

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

            // Devdiv 18365, Dev10 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
        }
Exemple #38
0
 protected virtual void OverrideAssemblyPrefix(TParser parser, AssemblyBuilder assemblyBuilder)
 {
 }
Exemple #39
0
        // 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);
            }
        }
        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);
        }