Example #1
0
        static void DisplayCompilerInfoForLanguage(string language)
        {
            CodeDomProvider provider;

            // Check for a provider corresponding to the input language.
            if (CodeDomProvider.IsDefinedLanguage(language))
            {
                provider = CodeDomProvider.CreateProvider(language);

                // Display information about this language provider.

                Console.WriteLine("Language provider:  {0}",
                                  provider.ToString());
                Console.WriteLine();
                Console.WriteLine("  Default file extension:  {0}",
                                  provider.FileExtension);
                Console.WriteLine();

                // Get the compiler settings for this language.

                CompilerInfo       langCompilerInfo   = CodeDomProvider.GetCompilerInfo(language);
                CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters();

                Console.WriteLine("  Compiler options:        {0}",
                                  langCompilerConfig.CompilerOptions);
                Console.WriteLine("  Compiler warning level:  {0}",
                                  langCompilerConfig.WarningLevel);
            }
            else
            {
                // Tell the user that the language provider was not found.
                Console.WriteLine("There is no provider configured for input language \"{0}\".",
                                  language);
            }
        }
      private async void GenerateTypeFile(string filePath, CodeCompileUnit targetUnit)
      {
          await Task.Run(() =>
            {
                if (!CodeDomProvider.IsDefinedLanguage(LocalizationEditorData.CodeDomProviderLanguage))
                {
                    throw new Exception($"{LocalizationEditorData.CodeDomProviderLanguage} is not a valid language!");
                }

                var codeDomProvider = CodeDomProvider.CreateProvider(LocalizationEditorData.CodeDomProviderLanguage);

                var codeGeneratorOptions = new CodeGeneratorOptions
                {
                    BracingStyle             = LocalizationEditorData.CodeGeneratorOptionsBracingStyle,
                    BlankLinesBetweenMembers = false
                };

                using (var streamWriter = new StreamWriter(filePath))
                {
                    codeDomProvider.GenerateCodeFromCompileUnit(targetUnit, streamWriter, codeGeneratorOptions);
                }

                codeDomProvider.Dispose();
            });
      }
Example #3
0
        internal CompilerType GetCompilerInfoFromLanguage(string language)
        {
            CompilerType compilerTypeInternal;

            this.EnsureCompilerCacheInit();
            object   obj2     = this._compilerLanguages[language];
            Compiler compiler = obj2 as Compiler;

            if (compiler != null)
            {
                compilerTypeInternal = compiler.CompilerTypeInternal;
                this._compilerLanguages[language] = compilerTypeInternal;
            }
            else
            {
                compilerTypeInternal = obj2 as CompilerType;
            }
            if ((compilerTypeInternal == null) && CodeDomProvider.IsDefinedLanguage(language))
            {
                CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(language);
                compilerTypeInternal = new CompilerType(compilerInfo.CodeDomProviderType, compilerInfo.CreateDefaultCompilerParameters());
                this._compilerLanguages[language] = compilerTypeInternal;
            }
            if (compilerTypeInternal == null)
            {
                throw new HttpException(System.Web.SR.GetString("Invalid_lang", new object[] { language }));
            }
            CompilationUtil.CheckCompilerOptionsAllowed(compilerTypeInternal.CompilerParameters.CompilerOptions, true, null, 0);
            compilerTypeInternal = compilerTypeInternal.Clone();
            compilerTypeInternal.CompilerParameters.IncludeDebugInformation = this.Debug;
            return(compilerTypeInternal);
        }
Example #4
0
        public override bool Execute()
        {
            if (CodeDomProvider.IsDefinedLanguage(this.CodeLanguage))
            {
                using (var codeDomProvider = CodeDomProvider.CreateProvider(this.CodeLanguage))
                {
                    this.generatedFile = new CodeCompileUnit();
                    this.generatedFile.AssemblyCustomAttributes.AddRange(this.CreateAssemblyAttributes().ToArray());

                    var ns = new CodeNamespace();
                    this.generatedFile.Namespaces.Add(ns);
                    ns.Types.Add(this.CreateThisAssemblyClass());

                    Directory.CreateDirectory(Path.GetDirectoryName(this.OutputFile));
                    using (var file = File.OpenWrite(this.OutputFile))
                    {
                        using (var fileWriter = new StreamWriter(file, new UTF8Encoding(true), 4096, leaveOpen: true))
                        {
                            codeDomProvider.GenerateCodeFromCompileUnit(this.generatedFile, fileWriter, codeGeneratorOptions);
                        }

                        // truncate to new size.
                        file.SetLength(file.Position);
                    }
                }
            }
            else
            {
                this.Log.LogError("CodeDomProvider not available for language: {0}. No version info will be embedded into assembly.", this.CodeLanguage);
            }

            return(!this.Log.HasLoggedErrors);
        }
Example #5
0
        static void Main()
        {
            CodeDomProvider provider = null;
            String          exeName  = "HelloWorld.exe";

            Console.WriteLine("Enter the source language for Hello World (cs, vb, etc):");
            String inputLang = Console.ReadLine();

            Console.WriteLine();

            if (CodeDomProvider.IsDefinedLanguage(inputLang))
            {
                provider = CodeDomProvider.CreateProvider(inputLang);
            }

            if (provider == null)
            {
                Console.WriteLine("There is no CodeDomProvider for the input language.");
            }
            else
            {
                CodeCompileUnit helloWorld = BuildHelloWorldGraph();

                String sourceFile = GenerateCode(provider, helloWorld);

                Console.WriteLine("HelloWorld source code generated.");

                if (CompileCode(provider, sourceFile, exeName))
                {
                    Console.WriteLine("Starting HelloWorld executable.");
                    Process.Start(exeName);
                }
            }
        }
Example #6
0
        private void SupportedLanguages()
        {
            CompilerInfo[] aCompilerInfo = CodeDomProvider.GetAllCompilerInfo();

            foreach (CompilerInfo oCompilerInfo in aCompilerInfo)
            {
                foreach (string szLanguage in oCompilerInfo.GetLanguages())
                {
                    MessageBox.Show(szLanguage);
                }
            }

            if (!CodeDomProvider.IsDefinedLanguage("GW-BASIC"))
            {
                MessageBox.Show("GW-BASIC Not supported");
            }

            if (!CodeDomProvider.IsDefinedLanguage("CSharp"))
            {
                MessageBox.Show("CSharp Not supported");
            }

            if (!CodeDomProvider.IsDefinedExtension(".BAS"))
            {
                MessageBox.Show(".BAS Not supported");
            }

            if (!CodeDomProvider.IsDefinedExtension(".cs"))
            {
                MessageBox.Show(".cs Not supported");
            }
        }
Example #7
0
        private Boolean __CreateProvider(ProgrammingLanguages programmingLanguage, ref CodeDomProvider provider)
        {
            Boolean hasTheProvider = new Boolean();
            String  language       = programmingLanguage.ToString();

            switch (programmingLanguage)
            {
            case ProgrammingLanguages.CSharp:
                hasTheProvider = CodeDomProvider.IsDefinedLanguage(language);
                break;

            case ProgrammingLanguages.VisualBasic:
                hasTheProvider = CodeDomProvider.IsDefinedLanguage(language);
                break;

            default:     /*  C# Programming Language. */
                language       = "C#";
                hasTheProvider = !hasTheProvider;
                break;
            }
            ;

            provider = CodeDomProvider.CreateProvider(language);

            return(hasTheProvider);
        }
        private void Initialize(string language)
        {
            if (!CodeDomProvider.IsDefinedLanguage(language))
            {
                throw new InvalidOperationException(Resources.IdentifierValidatorUnknownLanguage);
            }

            provider = CodeDomProvider.CreateProvider(language);
        }
Example #9
0
        public static void CompileSourceFiles(string language, string assemblyPath, string[] sourceFiles, string[] managedPlugins)
        {
            if (!CodeDomProvider.IsDefinedLanguage(language))
            {
                throw new NotSupportedException(string.Format("Unable to compile source files because the language \"{0}\" is not supported!", language));
            }

            using (var provider = CodeDomProvider.CreateProvider(language))
            {
                var compilerParameters = new CompilerParameters();
                compilerParameters.GenerateExecutable = false;

#if RELEASE
                compilerParameters.GenerateInMemory        = true;
                compilerParameters.IncludeDebugInformation = false;
                compilerParameters.CompilerOptions         = "/optimize";
#else
                // Necessary for stack trace line numbers etc. IncludeDebugInformation can be false as long as /debug is in the CompilerOptions
                compilerParameters.IncludeDebugInformation = false;
                compilerParameters.CompilerOptions         = "/optimize /debug:portable";
                compilerParameters.GenerateInMemory        = false;
#endif

                if (!compilerParameters.GenerateInMemory)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(assemblyPath));
                    compilerParameters.OutputAssembly = Path.Combine(assemblyPath);
                }

                AddReferencedAssembliesForSourceFiles(managedPlugins, ref compilerParameters);

                var results = provider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
                if (!results.Errors.HasErrors)
                {
                    return;
                }

                string compilationError = string.Format("Compilation failed; {0} errors: ", results.Errors.Count);

                foreach (CompilerError error in results.Errors)
                {
                    compilationError += Environment.NewLine;

                    if (!error.ErrorText.Contains("(Location of the symbol related to previous error)"))
                    {
                        compilationError += string.Format("{0}({1},{2}): {3} {4}: {5}", error.FileName, error.Line, error.Column, error.IsWarning ? "warning" : "error", error.ErrorNumber, error.ErrorText);
                    }
                    else
                    {
                        compilationError += "    " + error.ErrorText;
                    }
                }

                throw new CompilationFailedException(compilationError);
            }
        }
 public static CodeDomProvider GenerateCodeDomProvider(ProjectLanguage projectLanguage)
 {
     if (projectLanguage == null)
     {
         throw new ArgumentNullException("projectLanguage");
     }
     if (!CodeDomProvider.IsDefinedLanguage(projectLanguage.ToString()))
     {
         throw new InvalidOperationException("The project language is not supported.");
     }
     return(CodeDomProvider.CreateProvider(projectLanguage.ToString()));
 }
Example #11
0
        /*
         * Return a CompilerType that a language maps to.
         */
        internal CompilerType GetCompilerInfoFromLanguage(string language)
        {
            EnsureCompilerCacheInit();

            // First, try the cache (i.e. old <compilers> section)
            CompilerType compilerType;
            object       obj      = _compilerLanguages[language];
            Compiler     compiler = obj as Compiler;

            if (compiler != null)
            {
                compilerType = compiler.CompilerTypeInternal;
                _compilerLanguages[language] = compilerType;
            }
            else
            {
                compilerType = obj as CompilerType;
            }

            if (compilerType == null)
            {
                // Try the <codedom> section

                if (CodeDomProvider.IsDefinedLanguage(language))
                {
                    CompilerInfo ci = CodeDomProvider.GetCompilerInfo(language);

                    compilerType = new CompilerType(ci.CodeDomProviderType,
                                                    ci.CreateDefaultCompilerParameters());

                    // Cache it
                    _compilerLanguages[language] = compilerType;
                }
            }

            if (compilerType == null)
            {
                // Unsupported language: throw an exception
                throw new HttpException(SR.GetString(SR.Invalid_lang, language));
            }

            // Only allow the use of compilerOptions when we have UnmanagedCode access (ASURT 73678)
            CompilationUtil.CheckCompilerOptionsAllowed(compilerType.CompilerParameters.CompilerOptions,
                                                        true /*config*/, null, 0);

            // Clone it so the original is not modified
            compilerType = compilerType.Clone();

            // Set the value of the debug flag in the copy
            compilerType.CompilerParameters.IncludeDebugInformation = Debug;

            return(compilerType);
        }
Example #12
0
        public static CodeDomProvider GenerateCodeDomProvider(ProjectLanguage projectLanguage)
        {
            if (projectLanguage == null)
            {
                throw new ArgumentNullException("projectLanguage");
            }

            if (!CodeDomProvider.IsDefinedLanguage(projectLanguage.ToString()))
            {
                throw new InvalidOperationException(Resources.ScaffoldLanguageNotSupported);
            }

            return(CodeDomProvider.CreateProvider(projectLanguage.ToString()));
        }
Example #13
0
        static void DisplayCompilerInfoUsingExtension(string fileExtension)
        {
            // <Snippet5>
            if (fileExtension[0] != '.')
            {
                fileExtension = "." + fileExtension;
            }

            // Get the language associated with the file extension.
            if (CodeDomProvider.IsDefinedExtension(fileExtension))
            {
                CodeDomProvider provider;
                String          language = CodeDomProvider.GetLanguageFromExtension(fileExtension);

                Console.WriteLine("The language \"{0}\" is associated with file extension \"{1}\"",
                                  language, fileExtension);
                Console.WriteLine();

                // Next, check for a corresponding language provider.

                if (CodeDomProvider.IsDefinedLanguage(language))
                {
                    provider = CodeDomProvider.CreateProvider(language);

                    // Display information about this language provider.

                    Console.WriteLine("Language provider:  {0}",
                                      provider.ToString());
                    Console.WriteLine();

                    // Get the compiler settings for this language.

                    CompilerInfo       langCompilerInfo   = CodeDomProvider.GetCompilerInfo(language);
                    CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters();

                    Console.WriteLine("  Compiler options:        {0}",
                                      langCompilerConfig.CompilerOptions);
                    Console.WriteLine("  Compiler warning level:  {0}",
                                      langCompilerConfig.WarningLevel);
                }
            }
            else
            {
                // Tell the user that the language provider was not found.
                Console.WriteLine("There is no language provider associated with input file extension \"{0}\".",
                                  fileExtension);
            }
            // </Snippet5>
        }
        private static void CreateCodeProvider(string language, ref CodeDomProvider codeProvider, ref string fileExtension)
        {
            if (CodeDomProvider.IsDefinedLanguage(language))
            {
                try
                {
                    codeProvider = CodeDomProvider.CreateProvider(language);
                }
                catch (Exception ex)
                {
                    throw new ArgumentException("Invalid language of " + language, ex);
                }
            }
            else
            {
                Type type = Type.GetType(language, false, true);
                if (type == null)
                {
                    throw new ArgumentException("Invalid language of " + language);
                }
                object obj2 = Activator.CreateInstance(type);
                codeProvider = obj2 as CodeDomProvider;
                if (codeProvider == null)
                {
                    throw new ArgumentException("Invalid language of " + language);
                }
            }

            if (codeProvider != null)
            {
                fileExtension = codeProvider.FileExtension;
                if (fileExtension == null)
                {
                    fileExtension = string.Empty;
                    return;
                }
                if ((fileExtension.Length > 0) && (fileExtension[0] != '.'))
                {
                    fileExtension = "." + fileExtension;
                    return;
                }
            }
            else
            {
                fileExtension = ".src";
            }
        }
        public override bool Execute()
        {
            // attempt to use local codegen
            string fileContent = this.BuildCode();

            if (fileContent != null)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(this.OutputFile));
                Utilities.FileOperationWithRetry(() => File.WriteAllText(this.OutputFile, fileContent));
            }
            else if (CodeDomProvider.IsDefinedLanguage(this.CodeLanguage))
            {
                using (var codeDomProvider = CodeDomProvider.CreateProvider(this.CodeLanguage))
                {
                    this.generatedFile = new CodeCompileUnit();
                    this.generatedFile.AssemblyCustomAttributes.AddRange(this.CreateAssemblyAttributes().ToArray());

                    var ns = new CodeNamespace();
                    this.generatedFile.Namespaces.Add(ns);

                    if (this.EmitThisAssemblyClass)
                    {
                        ns.Types.Add(this.CreateThisAssemblyClass());
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(this.OutputFile));
                    FileStream file = null;
                    Utilities.FileOperationWithRetry(() => file = File.OpenWrite(this.OutputFile));
                    using (file)
                    {
                        using (var fileWriter = new StreamWriter(file, new UTF8Encoding(true), 4096, leaveOpen: true))
                        {
                            codeDomProvider.GenerateCodeFromCompileUnit(this.generatedFile, fileWriter, codeGeneratorOptions);
                        }

                        // truncate to new size.
                        file.SetLength(file.Position);
                    }
                }
            }
            else
            {
                this.Log.LogError("CodeDomProvider not available for language: {0}. No version info will be embedded into assembly.", this.CodeLanguage);
            }

            return(!this.Log.HasLoggedErrors);
        }
Example #16
0
        static void Main()
        {
            CodeDomProvider provider = null;
            String          exeName  = "DocProp.exe";

            Console.WriteLine("Enter the source language for DocumentProperties class (cs, vb, etc):");
            String inputLang = Console.ReadLine();

            Console.WriteLine();

            if (CodeDomProvider.IsDefinedLanguage(inputLang))
            {
                provider = CodeDomProvider.CreateProvider(inputLang);
            }

            if (provider == null)
            {
                Console.WriteLine("There is no CodeDomProvider for the input language.");
            }
            else
            {
                CodeCompileUnit docPropertyUnit = DocumentPropertyGraphBase();

                DocumentPropertyGraphExpand(ref docPropertyUnit);

                String sourceFile = GenerateCode(provider, docPropertyUnit);

                if (!String.IsNullOrEmpty(sourceFile))
                {
                    Console.WriteLine("Document property class code generated.");

                    if (CompileCode(provider, sourceFile, exeName))
                    {
                        Console.WriteLine("Starting DocProp executable.");
                        Process.Start(exeName);
                    }
                }
                else
                {
                    Console.WriteLine("Could not generate source file.");
                    Console.WriteLine(
                        "Target language code generator might not support partial type declarations.");
                }
            }
        }
        public AppResourcesAssemblyBuilder(string canonicAssemblyName, string baseAssemblyPath, AppResourcesCompiler appres)
        {
            this.appResourcesCompiler  = appres;
            this.baseAssemblyPath      = baseAssemblyPath;
            this.baseAssemblyDirectory = Path.GetDirectoryName(baseAssemblyPath);
            this.canonicAssemblyName   = canonicAssemblyName;

            config = WebConfigurationManager.GetWebApplicationSection("system.web/compilation") as CompilationSection;
            if (config == null || !CodeDomProvider.IsDefinedLanguage(config.DefaultLanguage))
            {
                throw new ApplicationException("Could not get the default compiler.");
            }
            ci = CodeDomProvider.GetCompilerInfo(config.DefaultLanguage);
            if (ci == null || !ci.IsCodeDomProviderTypeValid)
            {
                throw new ApplicationException("Failed to obtain the default compiler information.");
            }
        }
Example #18
0
        public List <string> Compile()
        {
            string language = "CSharp";

            if (CodeDomProvider.IsDefinedLanguage(language))
            {
                CSharpCodeProvider codeProvider = (CSharpCodeProvider)CodeDomProvider.CreateProvider(language);

                rtbCompileResult.Text = "";
                System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
                parameters.GenerateExecutable = false;
                parameters.GenerateInMemory   = true;

                foreach (string assemblyName in lbReferences.Items)
                {
                    parameters.ReferencedAssemblies.Add(assemblyName);
                }

                List <string>   errors  = new List <string>();
                CompilerResults results = null;

                try
                {
                    results = codeProvider.CompileAssemblyFromSource(parameters, CSharpCodeInformation.CompleteCode);
                }
                catch (Exception ex)
                {
                    errors.Add(ex.ToString());
                }

                if (results != null)
                {
                    foreach (CompilerError CompErr in results.Errors)
                    {
                        errors.Add("Line number " + CompErr.Line +
                                   ", Error Number: " + CompErr.ErrorNumber +
                                   ", '" + CompErr.ErrorText + ";");
                    }
                }
                return(errors);
            }
            return(new List <string>());
        }
Example #19
0
        public void Defaults()
        {
            cdp = new CodeDomProviderTest();              // execute ctor not a full trust
            Assert.AreEqual(String.Empty, cdp.FileExtension, "FileExtension");
            Assert.AreEqual(LanguageOptions.None, cdp.LanguageOptions, "LanguageOptions");
            Assert.IsNull(cdp.CreateCompiler(), "CreateCompiler");
            Assert.IsNull(cdp.CreateGenerator(), "CreateGenerator");
            Assert.IsNull(cdp.CreateGenerator(String.Empty), "CreateGenerator(string)");
            Assert.IsNull(cdp.CreateGenerator(writer), "CreateGenerator(TextWriter)");
            Assert.IsNull(cdp.CreateParser(), "CreateParser()");
            Assert.IsNotNull(cdp.GetConverter(typeof(string)), "GetConverter");
            Assert.IsNotNull(CodeDomProvider.GetAllCompilerInfo(), "GetAllCompilerInfo");

            // mono returns null (missing config?)
            CodeDomProvider.GetCompilerInfo("cs");
            CodeDomProvider.GetLanguageFromExtension("cs");

            Assert.IsFalse(CodeDomProvider.IsDefinedExtension(String.Empty), "String.Empty");
            Assert.IsFalse(CodeDomProvider.IsDefinedLanguage(String.Empty), "String.Empty");
        }
Example #20
0
        private Assembly BuildAssembly(string code)
        {
            CodeDomProvider provider;

            if (CodeDomProvider.IsDefinedLanguage(language))
            {
                provider = CodeDomProvider.CreateProvider(language);
                var options = new Dictionary <string, string> {
                    { "CompilerVersion", "v" + netVersion }
                };
                CSharpCodeProvider codeProvider   = new CSharpCodeProvider(options);
                CompilerParameters compilerparams = new CompilerParameters();
                compilerparams.GenerateExecutable = false;
                compilerparams.GenerateInMemory   = true;

                foreach (var Ref in Refs)
                {
                    compilerparams.ReferencedAssemblies.Add(Ref);
                }

                CompilerResults results = provider.CompileAssemblyFromSource(compilerparams, code);
                if (results.Errors.HasErrors)
                {
                    StringBuilder errors = new StringBuilder("xCracker Compiler Errors :\r\n");
                    foreach (CompilerError error in results.Errors)
                    {
                        errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
                    }
                    throw new Exception(errors.ToString());
                }
                else
                {
                    return(results.CompiledAssembly);
                }
            }
            else
            {
                throw new Exception("Something went wrong with the compiler (Unknown Language Provided?)");
            }
        }
Example #21
0
        private Assembly compile(string language, string code, bool inMemory, string outFileName)
        {
            if (CodeDomProvider.IsDefinedLanguage(language))
            {
                using (CodeDomProvider provider = CodeDomProvider.CreateProvider(language))
                {
                    CompilerInfo       langCompilerInfo   = CodeDomProvider.GetCompilerInfo(language);
                    CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters();

                    Assembly self = Assembly.GetExecutingAssembly();
                    string   dir  = Path.GetDirectoryName(self.Location);


                    langCompilerConfig.GenerateInMemory = inMemory;
                    if (!inMemory)
                    {
                        langCompilerConfig.OutputAssembly = outFileName;
                    }
                    langCompilerConfig.GenerateExecutable = false;
                    langCompilerConfig.ReferencedAssemblies.Clear();
                    langCompilerConfig.ReferencedAssemblies.Add("System.dll");
                    langCompilerConfig.ReferencedAssemblies.Add("System.Data.dll");
                    langCompilerConfig.ReferencedAssemblies.Add("System.Xml.dll");
                    langCompilerConfig.ReferencedAssemblies.Add(Path.Combine(dir, "SQL8r.Logic.dll"));
                    CompilerResults res = provider.CompileAssemblyFromSource(langCompilerConfig, code);
                    if (res.Errors.HasErrors)
                    {
                        throw new SQL8rException(res.Errors[0].ErrorText);
                    }
                    else
                    {
                        Assembly a = res.CompiledAssembly;
                        return(a);
                    }
                }
            }
            throw new SQL8rException("language not known");
        }
Example #22
0
        /// <summary>
        /// Compile the specified 'code' into an executable assembly. If 'assemblyFileName'
        /// is null then compile to an in-memory assembly.
        /// </summary>
        public static Assembly CompileTextToAssembly(string code, string assemblyFileName)
        {
            // See if we've already compiled this code. If so then return the assembly.
            if (AssemblyCache.ContainsKey(code))
            {
                return(AssemblyCache[code]);
            }

            lock (AssemblyCache)
            {
                if (AssemblyCache.ContainsKey(code))
                {
                    return(AssemblyCache[code]);
                }
                bool   VB = code.IndexOf("Imports System") != -1;
                string Language;
                if (VB)
                {
                    Language = CodeDomProvider.GetLanguageFromExtension(".vb");
                }
                else
                {
                    Language = CodeDomProvider.GetLanguageFromExtension(".cs");
                }

                if (Language != null && CodeDomProvider.IsDefinedLanguage(Language))
                {
                    CodeDomProvider Provider = CodeDomProvider.CreateProvider(Language);
                    if (Provider != null)
                    {
                        CompilerParameters Params = new CompilerParameters();

                        string[] source = new string[1];
                        if (assemblyFileName == null)
                        {
                            Params.GenerateInMemory = true;
                            source[0] = code;
                        }
                        else
                        {
                            Params.GenerateInMemory = false;
                            Params.OutputAssembly   = assemblyFileName;
                            string sourceFileName;
                            if (VB)
                            {
                                sourceFileName = Path.ChangeExtension(assemblyFileName, ".vb");
                            }
                            else
                            {
                                sourceFileName = Path.ChangeExtension(assemblyFileName, ".cs");
                            }
                            File.WriteAllText(sourceFileName, code);
                            source[0] = sourceFileName;
                        }
                        Params.TreatWarningsAsErrors   = false;
                        Params.IncludeDebugInformation = true;
                        Params.WarningLevel            = 2;
                        Params.ReferencedAssemblies.Add("System.dll");
                        Params.ReferencedAssemblies.Add("System.Xml.dll");
                        Params.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                        Params.ReferencedAssemblies.Add("System.Data.dll");
                        Params.ReferencedAssemblies.Add("System.Core.dll");
                        //Params.ReferencedAssemblies.Add("APSIM.Shared.dll");
                        Params.ReferencedAssemblies.Add(System.IO.Path.Combine(Assembly.GetExecutingAssembly().Location));

                        if (Assembly.GetCallingAssembly() != Assembly.GetExecutingAssembly())
                        {
                            Params.ReferencedAssemblies.Add(System.IO.Path.Combine(Assembly.GetCallingAssembly().Location));
                        }
                        Params.TempFiles           = new TempFileCollection(Path.GetTempPath()); // ensure that any temp files are in a writeable area
                        Params.TempFiles.KeepFiles = false;
                        CompilerResults results;
                        if (assemblyFileName == null)
                        {
                            results = Provider.CompileAssemblyFromSource(Params, source);
                        }
                        else
                        {
                            results = Provider.CompileAssemblyFromFile(Params, source);
                        }
                        string Errors = "";
                        foreach (CompilerError err in results.Errors)
                        {
                            if (Errors != "")
                            {
                                Errors += "\r\n";
                            }

                            Errors += err.ErrorText + ". Line number: " + err.Line.ToString();
                        }
                        if (Errors != "")
                        {
                            throw new Exception(Errors);
                        }

                        AssemblyCache.Add(code, results.CompiledAssembly);
                        return(results.CompiledAssembly);
                    }
                }
                throw new Exception("Cannot compile manager script to an assembly");
            }
        }
Example #23
0
 public void IsDefinedLanguage_NullLanguage_ThrowsArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("language", () => CodeDomProvider.IsDefinedLanguage(null));
 }
Example #24
0
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = ServiceTest.GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient                  wc     = new WebClient();
                Stream                     stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                #region csw 注释,因CreateCompiler已过期弃用
                //CSharpCodeProvider csc = new CSharpCodeProvider();
                //ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                //CompilerParameters cplist = new CompilerParameters();
                //cplist.GenerateExecutable = false;
                //cplist.GenerateInMemory = true;
                //cplist.ReferencedAssemblies.Add("System.dll");
                //cplist.ReferencedAssemblies.Add("System.XML.dll");
                //cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                //cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                //CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                #endregion

                #region csw修改,因CreateCompiler已过期弃用
                if (!CodeDomProvider.IsDefinedLanguage("CSharp"))
                {
                    return("编译失败");
                }
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                CompilerResults cr = provider.CompileAssemblyFromDom(cplist, ccu);
                #endregion

                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Example #25
0
        public Assembly Compile(bool debug, string languageOrExtension, params string[] sourceCode)
        {
            CodeDomProvider    provider;
            CompilerParameters parameters;
            CompilerResults    results;
            string             language = languageOrExtension;

            if (!CodeDomProvider.IsDefinedLanguage(languageOrExtension) && CodeDomProvider.IsDefinedExtension(languageOrExtension))
            {
                language = CodeDomProvider.GetLanguageFromExtension(languageOrExtension);
            }
            if (ConfigurationManager.GetSection("system.codedom") != null)
            {
                CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(language);
                provider   = compilerInfo.CreateProvider();
                parameters = compilerInfo.CreateDefaultCompilerParameters();
            }
            else
            {
                if ((!language.Equals("c#", StringComparison.OrdinalIgnoreCase) && !language.Equals("cs", StringComparison.OrdinalIgnoreCase)) && !language.Equals("csharp", StringComparison.OrdinalIgnoreCase))
                {
                    throw new CompilerException(string.Format("When running the {0} in an AppDomain without a system.codedom config section only the csharp language is supported. This happens if you are precompiling your views.", typeof(BatchCompiler).FullName));
                }
                string compilerVersion = GetCompilerVersion();
                Dictionary <string, string> dictionary2 = new Dictionary <string, string>();
                dictionary2.Add("CompilerVersion", compilerVersion);
                Dictionary <string, string> providerOptions = dictionary2;
                provider   = new CSharpCodeProvider(providerOptions);
                parameters = new CompilerParameters();
            }
            parameters.TreatWarningsAsErrors = false;
            string fileExtension = provider.FileExtension;

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (!assembly.IsDynamic())
                {
                    parameters.ReferencedAssemblies.Add(assembly.Location);
                }
            }
            string tempDir = AppDomain.CurrentDomain.SetupInformation.DynamicBase ?? Path.GetTempPath();

            parameters.TempFiles = new TempFileCollection(tempDir);
            if (debug)
            {
                parameters.IncludeDebugInformation = true;
                string        str5 = Path.Combine(tempDir, Guid.NewGuid().ToString("n"));
                List <string> list = new List <string>();
                int           num  = 0;
                foreach (string str6 in sourceCode)
                {
                    num++;
                    string path = string.Concat(new object[] { str5, "-", num, ".", fileExtension });
                    using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(str6);
                        }
                    }
                    list.Add(path);
                }
                if (!string.IsNullOrEmpty(this.OutputAssembly))
                {
                    parameters.OutputAssembly = Path.Combine(tempDir, this.OutputAssembly);
                }
                else
                {
                    parameters.OutputAssembly = str5 + ".dll";
                }
                results = provider.CompileAssemblyFromFile(parameters, list.ToArray());
            }
            else
            {
                if (!string.IsNullOrEmpty(this.OutputAssembly))
                {
                    parameters.OutputAssembly = Path.Combine(tempDir, this.OutputAssembly);
                }
                else
                {
                    parameters.GenerateInMemory = true;
                }
                results = provider.CompileAssemblyFromSource(parameters, sourceCode);
            }
            if (!results.Errors.HasErrors)
            {
                return(results.CompiledAssembly);
            }
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Dynamic view compilation failed.");
            foreach (CompilerError error in results.Errors)
            {
                builder.AppendFormat("{4}({0},{1}): {2} {3}: ", new object[] { error.Line, error.Column, error.IsWarning ? "warning" : "error", error.ErrorNumber, error.FileName });
                builder.AppendLine(error.ErrorText);
            }
            builder.AppendLine();
            foreach (string str8 in sourceCode)
            {
                using (StringReader reader = new StringReader(str8))
                {
                    int num2 = 1;
                    while (true)
                    {
                        string str9 = reader.ReadLine();
                        if (str9 != null)
                        {
                            builder.Append(num2).Append(' ').AppendLine(str9);
                            num2++;
                        }
                    }
                }
            }
            throw new BatchCompilerException(builder.ToString(), results);
        }
Example #26
0
        /// <summary>
        /// Generate a C# program from the Dafny program and, if "invokeCsCompiler" is "true", invoke
        /// the C# compiler to compile it.
        /// </summary>
        public static bool CompileDafnyProgram(Dafny.Program dafnyProgram, string dafnyProgramName,
                                               ReadOnlyCollection <string> otherFileNames, bool invokeCsCompiler,
                                               TextWriter outputWriter = null)
        {
            Contract.Requires(dafnyProgram != null);

            if (outputWriter == null)
            {
                outputWriter = Console.Out;
            }

            // Compile the Dafny program into a string that contains the C# program
            StringWriter sw            = new StringWriter();
            var          oldErrorCount = dafnyProgram.reporter.Count(ErrorLevel.Error);

            Dafny.Compiler compiler = new Dafny.Compiler(dafnyProgram.reporter);
            var            hasMain  = compiler.HasMain(dafnyProgram);

            compiler.Compile(dafnyProgram, sw);
            var  csharpProgram   = sw.ToString();
            bool completeProgram = dafnyProgram.reporter.Count(ErrorLevel.Error) == oldErrorCount;

            // blurt out the code to a file, if requested, or if other files were specified for the C# command line.
            string targetFilename = null;

            if (DafnyOptions.O.SpillTargetCode > 0 || otherFileNames.Count > 0)
            {
                targetFilename = WriteDafnyProgramToFile(dafnyProgramName, csharpProgram, completeProgram, outputWriter);
            }

            // compile the program into an assembly
            if (!completeProgram || !invokeCsCompiler)
            {
                // don't compile
                return(false);
            }
            else if (!CodeDomProvider.IsDefinedLanguage("CSharp"))
            {
                outputWriter.WriteLine("Error: cannot compile, because there is no provider configured for input language CSharp");
                return(false);
            }
            else
            {
                var provider = CodeDomProvider.CreateProvider("CSharp", new Dictionary <string, string> {
                    { "CompilerVersion", "v4.0" }
                });
                var cp = new System.CodeDom.Compiler.CompilerParameters();
                cp.GenerateExecutable = hasMain;
                if (DafnyOptions.O.RunAfterCompile)
                {
                    cp.GenerateInMemory = true;
                }
                else if (hasMain)
                {
                    cp.OutputAssembly   = Path.ChangeExtension(dafnyProgramName, "exe");
                    cp.GenerateInMemory = false;
                }
                else
                {
                    cp.OutputAssembly   = Path.ChangeExtension(dafnyProgramName, "dll");
                    cp.GenerateInMemory = false;
                }
                cp.CompilerOptions = "/debug /nowarn:0164 /nowarn:0219 /nowarn:1717 /nowarn:0162"; // warning CS0164 complains about unreferenced labels, CS0219 is about unused variables, CS1717 is about assignments of a variable to itself, CS0162 is about unreachable code
                cp.ReferencedAssemblies.Add("System.Numerics.dll");
                cp.ReferencedAssemblies.Add("System.Core.dll");
                cp.ReferencedAssemblies.Add("System.dll");

                var libPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
                if (DafnyOptions.O.UseRuntimeLib)
                {
                    cp.ReferencedAssemblies.Add(libPath + "DafnyRuntime.dll");
                }

                var immutableDllFileName = "System.Collections.Immutable.dll";
                var immutableDllPath     = libPath + immutableDllFileName;

                if (DafnyOptions.O.Optimize)
                {
                    cp.CompilerOptions += " /optimize /define:DAFNY_USE_SYSTEM_COLLECTIONS_IMMUTABLE";
                    cp.ReferencedAssemblies.Add(immutableDllPath);
                    cp.ReferencedAssemblies.Add("System.Runtime.dll");
                }

                int numOtherSourceFiles = 0;
                if (otherFileNames.Count > 0)
                {
                    foreach (var file in otherFileNames)
                    {
                        string extension = Path.GetExtension(file);
                        if (extension != null)
                        {
                            extension = extension.ToLower();
                        }
                        if (extension == ".cs")
                        {
                            numOtherSourceFiles++;
                        }
                        else if (extension == ".dll")
                        {
                            cp.ReferencedAssemblies.Add(file);
                        }
                    }
                }

                CompilerResults cr;
                if (numOtherSourceFiles > 0)
                {
                    string[] sourceFiles = new string[numOtherSourceFiles + 1];
                    sourceFiles[0] = targetFilename;
                    int index = 1;
                    foreach (var file in otherFileNames)
                    {
                        string extension = Path.GetExtension(file);
                        if (extension != null)
                        {
                            extension = extension.ToLower();
                        }
                        if (extension == ".cs")
                        {
                            sourceFiles[index++] = file;
                        }
                    }
                    cr = provider.CompileAssemblyFromFile(cp, sourceFiles);
                }
                else
                {
                    cr = provider.CompileAssemblyFromSource(cp, csharpProgram);
                }

                if (DafnyOptions.O.RunAfterCompile && !hasMain)
                {
                    // do no more
                    return(cr.Errors.Count == 0 ? true : false);
                }

                var assemblyName = Path.GetFileName(cr.PathToAssembly);
                if (DafnyOptions.O.RunAfterCompile && cr.Errors.Count == 0)
                {
                    outputWriter.WriteLine("Program compiled successfully");
                    outputWriter.WriteLine("Running...");
                    outputWriter.WriteLine();
                    var entry = cr.CompiledAssembly.EntryPoint;
                    try {
                        object[] parameters = entry.GetParameters().Length == 0 ? new object[] { } : new object[] { new string[0] };
                        entry.Invoke(null, parameters);
                    } catch (System.Reflection.TargetInvocationException e) {
                        outputWriter.WriteLine("Error: Execution resulted in exception: {0}", e.Message);
                        outputWriter.WriteLine(e.InnerException.ToString());
                    } catch (Exception e) {
                        outputWriter.WriteLine("Error: Execution resulted in exception: {0}", e.Message);
                        outputWriter.WriteLine(e.ToString());
                    }
                }
                else if (cr.Errors.Count == 0)
                {
                    outputWriter.WriteLine("Compiled assembly into {0}", assemblyName);
                    if (DafnyOptions.O.Optimize)
                    {
                        var outputDir = Path.GetDirectoryName(dafnyProgramName);
                        if (string.IsNullOrWhiteSpace(outputDir))
                        {
                            outputDir = ".";
                        }
                        var destPath = outputDir + Path.DirectorySeparatorChar + immutableDllFileName;
                        File.Copy(immutableDllPath, destPath, true);
                        outputWriter.WriteLine("Copied /optimize dependency {0} to {1}", immutableDllFileName, outputDir);
                    }
                }
                else
                {
                    outputWriter.WriteLine("Errors compiling program into {0}", assemblyName);
                    foreach (var ce in cr.Errors)
                    {
                        outputWriter.WriteLine(ce.ToString());
                        outputWriter.WriteLine();
                    }
                    return(false);
                }
                return(true);
            }
        }
Example #27
0
        public object Run(string in_lang, string in_source)
        {
            string tempPath = System.IO.Path.GetTempPath() + "DotNET-Script-Tmp";

            try
            {
                if (!CodeDomProvider.IsDefinedLanguage(in_lang))
                {
                    // No provider defined for this language
                    string sMsg = "No compiler is defined for " + in_lang;
                    Console.WriteLine(sMsg);
                    return(null);
                }

                CodeDomProvider    compiler   = CodeDomProvider.CreateProvider(in_lang);
                CompilerParameters parameters = new CompilerParameters();
                parameters.GenerateExecutable      = false;
                parameters.GenerateInMemory        = true;
                parameters.OutputAssembly          = tempPath;
                parameters.MainClass               = "Script.Main";
                parameters.IncludeDebugInformation = false;

                parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                parameters.ReferencedAssemblies.Add("System.Xaml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                parameters.GenerateInMemory = true;
                string dotNetSDKPath = AppDomain.CurrentDomain.BaseDirectory;
                parameters.ReferencedAssemblies.Add(dotNetSDKPath + "openmayacs.dll");

                CompilerResults results = compiler.CompileAssemblyFromSource(parameters, in_source);

                if (results.Errors.Count > 0)
                {
                    string sErrors = "Search Condition is invalid:\n";
                    foreach (CompilerError err in results.Errors)
                    {
                        sErrors += err.ToString() + "\n";
                    }
                    MessageBox.Show(sErrors, "DAG Explorer", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    object     o      = results.CompiledAssembly.CreateInstance("Script");
                    Type       type   = o.GetType();
                    MethodInfo m      = type.GetMethod("Main");
                    Object     Result = m.Invoke(o, null);

                    return(Result);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());

                // Done with the temp assembly
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
            }

            return(null);
        }
Example #28
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);
            }
        }
Example #29
0
 public void IsDefinedLanguage_ReturnsExpected(string language, bool expected)
 {
     Assert.Equal(expected, CodeDomProvider.IsDefinedLanguage(language));
 }
Example #30
0
        public bool Execute()
        {
            try
            {
                if (this.ApplicationMarkup == null || this.ApplicationMarkup.Count == 0)
                {
                    return(true);
                }
                if (!CodeDomProvider.IsDefinedLanguage(this.Language))
                {
                    throw FxTrace.Exception.Argument("Language", SR.UnrecognizedLanguage(this.Language));
                }

                if (this.SupportExtensions)
                {
                    this.xamlBuildTypeGenerationExtensions = XamlBuildTaskServices.GetXamlBuildTaskExtensions <IXamlBuildTypeGenerationExtension>(
                        this.XamlBuildTaskTypeGenerationExtensionNames,
                        this.BuildLogger,
                        this.MSBuildProjectDirectory);
                }

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(XamlBuildTaskServices.ReflectionOnlyAssemblyResolve);
                bool retVal = true;
                // We load the assemblies for the real builds
                // For intellisense builds, we load them the first time only
                if (!IsInProcessXamlMarkupCompile || this.LoadedAssemblyList == null)
                {
                    if (this.References != null)
                    {
                        try
                        {
                            this.LoadedAssemblyList = XamlBuildTaskServices.Load(this.References, IsInProcessXamlMarkupCompile);
                        }
                        catch (FileNotFoundException e)
                        {
                            XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.FileName, 0, 0);
                            retVal = false;
                        }
                    }
                }

                CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(this.Language);

                ProcessHelperClassGeneration(codeDomProvider);
                foreach (ITaskItem app in ApplicationMarkup)
                {
                    string inputMarkupFile = app.ItemSpec;
                    try
                    {
                        retVal &= ProcessMarkupItem(app, codeDomProvider);
                    }
                    catch (LoggableException e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.Source, e.LineNumber, e.LinePosition);
                        retVal = false;
                    }
                    catch (FileLoadException e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }

                        XamlBuildTaskServices.LogException(this.BuildLogger, SR.AssemblyCannotBeResolved(XamlBuildTaskServices.FileNotLoaded), inputMarkupFile, 0, 0);
                        retVal = false;
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, inputMarkupFile, 0, 0);
                        retVal = false;
                    }
                }

                // Add the files generated from extensions
                if (this.SupportExtensions)
                {
                    if (retVal)
                    {
                        foreach (string fileName in this.BuildContextForExtensions.GeneratedFiles)
                        {
                            this.GeneratedCodeFiles.Add(fileName);
                        }

                        foreach (string fileName in this.BuildContextForExtensions.GeneratedResourceFiles)
                        {
                            this.GeneratedResources.Add(fileName);
                        }
                    }
                }

                return(retVal);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                // Log unknown errors that do not originate from the task.
                // Assumes that all known errors are logged when the exception is thrown.
                if (!(e is LoggableException))
                {
                    XamlBuildTaskServices.LogException(this.BuildLogger, e.Message);
                }
                return(false);
            }
        }