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.
Related
I'm working on a small project that involves compiling code. I keep getting this error: An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Illegal characters in path.
I've tried finding the source of the problem, this line of code seems to be the problem: CompilerResults cr = provider.CompileAssemblyFromFile(parameters, source1);
This is my code for my class:
using System.IO;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace Plugin___Prototype
{
class CompileCode
{
public void Compile()
{
string source1 = File.ReadAllText(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\test.cs");
//string source2 = File.ReadAllText(#"Source path here");
Console.WriteLine(source1);
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("System.dll");
parameters.GenerateExecutable = true;
parameters.OutputAssembly = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\app1.exe";
Console.WriteLine(parameters.OutputAssembly);
parameters.GenerateInMemory = false;
CompilerResults cr = provider.CompileAssemblyFromFile(parameters, source1);
if (cr.Errors.Count == 0)
Console.WriteLine("No Errors");
else
{
foreach (CompilerError error in cr.Errors)
Console.WriteLine(error.ErrorText);
}
Console.ReadLine();
}
}
}
This is the output:
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Illegal characters in path.
The program '[14128] Plugin - Prototype.exe' has exited with code -1 (0xffffffff).
My expected result is for app1.exe to generated in my documents folder.
EDIT: These are the contents of source1:
// A Hello World! program in C#.
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
I've fixed it, CompilerResults cr = provider.CompileAssemblyFromFile(parameters, source1);, wanted the file not the contents of the file.
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.
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?