Is it possible to compile any given C# code in textbox, and then save it to an exe?
Is this possible? If so, how can it be done?
Yes, it is possible. You could use CodeDOM. And here's an example:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
#"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Rnge(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
Apart from compiling the code at runtime, you can just save the code from your textbox to disk, and then use csc.exe to compile it. The command would look similar to the following:
%systemroot%\Microsoft.NET\Framework\v3.5\csc /out:filename.exe filename.cs
Related
I'v been facing this problem for hours now.
I'm playing a little bit with codedom but i get : a type or namespace Threading not found.
My compilator code is this one:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CodeDom
{
public class Compiler
{
public Compiler(string sourceCode, string savePath)
{
string[] referencedAssemblies = new string[] { "System.dll", "System.Windows.Forms.dll", "System.Threading.Thread.dll" };
Dictionary<string, string> providerOptions = new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } };
string compilerOptions = "/target:winexe /platform:anycpu /optimize+";
using (CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(providerOptions))
{
CompilerParameters compilerParameters = new CompilerParameters(referencedAssemblies)
{
GenerateExecutable = true,
GenerateInMemory = false,
OutputAssembly = savePath,
CompilerOptions = compilerOptions,
TreatWarningsAsErrors = false,
IncludeDebugInformation = false,
};
CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters,sourceCode); // source.cs
if (compilerResults.Errors.Count > 0)
{
foreach (CompilerError compilerError in compilerResults.Errors)
{
MessageBox.Show(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", compilerError.ErrorText,
compilerError.Line, compilerError.Column, compilerError.FileName));
}
return;
}
else
{
MessageBox.Show("Compiled!");
}
}
}
}
}
I dont understand , I've referenced correctly the dll System.Threading.Thread.dll but it still don't find it.
Can you try System.Threading.dll it should be without Thread in the name.
I try to get balance in address.
It is my code:
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nethereum.Web3;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Bananas().Wait();
}
static private async Task Bananas()
{
var publicKey = "0xC0b4ec83028307053Fbe8d00ba4372384fe4b52B";
var web3 = new Nethereum.Web3.Web3("https://ropsten.infura.io/myInfura");
//var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(publicKey);
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
var etherAmount = Web3.Convert.FromWei(balance.Value);
Console.WriteLine(web3);
Console.WriteLine("Get txCount ", etherAmount);
Console.ReadLine();
}
}
}`
I installed Nethereum via PM console: Nethereum.
I use a normal link of infura.
Why don`t I get a next result without the balance in address?
I have just made a console application with your code and all the data is coming back fine from Nethereum.
Your issue is with your Console.WriteLine(... You are passing the etherAmount as a arg0 property into the Console.WriteLine which will not output correctly on the console when you run it.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nethereum.Web3;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Bananas().Wait();
}
static private async Task Bananas()
{
var publicKey = "0xC0b4ec83028307053Fbe8d00ba4372384fe4b52B";
var web3 = new Nethereum.Web3.Web3("https://ropsten.infura.io/myInfura");
//var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(publicKey);
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
var etherAmount = Web3.Convert.FromWei(balance.Value);
Console.WriteLine(web3);
Console.WriteLine("Get txCount " + etherAmount);
Console.ReadLine();
}
}
}
ps nice 1110.337873197299357846 ETH ;) (i know it is only test ETH but we can dream)
i have a class which is static and the it has one method which is also static. Now i'm trying to call this method from powerbuilder 12.5.2. When i run the program it gives me error i.e.
"Name not found calling external object function test at line 18 in open event of object w_main." How do I call this method from powerbuilder. I cant use Main method as i have to return an object and as far i know Main method can return int of void.
This is code of my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("ConsoleApplication1.CallWebService")]
public class CallWebService
{
public static ServiceReference1.DataResult callService(string
programId, string loginName, string [] arr)
{
try
{
string [] test = new string [1] ;
test[0] = "Yes";
System.IO.File.WriteAllLines("C:\\test.txt", test);
ServiceReference1.ESSServiceClient reService = new
ServiceReference1.ESSServiceClient();
ServiceReference1.DataPara para = new
ServiceReference1.DataPara();
para.AppAsset = arr;
ServiceReference1.DataResult ss = new
ServiceReference1.DataResult();
ss = reService.WSRes(programId, loginName, para);
return ss;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
This is code of powerbuilder :
String msg,arr[]
int li_providerType,li_rtn
oleobject lole_docx
dataresult res
TRY
any var
lole_docx = create oleobject
res = create dataresult
li_rtn = lole_docx.ConnectToNewObject("ConsoleApplication1.CallWebService")
IF li_rtn <> 0 then
MessageBox( "Error", "Error Loading DLL")
destroy lole_docx
ELSE
arr[1] = "A-Z000001,1"
res = lole_docx.callService("CM-WA-0001","naphas",arr)
destroy lole_docx
END IF
CATCH(RuntimeError er)
MessageBox( "Error", er.getmessage())
END TRY
Error in code
cmd result
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using RDotNet;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
namespace Con_R2
{
class Program
{
static string rPath = "";
static void Main(string[] args)
{
SetupPath(); // current process, soon to be deprecated
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
engine.Initialize(); // required since v1.5
REngine.SetDllDirectory(rPath);
foreach (string path in engine.Evaluate(".libPaths()").AsCharacter())
{
Console.WriteLine(path);
}
engine.Evaluate(".libPaths(C:\\Program Files\\R\\R-3.3.1\\library)");
engine.Evaluate("source('c:/Program Files/R/R-3.3.1/bin/clustering_loadprofiles.r')");
Console.ReadLine();
Console.ReadKey();
}
}
public static void SetupPath(string Rversion = "R-3.3.1")
{
var oldPath = System.Environment.GetEnvironmentVariable("PATH");
rPath = System.Environment.Is64BitProcess ?
string.Format(#"C:\Program Files\R\{0}\bin\x64", Rversion) :
string.Format(#"C:\Program Files\R\{0}\bin\i386", Rversion);
if (!Directory.Exists(rPath))
throw new DirectoryNotFoundException(
string.Format(" R.dll not found in : {0}", rPath));
var newPath = string.Format("{0}{1}{2}", rPath,
System.IO.Path.PathSeparator, oldPath);
System.Environment.SetEnvironmentVariable("PATH", newPath);
}
}
}
Getting this error
Error in sqlFetch(channel, "sysadmin.loadprofile_allcustomers") :
first argument is not an open RODBC channel In addition: Warning
messages: 1: In RODBC::odbcDriverConnect("DSN=informix116") :
[RODBC] ERROR: state IM014, code 0, message [Microsoft][ODBC Driver
Manager] he specified DSN contains an architecture mismatch between
the Driver and Appl ation 2: In
RODBC::odbcDriverConnect("DSN=informix116") : ODBC connection failed
I am creating a cutomization software which will do all the standardization to a mst file.
Below is the code of class that will change product name and genrate transform.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WindowsInstaller;
using System.Data;
namespace Automation
{
class CustomInstaller
{
public CustomInstaller()
{
}
public Record getInstaller(string msiFile,MsiOpenDatabaseMode mode,string query)
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer inst = (Installer)Activator.CreateInstance(type);
Database db = inst.OpenDatabase(msiFile, mode);
WindowsInstaller.View view = db.OpenView(query);
view.Execute(null);
Record record = view.Fetch();
db.Commit();
return record;
}
public bool generateTrans(string file1, string file2,string transName)
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer inst = (Installer)Activator.CreateInstance(type);
Database db1 = inst.OpenDatabase(file1, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
try
{
Database db2 = inst.OpenDatabase(file2, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
return db2.GenerateTransform(db1, transName);
}
catch (Exception e) { }
return false;
}
public int editTransform(string msiFile, MsiOpenDatabaseMode mode, string query)
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer inst = (Installer)Activator.CreateInstance(type);
Database db = inst.OpenDatabase(msiFile, mode);
WindowsInstaller.View view = db.OpenView(query);
view.Execute(null);
db.Commit();
int o=(int)db.DatabaseState;
db = null;
inst = null;
type = null;
return 1;
}
}
}
First editTransform() is called which will create a copy of original msi and do some changes in it, then generateTrans() is called which will get difference detween two msi files and create a transform file.
Now issue is when genrateTrans() is called, then it goes to catch block of it as inst.OpenDatabase return "MSI Api Error".
It seems to me that the copy of file crated by editTransform is still locked by it and is not available for use for generateTrans() menthod.
Please help here.
PS: mode used for edit transform is transact.
Instead of doing the COM Interop, checkout the far superior interop library ( Microsoft.Deployment.WindowsInstaller ) found in Windows Installer XML Deployment Tools Foundation. You'll find it much easier to use.
using System;
using System.IO;
using Microsoft.Deployment.WindowsInstaller;
namespace ConsoleApplication1
{
class Program
{
const string REFERENCEDATABASE = #"C:\orig.msi";
const string TEMPDATABASE = #"C:\temp.msi";
const string TRANSFORM = #"c:\foo.mst";
static void Main(string[] args)
{
File.Copy(REFERENCEDATABASE, TEMPDATABASE, true);
using (var origDatabase = new Database(REFERENCEDATABASE, DatabaseOpenMode.ReadOnly))
{
using (var database = new Database(TEMPDATABASE, DatabaseOpenMode.Direct))
{
database.Execute("Update `Property` Set `Property`.`Value` = 'Test' WHERE `Property`.`Property` = 'ProductName'");
database.GenerateTransform(origDatabase, TRANSFORM);
database.CreateTransformSummaryInfo(origDatabase, TRANSFORM, TransformErrors.None, TransformValidations.None);
}
}
}
}
}