How can i compile a c# winform application programmatically in c# - c#

I have created a tool that open a c# Winform application, the question is after I made some modification to the files I want to recompile those files programmatically using c#.

You can do it by using CSharpCodeProvider. You can find more information about this class in documentation.

after searching i have use this solution :
String[] csFiles = CopyAllSourceFilesToCLASSESFolder().ToArray();
String[] referenceAssemblies = { "System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "ICSharpCode.TextEditor.dll", "System.Xml.dll", "System.IO.dll", "System.ComponentModel.dll" , "System.Data.dll" , "System.linq.dll" };
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
string Output = "Out.exe";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(referenceAssemblies);
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromFileBatch(parameters, csFiles);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
ErrorTextBox.Text = ErrorTextBox.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
ErrorTextBox.ForeColor = Color.Blue;
ErrorTextBox.Text = "Success!";
//If we clicked run then launch our EXE
}
Process.Start(Output);

Related

How do I programmatically compile a C# Windows Forms App from a richtextbox? C#

I am trying to do a Visual Studio kind of program, which allows you to type code into a RichTextBox. After pressing F5(Compile), it would compile the code. How would the user compile said code? I know how to use the ConsoleApplication Compiler, but not compiling Windows Forms :(
Could someone help? A code-example is preferable, but at this point, I'll accept ANYTHING!
My current code for Console Apps is this:
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
string Output = "MCCACOut.exe";
Button ButtonObject = (Button)sender;
richTextBox201.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters, richTextBox301.Text);
if (results.Errors.Count > 0)
{
richTextBox201.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
richTextBox201.Text = richTextBox201.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
richTextBox201.ForeColor = Color.Blue;
richTextBox201.Text = "Success!";
//If we clicked run then launch our EXE
Process.Start(Output);
}
Could anyone convert this to compile WinForms instead of ConsoleApp? :)
I think you have to save your file with .cs extension and invoke a process to compile it using c# compiler csc.exe.
After saving the file, you can compile the code using,
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe [options] filename.cs
Take a look at this for options
You can invoke a process to do this from your IDE.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe filename.cs";
process.StartInfo = startInfo;
process.Start();
Hope this helps.
Finally, after many, many times of struggling, I got it to work :) With the help of Nishan Chathuranga
string compiledOutput = "Generated.exe";
//COMPILATION WORK
String[] referenceAssemblies = { "System.dll", "System.Drawing.dll", "System.Windows.Forms.dll" };
CodeDomProvider _CodeCompiler = CodeDomProvider.CreateProvider("CSharp");
System.CodeDom.Compiler.CompilerParameters _CompilerParameters =
new System.CodeDom.Compiler.CompilerParameters(referenceAssemblies, "");
_CompilerParameters.OutputAssembly = compiledOutput;
_CompilerParameters.GenerateExecutable = true;
_CompilerParameters.GenerateInMemory = false;
_CompilerParameters.WarningLevel = 3;
_CompilerParameters.TreatWarningsAsErrors = true;
_CompilerParameters.CompilerOptions = "/optimize /target:winexe";//!! HERE IS THE SOLUTION !!
string _Errors = null;
try
{
// Invoke compilation
CompilerResults _CompilerResults = null;
_CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, richTextBox1.Text);
if (_CompilerResults.Errors.Count > 0)
{
// Return compilation errors
_Errors = "";
foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors)
{
_Errors += "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";\r\n\r\n";
}
}
}
catch (Exception _Exception)
{
// Error occurred when trying to compile the code
_Errors = _Exception.Message;
}
//AFTER WORK
if (_Errors == null)
{
// lets run the program
MessageBox.Show(compiledOutput + " Compiled !");
System.Diagnostics.Process.Start(compiledOutput);
}
else
{
MessageBox.Show("Error occurred during compilation : \r\n" + _Errors);
}
This works like a charm!

C# - Compile c# code at runtime with custom configuration

I has a question, does CodeDom Compiler can compile c# code with custom configuration such as x64 bit or x86 bit.By default it compiles c# code to .exe with "Any CPU" configuration.
Compiling c# code:
public static string BCS(string[] sources,string[] libs,string outPath,bool exef)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters(libs);
parameters.GenerateExecutable = exef;
parameters.OutputAssembly = outPath;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sources);
if (results.Errors.Count > 0)
{
string errsText = "";
foreach (CompilerError CompErr in results.Errors)
{
errsText = "("+CompErr.ErrorNumber +
")Line " + CompErr.Line +
",Column "+CompErr.Column +
":"+CompErr.ErrorText + "" +
Environment.NewLine;
}
return errsText;
}
else
{
return "Success";
}
}
I think,youre understand my question,if not, leave a comment,i will give details.
Try to set CompilerOptions this way
parameters.CompilerOptions = "-platform:anycpu32bitpreferred";
using params from this link
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/platform-compiler-option
P.S. CSharpCodeProvider uses csc.exe
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe

c# generate hocr file using charlesw tesseract

how can i generate hocr using the tesseract wrapper here
currently i need to dynamically add the location of the tessdata to the environment variables and run my code
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + #"\tesseract-3.05.00dev-win32-vc19\tesseract.exe";
string inputImg = #"00067.jpg";
string hocrLocation = #"00067";
string argsPdf = "\"" + inputImg + "\"" + " " + "\"" + hocrLocation + "\"" + " hocr ";
Console.WriteLine(argsPdf);
pProcess.StartInfo.Arguments = argsPdf;
pProcess.StartInfo.CreateNoWindow = false;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
Console.WriteLine("OUtput: " + strOutput);
pProcess.WaitForExit();
and then i found the tesseract wrapper. how can i generate an hocr file using the wrapper? i cant find an example how to do it.
this is the current code(from the example ) im using but how to output an hocr file?
var testImagePath = "./phototest.tif";
if (args.Length > 0)
{
testImagePath = args[0];
}
try
{
using (var engine = new TesseractEngine(#"./tessdata", "eng", EngineMode.Default))
{
using (var img = Pix.LoadFromFile(testImagePath))
{
using (var page = engine.Process(img))
{
}
}
}
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
Console.WriteLine("Unexpected Error: " + e.Message);
Console.WriteLine("Details: ");
Console.WriteLine(e.ToString());
}
string hocrText = page.GetHOCRText(pageNum - 1);

how to prevent to open in console my dynamically generated exe

I am working in c# 4.0, i want to generate an executable file dynamically, so i used Code Dome, but when i executes it open in console and after then my form displays, i want to generate winform executable file. How can i achieve my aim. the code is below :
string Code = #"
using System;
using System.Windows.Forms;
namespace CSBSS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public class Form1 : Form
{
}
}
";
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string tempFolder = #"..\DynamicOutput";
string Output = System.IO.Path.Combine(tempFolder, #"CSBSS.exe");
if (!System.IO.Directory.Exists(tempFolder))
{
System.IO.Directory.CreateDirectory(tempFolder);
}
else
{
if (System.IO.File.Exists(Output)) System.IO.File.Delete(Output);
}
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
parameters.TempFiles = new TempFileCollection(tempFolder, false);
//Make sure we generate an exe.
parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, Code);
string OutputMsg = "";
if (results.Errors.Count > 0)
{
string msgDescr = "";
foreach (CompilerError CompErr in results.Errors)
{
msgDescr += "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
OutputMsg = #"Error occured while generating executable file, please check following internal error
" + msgDescr;
//return false;
}
else
{
OutputMsg = "Executable file has been generated successfully.";
}
Specify the output type to be a Windows application by using the CompilerOptions:
parameters.CompilerOptions = "/target:winexe";

C# code validation in Silverlight GUI

I'm making a Silverlight app for students and I'm looking for a key component. In the application, the students should be able to add C# code (one class) in a text box. What I would like to do, is to: Validate that the code is valid C# and ideally also make sure it correctly implements a given interface. Is there a control out there which can help me with this?
Chris
Example Code based on the CodecomProvider:
private void button1_Click(object sender, System.EventArgs e)
{
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
textBox2.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}
}
Add the beginning of the file, add these using statements:
using System.CodeDom.Compiler;
using System.Diagnostics;
Just to conclude and answer my own question (thanks to Luke Woodward): This isn't possible as the System.CodeDom.Compiler namespace is just about empty in the Silverlight framework :-(

Categories

Resources