Why compiling this create an exe which :
open a console
launch the form ?
What can be done for the runtime compiled form open alone, without console ?
//LIST OF USING
using System;
using System.Windows.Forms;
using System.CodeDom.Compiler;
//CODE TO COMPILE
string oSource = #"
using System.Windows.Forms;
using System;
namespace fTest
{
public static class Program
{
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
public class MyForm:Form
{
public MyForm()
{
this.Text=""Generated exe"";
MessageBox.Show(""Generated exe says H3110 W0r1d"");
}
}
}";
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, oSource);
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);
}
By default, csc compiles console applications. You need to add /target:winexe to compiler options.
have you tried adding "target:winexe" to the command line parameters?
Related
I have the below code and I want to get some VPN with some settings that I need to setup:
What I need is to
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotRas;
namespace vpnConsole
{
class Program
{
static void Main(string[] args)
{
string vpnName = "VPN Essai";
string destination = "113.244.66.3";
string preSharedKey = "Gs0r2!-8753";
try
{
RasPhoneBook phoneBook = new RasPhoneBook();
phoneBook.Open();
RasEntry vpnEntry = RasEntry.CreateVpnEntry(vpnName,destination,RasVpnStrategy.L2tpFirst,RasDevice.Create(vpnName,RasDeviceType.Vpn),false);
vpnEntry.Options.UsePreSharedKey = true;
vpnEntry.Options.UseLogOnCredentials = true;
vpnEntry.Options.RequirePap = true;
phoneBook.Entries.Add(vpnEntry);
vpnEntry.UpdateCredentials(RasPreSharedKey.Client, preSharedKey);
vpnEntry.Options.RequirePap = true;
bool isUpdated = vpnEntry.Update();
Console.WriteLine(#"Connection created and Updated with PreSharedKey=true, LogOnCredentials=true,RequirePap=true, RecordIsUpdated=" + isUpdated);
}
catch (Exception ex)
{
Console.WriteLine(#"ERROR: " + ex.Message + " Details: " + ex.Source );
Environment.Exit(999);
}
}
}
}
When I ran this code, it creates the VPN but does not keep settings I want to setup, for instance: RequirePap = true;
Configuration as I need it to be
I wrote a program in C # that takes, from a WPF interface, a folder path, a prefix, and a prefix of substitution. The purpose of the program is to search in the folder all the files that start with the prefix and rename them with the new prefix. This program works without any problems.
Now I have to write a second program that must call the previous, passing the parameters using args []. I wrote this second program, it seems that all the parameters have passed correctly to the other (I checked it), but every time the replacement program runs out after a few seconds (while the normal run in my folder of Trial is almost instantly). I'm not able to have any message error or exception, I can only obtain the windows alert message that reports the crash.
Here is the significant part of the code of both programs ... Can anyone help me to find the problem? Is it a problem with settings passed from one program to another? Thanks a lot to everyone.
Can it maybe be a problem about the setting parameters of the calling?
Replace prefix program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace replace_prefix
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] args;
args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
((MainWindow)App.Current.MainWindow).Close();
sf_textBox.Text = args[1];
rp_textBox.Text = args[2];
np_textBox.Text = args[2];
replace();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void ok_button_Click(object sender, RoutedEventArgs e)
{
replace();
}
private void replace() {
if (sf_textBox.Text == "" || rp_textBox.Text == "" || np_textBox.Text == "")
MessageBox.Show(this, "Insert all required parameters", "Parameter missing", MessageBoxButton.OK, MessageBoxImage.Error);
else
{
using (StreamWriter w = File.CreateText("log.txt"))
{
DirectoryInfo d = new DirectoryInfo(sf_textBox.Text);
FileInfo[] Files = d.GetFiles("*.*");
string filename, log;
foreach (FileInfo file in Files)
{
filename = file.Name;
int Place = filename.IndexOf(rp_textBox.Text);
if (Place == 0)
{
log = "file " + filename + " renamed ";
filename = filename.Remove(Place, rp_textBox.Text.Length).Insert(Place, np_textBox.Text);
file.MoveTo(file.Directory.FullName + "\\" + filename);
Log(log + filename, w);
}
}
w.Close();
}
Environment.Exit(0);
}
}
public static void Log(string logMessage, TextWriter w)
{
w.Write(DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
w.Write(" --> ");
w.WriteLine(logMessage);
}
}
}
Calling method in the other program:
public void LaunchCommandLineApp()
{
using (StreamWriter wl = File.CreateText(job.name + "_log.txt"))
{
lock (wl) wl.WriteLine("\\n" + DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " launched");
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = job.process;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
var count = job.args.Count(c => c == ';');
startInfo.Arguments = "";// "-f ";
while (count > 1)
{
startInfo.Arguments += job.args.Substring(0, job.args.IndexOf(';', 0));
int i = job.args.IndexOf(';', 0) + 1, k = job.args.Length - 1;
job.args = job.args.Substring((job.args.IndexOf(';', 0) + 1), (job.args.Length - 1) - (job.args.IndexOf(';', 0)));
count--;
}
if (count == 1) {
int i = job.args.IndexOf(';', 0);
startInfo.Arguments += job.args.Substring(0, job.args.IndexOf(';', 0));
}
if (job.recurrency) job.updateRecurrency();
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
string tl;
try
{
tl = Path.GetDirectoryName(job.process);
}
catch (ArgumentException e) {
tl = null;
}
if (tl != null)
{
try
{
tl = tl + "\\log.txt";
StreamReader input = new StreamReader(tl);
tl = input.ReadLine();
while (tl != null)
{
wl.WriteLine(tl);
tl = input.ReadLine();
}
input.Close();
}
catch (Exception e) { }
}
lock (wl) wl.WriteLine(DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " successfully ended.");
}
}
catch (Exception e)
{
//add local process log
lock (wl) wl.WriteLine(DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " failed to ended. " + e.Message.ToString());
}
wl.Close();
InvokeExecutionFinished(new EventArgs());
}
//Send log via email
//sendNotification();
}
Crash report
I made a simple compiler to learn about CodeDom. But it does not work, when I try to open my compiled file it does nothing.
When I run the code and slect an dir to save the exe file the exe file is generated, but when I click the exe file it does nothing.
The builder:
using System;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Windows.Forms;
namespace TestBuilder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void build(string output, string title, string msg)
{
CompilerParameters p = new CompilerParameters();
p.GenerateExecutable = true;
p.ReferencedAssemblies.AddRange(new String[] { "System.dll"});
p.OutputAssembly = output;
p.CompilerOptions = "/t:winexe";
string source = File.ReadAllText(#"C:\Users\Gebruiker\Documents\visual studio 2015\Projects\TestCompiler\Test\Program.cs");
string errors = String.Empty;
source = source.Replace("[MESSAGE]", msg);
CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(p, source);
if (results.Errors.Count > 0)
{
foreach (CompilerError err in results.Errors)
{
errors += "Error: " + err.ToString() + "\r\n\r\n";
}
}
else errors = "Successfully built:\n" + output;
MessageBox.Show(errors, "Build", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "EXE files (*.exe)|*.exe";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.OK)
{
build(sfd.FileName, textBox1.Text, textBox1.Text);
}
}
}
}
The program.cs file:
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("[MESSAGE]");
Console.ReadLine();
}
}
}
How can I fix this problem, so when I compile a file and execute it, it shows the message I put in the textbox?
Change p.CompilerOptions = "/t:winexe"; to p.CompilerOptions = "/t:exe";.
After that the compiled program should output whatever you've put inside your TextBox when you run it.
Source
Use /target:exe to create a console application.
I'm using the code:
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();
string source = Properties.Resources.source;
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = sfd.FileName + ".exe";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.CompilerOptions = "/target:winexe";
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
parameters.ReferencedAssemblies.Add("System.Management.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll");
parameters.ReferencedAssemblies.Add("System.DirectoryServices.AccountManagement.dll");
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, Properties.Resources.source);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
MessageBox.Show("Error on line #" + CompErr.Line + " " + CompErr.ErrorText);
}
}
else
{
MessageBox.Show("Successfully Compiled.");
}
To compile my source, which is:
using System;
static void Main(string[] args)
{
}
I'm getting the error:
Error on line #0 Program 'c:\Users\Tom\Desktop\s.exe' does not contain a static 'Main' method suitable for an entry point
From Googling and looking here, I am unable to find why this is throwing an error..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
public static void Main(string[] args)
{
}
}
}
This is also not working, I'm getting the same error.
Here's my C# console program that uses Powerpoint to convert ppt files to folders of pngs. This is supposed to be an automated process that runs on its own server.
I expect that as soon as a thread creates an image from a file, it should immediately remove the images and the source file.
The actual behavior is that, if five threads are running, it'll wait for five folders of images to be created before any thread can move any files. I'm able to see the images being created, and compare that with the Console readout, so I can see that a thread isn't trying to move the file.
Only after all the other threads have made their images, will any thread try to move the files. I suspect this is wrong.
This is an Amazon EC2 Medium instance, and it appears to max out the CPU, so five threads might be too much for this.
I also find that I can hardly use Windows Explorer while this program is running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static int currThreads = 0;
static void Main(string[] args)
{
var inDir = args[0];
var outDir = args[1]+"\\";
var procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
Thread[] converterThreads = new Thread[threadLimit];
while (true)
{
System.Threading.Thread.Sleep(1000);
var filePaths = Directory.GetFiles(inDir, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".pptx") && !s.Contains("~$") || s.EndsWith(".ppt") && !s.Contains("~$"));
var arrPaths = filePaths.ToArray();
for(var i=0; i< arrPaths.Length; i++)
{
if (currThreads < threadLimit && currThreads < arrPaths.Length)
{
Console.WriteLine("currThreads= " + currThreads + " paths found= " + arrPaths.Length);
try
{
var fileNameWithoutExtension = arrPaths[currThreads].Replace(inDir, "").Replace(".pptx", "").Replace(".ppt", "").Replace("\\", "");
var filenameWithExtension = arrPaths[currThreads].Substring(arrPaths[currThreads].LastIndexOf("\\") + 1);
var dir = arrPaths[currThreads].Replace(".pptx", "").Replace(".ppt", "");
Conversion con = new Conversion(arrPaths[currThreads], dir, outDir, procDir, filenameWithExtension, fileNameWithoutExtension);
converterThreads[i] = new Thread(new ThreadStart(con.convertPpt));
converterThreads[i].Start();
Console.WriteLine(converterThreads[i].ManagedThreadId + " is converting " + fileNameWithoutExtension);
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to convert {0} ", arrPaths[i]) + e);
}
}
}
for (var i = 0; i < converterThreads.Length; i++)
{
if (converterThreads[i] != null)
{
if (!converterThreads[i].IsAlive)
{
converterThreads[i].Abort();
converterThreads[i].Join(1);
Console.WriteLine("thread " + converterThreads[i].ManagedThreadId + " finished, "+currThreads+" remaining");
converterThreads[i] = null;
}
}
}
if (currThreads == 0)
{
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
class Conversion{
static int numberOfThreads=0;
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
int elapsedTime;
System.Timers.Timer time;
public Conversion(String input, String output, String outDir, String processDir, String nameWith, String nameWithout)
{
this.input = input;
this.output = output;
this.outDir = outDir;
process = processDir;
this.nameWith = nameWith;
this.nameWithout = nameWithout;
numberOfThreads++;
Console.WriteLine("number of threads running: " + numberOfThreads);
Program.currThreads = numberOfThreads;
time = new System.Timers.Timer(1000);
time.Start();
time.Elapsed += new ElapsedEventHandler(OnTimedEvent);
elapsedTime = 0;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
elapsedTime++;
}
public void convertPpt()
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
try
{
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed");
}
moveFile();
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
Console.WriteLine("moving dir " + output);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
finally
{
numberOfThreads--;
Program.currThreads = numberOfThreads;
Console.WriteLine("took " + elapsedTime + "seconds");
}
}
}
}
Every 1000ms you get a list of files in inDir and potentially start a thread to process each file. You have very complex logic surrounding whether or not to start a new thread, and how to manage the lifetime of the thread.
The logic is too complex for me to spot the error without debugging the code. However, I would propose an alternative.
Have a single thread watch for new files and place the file path into a BlockingCollection of files for processing. That thread does nothing else.
Have N additional threads that retrieve file paths from the BlockingCollection and process them.
This is known as a Producer / Consumer pattern and is ideal for what you are doing.
The example code at the bottom of the linked MSDN page shows an implementation example.
On a side note, you are catching and swallowing Exception e3. Don't catch something you will not handle, it hides problems.