Add() публичный Метод

public Add ( CompilerError value ) : int
value CompilerError
Результат int
Пример #1
0
        public override CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames)
        {
            var units = new CodeCompileUnit[fileNames.Length];
            var errors = new CompilerErrorCollection();
            var syntax = new Parser(options);

            for (int i = 0; i < fileNames.Length; i++)
            {
                try
                {
                    units[i] = syntax.Parse(new StreamReader(fileNames[i]), fileNames[i]);
                }
            #if !DEBUG
                catch (ParseException e)
                {
                    errors.Add(new CompilerError(e.Source, e.Line, 0, e.Message.GetHashCode().ToString(), e.Message));
                }
                catch (Exception e)
                {
                    errors.Add(new CompilerError { ErrorText = e.Message });
                }
            #endif
                finally
                {
                }
            }

            var results = CompileAssemblyFromDom(options, units);
            results.Errors.AddRange(errors);

            return results;
        }
		private void HandleException(Exception ex, ProjectFile file, SingleFileCustomToolResult result)
		{
			if (ex is SpecFlowParserException)
			{
				SpecFlowParserException sfpex = (SpecFlowParserException) ex;
			                
				if (sfpex.ErrorDetails == null || sfpex.ErrorDetails.Count == 0)
				{
					result.UnhandledException = ex;
				}
				else
				{
					var compilerErrors = new CompilerErrorCollection();
					
					foreach (var errorDetail in sfpex.ErrorDetails)
					{
						var compilerError = new CompilerError(file.Name, errorDetail.ForcedLine, errorDetail.ForcedColumn, "0", errorDetail.Message);
						compilerErrors.Add(compilerError);
					}
							
					result.Errors.AddRange(compilerErrors);
				}
			}
			else
			{
				result.UnhandledException = ex;
			}
		}
Пример #3
0
            public override void Done(CompilerErrorCollection result)
            {
                if (!FileSystemHelper.FileCompare(TempFilePath, FilePath))
                {
                    string message = String.Format("Error during file generation. The target file '{0}' is read-only, but different from the transformation result. This problem can be a sign of an inconsistent source code package. Compile and check-in the current version of the file from the development environment or remove the read-only flag from the generation result. To compile a solution that contains messaging project on a build server, you can also exclude the messaging project from the build-server solution or set the <OverwriteReadOnlyFiles> msbuild project parameter to 'true' in the messaging project file.", 
                        Path.GetFullPath(FilePath));
                    result.Add(new CompilerError(String.Empty, 0, 0, null, message));
                }

                base.Done(result);
            }
 internal static void LogicalSetData(string name, object value,
                                     System.CodeDom.Compiler.CompilerErrorCollection errors)
 {
     //FIXME: CallContext.LogicalSetData not implemented in Mono
     try {
         System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(name, value);
     } catch (NotImplementedException) {
         errors.Add(new System.CodeDom.Compiler.CompilerError(
                        null, -1, -1, null,
                        "Could not set " + name + " - CallContext.LogicalSetData not implemented in this Mono version"
                        )
         {
             IsWarning = true
         });
     }
 }
Пример #5
0
        /// <summary>
        /// Creates an Assembly from DynamicAssembly definition
        /// </summary>
        /// <param name="assemblyDefinition">assembly description</param>
        /// <returns>result with assembly or error info</returns>
        public static CompileResult CompileDynamicAssembly(DynamicAssembly assemblyDefinition)
        {
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters compilerParameters = new CompilerParameters();
            compilerParameters.CompilerOptions = "/t:library /platform:anycpu /lib:" + "\"" + 
                (String.IsNullOrWhiteSpace(assemblyDefinition.ReferencesPath) ? GetCurrentPath() : assemblyDefinition.ReferencesPath) + "\"";
            compilerParameters.IncludeDebugInformation = false;
            //compilerParameters.OutputAssembly = assemblyDefinition.Name;
            compilerParameters.GenerateInMemory = true;
            compilerParameters.GenerateExecutable = false;   
            
            foreach (var item in assemblyDefinition.References)
                compilerParameters.ReferencedAssemblies.Add(item);

            List<string> codeModules = new List<string>();
            foreach (DynamicClass item in assemblyDefinition.Classes)
            {
                string code = DynamicClass.Template;
                code = DynamicClass.AddUsingsToTemplate(item, code);
                code = DynamicClass.AddInterfacesToTemplate(item, code);
                code = DynamicClass.AddNamespaceToTemplate(String.IsNullOrWhiteSpace(item.Namespace) ? assemblyDefinition.Name : item.Namespace, code);
                code = DynamicClass.AddNameToTemplate(item, code);
                code = DynamicClass.AddPropertiesToTemplate(item, code);
                code = DynamicClass.AddMethodsToTemplate(item, code);
                codeModules.Add(code);
            }

            foreach (DynamicCustomClass item in assemblyDefinition.CustomClasses)
                codeModules.Add(item.Code);

            // we dont allow empty class definitions(fun fact: its okay for the c# compiler)
            foreach (DynamicCustomClass item in assemblyDefinition.CustomClasses)
            {
                if (String.IsNullOrWhiteSpace(item.Code))
                {
                    CompilerErrorCollection collection = new CompilerErrorCollection();
                    CompilerError customError = new CompilerError("CustomClass", 0, 0, "Custom", "Unable to compile an empty code module.");
                    collection.Add(customError);
                    return new CompileResult(codeModules.ToArray(), collection, null);
                }
            }

            CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(compilerParameters, codeModules.ToArray());
            codeDomProvider.Dispose();

            return new CompileResult(codeModules.ToArray(), compilerResults.Errors, compilerResults.Errors.Count > 0 ? null : compilerResults.CompiledAssembly);
        }
Пример #6
0
		public void Constructor0_Deny_Unrestricted ()
		{
			CompilerErrorCollection coll = new CompilerErrorCollection ();
			Assert.AreEqual (0, coll.Add (ce), "Add");
			Assert.AreSame (ce, coll[0], "this[int]");
			coll[0] = ce;
			coll.CopyTo (array, 0);
			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 = false;
			Assert.IsTrue (coll.HasErrors, "HasErrors");
			Assert.IsFalse (coll.HasWarnings, "HasWarnings");
		}
Пример #7
0
		public string GenerateCode (out CompilerErrorCollection errors)
		{
			errors = new CompilerErrorCollection ();

			// Create the engine
			RazorTemplateEngine engine = new RazorTemplateEngine(this);

			// Generate code
			GeneratorResults results = null;
			try
			{
				Stream stream = File.OpenRead(_fullPath);
				using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
				{
					results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath);
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}

			// Output errors
			foreach (RazorError error in results.ParserErrors) {
				errors.Add (new CompilerError (FullPath, error.Location.LineIndex + 1, error.Location.CharacterIndex + 1, null, error.Message));
			}

			try
			{
				using (StringWriter writer = new StringWriter()) {
					//Generate the code
					writer.WriteLine("#pragma warning disable 1591");
					_codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, _codeGeneratorOptions);
					writer.WriteLine("#pragma warning restore 1591");
					return writer.ToString();
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}
		}
		public string GenerateCode (out CompilerErrorCollection errors)
		{
			errors = new CompilerErrorCollection ();

			var engine = new RewritingRazorTemplateEngine (this, new PreprocessedAttributeRewriter ());

			// Generate code
			GeneratorResults results;
			try {
				Stream stream = File.OpenRead (FullPath);
				using (var reader = new StreamReader (stream, Encoding.Default, true)) {
					results = engine.GenerateCode (reader, DefaultClassName, DefaultNamespace, FullPath);
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}

			// Output errors
			foreach (RazorError error in results.ParserErrors) {
				errors.Add (new CompilerError (FullPath, error.Location.LineIndex + 1, error.Location.CharacterIndex + 1, null, error.Message));
			}

			try {
				using (var writer = new StringWriter ()) {
					writer.WriteLine ("#pragma warning disable 1591");
					_codeDomProvider.GenerateCodeFromCompileUnit (results.GeneratedCode, writer, codeGeneratorOptions);
					writer.WriteLine ("#pragma warning restore 1591");
					string s = writer.ToString ();
					return MakeLineDirectivePathsRelative (Path.GetDirectoryName (FullPath), s);
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}
		}
        public static void OnTransformationEnded(TextTransformation transformation)
        {
            try
            {
                if (transformation == null)
                {
                    throw new ArgumentNullException("transformation");
                }

                if (TransformationContext.transformation != null && !TransformationContext.Errors.HasErrors)
                {
                    //Update the files in the default AppDomain to avoid remoting errors on Database projects
                    //BindingFlags invokeInternalStaticMethod = BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic;
                    //AppDomain defaultDomain = (AppDomain)typeof(AppDomain).InvokeMember("GetDefaultDomain", invokeInternalStaticMethod, null, null, null, CultureInfo.InvariantCulture);

                    //var bd1 = defaultDomain.BaseDirectory;

                    //var setup = new AppDomainSetup();
                    //setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                    //AppDomain serverAppDomain = AppDomain.CreateDomain("ServerAppDomain", null, setup);

                    //var udf = TransformationContext.outputManager;
                    //defaultDomain.DoCallBack(udf.UpdateFiles);

                    OutputProcessor.Host = Host;
                    outputManager.UpdateFiles();
                }

                TransformationContext.transformation = null;
                TransformationContext.outputManager = null;
                TransformationContext.project = null;
                TransformationContext.projectItem = null;
                TransformationContext.dte = null;

                if (TransformationContext.TransformationEnded != null)
                {
                    TransformationContext.TransformationEnded(null, EventArgs.Empty);
                }
            }
            catch (TransformationException e)
            {
                // Display expected errors in the Error List window without the call stack
                CompilerErrorCollection errors = new CompilerErrorCollection();
                CompilerError error = new CompilerError();
                error.ErrorText = e.Message;
                error.FileName = Host.TemplateFile;
                errors.Add(error);
                TransformationContext.Host.LogErrors(errors);
            }
            finally
            {
                DestroyTraceListener();
            }
        }
Пример #10
0
		public bool Run(string sourceCode, out CompilerErrorCollection compilationErrors)
		{
			bool compilationSucceeded = true;
			compilationErrors = new CompilerErrorCollection();
			CSharpCodeProvider provider = new CSharpCodeProvider();

			// Build the parameters for source compilation.
			CompilerParameters cp = new CompilerParameters();
			cp.TreatWarningsAsErrors = false;

			// Add assembly references.
			cp.ReferencedAssemblies.AddRange(DEFAULT_ASSEMBLIES);
			//cp.ReferencedAssemblies.AddRange(ReferencedAssemblies.ToArray());

			cp.GenerateInMemory = true;

			// Add using statements.
			StringBuilder script = new StringBuilder();
			foreach (var usingNamespace in DEFAULT_NAMESPACES)
				script.AppendFormat("using {0};\n", usingNamespace);

//			foreach (var additionalUsingNamespace in UsingNamespaces)
//				script.AppendFormat("using {0};\n", additionalUsingNamespace);

			// Create the script.
			script.AppendLine();
			script.AppendLine("namespace ScriptEngine");
			script.AppendLine("{");
			script.AppendLine("    public class Program");
			script.AppendLine("    {");
			script.AppendLine("        public void Run()");
			script.AppendLine("        {");
			script.AppendLine("            try");
			script.AppendLine("            {");
			script.AppendFormat("              {0}\n", sourceCode);
			script.AppendLine("            }");
			script.AppendLine("            catch (Exception e)");
			script.AppendLine("            {");
//			script.AppendLine("                Context.Error = _compilationException;");
			script.AppendLine("            }");
			script.AppendLine("        }");
			script.AppendLine("    }");
			script.AppendLine("}");

			// Invoke compilation.
			CompilerResults cr = provider.CompileAssemblyFromSource(cp, script.ToString());

			if (cr.Errors.Count > 0)
			{
				foreach (CompilerError ce in cr.Errors)
				{
					#if DEBUG
					Console.WriteLine("  {0}", ce.ToString());
					Console.WriteLine();
					#endif
					ce.Line = ce.Line - 13;
					compilationErrors.Add(ce);

					if (!ce.IsWarning)
						compilationSucceeded = false;
				}
			}

			if (compilationSucceeded)
			{
				var ass = cr.CompiledAssembly;
				var execInstance = ass.CreateInstance("ScriptEngine.Program");

				var type = execInstance.GetType();
				var methodInfo = type.GetMethod("Run");

				// Execute the code.
//				methodInfo.Invoke(execInstance, new object[] { context });
				methodInfo.Invoke(execInstance, new object[] {});
			}

			return compilationSucceeded;
		}
        public CompilerErrorCollection RunSource( string source, ref ScriptContext context )
        {
            bool compilationSucceeded = true;
            CompilerErrorCollection compilationErrors = new CompilerErrorCollection ( );
            CSharpCodeProvider provider = new CSharpCodeProvider ( );

            // Build the parameters for source compilation.
            CompilerParameters cp = new CompilerParameters ( );
            cp.TreatWarningsAsErrors = false;

            // Add assembly references.
            cp.ReferencedAssemblies.AddRange ( DEFAULT_ASSEMBLIES );
            cp.ReferencedAssemblies.AddRange ( ReferencedAssemblies.ToArray ( ) );

            cp.GenerateInMemory = true;

            // Add using statements.
            StringBuilder script = new StringBuilder ( );
            foreach ( var usingNamespace in DEFAULT_NAMESPACES )
                script.AppendFormat ( "using {0};\r\n", usingNamespace );

            foreach ( var additionalUsingNamespace in UsingNamespaces )
                script.AppendFormat ( "using {0};\r\n", additionalUsingNamespace );

            // Create the script.
            script.AppendLine ( );
            script.AppendLine ( "namespace BlizzetaZero.Kernel.Scripts" );
            script.AppendLine ( "{" );
            script.AppendFormat ( "\t{0}", source );
            script.AppendLine ( "}" );

            Console.WriteLine ( script.ToString ( ) );

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromSource ( cp, script.ToString ( ) );

            if ( cr.Errors.Count > 0 )
            {
                foreach ( CompilerError ce in cr.Errors )
                {
            #if DEBUG
                    Console.WriteLine ( "->\t{0}", ce.ToString ( ) );
                    Console.WriteLine ( );
            #endif
                    ce.Line = ce.Line - 13;
                    compilationErrors.Add ( ce );

                    if ( !ce.IsWarning )
                        compilationSucceeded = false;
                }
            }

            if ( compilationSucceeded )
            {
                var ass = cr.CompiledAssembly;
                var execInstance = ass.CreateInstance ( "BlizzetaZero.Kernel.Scripts.Script" );

                var type = execInstance.GetType ( );
                var methodInfo = type.GetMethod ( "Load" );

                // Execute the code.
                methodInfo.Invoke ( execInstance, new object[] { context } );
            }

            return compilationErrors;
        }