Exemplo n.º 1
0
 /// <summary>
 /// This function is called on every recompilation to discard all previous results
 /// </summary>
 private void Reset()
 {
     _compilerErrorColl = null;
     _outputSettings = null;
     _qil = null;
     _command = null;
 }
Exemplo n.º 2
0
 public GenericConstructionChecker(TypeSystemServices tss, Node constructionNode, TypeReferenceCollection argumentNodes, CompilerErrorCollection errorCollection)
 {
     _tss = tss;
     _constructionNode = constructionNode;
     _argumentNodes = argumentNodes;
     _errors = errorCollection;
 }
Exemplo n.º 3
0
 public GenericConstructionChecker(TypeSystemServices tss, Node constructionNode, IType[] typeArguments, CompilerErrorCollection errorCollection)
 {
     _tss = tss;
     _constructionNode = constructionNode;
     _typeArguments = typeArguments;
     _errors = errorCollection;
 }
Exemplo n.º 4
0
    /// <summary>
    /// Compiles a method body of C# script, wrapped in a basic void-returning method.
    /// </summary>
    /// <param name="methodText">The text of the script to place inside a method.</param>
    /// <param name="errors">The compiler errors and warnings from compilation.</param>
    /// <param name="methodIfSucceeded">The compiled method if compilation succeeded.</param>
    /// <returns>True if compilation was a success, false otherwise.</returns>
    public static bool CompileCSharpImmediateSnippet(string methodText, out CompilerErrorCollection errors, out MethodInfo methodIfSucceeded)
    {
        // wrapper text so we can compile a full type when given just the body of a method
        string methodScriptWrapper = @"
        using UnityEngine;
        using UnityEditor;
        using System.Collections;
        using System.Collections.Generic;
        using System.Text;
        using System.Xml;
        using System.Linq;
        public static class CodeSnippetWrapper
        {{
        public static void PerformAction()
        {{
        {0};
        }}
        }}";

        // default method to null
        methodIfSucceeded = null;

        // compile the full script
        Assembly assembly;
        if (CompileCSharpScript(string.Format(methodScriptWrapper, methodText), out errors, out assembly))
        {
            // if compilation succeeded, we can use reflection to get the method and pass that back to the user
            methodIfSucceeded = assembly.GetType("CodeSnippetWrapper").GetMethod("PerformAction", BindingFlags.Static | BindingFlags.Public);
            return true;
        }

        // compilation failed, caller has the errors, return false
        return false;
    }
Exemplo n.º 5
0
		private static void ThrowErrors(CompilerErrorCollection compilerErrorCollection)
		{
			StringBuilder sb = new StringBuilder();
			foreach (CompilerError e in compilerErrorCollection)
			{
				sb.AppendLine(e.ErrorText);
			}
			throw new ProxyGenerationException("Compiler errors:\n" + sb.ToString());
		}
Exemplo n.º 6
0
    /// <summary>
    /// Compiles a C# script as if it were a file in your project.
    /// </summary>
    /// <param name="scriptText">The text of the script.</param>
    /// <param name="errors">The compiler errors and warnings from compilation.</param>
    /// <param name="assemblyIfSucceeded">The compiled assembly if compilation succeeded.</param>
    /// <returns>True if compilation was a success, false otherwise.</returns>
    public static bool CompileCSharpScript(string scriptText, out CompilerErrorCollection errors, out Assembly assemblyIfSucceeded)
    {
        var codeProvider = new CSharpCodeProvider();
        var compilerOptions = new CompilerParameters();

        // we want a DLL and we want it in memory
        compilerOptions.GenerateExecutable = false;
        compilerOptions.GenerateInMemory = true;

        // add references to all currently loaded assemblies
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            compilerOptions.ReferencedAssemblies.Add(assembly.Location);
        }

        // default to null output parameters
        errors = null;
        assemblyIfSucceeded = null;

        // compile the assembly from the source script text
        CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerOptions, scriptText);

        // store the errors for the caller. even on successful compilation, we may have warnings.
        errors = result.Errors;

        // see if any errors are actually errors. if so return false
        foreach (CompilerError e in errors)
        {
            if (!e.IsWarning)
            {
                return false;
            }
        }

        // otherwise we pass back the compiled assembly and return true
        assemblyIfSucceeded = result.CompiledAssembly;
        return true;
    }
Exemplo n.º 7
0
        public string[] GetCompileErrors()
        {
            CompilerErrorCollection errors = this.results.Errors;
            int num  = 0;
            int num2 = 0;

            foreach (CompilerError error in errors)
            {
                if (error.IsWarning)
                {
                    num2++;
                }
                else
                {
                    num++;
                }
            }
            string[] strArray = new string[1 + (2 * num)];
            strArray[0] = "COMPILE";
            int num3 = 1;

            foreach (CompilerError error2 in errors)
            {
                if (!error2.IsWarning)
                {
                    strArray[num3++] = error2.ErrorText;
                    strArray[num3++] = error2.Line.ToString();
                    Console.WriteLine("Line {0}: {1}", strArray[num3 - 1], strArray[num3 - 2]);
                }
                else
                {
                    Console.WriteLine("Warning: Line {0}: {1}", error2.Line.ToString(), error2.ErrorText);
                }
            }
            return(strArray);
        }
Exemplo n.º 8
0
        internal static void LogCompileErrors(CompilerErrorCollection errors)
        {
            Directory.CreateDirectory(LogPath);
            string        file         = LogPath + Path.DirectorySeparatorChar + "Compile Errors.txt";
            CompilerError displayError = null;

            using (StreamWriter writer = File.CreateText(file))
            {
                foreach (CompilerError error in errors)
                {
                    writer.WriteLine(error.ToString());
                    writer.WriteLine();
                    if (!error.IsWarning && displayError == null)
                    {
                        displayError = error;
                    }
                }
            }
            string errorHeader = "An error ocurred while compiling a mod." + Environment.NewLine + Environment.NewLine;

            Interface.errorMessage.SetMessage(errorHeader + displayError);
            Interface.errorMessage.SetGotoMenu(Interface.modSourcesID);
            Interface.errorMessage.SetFile(file);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates the CompilerException instance from the specified compiler errors errors.
        /// </summary>
        /// <param name="Errors">The compiler errors.</param>
        /// <param name="hideCompilerWarnings">if set to <c>true</c> hide compiler warnings.</param>
        /// <returns></returns>
        public static CompilerException Create(CompilerErrorCollection Errors, bool hideCompilerWarnings)
        {
            StringBuilder compileErr = new StringBuilder();

            foreach (CompilerError err in Errors)
            {
                if (err.IsWarning && hideCompilerWarnings)
                {
                    continue;
                }

                //compileErr.Append(err.ToString());
                compileErr.Append(err.FileName);
                compileErr.Append("(");
                compileErr.Append(err.Line);
                compileErr.Append(",");
                compileErr.Append(err.Column);
                compileErr.Append("): ");
                if (err.IsWarning)
                {
                    compileErr.Append("warning ");
                }
                else
                {
                    compileErr.Append("error ");
                }
                compileErr.Append(err.ErrorNumber);
                compileErr.Append(": ");
                compileErr.Append(err.ErrorText);
                compileErr.Append(Environment.NewLine);
            }
            CompilerException retval = new CompilerException(compileErr.ToString());

            retval.Data.Add("Errors", Errors);
            return(retval);
        }
Exemplo n.º 10
0
 private void btnGenerateViews_Click(object sender, RoutedEventArgs e)
 {
     if (dataGridTables.SelectedItems.Count > 0)
     {
         CompilerErrorCollection errors = null;
         foreach (DataRowView selectedItem in dataGridTables.SelectedItems)
         {
             errors = ProcessTemplate(@"C:\practice\T4TemplateDemo\T4TemplateDemo\SQLViews.tt", selectedItem.Row[1].ToString(), selectedItem.Row[2].ToString());
             if (errors.HasErrors)
             {
                 MessageBox.Show("Error occured while processing template", "Code Generator", MessageBoxButton.OK);
                 break;
             }
         }
         if (errors != null && !errors.HasErrors)
         {
             MessageBox.Show("SQL Views Created!", "Code Generator", MessageBoxButton.OK);
         }
     }
     else
     {
         MessageBox.Show("Please select atleast one table.", "Select table(s).", MessageBoxButton.OK);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Compiles a C# script as if it were a file in your project.
        /// </summary>
        /// <param name="scriptText">The text of the script.</param>
        /// <param name="errors">The compiler errors and warnings from compilation.</param>
        /// <param name="assemblyIfSucceeded">The compiled assembly if compilation succeeded.</param>
        /// <returns>True if compilation was a success, false otherwise.</returns>
        public static bool CompileCSharpScript(string scriptText, out CompilerErrorCollection errors, out Assembly assemblyIfSucceeded)
        {
            var codeProvider    = new CSharpCodeProvider();
            var compilerOptions = new CompilerParameters();

            // We want a DLL and we want it in memory
            compilerOptions.GenerateExecutable = false;
            compilerOptions.GenerateInMemory   = true;

            // Add references for UnityEngine and UnityEditor DLLs
            compilerOptions.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);
            compilerOptions.ReferencedAssemblies.Add(typeof(EditorApplication).Assembly.Location);

            // Default to null output parameters
            errors = null;
            assemblyIfSucceeded = null;

            // Compile the assembly from the source script text
            CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerOptions, scriptText);

            // Store the errors for the caller. even on successful compilation, we may have warnings.
            errors = result.Errors;

            // See if any errors are actually errors. if so return false
            foreach (CompilerError e in errors)
            {
                if (!e.IsWarning)
                {
                    return(false);
                }
            }

            // Otherwise we pass back the compiled assembly and return true
            assemblyIfSucceeded = result.CompiledAssembly;
            return(true);
        }
Exemplo n.º 12
0
        private ObservableCollection <Problem> method_18(CompilerErrorCollection compilerErrorCollection_0, int int_14)
        {
            ObservableCollection <Problem> observableCollection = new ObservableCollection <Problem>();
            ObservableCollection <Problem> result;

            foreach (CompilerError compilerError in compilerErrorCollection_0)
            {
                Problem problem = new Problem();
                if (compilerError.ErrorText == "The name 'results' does not exist in the current context")
                {
                    problem.Description = "All queries must be assigned to a variable named \"results\"";
                    problem.ProblemType = RuleStatus.CompileError;
                    observableCollection.Add(problem);
                    result = observableCollection;
                    return(result);
                }
                problem.Description = compilerError.ErrorText;
                problem.LineNumber  = new int?(compilerError.Line - int_14);
                problem.ProblemType = RuleStatus.CompileError;
                observableCollection.Add(problem);
            }
            result = observableCollection;
            return(result);
        }
Exemplo n.º 13
0
        internal static void LogCompileErrors(CompilerErrorCollection errors)
        {
            string errorHeader = "An error ocurred while compiling a mod." + Environment.NewLine + Environment.NewLine;

            Console.WriteLine(errorHeader);
            Directory.CreateDirectory(LogPath);
            CompilerError displayError = null;

            using (var writer = File.CreateText(CompileErrorPath))
            {
                foreach (CompilerError error in errors)
                {
                    writer.WriteLine(error + Environment.NewLine);
                    Console.WriteLine(error);
                    if (!error.IsWarning && displayError == null)
                    {
                        displayError = error;
                    }
                }
            }
            Interface.errorMessage.SetMessage(errorHeader + displayError);
            Interface.errorMessage.SetGotoMenu(Interface.modSourcesID);
            Interface.errorMessage.SetFile(CompileErrorPath);
        }
Exemplo n.º 14
0
        /* convert shader-errors that come in the format of:
         * c:\self.demos\tooll2\n\a(58,12): error X3004: undeclared identifier 'col2'
         * c:\self.demos\tooll2\n\a(58,5): error X3080: 'PS': function must return a value
         **/
        protected CompilerErrorCollection ErrorsFromString(string errorString)
        {
            var errors           = new CompilerErrorCollection();
            var errorLinePattern = new Regex(@"\((\d+),(\d+)\): error\s*(\w+):\s*(.*?)\s*$");

            foreach (var line in errorString.Split('\n'))
            {
                var matches = errorLinePattern.Matches(line);
                if (matches.Count == 1)
                {
                    var    lineNumber   = int.Parse(matches[0].Groups[1].Value);
                    var    column       = int.Parse(matches[0].Groups[2].Value);
                    string errorCode    = matches[0].Groups[3].Value;
                    string errorMessage = matches[0].Groups[4].Value;

                    errors.Add(new CompilerError()
                    {
                        Column = column, ErrorNumber = errorCode, Line = lineNumber, ErrorText = errorMessage
                    });
                }
            }

            return(errors);
        }
Exemplo n.º 15
0
        private void SetUnitPriceExpression(string expression)
        {
            GridViewDataColumn      unitPriceColumn    = this.gridView.Columns["UnitPrice"];
            UnitPriceConverter      unitPriceConverter = unitPriceColumn.DataTypeConverter as UnitPriceConverter;
            CompilerErrorCollection compilerErrors     = unitPriceConverter.SetExpression(expression);

            if (!compilerErrors.HasErrors)
            {
                changedColumn = unitPriceColumn;
                return;
            }

            StringBuilder errorMessage = new StringBuilder();

            foreach (CompilerError error in compilerErrors)
            {
                errorMessage.AppendLine(error.ErrorText);
            }

            if (errorMessage.Length > 0)
            {
                RadMessageBox.Show(errorMessage.ToString(), "Expression Syntax Error", MessageBoxButtons.OK, RadMessageIcon.Error);
            }
        }
Exemplo n.º 16
0
        private CompilerErrorCollection Errors(ICompilable item, bool sourceHeader)
        {
            CompilerErrorCollection err = new CompilerErrorCollection();

            foreach (CompilerError e in item.CompilerResults.Errors)               // deep copy error collection
            {
                err.Add(new CompilerError(e.FileName, e.Line, e.Column, e.ErrorNumber, e.ErrorText));
            }
            for (int i = 0; i < err.Count; i++)               // adapt errors according to sourceHeader
            {
                if (err[i].Line < 0)
                {
                    if (sourceHeader)
                    {
                        err[i].Line = ErrorLine(item, sourceHeader, err[i].Line);
                    }
                }
                else if (sourceHeader)
                {
                    err.RemoveAt(i--);                                      // don't mark ordinary errors in SourceHeader.
                }
            }
            return(err);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Starts processing run.
 /// </summary>
 /// <param name="languageProvider">Target language provider.</param>
 /// <param name="templateContents">The contents of the template being processed</param>
 /// <param name="errors">colelction to report processing errors in</param>
 public override void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors)
 {
     if (languageProvider == null)
     {
         throw new ArgumentNullException("languageProvider");
     }
     base.StartProcessingRun(languageProvider, templateContents, errors);
     if (state != 0)
     {
         throw new InvalidOperationException(Resources.StartProcessingCallError);
     }
     state = ProcessorState.Started;
     languageCodeDomProvider = languageProvider;
     codeBuffer = new StringBuilder();
     preInitializationBuffer  = new StringBuilder();
     postInitializationBuffer = new StringBuilder();
 }
Exemplo n.º 18
0
        /// <summary>
        /// Parse a template file into blocks. Each block is of type boilerplate, directive,
        /// statement, classfeature or expression. Also puts position information (line/column
        /// number) for the block into each block.
        /// </summary>
        /// <param name="content">Template content.</param>
        /// <param name="fileName"></param>
        /// <param name="errors">Error collection to report errors to.</param>
        /// <returns>Name of template file.</returns>
        public static List <Block> ParseTemplateIntoBlocks(string content, string fileName, CompilerErrorCollection errors)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (errors == null)
            {
                throw new ArgumentNullException("errors");
            }
            List <Block>    list            = new List <Block>();
            MatchCollection matchCollection = templateParsingRegex.Matches(content);

            foreach (Match item in matchCollection)
            {
                Block block = new Block();
                Group group;
                if ((group = item.Groups["boilerplate"]).Success)
                {
                    block.Type = BlockType.BoilerPlate;
                }
                else if ((group = item.Groups["directive"]).Success)
                {
                    block.Type = BlockType.Directive;
                }
                else if ((group = item.Groups["classfeature"]).Success)
                {
                    block.Type = BlockType.ClassFeature;
                }
                else if ((group = item.Groups["expression"]).Success)
                {
                    block.Type = BlockType.Expression;
                }
                else if ((group = item.Groups["statement"]).Success)
                {
                    block.Type = BlockType.Statement;
                }
                if (group != null && group.Success)
                {
                    block.Text     = group.Value;
                    block.FileName = fileName;
                    list.Add(block);
                }
            }
            InsertPositionInformation(list);
            WarnAboutUnexpectedTags(list, errors);
            StripEscapeCharacters(list);
            CheckBlockSequence(list, errors);
            return(list);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Parse a directive block for the directive name and param-value pairs
        /// </summary>
        /// <param name="block"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        public static Directive ParseDirectiveBlock(Block block, CompilerErrorCollection errors)
        {
            if (block == null)
            {
                throw new ArgumentNullException("block");
            }
            if (errors == null)
            {
                throw new ArgumentNullException("errors");
            }
            if (!ValidateDirectiveString(block))
            {
                CompilerError compilerError = new CompilerError(block.FileName, block.StartLineNumber, block.StartColumnNumber, null, Resources.WrongDirectiveFormat);
                compilerError.IsWarning = false;
                errors.Add(compilerError);
                return(null);
            }
            MatchCollection             matchCollection = directiveParsingRegex.Matches(block.Text);
            string                      text            = null;
            Dictionary <string, string> dictionary      = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (Match item in matchCollection)
            {
                Group group;
                if ((group = item.Groups["name"]).Success)
                {
                    text = group.Value;
                }
                else
                {
                    string text2 = null;
                    string text3 = null;
                    if ((group = item.Groups["pname"]).Success)
                    {
                        text2 = group.Value;
                    }
                    if ((group = item.Groups["pvalue"]).Success)
                    {
                        text3 = group.Value;
                    }
                    if (text2 != null && text3 != null)
                    {
                        if (dictionary.ContainsKey(text2))
                        {
                            CompilerError compilerError2 = new CompilerError(block.FileName, block.StartLineNumber, block.StartColumnNumber, null, string.Format(CultureInfo.CurrentCulture, Resources.DuplicateDirectiveParameter, text2));
                            compilerError2.IsWarning = true;
                            errors.Add(compilerError2);
                        }
                        else
                        {
                            text3 = StripDirectiveEscapeCharacters(text3);
                            dictionary.Add(text2, text3);
                        }
                    }
                }
            }
            if (text != null)
            {
                return(new Directive(text, dictionary, block));
            }
            return(null);
        }
Exemplo n.º 20
0
 /// <summary>
 /// Log the compilation errors.
 /// </summary>
 /// <param name="errors">The errors.</param>
 public void LogErrors(CompilerErrorCollection errors)
 {
     _compilationErrors = errors;
 }
        protected virtual List <ValidationError> GetValidationErrorsFromCompilerErrors(CompilerErrorCollection compilerErrors)
        {
            var validationErrors = new List <ValidationError>();

            if (compilerErrors == null)
            {
                return(validationErrors);
            }

            for (int i = 0; i < compilerErrors.Count; i++)
            {
                CompilerError compilerError = compilerErrors[i];
                var           error         = ValidationError.CreateFromCompileError(compilerError);
                validationErrors.Add(error);
            }

            return(validationErrors);
        }
Exemplo n.º 22
0
 /// <summary>
 /// 记录错误信息
 /// The engine calls this method when it is done processing a text template to pass any errors that occurred to the host. The host can decide how to display them.
 /// 该引擎调用完成时,处理文本模板通过任何错误发生的主机此方法。主机可以决定如何显示它们。
 /// </summary>
 /// <param name="errors"></param>
 public void LogErrors(System.CodeDom.Compiler.CompilerErrorCollection errors)
 {
     _ErrorCollection = errors;
 }
Exemplo n.º 23
0
        public Assembly CreateAssembly(IList filenames, IList references)
        {
            string fileType = null;

            foreach (string filename in filenames)
            {
                string extension = Path.GetExtension(filename);
                if (fileType == null)
                {
                    fileType = extension;
                }
                else if (fileType != extension)
                {
                    throw new ArgumentException("All files in the file list must be of the same type.");
                }
            }


            compilerErrors = null;


            CodeDomProvider codeProvider = null;

            switch (fileType)
            {
            case ".cs":
                codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            case ".vb":
                codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            default:
                throw new InvalidOperationException("Script files must have a .cs, .vb, or .js extension, for C#, Visual Basic.NET, or JScript respectively.");
            }



            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.CompilerOptions         = "/target:library /optimize";
            compilerParams.GenerateExecutable      = false;
            compilerParams.GenerateInMemory        = true;
            compilerParams.IncludeDebugInformation = false;
            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");


            foreach (string reference in references)
            {
                if (!compilerParams.ReferencedAssemblies.Contains(reference))
                {
                    compilerParams.ReferencedAssemblies.Add(reference);
                }
            }


            CompilerResults results = codeProvider.CompileAssemblyFromFile(
                compilerParams, (string[])ArrayList.Adapter(filenames).ToArray(typeof(string)));


            if (results.Errors.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError item in results.Errors)
                {
                    sb.AppendFormat("{0} line:{1}   {2}\r\n", item.FileName, item.Line, item.ErrorText);
                }
                compilerErrors = results.Errors;
                throw new Exception(
                          "Compiler error(s)\r\n" + sb.ToString());
            }

            Assembly createdAssembly = results.CompiledAssembly;

            return(createdAssembly);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Checks whether a given set of arguments can be used to construct a generic type or method from a specified definition.
        /// </summary>
        public bool CheckGenericConstruction(Node node, IEntity definition, IType[] argumentTypes, CompilerErrorCollection errors)
        {
            GenericConstructionChecker checker = new GenericConstructionChecker(
                TypeSystemServices, node, argumentTypes, Errors);

            return !(
                checker.NotGenericDefinition(definition) ||
                checker.IncorrectGenerity(definition) ||
                checker.ViolatesParameterConstraints(definition));
        }
Exemplo n.º 25
0
		public void ReportErrors(CompilerErrorCollection targetErrorCollection)
		{
			targetErrorCollection.Extend(Errors);
		}
Exemplo n.º 26
0
 public CompilationErrorsException(CompilerErrorCollection errors)
     : base(errors.ToString())
 {
     _errors = errors;
 }
Exemplo n.º 27
0
        /// <summary>
        /// Checks whether a given set of arguments can be used to construct a generic type or method from a specified definition.
        /// </summary>
        public bool CheckGenericConstruction(IEntity definition, Node node, TypeReferenceCollection arguments, CompilerErrorCollection errors)
        {
            // Ensure definition is a valid entity
            if (definition == null || TypeSystemServices.IsError(definition))
            {
                return false;
            }

            // Ensure definition really is a generic definition
            GenericConstructionChecker checker = new GenericConstructionChecker(
                TypeSystemServices, node, arguments, Errors);

            return !(
                checker.NotGenericDefinition(definition) ||
                checker.IncorrectGenerity(definition) ||
                checker.ViolatesParameterConstraints(definition));
        }
Exemplo n.º 28
0
        public static void ConvertCodeSourceStreamToAssemblyFile(ArrayList outCodeStreamList, string assemblyPath, string strongNameFilename)
        {
            CompilerResults results = null;
            string          path    = "__Sn.cs";

            try
            {
                if (strongNameFilename != null)
                {
                    if (assemblyPath != null)
                    {
                        int num = assemblyPath.LastIndexOf(@"\");
                        if (num > 0)
                        {
                            path = assemblyPath.Substring(0, num + 1) + path;
                        }
                    }
                    FileStream   stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
                    StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false, true));
                    writer.WriteLine("// CLR Remoting Autogenerated Key file (to create a key file use: sn -k tmp.key)");
                    writer.WriteLine("using System;");
                    writer.WriteLine("using System.Reflection;");
                    writer.WriteLine("[assembly: AssemblyKeyFile(@\"" + strongNameFilename + "\")]");
                    writer.WriteLine("[assembly: AssemblyVersion(@\"1.0.0.1\")]");
                    writer.Flush();
                    writer.Close();
                    stream.Close();
                    outCodeStreamList.Add(path);
                }
                string[] sources   = new string[outCodeStreamList.Count];
                string[] strArray2 = new string[outCodeStreamList.Count];
                int      num2      = 0;
                for (int i = 0; i < outCodeStreamList.Count; i++)
                {
                    Stream stream2;
                    bool   flag = false;
                    if (outCodeStreamList[i] is string)
                    {
                        string str2 = (string)outCodeStreamList[i];
                        strArray2[i] = str2;
                        stream2      = System.IO.File.OpenRead(str2);
                        flag         = true;
                    }
                    else
                    {
                        if (!(outCodeStreamList[i] is Stream))
                        {
                            throw new RemotingException(CoreChannel.GetResourceString("Remoting_UnknownObjectInCodeStreamList"));
                        }
                        stream2      = (Stream)outCodeStreamList[i];
                        strArray2[i] = "Stream" + num2++;
                    }
                    sources[i] = new StreamReader(stream2).ReadToEnd();
                    if (flag)
                    {
                        stream2.Close();
                    }
                }
                string   outputName    = assemblyPath;
                string[] assemblyNames = new string[] { "System.dll", "System.Runtime.Remoting.dll", "System.Data.dll", "System.Xml.dll", "System.Web.Services.dll" };
                if (sources.Length > 0)
                {
                    CodeDomProvider    provider = new CSharpCodeProvider();
                    CompilerParameters options  = new CompilerParameters(assemblyNames, outputName, true)
                    {
                        GenerateExecutable = false
                    };
                    results = provider.CompileAssemblyFromSource(options, sources);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }
            finally
            {
                System.IO.File.Delete(path);
            }
            if (results.Errors.HasErrors)
            {
                CompilerErrorCollection errors = results.Errors;
                if (errors.Count > 0)
                {
                    foreach (CompilerError error in errors)
                    {
                        Console.WriteLine(error.ToString());
                    }
                }
            }
        }
	public CompilerErrorCollection(CompilerErrorCollection value) {}
        /// <summary>
        /// Preprocesses the input from <paramref name="input"/> and writes the output to <paramref name="output"/>
        /// </summary>
        /// <param name="input">The input source to preprocess</param>
        /// <param name="output">The output target for the post-processed <paramref name="input"/></param>
        /// <param name="args">The arguments to pass to the T4 code. Accessed through "Arguments" in the code. If null, an empty dictionary will be created</param>
        /// <param name="lang">The language to use for the T4 code - defaults to C#</param>
        public static void Preprocess(TextReader input, TextWriter output, IDictionary <string, object> args = null, string lang = "cs")
        {
            CompilerErrorCollection errors = null;
            // TODO: Add error handling, even though output codegen errors shouldn't occur with this
            var method = new CodeMemberMethod();

            method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            method.Name       = "Preprocess";
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(TextWriter), "Response"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IDictionary <string, object>), "Arguments"));
            int cur;
            var more = true;

            while (more)
            {
                var text = _ReadUntilStartContext(input);
                if (0 < text.Length)
                {
                    method.Statements.Add(new CodeMethodInvokeExpression(
                                              new CodeArgumentReferenceExpression("Response"),
                                              "Write",
                                              new CodePrimitiveExpression(text)));
                }
                cur = input.Read();
                if (-1 == cur)
                {
                    more = false;
                }
                else if ('=' == cur)
                {
                    method.Statements.Add(new CodeMethodInvokeExpression(
                                              new CodeArgumentReferenceExpression("Response"),
                                              "Write",
                                              new CodeSnippetExpression(_ReadUntilEndContext(-1, input))));
                }
                else
                {
                    method.Statements.Add(new CodeSnippetStatement(_ReadUntilEndContext(cur, input)));
                }
            }
            method.Statements.Add(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("Response"), "Flush"));
            var cls = new CodeTypeDeclaration("Preprocessor");

            cls.TypeAttributes = TypeAttributes.Public;
            cls.IsClass        = true;
            cls.Members.Add(method);
            var ns = new CodeNamespace();

            ns.Types.Add(cls);
            var cu = new CodeCompileUnit();

            cu.Namespaces.Add(ns);
            var prov = CodeDomProvider.CreateProvider(lang);
            var opts = new CompilerParameters();
            var outp = prov.CompileAssemblyFromDom(opts, cu);

            if (outp.Errors.HasErrors)
            {
                var sb = new StringBuilder();
                foreach (CompilerError err in outp.Errors)
                {
                    if (!err.IsWarning)
                    {
                        sb.AppendLine(err.ErrorText);
                    }
                }
                throw new InvalidOperationException(sb.ToString());
            }
            var asm = outp.CompiledAssembly;

            if (null == args)
            {
                args = new Dictionary <string, object>();
            }
            var ran = false;

            if (null != asm)
            {
                var t = asm.GetType("Preprocessor");
                var m = t.GetMethod("Preprocess");
                if (null != m)
                {
                    try
                    {
                        m.Invoke(null, new object[] { output, args });
                        ran = true;
                    }
                    catch (TargetInvocationException tex)
                    {
                        throw tex.InnerException;
                    }
                }
            }
            if (!ran)
            {
                errors = outp.Errors;
                if (0 < errors.Count)
                {
                    CompilerError err = errors[0];
                    throw new InvalidOperationException(err.ErrorText);
                }
            }
        }
	public void AddRange(CompilerErrorCollection value) {}
Exemplo n.º 32
0
        public static void ConvertCodeSourceStreamToAssemblyFile(ArrayList outCodeStreamList, String assemblyPath, String strongNameFilename)
        {
#if FEATURE_PAL
            throw new NotImplementedException("Not Implemented in Rotor");
#else
            Util.Log("MetaData.ConvertCodeSourceStreamToAssemblyFile " + assemblyPath);
            CompilerResults results = null;


            String stfilename = "__Sn.cs";
            try
            {
                if (strongNameFilename != null)
                {
                    // Create strong name file with assembly attribute
                    if (assemblyPath != null)
                    {
                        int index = assemblyPath.LastIndexOf("\\");
                        if (index > 0)
                        {
                            stfilename = assemblyPath.Substring(0, index + 1) + stfilename;
                        }
                    }
                    FileStream   fs       = new FileStream(stfilename, FileMode.Create, FileAccess.ReadWrite);
                    StreamWriter fsWriter = new StreamWriter(fs, new UTF8Encoding(false, true));
                    fsWriter.WriteLine("// CLR Remoting Autogenerated Key file (to create a key file use: sn -k tmp.key)");
                    fsWriter.WriteLine("using System;");
                    fsWriter.WriteLine("using System.Reflection;");
                    fsWriter.WriteLine("[assembly: AssemblyKeyFile(@\"" + strongNameFilename + "\")]");
                    fsWriter.WriteLine("[assembly: AssemblyVersion(@\"1.0.0.1\")]");
                    fsWriter.Flush();
                    fsWriter.Close();
                    fs.Close();
                    outCodeStreamList.Add(stfilename);
                    Util.Log("MetaData.ConvertCodeSourceStreamToAssemblyFile key file " + stfilename);
                }

                String[] sourceTexts     = new String[outCodeStreamList.Count];
                String[] sourceTextNames = new String[outCodeStreamList.Count];

                int streamCount = 0; // used for naming sourceTexts streams

                for (int item = 0; item < outCodeStreamList.Count; item++)
                {
                    Stream inputStream;
                    bool   close = false;

                    if (outCodeStreamList[item] is String)
                    {
                        // it's a file
                        String filename = (String)outCodeStreamList[item];
                        sourceTextNames[item] = (String)filename;
                        Util.Log("MetaData.ConvertCodeSourceStreamToAssemblyFile  filename " + filename);
                        inputStream = File.OpenRead(filename);
                        close       = true;
                    }
                    else if (outCodeStreamList[item] is Stream)
                    {
                        // it's a stream
                        inputStream           = (Stream)outCodeStreamList[item];
                        sourceTextNames[item] = "Stream" + (streamCount++);
                    }
                    else
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_UnknownObjectInCodeStreamList"));
                    }

                    StreamReader streamReader = new StreamReader(inputStream);
                    sourceTexts[item] = streamReader.ReadToEnd();

                    if (true == close)
                    {
                        inputStream.Close();
                    }
                }

                String target = assemblyPath;

                String[] imports = new String[5];
                imports[0] = "System.dll";
                imports[1] = "System.Runtime.Remoting.dll";
                imports[2] = "System.Data.dll";
                imports[3] = "System.Xml.dll";
                imports[4] = "System.Web.Services.dll";

                if (sourceTexts.Length > 0)
                {
                    CodeDomProvider    csharpCompiler = new CSharpCodeProvider();
                    CompilerParameters compileParams  = new CompilerParameters(imports, target, true);
                    compileParams.GenerateExecutable = false;          // target:library
                    results = csharpCompiler.CompileAssemblyFromSource(compileParams, sourceTexts);
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally {
                File.Delete(stfilename);
            }

            if (results.Errors.HasErrors)
            {
                CompilerErrorCollection errors = results.Errors;
                if (errors.Count > 0)
                {
                    foreach (CompilerError error in errors)
                    {
                        Console.WriteLine(error.ToString());
                    }
                }
            }
#endif //!FEATURE_PAL
        }
 public virtual void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors)
 {
     if (languageProvider == null)
     {
         throw new ArgumentNullException("languageProvider");
     }
 }
Exemplo n.º 34
0
 public void LogErrors(CompilerErrorCollection errors)
 {
     this.errorCollection = errors;
 }
Exemplo n.º 35
0
 /// <summary>
 /// Begin a round of directive processing
 /// </summary>
 /// <param name="languageProvider"></param>
 /// <param name="templateContents">the contents of the template being processed</param>\
 /// <param name="errors">collection to report processing errors in</param>
 public virtual void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors)
 {
     Errors = errors;
 }
Exemplo n.º 36
0
 public static RunResults CompilationFailed(CompilFailure reason, CompilerErrorCollection errors)
 {
     return(new RunResults(false, false, reason, errors));
 }
Exemplo n.º 37
0
 internal ErrorTrap(ConverterSettings settings)
 {
     this.errors   = settings.Errors;
     this.fileName = settings.FileName;
 }
Exemplo n.º 38
0
 public static List <Block> ParseTemplateIntoBlocks(string content, CompilerErrorCollection errors)
 {
     return(ParseTemplateIntoBlocks(content, "", errors));
 }
Exemplo n.º 39
0
        //---------------------------------------------------------------
        #endregion
        //---------------------------------------------------------------

        //---------------------------------------------------------------
        #region Initialisation
        //---------------------------------------------------------------
        /// <summary>
        /// scripting exception taking className and collection of CompilerErrors as parameters
        /// </summary>
        /// <param name="className">name of compiled class</param>
        /// <param name="errors">collection of CompilerErrors</param>
        public CompilerErrorException(string className, CompilerErrorCollection errors)
        {
            this.className = className;
            this.errors    = errors;
        }
Exemplo n.º 40
0
 //The engine calls this method when it is done processing a text
 //template to pass any errors that occurred to the host.
 //The host can decide how to display them.
 //---------------------------------------------------------------------
 public void LogErrors(CompilerErrorCollection errors)
 {
     errorsValue = errors;
 }
 public override void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors)
 {
     base.StartProcessingRun(languageProvider, templateContents, errors);
     this.provider = languageProvider;
     //HACK: Mono as of 2.10.2 doesn't implement GenerateCodeFromMember
     if (Type.GetType("Mono.Runtime") != null)
     {
         useMonoHack = true;
     }
     if (languageProvider is Microsoft.CSharp.CSharpCodeProvider)
     {
         isCSharp = true;
     }
     postStatements.Clear();
     members.Clear();
 }
Exemplo n.º 42
0
 void ITextTemplatingEngineHost.LogErrors(CompilerErrorCollection errors)
 {
     this.errors.AddRange(errors);
 }
Exemplo n.º 43
0
 private void CompileXsltToQil(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
 {
     _compilerErrorColl = new Compiler(settings, _enableDebug, null).Compile(stylesheet, stylesheetResolver, out _qil);
 }