Lost in the matrix

C/C++/C#/Java, Multithreading

using System;
using System.CodeDom.Compiler;
using System.Diagnostics;

public class MicroCompiler
{
public MicroCompiler()
{
this.Language = "CSharp";
this.WarningLevel = 1;
this.OutputPath = "./~TMP.exe";
}

public bool Compile()
{
this.Result = string.Empty;
this.KillCompiledProgram();
using (CodeDomProvider codeProvider = CodeDomProvider.CreateProvider(this.Language))
{
// Paramètres de la compilation
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.WarningLevel = this.WarningLevel;
parameters.OutputAssembly = this.OutputPath;
// on compile
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters,
new string[] { this.Source });
// est ce qu'il y a des erreurs ?
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
this.Result += "Line: " + CompErr.Line + " : " + CompErr.ErrorNumber +
" => " + CompErr.ErrorText + Environment.NewLine;
return (false);
}
}
// on créer le processus pour éxecuter le code
this.CompiledProgram = new Process();
this.CompiledProgram.StartInfo.FileName = this.OutputPath;
return (true);
}

public bool KillCompiledProgram()
{
if (this.CompiledProgram == null || this.CompiledProgram.HasExited)
return (false);
this.CompiledProgram.Kill();
return (true);
}

public bool StartCompiledProgram()
{
if (this.CompiledProgram == null)
return (false);
return (this.CompiledProgram.Start());
}

#region Properties

// Niveau d'avertissement.
public int WarningLevel { get; set; }

// Emplacement du programme généré
public string OutputPath { get; set; }

// Résultat de la compilation
public string Result { get; private set; }

// Le code source
public string Source { get; set; }

// Langage de la source (ex: CSharp)
public string Language { get; set; }

// Instance du programme en exécution.
public Process CompiledProgram { get; private set; }

#endregion
}

namespace Test
{
class Program
{
static void Main(string[] args)
{
MicroCompiler mc = new MicroCompiler();
mc.Source = "mettre le code C# ici!";
if (mc.Compile())
mc.StartCompiledProgram();
}
}
}

0 commentaires:

Enregistrer un commentaire