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);
            }
        }
Example #2
0
        public ScriptClass GetScriptClass(string ns, string language, IErrorHelper errorHelper)
        {
            CompilerInfo compilerInfo;

            try {
                compilerInfo = CodeDomProvider.GetCompilerInfo(language);
                Debug.Assert(compilerInfo != null);
            }
            catch (ConfigurationException) {
                // There is no CodeDom provider defined for this language
                errorHelper.ReportError(/*[XT_010]*/ Res.Xslt_ScriptInvalidLanguage, language);
                return(null);
            }

            foreach (ScriptClass scriptClass in scriptClasses)
            {
                if (ns == scriptClass.ns)
                {
                    // Use object comparison because CompilerInfo.Equals may throw
                    if (compilerInfo != scriptClass.compilerInfo)
                    {
                        errorHelper.ReportError(/*[XT_011]*/ Res.Xslt_ScriptMixedLanguages, ns);
                        return(null);
                    }
                    return(scriptClass);
                }
            }

            ScriptClass newScriptClass = new ScriptClass(ns, compilerInfo);

            newScriptClass.typeDecl.TypeAttributes = TypeAttributes.Public;
            scriptClasses.Add(newScriptClass);
            return(newScriptClass);
        }
Example #3
0
        internal static CodeDomProvider CreateProvider(HttpContext context, string lang, out CompilerParameters par, out string tempdir)
        {
            CodeDomProvider ret = null;

            par = null;

            CompilationSection config = (CompilationSection)WebConfigurationManager.GetWebApplicationSection("system.web/compilation");
            Compiler           comp   = config.Compilers[lang];

            if (comp == null)
            {
                CompilerInfo info = CodeDomProvider.GetCompilerInfo(lang);
                if (info != null && info.IsCodeDomProviderTypeValid)
                {
                    ret = info.CreateProvider();
                    par = info.CreateDefaultCompilerParameters();
                }
            }
            else
            {
                Type t = HttpApplication.LoadType(comp.Type, true);
                ret = Activator.CreateInstance(t) as CodeDomProvider;

                par = new CompilerParameters();
                par.CompilerOptions = comp.CompilerOptions;
                par.WarningLevel    = comp.WarningLevel;
            }
            tempdir = config.TempDirectory;

            return(ret);
        }
Example #4
0
        internal static IDictionary <string, string> GetProviderOptionsCollection(string fileExt)
        {
            Dictionary <string, string> opts = new Dictionary <string, string>();

            if (!CodeDomProvider.IsDefinedExtension(fileExt))
            {
                return(new ReadOnlyDictionary <string, string>(opts));
            }

            CompilerInfo ci = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(fileExt));

            if (ci == null)
            {
                return(new ReadOnlyDictionary <string, string>(opts));
            }

            // There is a fun little comment about this property in the framework code about making it
            // public after 3.5. Guess that didn't happen. Oh well. :)
            PropertyInfo pi = ci.GetType().GetProperty("ProviderOptions",
                                                       BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);

            if (pi == null)
            {
                return(new ReadOnlyDictionary <string, string>(opts));
            }

            return(new ReadOnlyDictionary <string, string>((IDictionary <string, string>)pi.GetValue(ci, null)));
        }
Example #5
0
        internal CompilerType GetCompilerInfoFromExtension(string extension, bool throwOnFail)
        {
            CompilerType compilerTypeInternal;

            this.EnsureCompilerCacheInit();
            object   obj2     = this._compilerExtensions[extension];
            Compiler compiler = obj2 as Compiler;

            if (compiler != null)
            {
                compilerTypeInternal = compiler.CompilerTypeInternal;
                this._compilerExtensions[extension] = compilerTypeInternal;
            }
            else
            {
                compilerTypeInternal = obj2 as CompilerType;
            }
            if ((compilerTypeInternal == null) && CodeDomProvider.IsDefinedExtension(extension))
            {
                CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(extension));
                compilerTypeInternal = new CompilerType(compilerInfo.CodeDomProviderType, compilerInfo.CreateDefaultCompilerParameters());
                this._compilerExtensions[extension] = compilerTypeInternal;
            }
            if (compilerTypeInternal == null)
            {
                if (throwOnFail)
                {
                    throw new HttpException(System.Web.SR.GetString("Invalid_lang_extension", new object[] { extension }));
                }
                return(null);
            }
            compilerTypeInternal = compilerTypeInternal.Clone();
            compilerTypeInternal.CompilerParameters.IncludeDebugInformation = this.Debug;
            return(compilerTypeInternal);
        }
Example #6
0
        static void DisplayCompilerInfoForConfigLanguage(string configLanguage)
        {
            CompilerInfo info = CodeDomProvider.GetCompilerInfo(configLanguage);

            // Check whether there is a provider configured for this language.
            if (info.IsCodeDomProviderTypeValid)
            {
                // Get a provider instance using the configured type information.
                CodeDomProvider provider;
                provider = (CodeDomProvider)Activator.CreateInstance(info.CodeDomProviderType);

                // 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.

                CompilerParameters langCompilerConfig = info.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}\".",
                                  configLanguage);
            }
        }
Example #7
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 #8
0
        public void GetExtensions_Invoke_ReturnsExpected(string language, string[] extensions)
        {
            CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(language);

            Assert.Equal(extensions, compilerInfo.GetExtensions());
            Assert.NotSame(compilerInfo.GetExtensions(), compilerInfo.GetExtensions());
        }
Example #9
0
        public static string getCompilerStr()
        {
            CompilerInfo info      = CodeDomProvider.GetCompilerInfo("CSharp");
            var          dotnetver = info.CodeDomProviderType.Assembly.ImageRuntimeVersion;

            return(dotnetver);
        }
Example #10
0
        /*
         * Return a CompilerType that a extension maps to.
         */
        internal CompilerType GetCompilerInfoFromExtension(string extension, bool throwOnFail)
        {
            EnsureCompilerCacheInit();

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

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

            if (compilerType == null)
            {
                // If not, try the <codedom> section

                if (CodeDomProvider.IsDefinedExtension(extension))
                {
                    string language = CodeDomProvider.GetLanguageFromExtension(extension);

                    CompilerInfo ci = CodeDomProvider.GetCompilerInfo(language);

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

                    // Cache it
                    _compilerExtensions[extension] = compilerType;
                }
            }

            if (compilerType == null)
            {
                if (!throwOnFail)
                {
                    return(null);
                }

                // Unsupported extension: throw an exception
                throw new HttpException(SR.GetString(SR.Invalid_lang_extension, extension));
            }

            // 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 #11
0
        internal static IDictionary <string, string> GetProviderOptions(Type codeDomProviderType)
        {
            CodeDomProvider provider      = (CodeDomProvider)Activator.CreateInstance(codeDomProviderType);
            string          fileExtension = provider.FileExtension;

            if (CodeDomProvider.IsDefinedExtension(fileExtension))
            {
                return(GetProviderOptions(CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(fileExtension))));
            }
            return(null);
        }
Example #12
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 #13
0
        internal static IDictionary <string, string> GetProviderOptions(Type codeDomProviderType)
        {
            // Using reflection to get the property for the time being.
            // This could simply return CompilerInfo.PropertyOptions if it goes public in future.
            CodeDomProvider provider  = (CodeDomProvider)Activator.CreateInstance(codeDomProviderType);
            string          extension = provider.FileExtension;

            if (CodeDomProvider.IsDefinedExtension(extension))
            {
                CompilerInfo ci = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(extension));
                return(GetProviderOptions(ci));
            }
            return(null);
        }
Example #14
0
        private void ThrowIfErrorsIn(CompilerResults results, IEnumerable <SourceFile> files)
        {
            if (results.Errors.Count > 0)
            {
                StringBuilder   message = new StringBuilder();
                CodeDomProvider cSharpCodeProvider;
                try
                {
                    cSharpCodeProvider = CodeDomProvider.GetCompilerInfo("csharp").CreateProvider();
                }
                catch (SecurityException)
                {
                    cSharpCodeProvider = new CSharpCodeProvider();
                }
                catch (ConfigurationException)
                {
                    cSharpCodeProvider = new CSharpCodeProvider();
                }

                try
                {
                    foreach (SourceFile file in files)
                    {
                        CompilerResults result = cSharpCodeProvider.CompileAssemblyFromSource(parameters, file.ConcreteClass);
                        if (result.Errors.Count > 0)
                        {
                            foreach (CompilerError err in result.Errors)
                            {
                                message.AppendLine(string.Format(@"
On '{0}' (class name: {1}) Line {2}, Column {3}, {4} {5}:
{6}
========================================",
                                                                 file.ViewName,
                                                                 file.ClassName,
                                                                 err.Line,
                                                                 err.Column,
                                                                 err.IsWarning ? "Warning" : "Error",
                                                                 err.ErrorNumber,
                                                                 err.ErrorText));
                            }
                        }
                    }
                }
                finally
                {
                    cSharpCodeProvider.Dispose();
                }
                throw new Exception("Error while compiling views: " + message);
            }
        }
Example #15
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>
        }
Example #16
0
        /// <summary>
        /// 生成源代码
        /// </summary>
        /// <param name="nspace">源代码描述信息</param>
        /// <returns>所生成源代码文本</returns>
        public string GengerCode(CodeNamespace nspace)
        {
            StringBuilder sb = new StringBuilder();

            System.IO.StringWriter sw          = new System.IO.StringWriter(sb);
            CodeGeneratorOptions   geneOptions = new CodeGeneratorOptions();//代码生成选项

            geneOptions.BlankLinesBetweenMembers = false;
            geneOptions.BracingStyle             = "C";
            geneOptions.ElseOnClosing            = true;
            geneOptions.IndentString             = "    ";
            CodeDomProvider.GetCompilerInfo("c#").CreateProvider().GenerateCodeFromNamespace(nspace, sw, geneOptions);//代码生成
            sw.Close();

            return(sb.ToString());
        }
Example #17
0
        public CustomScriptAction(string id, string language, string code)
        {
            Id       = id;
            Language = language;
            Code     = code;

            Class = string.Format("{0}{1}", Id, "Class");

            var provider = CodeDomProvider.CreateProvider(Language);
            var info     = CodeDomProvider.GetCompilerInfo(Language);

            var parameters = info.CreateDefaultCompilerParameters();

            parameters.MainClass = Class;
            parameters.IncludeDebugInformation = false;
            parameters.GenerateInMemory        = true;
            parameters.GenerateExecutable      = false;
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

            var classCode = string.Format(@"class {0} {{ {1} }}", Class, Code);
            var compiled  = provider.CompileAssemblyFromSource(parameters, classCode);

            #region Log compiler output
            if (compiled.Errors.Count > 0)
            {
                foreach (var error in compiled.Errors)
                {
                    Trace.TraceError(error.ToString());
                }

                throw new Exception();
            }

            foreach (var output in compiled.Output)
            {
                Trace.TraceInformation(output);
            }
            #endregion

            Assembly = compiled.CompiledAssembly;
            Type     = Assembly.GetType(parameters.MainClass);
            Instance = Activator.CreateInstance(Type);
            Method   = Type.GetMethod(Id);
        }
Example #18
0
        public static CodeDomProvider CreateProvider(string language)
        {
            CompilerInfo compilerInfo        = CodeDomProvider.GetCompilerInfo(language);
            Type         codeDomProviderType = compilerInfo.CodeDomProviderType;

            if (Compiler.providerOptions.ContainsKey(codeDomProviderType))
            {
                ConstructorInfo constructor = codeDomProviderType.GetConstructor(new Type[]
                {
                    typeof(IDictionary <string, string>)
                });
                return(constructor.Invoke(new object[]
                {
                    Compiler.providerOptions[codeDomProviderType]
                }) as CodeDomProvider);
            }
            return(compilerInfo.CreateProvider());
        }
        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 #20
0
        public static IEnumerable <object[]> Equals_TestData()
        {
            CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo("cs");

            yield return(new object[] { compilerInfo, compilerInfo, true });

            yield return(new object[] { compilerInfo, CodeDomProvider.GetCompilerInfo("cs"), true });

            yield return(new object[] { compilerInfo, CodeDomProvider.GetCompilerInfo("vb"), false });

            // .NET Core fixes a typo in .NET Full Framework and validates that the casted object
            // instead of validating the object typed parameter.
            if (!PlatformDetection.IsFullFramework)
            {
                yield return(new object[] { compilerInfo, new object(), false });
            }
            yield return(new object[] { compilerInfo, null, false });
        }
Example #21
0
 /// <summary>
 /// Compiles the specified language.
 /// </summary>
 /// <param name="language">The language.</param>
 /// <param name="code">The code.</param>
 /// <param name="isSnippet">if set to <c>true</c> then <paramref name="code"/> will be placed into
 /// templated "application code", such as a static void main.</param>
 /// <param name="throwExceptionOnCompileError">if set to <c>true</c> [throw exception on compile error].</param>
 /// <returns></returns>
 /// <exception cref="Utilities.Code.CodeUtilities.CompileException"/>
 /// <exception cref="Utilities.Code.CodeUtilities.NativeCompileException"/>
 public static CompilerResults Compile(Language language, string code, bool isSnippet, bool throwExceptionOnCompileError)
 {
     using (CodeDomProvider domProvider = CodeDomProvider.CreateProvider(language.ToString()))
     {
         CompilerInfo       compilerInfo       = CodeDomProvider.GetCompilerInfo(language.ToString());
         CompilerParameters compilerParameters = compilerInfo.CreateDefaultCompilerParameters();
         PrepareCompilerParameters(language, compilerParameters);
         if (isSnippet)
         {
             code = GetApplicationCode(language, code, DefaultClassName, DefaultNamespace);
         }
         CompilerResults results = domProvider.CompileAssemblyFromSource(compilerParameters, code);
         if (throwExceptionOnCompileError)
         {
             CheckCompilerResultsThrow(results);
         }
         return(results);
     }
 }
        public ICodeProviderAdapter GetAdapter()
        {
            CodeDomProvider codeProvider;

            try
            {
                codeProvider = CodeDomProvider.GetCompilerInfo("csharp").CreateProvider();
            }
            catch (SecurityException)
            {
                codeProvider = new CSharpCodeProvider();
            }
            catch (ConfigurationException)
            {
                codeProvider = new CSharpCodeProvider();
            }

            return(new DefaultCodeProviderAdapter(codeProvider));
        }
Example #23
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 #24
0
        public void CreateCompilerParameters_Invoke_ReturnsExpected(string language)
        {
            CompilerInfo       compilerInfo = CodeDomProvider.GetCompilerInfo(language);
            CompilerParameters parameters   = compilerInfo.CreateDefaultCompilerParameters();

            Assert.Null(parameters.CompilerOptions);
            Assert.Empty(parameters.CoreAssemblyFileName);
            Assert.Empty(parameters.EmbeddedResources);
            Assert.False(parameters.GenerateExecutable);
            Assert.False(parameters.GenerateInMemory);
            Assert.False(parameters.IncludeDebugInformation);
            Assert.Empty(parameters.LinkedResources);
            Assert.Null(parameters.MainClass);
            Assert.Null(parameters.OutputAssembly);
            Assert.Empty(parameters.ReferencedAssemblies);
            Assert.False(parameters.TreatWarningsAsErrors);
            Assert.Equal(IntPtr.Zero, parameters.UserToken);
            Assert.Equal(4, parameters.WarningLevel);
            Assert.Null(parameters.Win32Resource);

            Assert.NotSame(compilerInfo.CreateDefaultCompilerParameters(), compilerInfo.CreateDefaultCompilerParameters());
        }
Example #25
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 #26
0
 static CompilerInfo GetCompilerInfo(string name)
 {
     return(CodeDomProvider.GetCompilerInfo(
                CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(name))));
 }
Example #27
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);
        }
 static CompilerInfo GetCSharpCompilerInfo()
 {
     return(CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(".cs")));
 }
Example #29
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 #30
0
        /// <summary>
        /// Creates a .pdb file for the code creation in the
        /// </summary>
        /// <returns></returns>
        private string CreatePdbFile(out Guid pdbSig, out uint pdbAge)
        {
            StringBuilder pdbCode = new StringBuilder();

            pdbCode.Append("class JavaScriptFunctions {");

            int    id = 0;
            string dllDirectory;

            for (; ;)
            {
                dllDirectory = Path.Combine(Path.GetTempPath(), "JavaScriptFunctions_" + id);
                id++;
                if (!Directory.Exists(dllDirectory))
                {
                    try {
                        Directory.CreateDirectory(dllDirectory);
                        break;
                    } catch {
                    }
                }
            }

            string dllPath     = Path.Combine(dllDirectory, "JavaScriptFunctions.dll");
            uint   methodToken = 0x06000001;

            using (var reader = new StreamReader(_filename)) {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    var records = SplitRecord(line);
                    if (records.Length == 0)
                    {
                        continue;
                    }
                    switch (records[0])
                    {
                    case "code-creation":
                        var funcInfo = ExtractNamespaceAndMethodName(records[4]);
                        if (funcInfo.LineNumber != null && funcInfo.Filename != null)
                        {
                            pdbCode.Append(String.Format(@"
#line {0} ""{1}""
public static void X{2:X}() {{
}}
", funcInfo.LineNumber, funcInfo.Filename, methodToken));
                        }
                        else
                        {
                            // we need to keep outputting methods just to keep tokens lined up.
                            pdbCode.Append(String.Format(@"
public static void X{0:X}() {{
}}
", methodToken));
                        }
                        methodToken++;
                        break;
                    }
                }
            }

            pdbCode.Append("}");

            var compiler   = CodeDomProvider.GetCompilerInfo("csharp");
            var parameters = compiler.CreateDefaultCompilerParameters();

            parameters.IncludeDebugInformation = true;
            parameters.OutputAssembly          = dllPath;
            parameters.GenerateExecutable      = false;
            var res = compiler.CreateProvider().CompileAssemblyFromSource(parameters, pdbCode.ToString());

            if (res.Errors.Count > 0)
            {
#if DEBUG
                var tempPath = Path.GetTempFileName();
                File.WriteAllText(tempPath, pdbCode.ToString());
#endif
                StringBuilder errors = new StringBuilder("Error while generating symbols:");
                foreach (var error in res.Errors)
                {
                    errors.AppendFormat("    {0}", error);
                    errors.AppendLine();
                }
#if DEBUG
                Console.WriteLine(errors.ToString());
                MessageBox.Show("Code saved to: " + tempPath + Environment.NewLine + errors.ToString());
#endif
            }

            ReadPdbSigAndAge(dllPath, out pdbSig, out pdbAge);
            return(dllPath);
        }