public void EmitSummary_Logs_Expected_Messages_With_Valid_Results_That_Has_A_Warning_But_No_Errors() { // Arrange var loggerMock = new Mock<ILog>(); ConsoleEmitter.SetLogger(loggerMock.Object); var expectedCompiledCode = "CompiledCode" + Guid.NewGuid(); var compilerResults = new CompilerResults { OutputFilePath = string.Empty, Errors = null, Warnings = new List<CompilerError> { new CompilerError { Lineno = 0, Type = string.Empty, Error = string.Empty, Line = string.Empty, } }, CompiledCode = expectedCompiledCode, }; var emitter = new ConsoleEmitter(); // Act emitter.EmitSummary(compilerResults); // Assert loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "----------------------------")), Times.Exactly(2)); loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "Code Emitted:")), Times.Once); loggerMock.Verify(m => m.Info(It.Is<string>(s => s == expectedCompiledCode)), Times.Once); loggerMock.Verify(m => m.Info(It.Is<string>(s => s.Contains("1 Warnings"))), Times.Once); }
public void EmitSummary_Logs_Expected_Messages_With_Valid_Results_That_Has_Empty_Errors_And_Null_Warnings() { // Arrange var loggerMock = new Mock<ILog>(); ConsoleEmitter.SetLogger(loggerMock.Object); var expectedCompiledCode = "CompiledCode" + Guid.NewGuid(); var compilerResults = new CompilerResults { OutputFilePath = string.Empty, Errors = new List<CompilerError>(), Warnings = null, CompiledCode = expectedCompiledCode, }; var emitter = new ConsoleEmitter(); // Act emitter.EmitSummary(compilerResults); // Assert loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "----------------------------")), Times.Exactly(2)); loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "No Errors or Warnings Found!")), Times.Once); loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "Code Emitted:")), Times.Once); loggerMock.Verify(m => m.Info(It.Is<string>(s => s == expectedCompiledCode)), Times.Once); }
CompilerContext(CompilerParameters parameters, CompilerResults results) { this.Parameters = parameters; this.Results = results; this.CompilationUnits = new ArrayList<CompilationUnitNode>(); this.TypeBuilders = new ArrayList<TypeBuilder>(); this.Iterables = new HashMap<MethodBuilder, TypeBuilder>(); this.ConstructorBuilders = new ArrayList<MethodBuilder>(); this.CodeValidationContext = new CodeValidationContext(this); this.MethodGenerationContext = new MethodGenerationContext(); this.LambdaScopes = new HashMap<MethodBuilder, TypeBuilder>(); this.ConstantBuilder = new ConstantBuilder(this); this.PrivateAccessors = new HashMap<Object, MethodInfo>(); this.PrivateMutators = new HashMap<Object, MethodInfo>(); this.localFields = new HashMap<LocalMemberInfo, FieldInfo>(); }
public void Test_That_Emit_Function_Emits_Warnings_Errors_And_Summary_Twice_With_Two_Emitters() { // Arrange var results = new CompilerResults(); var emitterMock = new Mock<IResultsOutput>(); var emitters = new List<IResultsOutput> { emitterMock.Object, emitterMock.Object }; // Act results.Emit(emitters); // Assert emitterMock.Verify(m => m.EmitErrors(It.Is<CompilerResults>(cr => cr.Equals(results))), Times.Exactly(2)); emitterMock.Verify(m => m.EmitWarnings(It.Is<CompilerResults>(cr => cr.Equals(results))), Times.Exactly(2)); emitterMock.Verify(m => m.EmitSummary(It.Is<CompilerResults>(cr => cr.Equals(results))), Times.Exactly(2)); }
public void EmitErrors_Logs_Message_Once_With_Valid_Results_That_Has_Empty_Errors_Collection() { // Arrange var loggerMock = new Mock<ILog>(); ConsoleEmitter.SetLogger(loggerMock.Object); var compilerResults = new CompilerResults { OutputFilePath = string.Empty, Errors = new List<CompilerError>() // our empty Errors collection }; var emitter = new ConsoleEmitter(); // Act emitter.EmitErrors(compilerResults); // Assert loggerMock.Verify(m => m.Info(It.IsAny<string>()), Times.Never); }
public void EmitErrors_Logs_Message_Four_Times_With_Two_Errors() { // Arrange var loggerMock = new Mock<ILog>(); ConsoleEmitter.SetLogger(loggerMock.Object); var expectedFirstLineText = "expectedLineText" + Guid.NewGuid(); var expectedSecondLineText = "expectedLineText" + Guid.NewGuid(); var compilerResults = new CompilerResults { OutputFilePath = string.Empty, Errors = new List<CompilerError> { new CompilerError { Lineno = 0, Type = string.Empty, Error = string.Empty, Line = expectedFirstLineText }, new CompilerError { Lineno = 0, Type = string.Empty, Error = string.Empty, Line = expectedSecondLineText } }, }; var emitter = new ConsoleEmitter(); // Act emitter.EmitErrors(compilerResults); // Assert loggerMock.Verify(m => m.Info(It.IsAny<string>()), Times.Exactly(4)); loggerMock.Verify(m => m.Info(It.Is<string>(p => p == expectedFirstLineText)), Times.Once); loggerMock.Verify(m => m.Info(It.Is<string>(p => p == expectedSecondLineText)), Times.Once); }
public void Test_That_SupressWarningsFrom_Doesnt_Suppress_Any_Warnings_When_Passed_A_Null_Suppression_List() { // Arrange var jscBadTypeForBitOperationWarning = new CompilerError { Type = WarningCode.JscBadTypeForBitOperation }; var jscJscFunctionMasksVariableWarning = new CompilerError { Type = WarningCode.JscFunctionMasksVariable }; var results = new CompilerResults { Warnings = new List<CompilerError> { jscBadTypeForBitOperationWarning, jscJscFunctionMasksVariableWarning, } }; // Act results.SupressWarningsFrom(null); // Assert Assert.Equal(2, results.Warnings.Count); Assert.True(results.Warnings.Any(w => w == jscBadTypeForBitOperationWarning)); Assert.True(results.Warnings.Any(w => w == jscJscFunctionMasksVariableWarning)); }
private int CreateServices(string wsdl_text) { Type service; try { //Try Database Connection SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SAASDB"].ToString()); try { conn.Open(); } catch (Exception e) { //Return Error return -1; } localhost.Service serviceObj = new localhost.Service(); //Insert into Data Table the services int count = 0; List<string> fieldnames = new List<string>(); List<localhost.Field> fieldlist = new List<localhost.Field>(); localhost.Field[] fields = serviceObj.ReadField(11, 30); fieldlist = new List<localhost.Field>(fields); foreach (localhost.Field item in fieldlist) { fieldnames.Add(count.ToString()); count++; } Uri uri = new Uri(wsdl_text); WebRequest webRequest = WebRequest.Create(uri); System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream(); // Get a WSDL file describing a service ServiceDescription sd = ServiceDescription.Read(requestStream); string sdName = sd.Services[0].Name; // Initialize a service description servImport ServiceDescriptionImporter servImport = new ServiceDescriptionImporter(); servImport.AddServiceDescription(sd, String.Empty, String.Empty); servImport.ProtocolName = "Soap"; servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CodeNamespace nameSpace = new CodeNamespace(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(nameSpace); // Set Warnings ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit); if (warnings == 0) { StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture); Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(); prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions()); // Compile the assembly with the appropriate references string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" }; CompilerParameters param = new CompilerParameters(assemblyReferences); param.GenerateExecutable = false; param.GenerateInMemory = true; param.TreatWarningsAsErrors = false; param.WarningLevel = 4; CompilerResults results = new CompilerResults(new TempFileCollection()); results = prov.CompileAssemblyFromDom(param, codeCompileUnit); Assembly assembly = results.CompiledAssembly; service = assembly.GetType(sdName); string input_params = ""; string return_type = ""; MethodInfo[] methodInfo = service.GetMethods(); foreach (MethodInfo t in methodInfo) { List<string> valueNames = new List<string>(); if (t.Name == "Discover") break; input_params = ""; return_type = ""; foreach (ParameterInfo parameter in t.GetParameters()) { //paramname.Text = "(" + temp.ParameterType.Name + " " + temp.Name + ")"; input_params = input_params + parameter.Name + ":" + parameter.ParameterType.Name + " "; } //Get The Return type of the Service(Method) return_type = t.ReturnType.ToString(); //Insert into Service Object(Methods Table) valueNames.Add(Session["OrgID"].ToString()); valueNames.Add(wsdl_text); valueNames.Add(t.Name); valueNames.Add(input_params); valueNames.Add(return_type); bool success = serviceObj.InsertData(11, 30, "WSDL-Instance", fieldnames.ToArray(), valueNames.ToArray()); if (success == false) { return -1; } } return 1; } else { return -1; } } catch (Exception ex) { return -1; } }
public void Test_That_SupressWarningsFrom_Works_When_Specified_Filters_Do_Not_Exist() { // Arrange var jscBadTypeForBitOperationWarning = new CompilerError { Type = WarningCode.JscBadTypeForBitOperation }; var jscJscFunctionMasksVariableWarning = new CompilerError { Type = WarningCode.JscFunctionMasksVariable }; var results = new CompilerResults { Warnings = new List<CompilerError> { jscBadTypeForBitOperationWarning, jscJscFunctionMasksVariableWarning, } }; var supressWarnings = new List<string> { WarningCode.JscBadDeleteOperand, WarningCode.JscConstructorNotCallable, }; // Act results.SupressWarningsFrom(supressWarnings); // Assert Assert.Equal(2, results.Warnings.Count); Assert.True(results.Warnings.Any(w => w == jscBadTypeForBitOperationWarning)); Assert.True(results.Warnings.Any(w => w == jscJscFunctionMasksVariableWarning)); }
private static string RunCode(CompilerResults results) { Assembly executingAssembly = results.CompiledAssembly; object assemblyInstance = executingAssembly.CreateInstance("ExpressionEvaluator.Calculator"); return assemblyInstance.GetType().GetMethod("Calculate").Invoke(assemblyInstance, new object[] { }).ToString(); }
public static bool CompileVBScripts(bool debug, bool cache, out Assembly assembly) { Console.Write("Scripts: Compiling VB.NET scripts..."); string[] files = GetScripts("*.vb"); if (files.Length == 0) { Console.WriteLine("no files found."); assembly = null; return(true); } if (File.Exists("Scripts/Output/Scripts.VB.dll")) { if (cache && File.Exists("Scripts/Output/Scripts.VB.hash")) { byte[] hashCode = GetHashCode("Scripts/Output/Scripts.VB.dll", files, debug); try { using (FileStream fs = new FileStream("Scripts/Output/Scripts.VB.hash", FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BinaryReader bin = new BinaryReader(fs)) { byte[] bytes = bin.ReadBytes(hashCode.Length); if (bytes.Length == hashCode.Length) { bool valid = true; for (int i = 0; i < bytes.Length; ++i) { if (bytes[i] != hashCode[i]) { valid = false; break; } } if (valid) { assembly = Assembly.LoadFrom("Scripts/Output/Scripts.VB.dll"); if (!m_AdditionalReferences.Contains(assembly.Location)) { m_AdditionalReferences.Add(assembly.Location); } Console.WriteLine("done (cached)"); return(true); } } } } } catch { } } } DeleteFiles("Scripts.VB*.dll"); using (VBCodeProvider provider = new VBCodeProvider()) { string path = GetUnusedPath("Scripts.VB"); CompilerParameters parms = new CompilerParameters(GetReferenceAssemblies(), path, debug); string options = GetCompilerOptions(debug); if (options != null) { parms.CompilerOptions = options; } if (Core.HaltOnWarning) { parms.WarningLevel = 4; } CompilerResults results = provider.CompileAssemblyFromFile(parms, files); m_AdditionalReferences.Add(path); Display(results); if (results.Errors.Count > 0) { assembly = null; return(false); } if (cache && Path.GetFileName(path) == "Scripts.VB.dll") { try { byte[] hashCode = GetHashCode(path, files, debug); using (FileStream fs = new FileStream("Scripts/Output/Scripts.VB.hash", FileMode.Create, FileAccess.Write, FileShare.None)) { using (BinaryWriter bin = new BinaryWriter(fs)) { bin.Write(hashCode, 0, hashCode.Length); } } } catch { } } assembly = results.CompiledAssembly; return(true); } }
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; } String 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); 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); }
public static Object CompileExe(string infile, Args args, Environment environment) { currsymbols.Clear(); extracode = string.Empty; Environment localEnvironment = new Environment(environment); using (TextReader r = File.OpenText(infile)) { string src = "(do " + r.ReadToEnd() + ")"; object fc = Runtime.ReadString(src, localEnvironment); string gc = Compiler.Generate(fc, localEnvironment); string code = @" using System; [assembly:LSharp.LSharpExtension] [LSharp.Function] sealed class generated { [STAThread] static int Main(string[] cmdargs) { LSharp.Environment environment = null; object retval = null; "; code += gc; code += @" if (retval is int) { return (int) retval; } return 0; } "; code += extracode; code += @" }"; if (args.processonly) { string outfile = Path.ChangeExtension(infile, ".cs"); using (TextWriter w = File.CreateText(outfile)) { w.WriteLine(code); return(outfile); } } else { if (args.optimize) { copts.CompilerOptions = "/o+"; } else { copts.CompilerOptions = "/o-"; } copts.IncludeDebugInformation = args.debug; copts.GenerateExecutable = args.target == Target.Exe; string name = Path.ChangeExtension(infile, copts.GenerateExecutable ? ".exe" : ".dll"); copts.OutputAssembly = name; CompilerResults cr = comp.CompileAssemblyFromSource(copts, code); if (cr.NativeCompilerReturnValue == 0) { return(copts.OutputAssembly); } else { foreach (CompilerError err in cr.Errors) { Console.Error.WriteLine("Compiler error: {0}", err.ErrorText); } } } } return(null); }
void ShowErrors(CompilerResults cr, string codeStr) { StringBuilder sbErr; sbErr = new StringBuilder("Compiling string: "); sbErr.AppendFormat("'{0}'\n\n", codeStr); foreach(CompilerError err in cr.Errors) { sbErr.AppendFormat("{0}\n",err.ErrorText); } Utils.Print(sbErr.ToString()); }
/// <summary> /// instancia uma nova classe /// </summary> /// <param name="results">resultados dos erros</param> public CompilerErrors(CompilerResults results) { Results = results; }
private void CompileAssembly(ScriptingLanguage lang, Hashtable typeDecls, string nsName, Evidence evidence) { nsName = "Microsoft.Xslt.CompiledScripts." + nsName; CodeNamespace msXslt = new CodeNamespace(nsName); // Add all the default namespaces foreach (string ns in _defaultNamespaces) { msXslt.Imports.Add(new CodeNamespaceImport(ns)); } #if !FEATURE_PAL // visualbasic if (lang == ScriptingLanguage.VisualBasic) { msXslt.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic")); } #endif //!FEATURE_PAL foreach (CodeTypeDeclaration scriptClass in typeDecls.Values) { msXslt.Types.Add(scriptClass); } CodeCompileUnit unit = new CodeCompileUnit(); { unit.Namespaces.Add(msXslt); // This settings have sense for Visual Basic only. // We can consider in future to allow user set them in <xsl:script option="???"> attribute. unit.UserData["AllowLateBound"] = true; // Allow variables to be undeclared unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be declared untyped } // We want the assemblies generated for scripts to stick to the old security model unit.AssemblyCustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(System.Security.SecurityRulesAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(System.Security.SecurityRuleSet)), "Level1")))); CompilerParameters compilParams = new CompilerParameters(); { try { new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert(); try { compilParams.GenerateInMemory = true; #pragma warning disable 618 compilParams.Evidence = evidence; #pragma warning restore 618 compilParams.ReferencedAssemblies.Add(typeof(XPathNavigator).Module.FullyQualifiedName); compilParams.ReferencedAssemblies.Add("system.dll"); #if !FEATURE_PAL // visualbasic if (lang == ScriptingLanguage.VisualBasic) { compilParams.ReferencedAssemblies.Add("microsoft.visualbasic.dll"); } #endif // !FEATURE_PAL } finally { CodeAccessPermission.RevertAssert(); } } catch { throw; } } CompilerResults results = ChooseCodeDomProvider(lang).CompileAssemblyFromDom(compilParams, unit); if (results.Errors.HasErrors) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); foreach (CompilerError e in results.Errors) { FixCompilerError(e); stringWriter.WriteLine(e.ToString()); } throw XsltException.Create(Res.Xslt_ScriptCompileErrors, stringWriter.ToString()); } Assembly assembly = results.CompiledAssembly; foreach (DictionaryEntry entry in typeDecls) { string ns = (string)entry.Key; CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)entry.Value; this.stylesheet.ScriptObjectTypes.Add(ns, assembly.GetType(nsName + "." + scriptClass.Name)); } }
static void Main(string[] args) { try { Console.Title = "Brainfuck Compiler"; Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("Enter your Brainfuck source file path: "); string bfCode = File.ReadAllText(Console.ReadLine()); Console.Write("Enter memory size (in bytes): "); int memSize; try { memSize = int.Parse(Console.ReadLine()); } catch { memSize = 64 * 1024; } Console.Write("Enter cell type: (i. e. int): "); string cellType = Console.ReadLine(); Console.Write("Enter output file path: "); string outputPath = Console.ReadLine(); Code += $"{cellType}[] m=new {cellType}[{memSize}];"; foreach (char c in bfCode) { switch (c) { case '>': Code += "c++;"; break; case '<': Code += "c--;"; break; case '+': Code += "m[c]++;"; break; case '-': Code += "m[c]--;"; break; case '[': Code += "while(m[c]!=0){"; break; case ']': Code += "}"; break; case '.': Code += "Console.Write((char)m[c]);"; break; case ',': Code += "m[c]=Console.ReadKey().KeyChar;"; break; } } Code += "}}"; File.WriteAllText("work.cs", Code); Console.ForegroundColor = ConsoleColor.White; CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = outputPath; CompilerResults res = icc.CompileAssemblyFromSource(parameters, Code); Console.BackgroundColor = ConsoleColor.Red; foreach (CompilerError err in res.Errors) { Console.WriteLine($"[{err.ErrorNumber}][Line {err.Line}][Column {err.Column}] {err.ErrorText}"); } File.Delete("work.cs"); Console.BackgroundColor = ConsoleColor.Green; Console.WriteLine("Compilation finished. You now can run your compiled Brainfuck program (unless there are compilation errors)."); Console.ReadLine(); } catch (Exception e) { Console.WriteLine($"Error:\r\n{e}"); } }
/// <summary> /// Generate a C# assembly, compile it and load it up /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void generateCSharpButton_Click(object sender, System.EventArgs e) { CodeExpression[] emptyParams = new CodeExpression[] { }; // Generate the C# for the control CodeCompileUnit ccu = new CodeCompileUnit( ); // Create a namespace CodeNamespace ns = new CodeNamespace("MyControls"); // Add some imports statements ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); // Add the namespace to the code compile unit ccu.Namespaces.Add(ns); // Now create the class CodeTypeDeclaration ctd = new CodeTypeDeclaration("MyControl"); ctd.BaseTypes.Add(typeof(System.Windows.Forms.UserControl)); // Add the type to the namespace ns.Types.Add(ctd); // Add the default constructor CodeConstructor constructor = new CodeConstructor( ); constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression( ), "InitializeComponent", emptyParams)); constructor.Attributes = MemberAttributes.Public; ctd.Members.Add(constructor); // Create the private member variable to hold the label CodeMemberField labelField = new CodeMemberField(typeof(System.Windows.Forms.Label), "_label"); ctd.Members.Add(labelField); // Now add the InitializeComponent method CodeMemberMethod initializeComponent = new CodeMemberMethod( ); initializeComponent.Name = "InitializeComponent"; initializeComponent.ReturnType = new CodeTypeReference(typeof(void)); CodeAssignStatement labelNew = new CodeAssignStatement(new CodeVariableReferenceExpression("_label"), new CodeObjectCreateExpression(typeof(System.Windows.Forms.Label), emptyParams)); initializeComponent.Statements.Add(labelNew); // Add the SuspendLayout() call initializeComponent.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression( ), "SuspendLayout", emptyParams)); CodeBinaryOperatorExpression leftAndRight = new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.AnchorStyles)), "Left"), CodeBinaryOperatorType.BitwiseOr, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.AnchorStyles)), "Right")); CodeBinaryOperatorExpression topToo = new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.AnchorStyles)), "Top"), CodeBinaryOperatorType.BitwiseOr, leftAndRight); // Setup the Anchor property of the label initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Anchor"), topToo)); // And setup the border style initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "BorderStyle"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.BorderStyle)), "Fixed3D"))); // Set the location of the control initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Location"), new CodeObjectCreateExpression(typeof(System.Drawing.Point), new CodeExpression[] { new CodePrimitiveExpression(8), new CodePrimitiveExpression(8) }))); // Set the name of the control initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Name"), new CodePrimitiveExpression("_label"))); // Set the size of the control initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Size"), new CodeObjectCreateExpression(typeof(System.Drawing.Size), new CodeExpression[] { new CodePrimitiveExpression(312), new CodePrimitiveExpression(23) }))); // Set the tab index initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "TabIndex"), new CodePrimitiveExpression(0))); // And then the text! initializeComponent.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Text"), new CodePrimitiveExpression(messageText.Text))); // Now add the label control to the controls collection initializeComponent.Statements.Add( new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Controls"), "Add", new CodeExpression[] { new CodeVariableReferenceExpression("_label") })); // And set the name of the control to MyControl initializeComponent.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Name"), new CodePrimitiveExpression("MyControl"))); // And the size of the control initializeComponent.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Size"), new CodeObjectCreateExpression(typeof(System.Drawing.Size), new CodeExpression[] { new CodePrimitiveExpression(328), new CodePrimitiveExpression(100) }))); // Add the ResumeLayout ( false ) call initializeComponent.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression( ), "ResumeLayout", new CodeExpression [] { new CodePrimitiveExpression(false) })); // And finally add initializeComponent to the members for the class ctd.Members.Add(initializeComponent); // Finally create the C# CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider( ); #if DEBUG // Generate the source code on disk ICodeGenerator generator = provider.CreateGenerator( ); using (StreamWriter sw = new StreamWriter("code.cs", false)) { CodeGeneratorOptions options = new CodeGeneratorOptions( ); options.BracingStyle = "C"; generator.GenerateCodeFromCompileUnit(ccu, sw, options); } #endif ICodeCompiler compiler = provider.CreateGenerator( ) as ICodeCompiler; CompilerParameters cp = new CompilerParameters(new string[] { "System.dll", "System.Windows.Forms.dll", "System.Drawing.dll" }); cp.GenerateInMemory = true; cp.OutputAssembly = "AutoGenerated"; CompilerResults results = compiler.CompileAssemblyFromDom(cp, ccu); if (results.Errors.Count == 0) { Type t = results.CompiledAssembly.GetType("MyControls.MyControl"); Control c = Activator.CreateInstance(t) as Control; c.Dock = DockStyle.Fill; controlPanel.SuspendLayout( ); controlPanel.Controls.Clear( ); controlPanel.Controls.Add(c); controlPanel.ResumeLayout( ); } else { CompilerError error = results.Errors[0]; int i = 0; i++; } }
public void Start() { var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); var basePath = Path.Combine(di.Parent?.Parent?.FullName, WatchDirectory); if (!Directory.Exists(basePath)) { return; } fsw = new FileSystemWatcher(basePath, @"*.cs") { EnableRaisingEvents = true, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime, }; fsw.Changed += (sender, e) => { CompilerParameters cp = new CompilerParameters { GenerateInMemory = true, TreatWarningsAsErrors = false, GenerateExecutable = false, }; var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location); cp.ReferencedAssemblies.AddRange(assemblies.ToArray()); string source; while (true) { try { source = File.ReadAllText(e.FullPath); break; } catch { Thread.Sleep(100); } } Logger.Log($@"Recompiling {e.Name}...", LoggingTarget.Runtime, LogLevel.Important); CompilationStarted?.Invoke(); Type newType = null; using (var provider = createCodeProvider()) { CompilerResults compile = provider.CompileAssemblyFromSource(cp, source); if (compile.Errors.HasErrors) { string text = "Compile error: "; foreach (CompilerError ce in compile.Errors) { text += "\r\n" + ce; } Logger.Log(text, LoggingTarget.Runtime, LogLevel.Error); } else { Module module = compile.CompiledAssembly.GetModules()[0]; if (module != null) { newType = module.GetTypes()[0]; } } } CompilationFinished?.Invoke(newType); if (newType != null) { Logger.Log(@"Complete!", LoggingTarget.Runtime, LogLevel.Important); } }; }
/// <summary> /// /// </summary> /// <param name="pCodeToCompile"></param> /// <param name="pReferencedAssemblies"></param> /// <param name="pMainClassName"></param> /// <param name="pInstanceName"></param> /// <param name="pExecutionMethodName"></param> /// <param name="pMethodParameters"></param> /// <returns></returns> public List <String> CompileAndExecute(String pCodeToCompile, List <String> pReferencedAssemblies, String pMainClassName, String pExecutionMethodName, Object[] pMethodParameters = null) { List <String> ReturnVal = new List <String>(); Dictionary <String, String> DOMProviderOptions = null; CSharpCodeProvider DOMProvider = null; CompilerParameters DOMCompilerParams = null; try { DOMProviderOptions = new Dictionary <String, String>(); DOMProviderOptions.Add(COMPILER_VERSION_KEY, COMPILER_VERSION_SUPPORTED); // Could use Microsoft.VisualBasic.VBCodeProvider for VB.NET code // The Dictionary specifies the compiler version. DOMProvider = new CSharpCodeProvider(DOMProviderOptions); // Add referenced assemblies to the provider parameters DOMCompilerParams = new CompilerParameters(); if (pReferencedAssemblies != null) { if (pReferencedAssemblies.Count > 0) { foreach (String RefAssembly in pReferencedAssemblies) { if (RefAssembly != null) { if (RefAssembly.Length > 0) { DOMCompilerParams.ReferencedAssemblies.Add(RefAssembly); } // END if (File.Exists(pExecutableFullPath)) else { ReturnVal.Add($"A reference file was empty.{Environment.NewLine}"); } } // END if (pExecutableFullPath.Length > 0) else { ReturnVal.Add($"A reference file was null.{Environment.NewLine}"); } } // END foreach (String RefAssembly in pReferencedAssemblies) } // END if (pReferencedAssemblies.Count > 0) } // END if (pReferencedAssemblies != null) // These references will always be there to support the code compiling // If these are not found, be sure to add them. // Note references are in the form of the file name. // If the reference is not in the GAC, you must supply the fully // qualified file name of the assembly, such as C:\SomeFiles\MyDLL.dll. if (!DOMCompilerParams.ReferencedAssemblies.Contains("System.dll")) { DOMCompilerParams.ReferencedAssemblies.Add("System.dll"); } if (!DOMCompilerParams.ReferencedAssemblies.Contains("System.Windows.Forms.dll")) { DOMCompilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); } if (!DOMCompilerParams.ReferencedAssemblies.Contains("System.Runtime.Serialization.dll")) { DOMCompilerParams.ReferencedAssemblies.Add("System.Runtime.Serialization.dll"); } // Adds this executable so it self-references. DOMCompilerParams.ReferencedAssemblies.Add(System.Reflection.Assembly.GetEntryAssembly().Location); // For this example, I am generating the DLL in memory, but you could // also create a DLL that gets reused. DOMCompilerParams.GenerateInMemory = true; DOMCompilerParams.GenerateExecutable = false; DOMCompilerParams.CompilerOptions = "/optimize"; DOMCompilerParams.IncludeDebugInformation = true; DOMCompilerParams.MainClass = pMainClassName; // Compile the code. CompilerResults CompileResults = DOMProvider.CompileAssemblyFromSource(DOMCompilerParams, pCodeToCompile); // Analyze the results. if (CompileResults != null) { if (CompileResults.Errors.Count != 0) { foreach (CompilerError oErr in CompileResults.Errors) { ReturnVal.Add($"Error# [{oErr.ErrorNumber.ToString()}] - [{oErr.ErrorText}] Line# [{oErr.Line.ToString()}] Column# [{oErr.Column.ToString()}].{Environment.NewLine}"); } // END foreach (CompilerError oErr in CompileResults.Errors) } // END if (CompileResults.Errors.Count != 0) else { // If we are here, it compiled OK, so we execute. Type[] ObjectTypes = CompileResults.CompiledAssembly.GetTypes(); if (ObjectTypes.Length > 0) { String FullTypeName = ObjectTypes[0].FullName; Object CompiledObject = CompileResults.CompiledAssembly.CreateInstance(FullTypeName); MethodInfo CompiledMethod = CompiledObject.GetType().GetMethod(pExecutionMethodName); Object ReturnValue = CompiledMethod.Invoke(CompiledObject, pMethodParameters); } // END if (ObjectTypes.Length > 0) else { ReturnVal.Add("No defined types found in the compiled object."); } } // END else of [if (CompileResults.Errors.Count != 0)] } // END if (CompileResults != null) else { ReturnVal.Add("No compiled object created."); } // END else of [if (CompileResults != null)] } // END try catch (Exception exUnhandled) { // Insert your exception handling code here. // This is only temporary. System.Windows.Forms.MessageBox.Show($"Error Message [{exUnhandled.Message}]{Environment.NewLine}Error Source [{exUnhandled.Source}]", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } // END catch (Exception exUnhandled) finally { if (DOMProviderOptions != null) { DOMProviderOptions.Clear(); DOMProviderOptions = null; } if (DOMProvider != null) { DOMProvider.Dispose(); DOMProvider = null; } if (DOMCompilerParams != null) { DOMCompilerParams = null; } } // END finally return(ReturnVal); } // END public void CompileAndExecute(String pCodeToCompile ...)
} // END public void CompileAndExecute(String pCodeToCompile ...) /// <summary> /// This compiles with additional information returned. CompileAndExecute /// does not return the detailed compiled information. /// </summary> /// <param name="pCodeToCompile"></param> /// <param name="pReferencedAssemblies"></param> /// <param name="pMainClassName"></param> /// <param name="pInstanceName"></param> /// <param name="pExecutionMethodName"></param> /// <param name="pMethodParameters"></param> /// <returns></returns> public List <String> Compile(String pCodeToCompile, List <String> pReferencedAssemblies, String pMainClassName, out String pFullTypeName, out String pModuleName, out List <String> pConstructors, out List <String> pMembers, out List <String> pFields, out List <String> pMethods, out List <String> pProperties) { List <String> ReturnVal = new List <String>(); Dictionary <String, String> DOMProviderOptions = null; CSharpCodeProvider DOMProvider = null; CompilerParameters DOMCompilerParams = null; pFullTypeName = ""; pModuleName = ""; pConstructors = new List <String>(); pMembers = new List <String>(); pFields = new List <String>(); pMethods = new List <String>(); pProperties = new List <String>(); try { DOMProviderOptions = new Dictionary <String, String>(); DOMProviderOptions.Add(COMPILER_VERSION_KEY, COMPILER_VERSION_SUPPORTED); DOMProvider = new CSharpCodeProvider(DOMProviderOptions); DOMCompilerParams = new CompilerParameters(); if (pReferencedAssemblies != null) { if (pReferencedAssemblies.Count > 0) { foreach (String RefAssembly in pReferencedAssemblies) { if (RefAssembly != null) { if (RefAssembly.Length > 0) { DOMCompilerParams.ReferencedAssemblies.Add(RefAssembly); } // END if (File.Exists(pExecutableFullPath)) else { ReturnVal.Add($"A reference file was empty.{Environment.NewLine}"); } } // END if (pExecutableFullPath.Length > 0) else { ReturnVal.Add($"A reference file was null.{Environment.NewLine}"); } } // END foreach (String RefAssembly in pReferencedAssemblies) } // END if (pReferencedAssemblies.Count > 0) } // END if (pReferencedAssemblies != null) // These references will always be there to support the code compiling if (!DOMCompilerParams.ReferencedAssemblies.Contains("System.dll")) { DOMCompilerParams.ReferencedAssemblies.Add("System.dll"); } if (!DOMCompilerParams.ReferencedAssemblies.Contains("System.Windows.Forms.dll")) { DOMCompilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); } if (!DOMCompilerParams.ReferencedAssemblies.Contains("System.Runtime.Serialization.dll")) { DOMCompilerParams.ReferencedAssemblies.Add("System.Runtime.Serialization.dll"); } // Adds this executable. DOMCompilerParams.ReferencedAssemblies.Add(System.Reflection.Assembly.GetEntryAssembly().Location); DOMCompilerParams.GenerateInMemory = true; DOMCompilerParams.GenerateExecutable = false; DOMCompilerParams.CompilerOptions = "/optimize"; DOMCompilerParams.IncludeDebugInformation = true; DOMCompilerParams.MainClass = pMainClassName; CompilerResults CompileResults = DOMProvider.CompileAssemblyFromSource(DOMCompilerParams, pCodeToCompile); if (CompileResults != null) { if (CompileResults.Errors.Count != 0) { foreach (CompilerError oErr in CompileResults.Errors) { ReturnVal.Add($"Error# [{oErr.ErrorNumber.ToString()}] - [{oErr.ErrorText}] Line# [{oErr.Line.ToString()}] Column# [{oErr.Column.ToString()}].{Environment.NewLine}"); } // END foreach (CompilerError oErr in CompileResults.Errors) } // END if (CompileResults.Errors.Count != 0) else { Type[] ObjectTypes = CompileResults.CompiledAssembly.GetTypes(); // List<String> pMembers, List<String> pFields, List<String> pMethods, List<String> pProperties if (ObjectTypes.Length > 0) { pFullTypeName = ObjectTypes[0].FullName; Object CompiledObject = CompileResults.CompiledAssembly.CreateInstance(pFullTypeName); Type CompiledType = CompiledObject.GetType(); pModuleName = CompiledType.Module.ScopeName; // Beginning here, you could create and populate class instances that // contain information gleaned from constructors, methods, members, // properties, etc. and their parameters instead of passing back these // generalized descriptions. ConstructorInfo[] TempConstructors = CompiledType.GetConstructors(); foreach (ConstructorInfo TempConstructor in TempConstructors) { String StringToAdd = ""; if (TempConstructor.Name == ".ctor") { StringToAdd = "void " + ObjectTypes[0].Name; } else { StringToAdd = "void " + TempConstructor.Name; } String ParmString = ""; if (TempConstructor.Module.ScopeName.Equals(pModuleName)) { ParameterInfo[] TempConstructorParam = TempConstructor.GetParameters(); foreach (ParameterInfo TempParam in TempConstructorParam) { ParmString += $"{TempParam.ParameterType.FullName} {TempParam.Name}, "; } } StringToAdd += "(" + ParmString + ")"; pConstructors.Add(StringToAdd); } MemberInfo[] TempDefaultMembers = CompiledType.GetDefaultMembers(); // List<String> pFields, List<String> pMethods, List<String> pProperties if (TempDefaultMembers.Length > 0) { foreach (MemberInfo TempMember in TempDefaultMembers) { if (TempMember.Module.ScopeName.Equals(pModuleName)) { String StringToAdd = ""; StringToAdd = $"{TempMember.ReflectedType.FullName} {TempMember.Name}"; pMembers.Add(StringToAdd); } // END if (TempMember.Module.ScopeName.Equals(pModuleName)) } // END if (TempDefaultMembers.Length > 0) } // END if (TempDefaultMembers.Length > 0) FieldInfo[] TempFields = CompiledType.GetFields(); // List<String> pFields, List<String> pMethods, List<String> pProperties if (TempFields.Length > 0) { foreach (FieldInfo TempField in TempFields) { if (TempField.Module.ScopeName.Equals(pModuleName)) { String StringToAdd = ""; StringToAdd = $"{TempField.ReflectedType.FullName} {TempField.Name}"; pFields.Add(StringToAdd); } // END if (TempField.Module.ScopeName.Equals(pModuleName)) } // END foreach (FieldInfo TempField in TempFields) } // END if (TempFields.Length > 0) MemberInfo[] TempMembers = CompiledType.GetMembers(); // List<String> pProperties if (TempMembers.Length > 0) { foreach (MemberInfo TempMember in TempMembers) { if (TempMember.Module.ScopeName.Equals(pModuleName)) { String StringToAdd = ""; StringToAdd = TempMember.ToString(); pMembers.Add(StringToAdd); } } // END if (TempDefaultMembers.Length > 0) } // END if (TempDefaultMembers.Length > 0) MethodInfo[] TempMethods = CompiledType.GetMethods(); foreach (MethodInfo TempMethod in TempMethods) { if ((TempMethod.Module.ScopeName.Equals(pModuleName)) && (!TempMethod.IsSpecialName)) { String StringToAdd = ""; StringToAdd = $"{TempMethod.ReturnType.FullName} {TempMethod.Name}"; ParameterInfo[] TempParams = TempMethod.GetParameters(); String ParmString = ""; foreach (ParameterInfo TempParam in TempParams) { String ParamName = TempParam.Name; String ParamTypeName = TempParam.ParameterType.FullName; Object DefaultValue = TempParam.DefaultValue; if (DefaultValue.ToString().Length == 0) { ParmString += $"{ParamTypeName} {ParamName}, "; } else { ParmString += $"{ParamTypeName} {ParamName}={DefaultValue.ToString()}, "; } } // END foreach (ParameterInfo TempParam in TempParams) if (ParmString.EndsWith(", ")) { ParmString = ParmString.Substring(0, ParmString.Length - 2); } StringToAdd += "(" + ParmString + ")"; pMethods.Add(StringToAdd); } // END if (TempMethod.Module.ScopeName.Equals(pModuleName)) } // END foreach (MethodInfo TempMethod in TempMethods) PropertyInfo[] TempProperties = CompiledType.GetProperties(); // List<String> pProperties if (TempProperties.Length > 0) { foreach (PropertyInfo TempProperty in TempProperties) { if (TempProperty.Module.ScopeName.Equals(pModuleName)) { String StringToAdd = ""; StringToAdd = $"{TempProperty.PropertyType.FullName} {TempProperty.Name}, "; if (TempProperty.CanRead && TempProperty.CanWrite) { StringToAdd += " (get/set)"; } else if (!TempProperty.CanRead && TempProperty.CanWrite) { StringToAdd += " (set ONLY)"; } else if (TempProperty.CanRead && !TempProperty.CanWrite) { StringToAdd += " (get ONLY)"; } else { // No action } pProperties.Add(StringToAdd); } // END if (TempProperty.Module.ScopeName.Equals(pModuleName)) } // END if (TempDefaultMembers.Length > 0) } // END if (TempDefaultMembers.Length > 0) } // END if (ObjectTypes.Length > 0) else { ReturnVal.Add("No defined types found in the compiled object."); } } // END else of [if (CompileResults.Errors.Count != 0)] } // END if (CompileResults != null) else { ReturnVal.Add("No compiled object created."); } // END else of [if (CompileResults != null)] } // END try catch (Exception exUnhandled) { // Insert your exception handling code here. // This is only temporary. System.Windows.Forms.MessageBox.Show($"Error Message [{exUnhandled.Message}]{Environment.NewLine}Error Source [{exUnhandled.Source}]", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } // END catch (Exception exUnhandled) finally { if (DOMProviderOptions != null) { DOMProviderOptions.Clear(); DOMProviderOptions = null; } if (DOMProvider != null) { DOMProvider.Dispose(); DOMProvider = null; } if (DOMCompilerParams != null) { DOMCompilerParams = null; } } // END finally return(ReturnVal); } // END public void CompileAndExecute(String pCodeToCompile ...)
public CompilerResults Compile(CompileOptions compileOptions) { CompilerResults result = new CompilerResults(); GameLoader loader = new GameLoader(); UpdateStatus(string.Format("Compiling {0} to {1}", compileOptions.Filename, compileOptions.OutputFolder)); if (!loader.Load(compileOptions.Filename)) { result.Errors = loader.Errors; } else { UpdateStatus("Loaded successfully"); result.Warnings = loader.Warnings; result.Success = true; var substitutionText = GetSubstitutionText(loader, compileOptions.Profile); UpdateStatus("Copying dependencies"); result.IndexHtml = CopyDependenciesToOutputFolder(compileOptions.OutputFolder, substitutionText, compileOptions.DebugMode, compileOptions.Profile, compileOptions.Minify, loader, compileOptions); string saveData = string.Empty; UpdateStatus("Saving"); GameSaver saver = new GameSaver(loader.Elements); saver.Progress += saver_Progress; saveData = saver.Save(); UpdateStatus("Copying resources"); CopyResourcesToOutputFolder(loader.ResourcesFolder, compileOptions.OutputFolder); saveData += GetEmbeddedHtmlFileData(loader.ResourcesFolder); string saveJs = System.IO.Path.Combine(compileOptions.OutputFolder, "game.js"); saveData = System.IO.File.ReadAllText(saveJs) + saveData; if (compileOptions.Minify) { var minifier = new Microsoft.Ajax.Utilities.Minifier(); saveData = minifier.MinifyJavaScript(saveData, new Microsoft.Ajax.Utilities.CodeSettings { MacSafariQuirks = true, RemoveUnneededCode = true, LocalRenaming = Microsoft.Ajax.Utilities.LocalRenaming.CrunchAll }); var encoding = (Encoding)Encoding.ASCII.Clone(); encoding.EncoderFallback = new Microsoft.Ajax.Utilities.JSEncoderFallback(); using (var writer = new System.IO.StreamWriter(saveJs, false, encoding)) { writer.Write(saveData); } } else { System.IO.File.WriteAllText(saveJs, saveData); } UpdateStatus("Finished"); } return result; }
public CompilerResults compileFromFiles(CompilerParameters parameters, File[] files) { var results = new CompilerResults(); this.context = new CompilerContext(parameters, results); this.statementValidator = new StatementValidator(this.context); this.expressionValidator = new ExpressionValidator(this.context); this.statementValidator.ExpressionValidator = this.expressionValidator; this.expressionValidator.StatementValidator = this.statementValidator; this.reachabilityChecker = new ReachabilityChecker(context); this.assignmentChecker = new AssignmentChecker(context); this.bytecodeGenerator = new BytecodeGenerator(context); bool tragicError = false; var buffer = new char[4096]; var sb = new StringBuilder(); var parser = new Parser(); foreach (var file in files) { sb.setLength(0); InputStreamReader reader = null; try { reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")); int read; while ((read = reader.read(buffer)) != -1) { sb.append(buffer, 0, read); } var text = new char[sb.length()]; sb.getChars(0, sizeof(text), text, 0); if (sizeof(text) > 0) { if (text[sizeof(text) - 1] == '\u001a') { text[sizeof(text) - 1] = ' '; } } var preprocessor = new Preprocessor(results.codeErrorManager, text); preprocessor.Filename = file.getAbsolutePath(); preprocessor.Symbols.addAll(parameters.Symbols); var scanner = new PreprocessedTextScanner(results.codeErrorManager, preprocessor.preprocess()); scanner.Filename = file.getAbsolutePath(); var compilationUnit = parser.parseCompilationUnit(scanner); if (compilationUnit != null) { compilationUnit.Symbols = preprocessor.Symbols; context.CompilationUnits.add(compilationUnit); } } catch (CodeErrorException) { } catch (Exception e) { e.printStackTrace(); tragicError = true; break; } finally { if (reader != null) { try { reader.close(); } catch (IOException) { } } } } if (!tragicError) { if (!context.HasErrors) { if (parameters.ProgressTracker != null) { parameters.ProgressTracker.compilationStageFinished(CompilationStage.Parsing); } doCompile(); } } this.context = null; this.statementValidator = null; this.expressionValidator = null; this.reachabilityChecker = null; this.assignmentChecker = null; this.queryTranslator = null; this.documentationBuilder = null; if (parameters.ProgressTracker != null) { parameters.ProgressTracker.compilationFinished(); } return results; }
public static string RunCode(Level current) { inputNum = 0; form.outputWindow.Text = ""; output = ""; CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); string code = "using DianaWorkshop;namespace Workshop{" + current.producer(form.TextArea.Text) + "\r\nclass Console{public static void WriteLine(object pat, params object[] fill) { Game.WriteLine(pat, fill); } public static void Write(object pat, params object[] fill) { Game.Write(pat, fill); } public static string ReadLine() { return Game.ReadLine(); } }}"; // True - memory generation, false - external file generation parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); parameters.GenerateInMemory = true; // True - exe file generation, false - dll file generation parameters.GenerateExecutable = true; CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError error in results.Errors) { if (error.ErrorNumber == "CS0017") { sb.AppendLine("You can't write a Main method here. Please write a Main method only when given one."); } else { sb.AppendLine(string.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText)); } } Console.WriteLine("Build errors:"); Console.WriteLine(sb.ToString()); WriteLine(sb.ToString()); return(output); } Assembly assembly = results.CompiledAssembly; Type program = assembly.GetType("Workshop.Program"); MethodInfo main = program.GetMethod("Main"); try { main.Invoke(Activator.CreateInstance(program), new object[] { null }); } catch (Exception e) { if (e is TargetInvocationException) { Console.WriteLine("Runtime exception:\n" + e.InnerException); WriteLine("Runtime exception:\n" + e.InnerException + "\n"); } else { Console.WriteLine("Runtime exception:\n" + e); WriteLine("Runtime exception:\n" + e + "\n"); } } return(output); }
public string test() { List <Stream> lsstream = new List <Stream>(); List <ServiceDescription> lsdescription = new List <ServiceDescription>(); Dictionary <string, ServiceDescription> dicdescription = new Dictionary <string, ServiceDescription>(); XmlDocument doc = new XmlDocument(); doc.Load("DllConfig.xml"); string ServerURL = ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("URLAddres")).GetAttribute("URL"); //CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit = new CodeCompileUnit(); //unit.Namespaces.Add(nmspace); foreach (XmlNode xn in doc.SelectSingleNode("AutoCreate").SelectSingleNode("FileList").ChildNodes) { string _temp = ((XmlElement)xn).GetAttribute("Name"); if (!string.IsNullOrEmpty(_temp)) { //nmspace.Name = string.Format("WebServices.{0}", _temp.Split('.')[0]); //unit.Namespaces.Add(nmspace); dicdescription.Add(string.Format("WebServices.{0}", _temp.Split('.')[0]), ServiceDescription.Read(web.OpenRead(string.Format("{0}{1}?WSDL", ServerURL, _temp)))); //lsdescription.Add(ServiceDescription.Read(web.OpenRead(string.Format("{0}{1}?WSDL", ServerURL, _temp)))); } } //int x = 0; //foreach (ServiceDescription description in lsdescription) //{ // ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); // importer.ProtocolName = "Soap"; // importer.Style = ServiceDescriptionImportStyle.Client; // importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; // importer.AddServiceDescription(description, null, null); // //ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); // ServiceDescriptionImportWarnings warning = importer.Import(unit.Namespaces[x], unit); // x++; //} foreach (string str in dicdescription.Keys) { CodeNamespace nmspace = new CodeNamespace(); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap"; importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; nmspace.Name = str; unit.Namespaces.Add(nmspace); importer.AddServiceDescription(dicdescription[str], null, null); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); } CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.OutputAssembly = "getWebServices.dll"; parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); StringBuilder err = new StringBuilder(50000); if (result.Errors.HasErrors) { for (int i = 0; i < result.Errors.Count; i++) { err.AppendLine(result.Errors[i].ErrorText); } } return(err.ToString()); }
public static bool CompileCSScripts(bool debug, bool cache, out Assembly assembly) { Console.Write("Scripts: Compiling C# scripts..."); string[] files = GetScripts("*.cs"); if (files.Length == 0) { Console.WriteLine("no files found."); assembly = null; return(true); } if (File.Exists("Scripts/Output/Scripts.CS.dll")) { if (cache && File.Exists("Scripts/Output/Scripts.CS.hash")) { try { byte[] hashCode = GetHashCode("Scripts/Output/Scripts.CS.dll", files, debug); using (FileStream fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BinaryReader bin = new BinaryReader(fs)) { byte[] bytes = bin.ReadBytes(hashCode.Length); if (bytes.Length == hashCode.Length) { bool valid = true; for (int i = 0; i < bytes.Length; ++i) { if (bytes[i] != hashCode[i]) { valid = false; break; } } if (valid) { assembly = Assembly.LoadFrom("Scripts/Output/Scripts.CS.dll"); if (!m_AdditionalReferences.Contains(assembly.Location)) { m_AdditionalReferences.Add(assembly.Location); } Console.WriteLine("done (cached)"); return(true); } } } } } catch { } } } DeleteFiles("Scripts.CS*.dll"); #if Framework_3_5 using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string>() { { "CompilerVersion", "v3.5" } })) #else using (CSharpCodeProvider provider = new CSharpCodeProvider()) #endif { string path = GetUnusedPath("Scripts.CS"); CompilerParameters parms = new CompilerParameters(GetReferenceAssemblies(), path, debug); string defines = GetDefines(); if (defines != null) { parms.CompilerOptions = defines; } if (Core.HaltOnWarning) { parms.WarningLevel = 4; } #if !MONO CompilerResults results = provider.CompileAssemblyFromFile(parms, files); #else parms.CompilerOptions = String.Format("{0} /nowarn:169,219,414 /recurse:Scripts/*.cs", parms.CompilerOptions); CompilerResults results = provider.CompileAssemblyFromFile(parms, ""); #endif m_AdditionalReferences.Add(path); Display(results); #if !MONO if (results.Errors.Count > 0) { assembly = null; return(false); } #else if (results.Errors.Count > 0) { foreach (CompilerError err in results.Errors) { if (!err.IsWarning) { assembly = null; return(false); } } } #endif if (cache && Path.GetFileName(path) == "Scripts.CS.dll") { try { byte[] hashCode = GetHashCode(path, files, debug); using (FileStream fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Create, FileAccess.Write, FileShare.None)) { using (BinaryWriter bin = new BinaryWriter(fs)) { bin.Write(hashCode, 0, hashCode.Length); } } } catch { } } assembly = results.CompiledAssembly; return(true); } }
public void Webservicecall(string contryname) { WebRequest webRequest = WebRequest.Create("http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc?singleWsdl"); WebResponse webResponse = webRequest.GetResponse(); // Stream stream = webResponse.GetResponseStream(); ServiceDescription description = new ServiceDescription(); using (Stream stream = webResponse.GetResponseStream()) { description = ServiceDescription.Read(stream); } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap12";//' Use SOAP 1.2. importer.AddServiceDescription(description, null, null); importer.Style = ServiceDescriptionImportStyle.Client; //'--Generate properties to represent primitive values. importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; //'Initialize a Code-DOM tree into which we will import the service. CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit1 = new CodeCompileUnit(); unit1.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1); CodeDomProvider provider1 = CodeDomProvider.CreateProvider("C#"); //'--Compile the assembly proxy with the // appropriate references String[] assemblyReferences; assemblyReferences = new String[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" }; CompilerParameters parms = new CompilerParameters(assemblyReferences); parms.GenerateInMemory = true; CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1); if (results.Errors.Count > 0) { } Type foundType = null; Type[] types = results.CompiledAssembly.GetTypes(); foreach (Type type1 in types) { if (type1.BaseType == typeof(SoapHttpClientProtocol)) { foundType = type1; } } if (!String.IsNullOrEmpty(contryname)) { Object[] args = new Object[1]; args[0] = contryname; Object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString()); MethodInfo mi = wsvcClass.GetType().GetMethod("Prueba"); var returnValue = mi.Invoke(wsvcClass, null); DataSet ds = new DataSet(); //grdcountrydata.DataSource = ConvertXMLToDataSet(returnValue.ToString()); //grdcountrydata.DataBind(); } else { Object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString()); MethodInfo mi = wsvcClass.GetType().GetMethod("Prueba"); var returnValue = mi.Invoke(wsvcClass, null); DataSet ds = new DataSet(); //grdcountry.DataSource = ConvertXMLToDataSet(returnValue.ToString()); //grdcountry.DataBind(); } }
public override CompilerResults CompileAssemblyFromSource(CompilerParameters cp, string code) { CodeAnalysis.SyntaxTree codeTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(code); VisualBasicCompilationOptions options = new VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, true, optimizationLevel: OptimizationLevel.Release, generalDiagnosticOption: ReportDiagnostic.Default); List <MetadataReference> references = new List <MetadataReference>(); foreach (string reference in cp.ReferencedAssemblies) { references.Add(GetReference(reference)); } if (!cp.ReferencedAssemblies.Contains("netstandard")) { references.Add(GetReference("netstandard")); } if (!cp.ReferencedAssemblies.Contains("System.Runtime")) { references.Add(GetReference("System.Runtime")); } if (!cp.ReferencedAssemblies.Contains("System.ComponentModel.Primitives")) { references.Add(GetReference("System.ComponentModel.Primitives")); } Compilation compilation = VisualBasicCompilation.Create( "_" + Guid.NewGuid().ToString("D"), new SyntaxTree[] { codeTree }, references: references, options: options ); using (MemoryStream ms = new MemoryStream()) { CodeAnalysis.Emit.EmitResult results = compilation.Emit(ms); if (results.Success) { return(new CompilerResults() { CompiledAssembly = Assembly.Load(ms.ToArray()) }); } else { CompilerResults result = new CompilerResults(); foreach (Diagnostic d in results.Diagnostics) { if (d.Severity == DiagnosticSeverity.Error) { result.Errors.Add(new CompilerError() { ErrorText = d.GetMessage(), ErrorNumber = d.Id, Line = d.Location.GetLineSpan().StartLinePosition.Line, Column = d.Location.GetLineSpan().StartLinePosition.Character }); } } return(result); } } }
protected override void ProcessCompilerOutputLine(CompilerResults results, string line) { }
private Effect CreateEffect(string effectName, EffectBytecodeCompilerResult effectBytecodeCompilerResult, CompilerResults compilerResult) { Effect effect; lock (cachedEffects) { if (!isInitialized) { throw new ObjectDisposedException(nameof(EffectSystem), "EffectSystem has been disposed. This Effect compilation has been cancelled."); } if (effectBytecodeCompilerResult.CompilationLog.HasErrors) { // Unregister result (or should we keep it so that failure never change?) List <CompilerResults> effectCompilerResults; if (earlyCompilerCache.TryGetValue(effectName, out effectCompilerResults)) { effectCompilerResults.Remove(compilerResult); } } CheckResult(effectBytecodeCompilerResult.CompilationLog); var bytecode = effectBytecodeCompilerResult.Bytecode; if (bytecode == null) { throw new InvalidOperationException("EffectCompiler returned no shader and no compilation error."); } if (!cachedEffects.TryGetValue(bytecode, out effect)) { effect = new Effect(GraphicsDevice, bytecode) { Name = effectName }; cachedEffects.Add(bytecode, effect); #if STRIDE_PLATFORM_DESKTOP foreach (var type in bytecode.HashSources.Keys) { var storagePath = EffectCompilerBase.GetStoragePathFromShaderType(type); if (!FileProvider.TryGetFileLocation(storagePath, out var filePath, out _, out _)) { // TODO: the "/path" is hardcoded, used in ImportStreamCommand and ShaderSourceManager. Find a place to share this correctly. var pathUrl = storagePath + "/path"; if (FileProvider.FileExists(pathUrl)) { using (var pathStream = FileProvider.OpenStream(pathUrl, VirtualFileMode.Open, VirtualFileAccess.Read)) using (var reader = new StreamReader(pathStream)) { filePath = reader.ReadToEnd(); } } } if (filePath != null) { directoryWatcher.Track(filePath); } } #endif } } return(effect); }
public static void Display(CompilerResults results) { if (results.Errors.Count > 0) { Dictionary <string, List <CompilerError> > errors = new Dictionary <string, List <CompilerError> >(results.Errors.Count, StringComparer.OrdinalIgnoreCase); Dictionary <string, List <CompilerError> > warnings = new Dictionary <string, List <CompilerError> >(results.Errors.Count, StringComparer.OrdinalIgnoreCase); foreach (CompilerError e in results.Errors) { string file = e.FileName; // Ridiculous. FileName is null if the warning/error is internally generated in csc. if (string.IsNullOrEmpty(file)) { Console.WriteLine("ScriptCompiler: {0}: {1}", e.ErrorNumber, e.ErrorText); continue; } Dictionary <string, List <CompilerError> > table = e.IsWarning ? warnings : errors; List <CompilerError> list = null; table.TryGetValue(file, out list); if (list == null) { table[file] = list = new List <CompilerError>(); } list.Add(e); } if (errors.Count > 0) { Console.WriteLine("failed ({0} errors, {1} warnings)", errors.Count, warnings.Count); } else { Console.WriteLine("done ({0} errors, {1} warnings)", errors.Count, warnings.Count); } string scriptRoot = Path.GetFullPath(Path.Combine(Core.BaseDirectory, "Scripts" + Path.DirectorySeparatorChar)); Uri scriptRootUri = new Uri(scriptRoot); Utility.PushColor(ConsoleColor.Yellow); if (warnings.Count > 0) { Console.WriteLine("Warnings:"); } foreach (KeyValuePair <string, List <CompilerError> > kvp in warnings) { string fileName = kvp.Key; List <CompilerError> list = kvp.Value; string fullPath = Path.GetFullPath(fileName); string usedPath = Uri.UnescapeDataString(scriptRootUri.MakeRelativeUri(new Uri(fullPath)).OriginalString); Console.WriteLine(" + {0}:", usedPath); Utility.PushColor(ConsoleColor.DarkYellow); foreach (CompilerError e in list) { Console.WriteLine(" {0}: Line {1}: {3}", e.ErrorNumber, e.Line, e.Column, e.ErrorText); } Utility.PopColor(); } Utility.PopColor(); Utility.PushColor(ConsoleColor.Red); if (errors.Count > 0) { Console.WriteLine("Errors:"); } foreach (KeyValuePair <string, List <CompilerError> > kvp in errors) { string fileName = kvp.Key; List <CompilerError> list = kvp.Value; string fullPath = Path.GetFullPath(fileName); string usedPath = Uri.UnescapeDataString(scriptRootUri.MakeRelativeUri(new Uri(fullPath)).OriginalString); Console.WriteLine(" + {0}:", usedPath); Utility.PushColor(ConsoleColor.DarkRed); foreach (CompilerError e in list) { Console.WriteLine(" {0}: Line {1}: {3}", e.ErrorNumber, e.Line, e.Column, e.ErrorText); } Utility.PopColor(); } Utility.PopColor(); } else { Console.WriteLine("done (0 errors, 0 warnings)"); } }
private string InvokeMethod(string wsdl_text,string MethodName,Object[] param1) { try { Uri uri = new Uri(wsdl_text); WebRequest webRequest = WebRequest.Create(uri); System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream(); // Get a WSDL file describing a service ServiceDescription sd = ServiceDescription.Read(requestStream); string sdName = sd.Services[0].Name; // Initialize a service description servImport ServiceDescriptionImporter servImport = new ServiceDescriptionImporter(); servImport.AddServiceDescription(sd, String.Empty, String.Empty); servImport.ProtocolName = "Soap"; servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CodeNamespace nameSpace = new CodeNamespace(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(nameSpace); // Set Warnings ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit); if (warnings == 0) { StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture); Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(); prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions()); // Compile the assembly with the appropriate references string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" }; CompilerParameters param = new CompilerParameters(assemblyReferences); param.GenerateExecutable = false; param.GenerateInMemory = true; param.TreatWarningsAsErrors = false; param.WarningLevel = 4; CompilerResults results = new CompilerResults(new TempFileCollection()); results = prov.CompileAssemblyFromDom(param, codeCompileUnit); Assembly assembly = results.CompiledAssembly; service = assembly.GetType(sdName); MethodInfo[] methodinfo = service.GetMethods(); string result = null; foreach (MethodInfo t in methodinfo) if (t.Name == MethodName) { //Invoke Method Object obj = Activator.CreateInstance(service); Object response = t.Invoke(obj, param1); Array myArrayList = response as Array; if (myArrayList != null) { List<Object> result_obj = new List<Object>(); foreach (var item in myArrayList) { foreach (var currentPropertyInformation in item.GetType().GetProperties()) { //currentPropertyInformation.GetValue(item, null); //Result.Text = Result.Text + currentPropertyInformation.Name + ":" + currentPropertyInformation.GetValue(item, null); result = currentPropertyInformation.GetValue(item, null).ToString(); } } } else if(response.GetType().ToString() != "System.String") { foreach (var currentPropertyInformation in response.GetType().GetProperties()) { //currentPropertyInformation.GetValue(item, null); //Result.Text = Result.Text + currentPropertyInformation.Name + ":" + currentPropertyInformation.GetValue(item, null); if (currentPropertyInformation.GetValue(response, null) != null) { result = result + currentPropertyInformation.Name + ":" + currentPropertyInformation.GetValue(response, null) + "|"; } else { result = result + currentPropertyInformation.Name + ":NULL,"; } } } if(response!=null && result==null) { result = response.ToString(); } break; } return result; } else { return null; } } catch (Exception ex) { return null; } }
public bool GenerateandCompileLibrary(string moduleFolderPath, string moduleName, Dictionary<string, string> columnlist, Dictionary<string, string> updateList, bool isNewModule, bool autoIncrement) { string filePathInfo = Server.MapPath("/Modules/Admin/ModuleMaker/RawModule/library/ModuleInfo.cs"); string filePathController = Server.MapPath("/Modules/Admin/ModuleMaker/RawModule/library/ModuleController.cs"); string filePathDataProvider = Server.MapPath("/Modules/Admin/ModuleMaker/RawModule/library/ModuleDataProvider.cs"); string bigCode = string.Empty; string code = string.Empty; bool isCompiled = false; try { string libraryPath = Server.MapPath(moduleFolderPath + moduleName + "/SageFrame." + moduleName); ModuleHelper.CreateDirectory(libraryPath); string infoPath = libraryPath + "/Info"; ModuleHelper.CreateDirectory(infoPath); string destinationPath = infoPath + "/" + moduleName + "Info.cs"; using (StreamWriter sw = new StreamWriter(destinationPath)) { using (StreamReader rdr = new StreamReader(filePathInfo)) { code = rdr.ReadToEnd(); } StringBuilder html = new StringBuilder(); foreach (KeyValuePair<string, string> datatype in columnlist) { html.Append(ModuleHelper.SageProp(datatype.Value, datatype.Key)); } code = code.Replace("//properties", html.ToString()); string references = "using System;"; references = "using System;\nusing SageFrame.Web.Utilities;\nusing System.Collections.Generic;\n"; code = code.Replace("//references", references); code = code.Replace("ModuleName", moduleName); sw.Write(code); bigCode = code; } string contollerPath = libraryPath + "/Controller"; ModuleHelper.CreateDirectory(contollerPath); destinationPath = contollerPath + "/" + moduleName + "Controller.cs"; using (StreamWriter sw = new StreamWriter(destinationPath)) { using (StreamReader rdr = new StreamReader(filePathController)) { code = rdr.ReadToEnd(); } string controllerCode = ModuleHelper.ControllerCode(columnlist, moduleName).ToString(); code = code.Replace("//properties", controllerCode); code = code.Replace("ModuleName", moduleName); bigCode += "\n" + code; string references = "using System; using System.Collections.Generic;"; code = code.Replace("//references", references); sw.Write(code); } string dataProviderPath = libraryPath + "/DataProvider"; ModuleHelper.CreateDirectory(dataProviderPath); destinationPath = dataProviderPath + "/" + moduleName + "DataProvider.cs"; using (StreamWriter sw = new StreamWriter(destinationPath)) { using (StreamReader rdr = new StreamReader(filePathDataProvider)) { code = rdr.ReadToEnd(); } string dataProviderCode = ModuleHelper.DataProviderCode(columnlist, moduleName, updateList, autoIncrement).ToString(); code = code.Replace("//properties", dataProviderCode); code = code.Replace("ModuleName", moduleName); bigCode += "\n" + code; string references = "using System;\n using SageFrame.Web.Utilities;\n using System.Collections.Generic;\n"; code = code.Replace("//references", references); sw.Write(code); } } catch (Exception ex) { ShowMessage("", ex.ToString(), "", SageMessageType.Error); ProcessException(ex); } if (isNewModule) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); //CSharpCodeProvider csp = new CSharpCodeProvider(); // ICodeCompiler cc = provider.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); string OutputAssembly = Path.Combine(Server.MapPath("/bin/"), "SageFrame." + moduleName + ".dll"); cp.OutputAssembly = OutputAssembly; cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "bin\\SageFrame.Common.dll"); cp.WarningLevel = 3; //cp.CompilerOptions = "/target:library /optimize"; cp.GenerateExecutable = false; cp.GenerateInMemory = false; System.CodeDom.Compiler.TempFileCollection tfc = new TempFileCollection(GetApplicationName, false); CompilerResults cr = new CompilerResults(tfc); cr = provider.CompileAssemblyFromSource(cp, bigCode); if (cr.Errors.Count > 0) { string error = string.Empty; foreach (CompilerError ce in cr.Errors) { error += ce.ErrorNumber + ": " + ce.ErrorText; } ShowMessage("", error, "", SageMessageType.Error); isCompiled = false; } else { isCompiled = true; } } return isCompiled; }
public static Assembly CompileCSharp(EditForm editForm, string CSharpCode) { // Code compiler and provider CodeDomProvider cc = new CSharpCodeProvider(); // Compiler parameters CompilerParameters cp = new CompilerParameters(); // Sept 15, 2007 -> 3, 30 oct 2007 -> 4 if (!Properties.Settings.Default.SkipWarnings) { cp.WarningLevel = 4; } // Add common assemblies cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // LSLEditor.exe contains all base SecondLife class stuff cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); // Compiling to memory cp.GenerateInMemory = true; // Does this work? cp.IncludeDebugInformation = true; // Wrap strCSharpCode into my namespace string strRunTime = "namespace LSLEditor\n{\n"; strRunTime += CSharpCode; strRunTime += "\n}\n"; int intDefaultLineNumber = FindDefaultLineNumber(strRunTime); // Here we go CompilerResults cr = cc.CompileAssemblyFromSource(cp, strRunTime); // get the listview to store some errors ListView ListViewErrors = editForm.parent.SyntaxErrors.ListView; // Console.WriteLine(cr.Errors.HasWarnings.ToString()); // Check for compilation errors... if (ListViewErrors != null && (cr.Errors.HasErrors || cr.Errors.HasWarnings)) { int intNr = 1; foreach (CompilerError err in cr.Errors) { int intLine = err.Line; if (intLine < intDefaultLineNumber) { intLine -= 4; } else { intLine -= 5; } string strError = OopsFormatter.ApplyFormatting(err.ErrorText); int intImageIndex = 0; if (err.IsWarning) { intImageIndex = 1; } ListViewItem lvi = new ListViewItem(new string[] { "", // 0 intNr.ToString(), // 1 strError, // 2 editForm.ScriptName, // 3 intLine.ToString(), // 4 err.Column.ToString(), // 5 editForm.ProjectName, // 6 editForm.FullPathName, // 7 editForm.guid.ToString(), // 8 editForm.IsScript.ToString() // 9 }, intImageIndex); ListViewErrors.Items.Add(lvi); intNr++; } return(null); } return(cr.CompiledAssembly); }
/// <summary> /// Compiles a written function from source into a DLL. /// </summary> /// <param name="commandName">Name of the command file to be compiled (without the extension)</param> /// <returns>True on successful compile, false on failure.</returns> public static bool Compile(string commandName) { string divider = new string('-', 25); if (!File.Exists(sourcepath + "Cmd" + commandName + ".cs")) { bool check = File.Exists("logs/errors/compiler.log"); StreamWriter errlog = new StreamWriter("logs/errors/compiler.log", check); if (check) { errlog.WriteLine(); errlog.WriteLine(divider); errlog.WriteLine(); } errlog.WriteLine("File not found: Cmd" + commandName + ".cs"); errlog.Dispose(); return(false); } if (!Directory.Exists(dllpath)) { Directory.CreateDirectory(dllpath); } parameters.GenerateExecutable = false; parameters.MainClass = commandName; parameters.OutputAssembly = dllpath + "Cmd" + commandName + ".dll"; parameters.ReferencedAssemblies.Add("MCWorlds_.dll"); StreamReader sr = new StreamReader(sourcepath + "cmd" + commandName + ".cs"); results = compiler.CompileAssemblyFromSource(parameters, sr.ReadToEnd()); sr.Dispose(); switch (results.Errors.Count) { case 0: return(true); case 1: CompilerError error = results.Errors[0]; bool exists = (File.Exists("logs/errors/compiler.log")) ? true : false; StringBuilder sb = new StringBuilder(); if (exists) { sb.AppendLine(); sb.AppendLine(divider); sb.AppendLine(); } sb.AppendLine("Error " + error.ErrorNumber); sb.AppendLine("Message: " + error.ErrorText); sb.AppendLine("Line: " + error.Line); StreamWriter sw = new StreamWriter("logs/errors/compiler.log", exists); sw.Write(sb.ToString()); sw.Dispose(); return(false); default: exists = (File.Exists("logs/errors/compiler.log")) ? true : false; sb = new StringBuilder(); bool start = true; if (exists) { sb.AppendLine(); sb.AppendLine(divider); sb.AppendLine(); } foreach (CompilerError err in results.Errors) { if (!start) { sb.AppendLine(); sb.AppendLine(divider); sb.AppendLine(); } sb.AppendLine("Error #" + err.ErrorNumber); sb.AppendLine("Message: " + err.ErrorText); sb.AppendLine("Line: " + err.Line); if (start) { start = false; } } sw = new StreamWriter("logs/errors/compiler.log", exists); sw.Write(sb.ToString()); sw.Dispose(); return(false); } }
/* goodB2G1() - use badsource and goodsink by changing second PRIVATE_CONST_TRUE to PRIVATE_CONST_FALSE */ private void GoodB2G1() { string data; if (PRIVATE_CONST_TRUE) { data = ""; /* Initialize data */ { /* read user input from console with ReadLine */ try { /* POTENTIAL FLAW: Read data from the console using ReadLine */ data = Console.ReadLine(); } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }
public void Test_That_SupressWarningsFrom_Filters_Out_A_Single_Warning() { // Arrange var jscBadTypeForBitOperationWarning = new CompilerError { Type = WarningCode.JscBadTypeForBitOperation }; var jscConstructorNotCallableWarning = new CompilerError { Type = WarningCode.JscConstructorNotCallable }; var results = new CompilerResults { Warnings = new List<CompilerError> { new CompilerError { Type = WarningCode.JscBadDeleteOperand }, jscBadTypeForBitOperationWarning, jscConstructorNotCallableWarning, } }; var supressWarnings = new List<string> { WarningCode.JscBadDeleteOperand, }; // Act results.SupressWarningsFrom(supressWarnings); // Assert Assert.Equal(2, results.Warnings.Count); Assert.True(results.Warnings.Any(w => w == jscBadTypeForBitOperationWarning)); Assert.True(results.Warnings.Any(w => w == jscConstructorNotCallableWarning)); }
protected abstract void ProcessCompilerOutputLine(CompilerResults results, string line);
private CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { if (options == null) { throw new ArgumentNullException("options"); } if (fileNames == null) { throw new ArgumentNullException("fileNames"); } new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); string outputFile = null; int retValue = 0; var results = new CompilerResults(options.TempFiles); var perm1 = new SecurityPermission(SecurityPermissionFlag.ControlEvidence); perm1.Assert(); try { #pragma warning disable 618 results.Evidence = options.Evidence; #pragma warning restore 618 } finally { SecurityPermission.RevertAssert(); } bool createdEmptyAssembly = false; if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) { string extension = (options.GenerateExecutable) ? "exe" : "dll"; options.OutputAssembly = results.TempFiles.AddExtension(extension, !options.GenerateInMemory); // Create an empty assembly. This is so that the file will have permissions that // we can later access with our current credential. If we don't do this, the compiler // could end up creating an assembly that we cannot open. new FileStream(options.OutputAssembly, FileMode.Create, FileAccess.ReadWrite).Close(); createdEmptyAssembly = true; } var pdbname = "pdb"; // Don't delete pdbs when debug=false but they have specified pdbonly. if (options.CompilerOptions != null && -1 != CultureInfo.InvariantCulture.CompareInfo.IndexOf(options.CompilerOptions, "/debug:pdbonly", CompareOptions.IgnoreCase)) { results.TempFiles.AddExtension(pdbname, true); } else { results.TempFiles.AddExtension(pdbname); } string args = GetCompilationArgumentString(options) + " " + JoinStringArray(fileNames, " "); // Use a response file if the compiler supports it string responseFileArgs = GetResponseFileCmdArgs(options, args); string trueArgs = null; if (responseFileArgs != null) { trueArgs = args; args = responseFileArgs; } // Appending TTL to the command line arguments. if (_providerOptions.CompilerServerTimeToLive > 0) { args = string.Format("/shared /keepalive:\"{0}\" {1}", _providerOptions.CompilerServerTimeToLive, args); } Compile(options, CompilerName, args, ref outputFile, ref retValue); results.NativeCompilerReturnValue = retValue; // only look for errors/warnings if the compile failed or the caller set the warning level if (retValue != 0 || options.WarningLevel > 0) { // The output of the compiler is in UTF8 string[] lines = ReadAllLines(outputFile, Encoding.UTF8, FileShare.ReadWrite); bool replacedArgs = false; foreach (string line in lines) { if (!replacedArgs && trueArgs != null && line.Contains(args)) { replacedArgs = true; var outputLine = string.Format("{0}>{1} {2}", Environment.CurrentDirectory, CompilerName, trueArgs); results.Output.Add(outputLine); } else { results.Output.Add(line); } ProcessCompilerOutputLine(results, line); } // Delete the empty assembly if we created one if (retValue != 0 && createdEmptyAssembly) { File.Delete(options.OutputAssembly); } } if (retValue != 0 || results.Errors.HasErrors || !options.GenerateInMemory) { results.PathToAssembly = options.OutputAssembly; return(results); } // Read assembly into memory: byte[] assemblyBuff = File.ReadAllBytes(options.OutputAssembly); // Read symbol file into memory and ignore any errors that may be encountered: // (This functionality was added in NetFx 4.5, errors must be ignored to ensure compatibility) byte[] symbolsBuff = null; try { string symbFileName = options.TempFiles.BasePath + "." + pdbname; if (File.Exists(symbFileName)) { symbolsBuff = File.ReadAllBytes(symbFileName); } } catch { symbolsBuff = null; } // Now get permissions and load assembly from buffer into the CLR: var perm = new SecurityPermission(SecurityPermissionFlag.ControlEvidence); perm.Assert(); try { #pragma warning disable 618 // Load with evidence is obsolete - this warning is passed on via the options.Evidence property results.CompiledAssembly = Assembly.Load(assemblyBuff, symbolsBuff, options.Evidence); #pragma warning restore 618 } finally { SecurityPermission.RevertAssert(); } return(results); }
public static CompilerResults Build(string path, Project project) { string code = BuildCode(project); WindowMain.Singleton.OverlayTitle = "Compiling '" + Path.GetFileName(path) + "'"; WindowMain.Singleton.OverlayIsIndeterminate = true; string manifestPath = null; try { bool isManifestResource; manifestPath = Path.GetTempFileName(); byte[] manifestFile; switch (project.Manifest) { case BuildManifest.None: manifestFile = Properties.Resources.FileManifestNone; isManifestResource = true; break; case BuildManifest.AsInvoker: manifestFile = Properties.Resources.FileManifestAsInvoker; isManifestResource = false; break; case BuildManifest.RequireAdministrator: manifestFile = Properties.Resources.FileManifestRequireAdministrator; isManifestResource = false; break; default: throw new InvalidOperationException(); } File.WriteAllBytes(manifestPath, manifestFile); using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } })) { string platformName; switch (project.Platform) { case BuildPlatform.Win32: platformName = "x86"; break; case BuildPlatform.Win64: platformName = "x64"; break; case BuildPlatform.AnyCPU: platformName = "anycpu"; break; default: throw new InvalidOperationException(); } CompilerParameters parameters = new CompilerParameters { GenerateExecutable = true, GenerateInMemory = true, OutputAssembly = path, CompilerOptions = "/nostdlib /target:winexe /platform:" + platformName + (isManifestResource ? null : " /win32manifest:" + manifestPath), Win32Resource = isManifestResource ? manifestPath : null }; parameters.ReferencedAssemblies.AddRange(new[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Windows.Forms.dll" }); CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count == 0 && project.IconPath != null) { WindowMain.Singleton.OverlayTitle = "Applying icon '" + Path.GetFileName(project.IconPath) + "'"; new ResourceFileInfo(path).ChangeIcon(project.IconPath); } return(results); } } finally { if (manifestPath != null) { File.Delete(manifestPath); } } }
private void DynamicInvocation(string wsUrl, TreeView tv, ref MethodInfo[] methodInfo) { try { Uri uri = new Uri(wsUrl); //txtUrl.Text); WebRequest webRequest = WebRequest.Create(uri); System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream(); // Get a WSDL file describing a service ServiceDescription sd = ServiceDescription.Read(requestStream); string sdName = sd.Services[0].Name; // Add in tree view TreeNode n = new TreeNode(sdName); tv.Nodes.Add(n); //treMethods.Nodes.Add(n); // Initialize a service description servImport ServiceDescriptionImporter servImport = new ServiceDescriptionImporter(); servImport.AddServiceDescription(sd, String.Empty, String.Empty); servImport.ProtocolName = "Soap"; servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CodeNamespace nameSpace = new CodeNamespace(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(nameSpace); // Set Warnings ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit); if (warnings == 0) { StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture); Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(); prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions()); // Compile the assembly with the appropriate references string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" }; CompilerParameters par = new CompilerParameters(assemblyReferences); par.GenerateExecutable = false; par.GenerateInMemory = true; par.TreatWarningsAsErrors = false; par.WarningLevel = 4; CompilerResults results = new CompilerResults(new TempFileCollection()); results = prov.CompileAssemblyFromDom(par, codeCompileUnit); Assembly assembly = results.CompiledAssembly; service = assembly.GetType(sdName); methodInfo = service.GetMethods(); foreach (MethodInfo t in methodInfo) { if (t.Name == "Discover") break; n = new TreeNode(t.Name); tv.Nodes[0].ChildNodes.Add(n); } tv.Nodes[0].Expand(); } else lblMsg.Text += warnings; } catch (Exception ex) { lblMsg.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString(); ; } }
protected override void ProcessCompilerOutputLine(CompilerResults results, string line) { throw new NotImplementedException(); }
public void StartCompile(CompileOptions compileOptions) { try { CompilerResults results = Compile(compileOptions); if (CompileFinished != null) { CompileFinished(this, results); } } catch (Exception ex) { CompilerResults results = new CompilerResults { Success = false, Errors = new List<string> { ex.ToString() } }; if (CompileFinished != null) { CompileFinished(this, results); } } }
public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public CompilerResults compileFromCompilationUnits(CompilerParameters parameters, CompilationUnitNode[] compilationUnits) { var results = new CompilerResults(); this.context = new CompilerContext(parameters, results); this.statementValidator = new StatementValidator(this.context); this.expressionValidator = new ExpressionValidator(this.context); this.statementValidator.ExpressionValidator = this.expressionValidator; this.expressionValidator.StatementValidator = this.statementValidator; this.reachabilityChecker = new ReachabilityChecker(context); this.assignmentChecker = new AssignmentChecker(context); this.bytecodeGenerator = new BytecodeGenerator(context); foreach (var cu in compilationUnits) { context.CompilationUnits.add(cu); } doCompile(); this.context = null; this.statementValidator = null; this.expressionValidator = null; this.reachabilityChecker = null; this.assignmentChecker = null; this.queryTranslator = null; this.documentationBuilder = null; if (parameters.ProgressTracker != null) { parameters.ProgressTracker.compilationFinished(); } return results; }
internal void method_14(Rule rule_1, bool bool_4) { if (rule_1 != null) { rule_1.QueryResults.Problems = new ObservableCollection <Problem>(); rule_1.QueryResults.Output = ""; string code = rule_1.Code; List <string> list = new List <string> { "CodeDom", "IO", "Net", "Media", "Reflection", "Runtime", "Security", "Threading", "Web", "Windows" }; Builder builder = new Builder("|"); foreach (string current in list) { builder.Append(string.Concat(new string[] { "^(?<namespace>System\\.", current, ")\\.|[\\s;:!{}()[\\]](?<namespace>System\\.", current, ")\\." })); } MatchCollection matchCollection = Regex.Matches(code, builder.ToString()); if (matchCollection.Count > 0) { string description = "It looks like you're trying to use a class in the \"" + matchCollection[0].Groups["namespace"].Value + "\" namespace.\r\nWe can't let you complete the query because of security concerns, sorry.\r\nIf you believe you've received this message erroneously please contact [email protected] with the text of your query"; ObservableCollection <Problem> observableCollection = new ObservableCollection <Problem>(); observableCollection.Add(new Problem { Description = description, ProblemType = RuleStatus.CompileError }); rule_1.QueryResults.Problems = observableCollection; rule_1.QueryResults.Results = null; rule_1.QueryResults.Description = "The query \"" + rule_1.Name + "\" had a compile time error"; } else { string text = "\r\n\t\t\t\t using System;\r\n\t\t\t\t using System.Collections; \r\n using System.Collections.Generic; \r\n\t\t\t\t using System.Linq;\r\n\t\t\t\t using System.Text;\r\n\t\t\t\t using System.Text.RegularExpressions;\r\n\t\t\t\t using Nitriq.Analysis.Models;\r\n\t\t\t\t \r\n\t\t\t\t namespace Runner\r\n\t\t\t\t {\r\n\t\t\t\t public static class ExtensionMethods\r\n\t\t\t\t {\r\n\t\t\t\t public static int Count(this IEnumerable enumerable)\r\n\t\t\t\t {\r\n\t\t\t\t if (enumerable == null)\r\n\t\t\t\t return 0;\r\n\r\n\t\t\t\t int count = 0;\r\n\r\n\t\t\t\t foreach (object obj in enumerable)\r\n\t\t\t\t count++;\r\n\r\n\t\t\t\t return count;\r\n\t\t\t\t }\r\n\r\n public static List<object> ToList(this IEnumerable enumerable)\r\n {\r\n List<object> list = new List<object>();\r\n foreach (object obj in enumerable)\r\n {\r\n list.Add(obj);\r\n }\r\n return list;\r\n }\r\n\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public class RunnerClass\r\n\t\t\t\t {\r\n\t\t\t\t //public BfCache _cache;\r\n\t\t\t\t \r\n\t\t\t\t public void ConsoleWrite(object message)\r\n\t\t\t\t {\r\n\t\t\t\t ConsoleWrite(message.ToString());\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void ConsoleWriteLine(object message)\r\n\t\t\t\t {\r\n\t\t\t\t ConsoleWriteLine(message.ToString());\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void ConsoleWrite(string message)\r\n\t\t\t\t {\r\n\t\t\t\t _debug(message);\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void ConsoleWriteLine(string message)\r\n\t\t\t\t {\r\n\t\t\t\t _debug(message + \"\\r\\n\");\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void Warn(bool condition, string message)\r\n\t\t\t\t {\r\n\t\t\t\t if (condition)\r\n\t\t\t\t _warn(message);\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void Error(bool condition, string message)\r\n\t\t\t\t {\r\n\t\t\t\t if (condition)\r\n\t\t\t\t _error(message);\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void Warn(IEnumerable results, int resultsCount)\r\n\t\t\t\t {\r\n\t\t\t\t if (results.Count() > resultsCount)\r\n\t\t\t\t _warn(\"More than \" + resultsCount + \" results were returned\");\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void Error(IEnumerable results, int resultsCount)\r\n\t\t\t\t {\r\n\t\t\t\t if (results.Count() > resultsCount)\r\n\t\t\t\t _error(\"More than \" + resultsCount + \" results were returned\");\r\n\t\t\t\t }\r\n\r\n /*\r\n\t\t\t\t public void Warn(bool condition)\r\n\t\t\t\t {\r\n\t\t\t\t if (condition)\r\n\t\t\t\t _warnNoMsg();\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public void Error(bool condition)\r\n\t\t\t\t {\r\n\t\t\t\t if (condition)\r\n\t\t\t\t _errorNoMsg();\r\n\t\t\t\t }\r\n */\r\n\r\n\t\t\t\t Action<string> _debug;\r\n\t\t\t\t Action<string> _warn;\r\n\t\t\t\t Action<string> _error;\r\n\t\t\t\t Action _warnNoMsg;\r\n\t\t\t\t Action _errorNoMsg;\r\n\r\n\t\t\t\t public RunnerClass(BfCache cache, Action<string> debug, Action<string> warn, Action<string> error, Action warnNoMsg, Action errorNoMsg)\r\n\t\t\t\t {\r\n\t\t\t\t //_cache = cache;\r\n\t\t\t\t _assemblies = cache.Assemblies;\r\n\t\t\t\t _namespaces = cache.Namespaces;\r\n\t\t\t\t _types = cache.Types;\r\n\t\t\t\t _methods = cache.Methods;\r\n\t\t\t\t _fields = cache.Fields;\r\n\t\t\t\t _events = cache.Events;\r\n\r\n\t\t\t\t _debug = debug;\r\n\t\t\t\t _warn = warn;\r\n\t\t\t\t _error = error;\r\n\t\t\t\t _warnNoMsg = warnNoMsg; \r\n\t\t\t\t _errorNoMsg = errorNoMsg;\r\n\t\t\t\t } \r\n\r\n\r\n\t\t\t\t private AssemblyCollection _assemblies;\r\n\t\t\t\t public AssemblyCollection Assemblies\r\n\t\t\t\t {\r\n\t\t\t\t get { return _assemblies; }\r\n\t\t\t\t set { _assemblies = value; }\r\n\t\t\t\t }\r\n\r\n\t\t\t\t private NamespaceCollection _namespaces;\r\n\t\t\t\t public NamespaceCollection Namespaces\r\n\t\t\t\t {\r\n\t\t\t\t get { return _namespaces; }\r\n\t\t\t\t set { _namespaces = value; }\r\n\t\t\t\t }\r\n\t\t\t\t \r\n\t\t\t\t private TypeCollection _types;\r\n\t\t\t\t public TypeCollection Types\r\n\t\t\t\t {\r\n\t\t\t\t get { return _types; }\r\n\t\t\t\t set { _types = value; }\r\n\t\t\t\t }\r\n\r\n\t\t\t\t private MethodCollection _methods;\r\n\t\t\t\t public MethodCollection Methods\r\n\t\t\t\t {\r\n\t\t\t\t get { return _methods; }\r\n\t\t\t\t set { _methods = value; }\r\n\t\t\t\t }\r\n\r\n\t\t\t\t private FieldCollection _fields;\r\n\t\t\t\t public FieldCollection Fields\r\n\t\t\t\t {\r\n\t\t\t\t get { return _fields; }\r\n\t\t\t\t set { _fields = value; }\r\n\t\t\t\t }\r\n\r\n\t\t\t\t private EventCollection _events;\r\n\t\t\t\t public EventCollection Events\r\n\t\t\t\t {\r\n\t\t\t\t get { return _events; }\r\n\t\t\t\t set { _events = value; }\r\n\t\t\t\t }\r\n\r\n\t\t\t\t public object RunMethod()\r\n\t\t\t\t {\r\n\t\t\t\t \r\n\t\t\t\t "; int count = Regex.Matches(text, "\\r\\n").Count; string text2 = text + code + "\r\n\t\t\t\t \r\n return results.ToList();\r\n \r\n\t\t\t\t }\r\n\t\t\t\t }\r\n\t\t\t\t }\r\n\r\n\t\t\t\t "; CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v3.5" } }); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.ReferencedAssemblies.Add(MainViewModelBase.string_0); compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Data.Linq.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("WindowsBase.dll"); compilerParameters.ReferencedAssemblies.Add("PresentationCore.dll"); compilerParameters.ReferencedAssemblies.Add("PresentationFramework.dll"); Stopwatch stopwatch = Stopwatch.StartNew(); CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, new string[] { text2 }); stopwatch.Stop(); if (compilerResults.Errors.Count != 0) { rule_1.QueryResults.Problems = this.method_18(compilerResults.Errors, count); rule_1.QueryResults.Results = null; rule_1.Status = RuleStatus.CompileError; if (!bool_4) { this.Status = string.Concat(new object[] { "The query \"", rule_1.Name, "\" had ", rule_1.QueryResults.Problems, " compilation errors" }); this.method_17(new LightWrapper(rule_1.QueryResults.Results, this.bfCache_0)); } this.method_11(false); } else { stopwatch = Stopwatch.StartNew(); Assembly compiledAssembly = compilerResults.CompiledAssembly; Type type = compiledAssembly.GetType("Runner.RunnerClass"); string text3 = "You don't have any analyzed assemblies loaded"; try { ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(BfCache), typeof(Action <string>), typeof(Action <string>), typeof(Action <string>), typeof(Action), typeof(Action) }); Action <string> action = delegate(string message) { QueryResults expr_0B = rule_1.QueryResults; expr_0B.Output += message; }; Action <string> action2 = delegate(string message) { rule_1.QueryResults.Problems.Add(new Problem { Description = message, ProblemType = RuleStatus.Warning }); }; Action <string> action3 = delegate(string message) { rule_1.QueryResults.Problems.Add(new Problem { Description = message, ProblemType = RuleStatus.Error }); }; Action action4 = delegate { rule_1.QueryResults.Problems.Add(new Problem { Description = string.Concat(new object[] { "\"", rule_1.Name, "\" returned ", rule_1.QueryResults.Results.Count(), " results" }), ProblemType = RuleStatus.Warning }); }; Action action5 = delegate { rule_1.QueryResults.Problems.Add(new Problem { Description = string.Concat(new object[] { "\"", rule_1.Name, "\" returned ", rule_1.QueryResults.Results.Count(), " results" }), ProblemType = RuleStatus.RuntimeError }); }; if (this.bfCache_0 == null) { throw new Exception(text3); } object obj = constructor.Invoke(new object[] { this.bfCache_0, action, action2, action3, action4, action5 }); MethodInfo method = type.GetMethod("RunMethod"); rule_1.QueryResults.Results = (IEnumerable)method.Invoke(obj, null); if (rule_1.QueryResults.ResultCount != 0 && rule_1.QueryResults.IdPropertyName == null) { rule_1.QueryResults.Problems.Add(new Problem { ProblemType = RuleStatus.Warning, Description = "This query's results type does not contain a TypeId, MethodId, FieldId, EventId, AssemblyId or NamespaceId.\r\nWithout one of these fields, Nitriq is unable to generate the CodeTree, nor is it able to highlight the results in the TreeMap" }); } if (!bool_4) { this.method_17(new LightWrapper(rule_1.QueryResults.Results, this.bfCache_0)); } rule_1.QueryResults.Description = string.Concat(new object[] { "The query \"", rule_1.Name, "\" has a successfully completed with ", rule_1.QueryResults.Results.Cast <object>().Count(), " items" }); if (rule_1 == this.CurrentRule) { this.method_11(true); } } catch (Exception ex) { ObservableCollection <Problem> observableCollection = new ObservableCollection <Problem>(); Problem problem = new Problem { Description = ex.ToString(), ProblemType = RuleStatus.RuntimeError }; if (ex.Message == text3) { problem.Description = text3; } observableCollection.Add(problem); rule_1.QueryResults.Problems = observableCollection; rule_1.QueryResults.Results = null; rule_1.QueryResults.Description = "The query \"" + rule_1.Name + "\" had a runtime error"; if (rule_1 == this.CurrentRule) { this.method_11(false); } } rule_1.CalculateStatus(); this.FirePropertyChanged("CurrentRule"); if (!bool_4) { this.Status = rule_1.QueryResults.Description; } stopwatch.Stop(); } } } }
private string EvalCode(string code, Contract.Page page, dynamic instance) { Assembly assembly = null; string codeHash = code.Hash(); if (!CacheManager.Session.CachedItemExists("themeCode", codeHash)) { CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.ReferencedAssemblies.AddRange(page.References.ToArray()); compilerParameters.CompilerOptions = string.Format("/t:library /lib:{0},{1}", HttpContext.Current.Server.MapPath("./bin/"), HttpContext.Current.Server.MapPath("./bin/Libraries/")); compilerParameters.GenerateInMemory = false; #region sourceCode string sourceCode = @"using System; using System.Xml; using System.Data; using System.Web; using System.Text; using BlazeSoft.Net.Web; using BlazeSoft.Net.Web.Core; using BlazeSoft.Net.Web.Link; public class CodeEvaler { public string Output = string.Empty; public dynamic Parent; public HttpContext Http; public ThemeLink Themes; public SettingsLink Settings; public dynamic Modules; public PageLink Pages; public void Write(object message, params object[] parameters) { string text = message != null ? message.ToString() : """"; for (int parameter = 0; parameter < parameters.Length; parameter++) text = text.Replace(""{"" + parameter + ""}"", parameters[parameter] != null ? parameters[parameter].ToString() : ""{NULL}""); Output += text; } public void WriteLine(object message, params object[] parameters) { string text = message != null ? message.ToString() : """"; for (int parameter = 0; parameter < parameters.Length; parameter++) text = text.Replace(""{"" + parameter + ""}"", parameters[parameter] != null ? parameters[parameter].ToString() : ""{NULL}""); Output += text + ""\r\n""; } public void Include(string templateFile) { Write(Themes.GetTheme().GetTemplateAndParse(templateFile, Parent)); } public void Eval() { " + code + @" } }"; #endregion CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(compilerParameters, sourceCode); if (compilerResults.Errors.Count > 0) { throw new Exceptions.TemplateSyntaxException(string.Format("{0} on line {1}", compilerResults.Errors[0].ErrorText, compilerResults.Errors[0].Line)); } assembly = Assembly.Load(File.ReadAllBytes(compilerResults.PathToAssembly)); CacheManager.Session.AddCachedItem("themeCode", codeHash, assembly); } assembly = CacheManager.Session.GetCachedItem("themeCode", codeHash); dynamic evalInstance = assembly.CreateInstance("CodeEvaler"); try { evalInstance.Http = instance.Http; evalInstance.Themes = instance.Themes; evalInstance.Settings = instance.Settings; evalInstance.Modules = instance.Modules; evalInstance.Pages = instance.Pages; } catch (RuntimeBinderException) { evalInstance.Http = HttpContext.Current; } evalInstance.Parent = instance; try { evalInstance.Eval(); } catch (Exception e) { throw new Exceptions.TemplateSyntaxException(e.Message); } return(evalInstance.Output); }
private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName) { DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); // if paramset is defaultcredential, set the flag in wcclient if (_usedefaultcredential.IsPresent) { dcp.UseDefaultCredentials = true; } // if paramset is credential, assign the credentials if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase)) { dcp.Credentials = _credential.GetNetworkCredential(); } try { dcp.AllowAutoRedirect = true; dcp.DiscoverAny(_uri.ToString()); dcp.ResolveAll(); } catch (WebException ex) { ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri); if (ex.InnerException != null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } WriteError(er); return(null); } catch (InvalidOperationException ex) { ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri); WriteError(er); return(null); } // create the namespace CodeNamespace codeNS = new CodeNamespace(); if (!string.IsNullOrEmpty(NameSpace)) { codeNS.Name = NameSpace; } // create the class and add it to the namespace if (!string.IsNullOrEmpty(ClassName)) { CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName); codeClass.IsClass = true; codeClass.Attributes = MemberAttributes.Public; codeNS.Types.Add(codeClass); } // create a web reference to the uri docs WebReference wref = new WebReference(dcp.Documents, codeNS); WebReferenceCollection wrefs = new WebReferenceCollection(); wrefs.Add(wref); // create a codecompileunit and add the namespace to it CodeCompileUnit codecompileunit = new CodeCompileUnit(); codecompileunit.Namespaces.Add(codeNS); WebReferenceOptions wrefOptions = new WebReferenceOptions(); wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; wrefOptions.Verbose = true; // create a csharpprovider and compile it CSharpCodeProvider csharpprovider = new CSharpCodeProvider(); StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions); StringBuilder codegenerator = new StringBuilder(); StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture); try { csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null); } catch (NotImplementedException ex) { ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); WriteError(er); } // generate the hashcode of the CodeCompileUnit _sourceHash = codegenerator.ToString().GetHashCode(); // if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so // return the instance of th eproxy in the cache if (s_srccodeCache.ContainsKey(_sourceHash)) { object obj; s_srccodeCache.TryGetValue(_sourceHash, out obj); WriteObject(obj, true); return(null); } CompilerParameters options = new CompilerParameters(); CompilerResults results = null; foreach (string warning in Warnings) { this.WriteWarning(warning); } // add the references to the required assemblies options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); options.ReferencedAssemblies.Add("System.Xml.dll"); options.ReferencedAssemblies.Add("System.Web.Services.dll"); options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); GetReferencedAssemblies(typeof(Cmdlet).Assembly, options); options.GenerateInMemory = true; options.TreatWarningsAsErrors = false; options.WarningLevel = 4; options.GenerateExecutable = false; try { results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString()); } catch (NotImplementedException ex) { ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); WriteError(er); } return(results.CompiledAssembly); }
public override void Bad() { string data; switch (6) { case 6: data = ""; /* Initialize data */ /* Read data using an outbound tcp connection */ { try { /* Read data using an outbound tcp connection */ using (TcpClient tcpConn = new TcpClient("host.example.org", 39544)) { /* read input from socket */ using (StreamReader sr = new StreamReader(tcpConn.GetStream())) { /* POTENTIAL FLAW: Read data using an outbound tcp connection */ data = sr.ReadLine(); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; break; } switch (7) { case 7: StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); /* POTENTIAL FLAW: Compile sourceCode containing unvalidated user input */ CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
public static void LoadCombatClass(string pathToCombatClassFile, bool settingOnly = false, bool resetSettings = false, bool cSharpFile = true) { try { _pathToCombatClassFile = pathToCombatClassFile; if (_instanceFromOtherAssembly != null) { _instanceFromOtherAssembly.Dispose(); } _instanceFromOtherAssembly = null; _assembly = null; _obj = null; if (cSharpFile) { CodeDomProvider cc = new CSharpCodeProvider(); var cp = new CompilerParameters(); IEnumerable <string> assemblies = AppDomain.CurrentDomain .GetAssemblies() .Where( a => !a.IsDynamic && !a.CodeBase.Contains((Process.GetCurrentProcess().ProcessName + ".exe"))) .Select(a => a.Location); cp.ReferencedAssemblies.AddRange(assemblies.ToArray()); StreamReader sr = File.OpenText(pathToCombatClassFile); string toCompile = sr.ReadToEnd(); CompilerResults cr = cc.CompileAssemblyFromSource(cp, toCompile); if (cr.Errors.HasErrors) { String text = cr.Errors.Cast <CompilerError>().Aggregate("Compilator Error :\n", (current, err) => current + (err + "\n")); Logging.WriteError(text); MessageBox.Show(text); return; } _assembly = cr.CompiledAssembly; _obj = _assembly.CreateInstance("Main", true); _threadName = "CombatClass CS"; } else { _assembly = Assembly.LoadFrom(_pathToCombatClassFile); _obj = _assembly.CreateInstance("Main", false); _threadName = "CombatClass DLL"; } if (_obj != null && _assembly != null) { _instanceFromOtherAssembly = _obj as ICombatClass; if (_instanceFromOtherAssembly != null) { if (settingOnly) { if (resetSettings) { _instanceFromOtherAssembly.ResetConfiguration(); } else { _instanceFromOtherAssembly.ShowConfiguration(); } _instanceFromOtherAssembly.Dispose(); return; } _worker = new Thread(_instanceFromOtherAssembly.Initialize) { IsBackground = true, Name = _threadName }; _worker.Start(); } else { Logging.WriteError("Custom Class Loading error."); } } } catch (Exception exception) { Logging.WriteError("LoadCombatClass(string _pathToCombatClassFile): " + exception); } }