public void Constructor1_Deny_Unrestricted()
        {
            CompilerErrorCollection coll = new CompilerErrorCollection(array);

            coll.CopyTo(array, 0);
            Assert.AreEqual(1, coll.Add(ce), "Add");
            Assert.AreSame(ce, coll[0], "this[int]");
            coll[0] = ce;
            coll.AddRange(array);
            coll.AddRange(coll);
            Assert.IsTrue(coll.Contains(ce), "Contains");
            Assert.AreEqual(0, coll.IndexOf(ce), "IndexOf");
            coll.Insert(0, ce);
            coll.Remove(ce);
            ce.IsWarning = true;
            Assert.IsFalse(coll.HasErrors, "HasErrors");
            Assert.IsTrue(coll.HasWarnings, "HasWarnings");
        }
        public static string CreateAssembly(IList <string> sourceFileList, IList <string> referencesFileList, string assemblyName, bool includeDebugInformation, out CompilerErrorCollection compilerErrors)
        {
            string pathToAssembly = string.Empty;

            compilerErrors = new CompilerErrorCollection();

            if (sourceFileList != null && sourceFileList.Count > 0)
            {
                CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                });

                CompilerParameters options = new CompilerParameters();
                options.GenerateInMemory        = false;
                options.OutputAssembly          = assemblyName;
                options.IncludeDebugInformation = includeDebugInformation;

                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.Core.dll");
                options.ReferencedAssemblies.Add("System.Data.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                options.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                options.ReferencedAssemblies.Add("System.Workflow.Activities.dll");
                options.ReferencedAssemblies.Add("System.Workflow.ComponentModel.dll");

                if (referencesFileList.Count > 0)
                {
                    foreach (string reference in referencesFileList)
                    {
                        options.ReferencedAssemblies.Add(reference);
                    }
                }

                CompilerResults results = provider.CompileAssemblyFromFile(options, sourceFileList.ToArray());

                if (results.Errors.Count > 0)
                {
                    compilerErrors.AddRange(results.Errors);
                }
                else
                {
                    results.CompiledAssembly.GetName().Version = new Version("1.0.0.0");

                    pathToAssembly = results.PathToAssembly;
                }
            }

            return(pathToAssembly);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Compiles and runs the source code for a complete assembly.
        /// </summary>
        /// <param name="lcSource"></param>
        /// <returns></returns>
        public bool CompileAssembly(string lcSource, CompilerErrorCollection errors)
        {
            //oParameters.GenerateExecutable = false;

            if (oAppDomain == null && cOutputAssembly == null)
            {
                _Parameters.GenerateInMemory = true;
            }
            else if (oAppDomain != null && cOutputAssembly == null)
            {
                // *** Generate an assembly of the same name as the domain
                cOutputAssembly            = "lead_" + Guid.NewGuid().ToString() + ".dll";
                _Parameters.OutputAssembly = cOutputAssembly;
            }
            else
            {
                _Parameters.OutputAssembly = cOutputAssembly;
            }

            oCompiled = _Compiler.CompileAssemblyFromSource(_Parameters, lcSource);

            if (oCompiled.Errors.HasErrors)
            {
                bError = true;

                errors.AddRange(oCompiled.Errors);
                // *** Create Error String
                _ErrorMsg = oCompiled.Errors.Count.ToString() + " Errors:";
                for (int x = 0; x < oCompiled.Errors.Count; x++)
                {
                    _ErrorMsg = _ErrorMsg + "\r\nLine: " + oCompiled.Errors[x].Line.ToString() + " - " +
                                oCompiled.Errors[x].ErrorText;
                }
                return(false);
            }

            if (oAppDomain == null)
            {
                _OutputAssembly = oCompiled.CompiledAssembly;
            }

            return(true);
        }
Ejemplo n.º 4
0
        private static Assembly CompileInternal(String outputAssembly, IEnumerable <String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp)
        {
            CompilerParameters options = new CompilerParameters();

            foreach (String str in references)
            {
                options.ReferencedAssemblies.Add(str);
            }
            options.WarningLevel = 4;

            CompilerResults results = null;

            if (Debug)
            {
                #region 调试状态,把生成的类文件和最终dll输出到XTemp目录下
                String tempPath = XTrace.TempPath;
                if (!String.IsNullOrEmpty(outputAssembly))
                {
                    tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                }

                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                options.TempFiles = new TempFileCollection(tempPath, false);

                List <String> files = new List <String>();
                foreach (var item in tmp.Templates)
                {
                    if (item.Included)
                    {
                        continue;
                    }

                    String name = item.Name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ? item.Name : item.ClassName;
                    // 猜测后缀
                    Int32 p = name.LastIndexOf("_");
                    if (p > 0 && name.Length - p <= 5)
                    {
                        name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1);
                    }
                    else if (!name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                    {
                        name += ".cs";
                    }

                    name = Path.Combine(tempPath, name);
                    File.WriteAllText(name, item.Source, Encoding.UTF8);

                    files.Add(name);
                }
                #endregion

                if (!String.IsNullOrEmpty(outputAssembly))
                {
                    options.OutputAssembly = Path.Combine(tempPath, outputAssembly);
                }
                options.GenerateInMemory        = true;
                options.IncludeDebugInformation = true;

                results = provider.CompileAssemblyFromFile(options, files.ToArray());
            }
            else
            {
                List <String> sources = new List <String>();
                foreach (var item in tmp.Templates)
                {
                    sources.Add(item.Source);
                }

                options.GenerateInMemory = true;

                results = provider.CompileAssemblyFromSource(options, sources.ToArray());
            }

            #region 编译错误处理
            if (results.Errors.Count > 0)
            {
                Errors.AddRange(results.Errors);

                var           sb  = new StringBuilder();
                CompilerError err = null;
                foreach (CompilerError error in results.Errors)
                {
                    error.ErrorText = error.ErrorText;
                    //if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile;

                    if (!error.IsWarning)
                    {
                        String msg = error.ToString();
                        if (sb.Length < 1)
                        {
                            String code = null;
                            // 屏蔽因为计算错误行而导致的二次错误
                            try
                            {
                                code = tmp.FindBlockCode(error.FileName, error.Line);
                            }
                            catch { }
                            if (code != null)
                            {
                                msg += Environment.NewLine;
                                msg += code;
                            }
                            err = error;
                        }
                        else
                        {
                            sb.AppendLine();
                        }

                        sb.Append(msg);
                    }
                }
                if (sb.Length > 0)
                {
                    TemplateException ex = new TemplateException(sb.ToString());
                    ex.Error = err;
                    throw ex;
                }
            }
            else
            {
                try
                {
                    options.TempFiles.Delete();
                }
                catch { }
            }
            #endregion

            if (!results.Errors.HasErrors)
            {
                try
                {
                    return(results.CompiledAssembly);
                }
                catch { }
            }
            return(null);
        }
Ejemplo n.º 5
0
        private static Assembly CompileInternal(String outputAssembly, IEnumerable <String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp)
        {
            var options = new CompilerParameters();

            foreach (var str in references)
            {
                options.ReferencedAssemblies.Add(str);
            }
            options.WarningLevel = 4;

            CompilerResults results = null;

            if (Debug)
            {
                //var sb = new StringBuilder();

                #region 调试状态,把生成的类文件和最终dll输出到XTemp目录下
                var tempPath = XTrace.TempPath;
                //if (!String.IsNullOrEmpty(outputAssembly)) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.EqualIgnoreCase(".dll"))
                {
                    tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                }

                //if (!String.IsNullOrEmpty(tempPath) && !Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);

                //var srcpath = tempPath.CombinePath("src").EnsureDirectory(false);

                var files = new List <String>();
                foreach (var item in tmp.Templates)
                {
                    // 输出模版内容,为了调试使用
                    File.WriteAllText(tempPath.CombinePath(item.Name), item.Content);
                    if (item.Included)
                    {
                        continue;
                    }

                    var name = item.Name.EndsWithIgnoreCase(".cs") ? item.Name : item.ClassName;
                    // 猜测后缀
                    Int32 p = name.LastIndexOf("_");
                    if (p > 0 && name.Length - p <= 5)
                    {
                        name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1);
                    }
                    else if (!name.EndsWithIgnoreCase(".cs"))
                    {
                        name += ".cs";
                    }

                    //name = Path.Combine(tempPath, name);
                    //name = srcpath.CombinePath(name);
                    // 必须放在同一个目录,编译时会搜索源码所在目录
                    name = tempPath.CombinePath(Path.GetFileNameWithoutExtension(name) + "_src" + Path.GetExtension(name));
                    File.WriteAllText(name, item.Source);

                    //sb.AppendLine(item.Source);
                    files.Add(name);
                }
                #endregion

                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.EqualIgnoreCase(".dll"))
                {
                    options.TempFiles      = new TempFileCollection(tempPath, false);
                    options.OutputAssembly = Path.Combine(tempPath, outputAssembly);
                    //options.GenerateInMemory = true;
                    options.IncludeDebugInformation = true;
                }

                results = provider.CompileAssemblyFromFile(options, files.ToArray());
                // 必须从内存字符串编译,否则pdb会定向到最终源代码文件
                //results = provider.CompileAssemblyFromSource(options, new String[] { sb.ToString() });
            }
            else
            {
                options.GenerateInMemory = true;

                results = provider.CompileAssemblyFromSource(options, tmp.Templates.Where(e => !e.Included).Select(e => e.Source).ToArray());
            }

            #region 编译错误处理
            if (results.Errors.Count > 0)
            {
                Errors.AddRange(results.Errors);

                var           sb  = new StringBuilder();
                CompilerError err = null;
                foreach (CompilerError error in results.Errors)
                {
                    error.ErrorText = error.ErrorText;
                    //if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile;

                    if (!error.IsWarning)
                    {
                        String msg = error.ToString();
                        if (sb.Length < 1)
                        {
                            String code = null;
                            // 屏蔽因为计算错误行而导致的二次错误
                            try
                            {
                                code = tmp.FindBlockCode(error.FileName, error.Line);
                            }
                            catch { }
                            if (code != null)
                            {
                                msg += Environment.NewLine;
                                msg += code;
                            }
                            err = error;
                        }
                        else
                        {
                            sb.AppendLine();
                        }

                        sb.Append(msg);
                    }
                }
                if (sb.Length > 0)
                {
                    var ex = new TemplateException(sb.ToString());
                    ex.Error = err;
                    throw ex;
                }
            }
            else
            {
                try
                {
                    options.TempFiles.Delete();
                }
                catch { }
            }
            #endregion

            if (!results.Errors.HasErrors)
            {
                try
                {
                    return(results.CompiledAssembly);
                }
                catch { }
            }
            return(null);
        }
Ejemplo n.º 6
0
 public virtual void LogErrors(CompilerErrorCollection errors)
 {
     Errors.AddRange(errors);
 }
Ejemplo n.º 7
0
        public bool CompileClasses(out CompilerErrorCollection compilerErrorCollection, bool copyCompiledCode, params string[] definitions)
        {
            if (this.CompilerLanguage == "Html")
            {
                compilerErrorCollection = new CompilerErrorCollection();
                return(true);
            }

            this.assembly = null;

            Debug.StartTimer("Page:" + this.ID + ":Compile()");

            List <string> classCode = new List <string>();

            foreach (PageClass pageClass in LatestReversion.Classes)
            {
                classCode.Add(pageClass.Data);
            }

            if (this.CompilerLanguage == null || this.CompilerLanguage == string.Empty)
            {
                this.CompilerLanguage = "CSharp";
            }

            dynamic languageHandler = null;

            try
            {
                languageHandler = ModuleSession.Get(HttpContext.Current).GetLanguageHandler(this.CompilerLanguage);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Could not fetch language handler for {0}, Exception: {1}", this.ID, e);
                compilerErrorCollection = new CompilerErrorCollection();
                return(false);
            }

            if (languageHandler != null)
            {
                if (copyCompiledCode)
                {
                    this.CompiledCode = languageHandler.CompileClasses(classCode.ToArray(), this.References.ToArray(), out compilerErrorCollection);
                }
                else
                {
                    languageHandler.CompileClasses(classCode.ToArray(), this.References.ToArray(), out compilerErrorCollection);
                }

                return(true);
            }
            else
            {
                string[] references = this.References.ToArray();

                for (int i = 0; i < references.Length; i++)
                {
                    if (references[i].ToLower().EndsWith(".bmf"))
                    {
                        string moduleID = references[i].Substring(0, references[i].Length - 4);
                        File.WriteAllBytes(HttpContext.Current.Server.MapPath("./Data/Temp/") + moduleID + ".bmf.dll", ModuleManager.Session.GetModuleByID(moduleID).CompiledCode);
                        references[i] += ".dll";
                    }
                }

                CodeDomProvider    codeDomProvider = CodeDomProvider.CreateProvider(this.CompilerLanguage);
                CompilerParameters codeParameters  = new CompilerParameters();

                codeParameters.IncludeDebugInformation = true;
                codeParameters.CompilerOptions         = string.Format("{0}/lib:{1},{2},{3} /define:{4}", this.CompilerLanguage != "JScript" ? "/debug:pdbonly " : "", HttpContext.Current.Server.MapPath("./bin/"), HttpContext.Current.Server.MapPath("./bin/Libraries/"), HttpContext.Current.Server.MapPath("./Data/Temp/"), definitions.Length > 0 ? "WEBCORE;WEBCORE_2014;" + string.Join(";", definitions) : "WEBCORE;WEBCORE_2014");
                codeParameters.GenerateInMemory        = false;
                codeParameters.WarningLevel            = 4;
                codeParameters.ReferencedAssemblies.AddRange(References.ToArray());

                CompilerErrorCollection tmpCompilerErrorCollection = new CompilerErrorCollection();

                CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(codeParameters, classCode.ToArray());

                compilerErrorCollection = compilerResults.Errors;
                Debug.StopTimer("Page:" + this.ID + ":Compile()");

                if (tmpCompilerErrorCollection.Count > 0)
                {
                    compilerErrorCollection.AddRange(tmpCompilerErrorCollection);
                }

                if (compilerErrorCollection.HasErrors)
                {
                    return(false);
                }

                FileInfo AssemblyFileInfo = new FileInfo(compilerResults.PathToAssembly);

                if (copyCompiledCode)
                {
                    this.CompiledCode = File.ReadAllBytes(AssemblyFileInfo.FullName);
                    if (File.Exists(AssemblyFileInfo.FullName.Replace(".dll", ".pdb")))
                    {
                        this.CompiledCodeSymbols = File.ReadAllBytes(AssemblyFileInfo.FullName.Replace(".dll", ".pdb"));
                    }
                }

                return(true);
            }
        }
        /// <summary>
        /// Generate the code
        /// </summary>
        /// <returns></returns>
        protected bool GenerateCode()
        {
            m_assembly = null;

            #region Generate the code
            if (this.CodeGeneratorOptions.GenerateCodeString)
            {
                //CodeCompileUnit compileUnit = new CodeCompileUnit();
                //compileUnit.Namespaces.Add(m_codeNamespace);
                //CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
                //provider.GenerateCodeFromCompileUnit(compileUnit, sw, options);

                StringWriter         sw      = new StringWriter();
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.VerbatimOrder = true;
                GetCodeWriter().GenerateCodeFromNamespace(m_codeNamespace, sw, options);

                m_codeString = sw.ToString();
            }
            #endregion

            AddReferencedAssemblies();

            #region compile the generated code
            CompilerResults compilerResults = null;
            if (this.CodeGeneratorOptions.CompileAssembly)
            {
                CodeCompileUnit compileUnit = new CodeCompileUnit();
                compileUnit.Namespaces.Add(m_codeNamespace);
                CodeDomProvider provider = GetCodeWriter();
                compilerResults = provider.CompileAssemblyFromDom(m_compilerParameters, new CodeCompileUnit[] { compileUnit });

                // handle the errors if there are any
                if (compilerResults.Errors.HasErrors)
                {
                    m_compilerErrors.AddRange(compilerResults.Errors);

                    // check to see if there are fatal errors
                    bool fatalErrors = false;
                    foreach (CompilerError error in compilerResults.Errors)
                    {
                        if (!error.IsWarning)
                        {
                            fatalErrors = true;
                        }
                    }

                    #region trace the errors at this point
                    if (Trace.Switch.ShouldTrace(TraceEventType.Error))
                    {
                        string errorString = BuildCompileErrorString(compilerResults);
                        Trace.TraceError(errorString);
                    }
                    #endregion

                    #region throw exception if we've ben told to
                    if (this.ThrowExceptions && fatalErrors)
                    {
                        string errorString = BuildCompileErrorString(compilerResults);
                        throw new ApplicationException(errorString);
                    }
                    #endregion

                    return(!fatalErrors);
                }
            }

            if (compilerResults != null)
            {
                m_assembly = compilerResults.CompiledAssembly;
            }
            #endregion

            return(true);
        }
Ejemplo n.º 9
0
        // CompilerErrorCollection
        public void CompilerErrorCollectionExample()
        {
            //<Snippet1>
            //<Snippet2>
            // Creates an empty CompilerErrorCollection.
            CompilerErrorCollection collection = new CompilerErrorCollection();

            //</Snippet2>

            //<Snippet3>
            // Adds a CompilerError to the collection.
            collection.Add(new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            //</Snippet3>

            //<Snippet4>
            // Adds an array of CompilerError objects to the collection.
            CompilerError[] errors = { new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"), new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text") };
            collection.AddRange(errors);

            // Adds a collection of CompilerError objects to the collection.
            CompilerErrorCollection errorsCollection = new CompilerErrorCollection();

            errorsCollection.Add(new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            errorsCollection.Add(new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            collection.AddRange(errorsCollection);
            //</Snippet4>

            //<Snippet5>
            // Tests for the presence of a CompilerError in the
            // collection, and retrieves its index if it is found.
            CompilerError testError = new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text");
            int           itemIndex = -1;

            if (collection.Contains(testError))
            {
                itemIndex = collection.IndexOf(testError);
            }
            //</Snippet5>

            //<Snippet6>
            // Copies the contents of the collection, beginning at index 0,
            // to the specified CompilerError array.
            // 'errors' is a CompilerError array.
            collection.CopyTo(errors, 0);
            //</Snippet6>

            //<Snippet7>
            // Retrieves the count of the items in the collection.
            int collectionCount = collection.Count;

            //</Snippet7>

            //<Snippet8>
            // Inserts a CompilerError at index 0 of the collection.
            collection.Insert(0, new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            //</Snippet8>

            //<Snippet9>
            // Removes the specified CompilerError from the collection.
            CompilerError error = new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text");

            collection.Remove(error);
            //</Snippet9>

            //<Snippet10>
            // Removes the CompilerError at index 0.
            collection.RemoveAt(0);
            //</Snippet10>
            //</Snippet1>
        }