Creating winforms executable dynamically C# - c#

I want to create an application, that will take out the text from textBox1, compile it, and save it as an executable. I never tried this before, but I would really like to get it working. This is the code that I'm using in my "compiler" application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Diagnostics;
namespace Compiler
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
string Output = "out.exe";
Button ButtonObject = (Button)sender;
CompilerParameters parameters = new CompilerParameters();
string[] references = { "System.dll","System.Windows.Forms.dll","System.Drawing.dll" };
parameters.EmbeddedResources.AddRange(references);
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
MessageBox.Show(CompErr.ToString());
}
}
else
{
//Successful Compile
textBox1.ForeColor = Color.Blue;
textBox1.Text = "Success!";
}
}
}
}
The textbox1 text, meaning the source that I am trying to compile is:
class Program
{
static void Main(string[] args)
{
System.Windows.Forms.Form f = new System.Windows.Forms.Form();
f.ShowDialog();
}
}
Basically, I am trying to generate an executable file dynamically, that will just show a Form. I've also tried, instead of making and showing a form to show a System.Windows.MessageBox.Show("testing");
In both cases I get this errors:
Line number 5, Error Number: CS0234, 'The type or namespace name
'Windows' does not exist in the namespace 'System' (are you missing an
assembly reference?);
Line number 5, Error Number: CS0234, 'The type or namespace name
'Windows' does not exist in the namespace 'System' (are you missing an
assembly reference?);

You are adding 3 files ("System.dll","System.Windows.Forms.dll","System.Drawing.dll") as embedded resources not as references. Add them to ReferencedAssemblies instead.

Related

Dynamic c# compiler in Xamarin.Forms not finding type or namespace

I've got a Xamarin.Forms app to dynamically compile c# code on a button press, but I get errors in the code.
This is the code for the button being pressed:
{
string text = ((Editor)sender).Text;
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, text);
results.Errors.Cast<CompilerError>().ToList().ForEach(error => string errors = error.ErrorText;
}
and I am using:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
With the XAML being this:
<Button x:Name="compilebutton" Text="Compile" Clicked="oncompile" />
The type or namespace name 'CompilerParameters' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'CompilerResults' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'CompilerError' could not be found (are you missing a using directive or an assembly reference?)
I have tested this without Xamarin.Forms in a Console Application and it worked fine, i'm not sure what the issue is, any help would be appreciated, thanks!

Create new outlook email using Windows Forms

This is probably very beginner question. I am trying to create my first Windows Forms application and would like to create an outlook email message by clicking a button on my form.
The problem is that there are 13 errors mainly saying:
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'Outlook' could not be found
(are you missing a using directive or an assembly reference?) Offer
machine v.0.0.1 C:\Users\PC\source\repos\Offer machine v.0.0.1\Offer
machine v.0.0.1\Form1.cs 29 Active
I have added references to my project:
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Offer_machine_v._0._0._1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
List<string> lstAllRecipients = new List<string>();
//Below is hardcoded - can be replaced with db data
lstAllRecipients.Add("sanjeev.kumar#testmail.com");
lstAllRecipients.Add("chandan.kumarpanda#testmail.com");
Outlook.Application outlookApp = new Outlook.Application();
Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMailItem.GetInspector;
// Thread.Sleep(10000);
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
foreach (String recipient in lstAllRecipients)
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
//Add CC
Outlook.Recipient oCCRecip = oRecips.Add("THIYAGARAJAN.DURAIRAJAN#testmail.com");
oCCRecip.Type = (int)Outlook.OlMailRecipientType.olCC;
oCCRecip.Resolve();
//Add Subject
oMailItem.Subject = "Test Mail";
// body, bcc etc...
//Display the mailbox
oMailItem.Display(true);
}
catch (Exception objEx)
{
Response.Write(objEx.ToString());
}
}
private void Label1_Click(object sender, EventArgs e)
{
}
}
}
You are not adding the proper using to your code. You need to add:
using Microsoft.Office.Interop.Outlook;
Without this line you should type the full namespace before each object from the Interop libraries. With that using in place you can remove all the Outlook. before the objects coming from the interop. But the one creating the main Application object needs the full namespace to avoid conflicts with the Application class defined in Winforms.
Microsoft.Office.Interop.Outlook.Application outlookApp =
new Microsoft.Office.Interop.Outlook.Application();
_MailItem oMailItem = (_MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
Inspector oInspector = oMailItem.GetInspector;
..... and so on ....
It seems you have added Outlook interops to the project References twice.
As for the error message, you just need to add an alias to the Outlook namespace:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
Also, you may find the C# app automates Outlook (CSAutomateOutlook) sample project helpful.

the type or namespace component data is missing error in using MathWorks.MATLAB.NET.ComponentData; help me how to solve this error?

i am currently deploying matlab over .net i have included my matlab project dll and mwarray.dll of matlab run-time compiler successfully but when i tried in using component data i have 2 errors one is:
name space missing using MathWorks.MATLAB.NET.ComponentData;
second one is:
cannot convert type void MathWorks.MATLAB.NET.Arrays.Mwcellarray in
line cellout = (MWCellArray)obj.braille();
complete code is as mentioned below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsharpMatlab;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.ComponentData;
namespace MATCsharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Code For Matlab to C#");
MWCellArray cellout = null;
CsharpMatlab.CellExampleApp obj = new CsharpMatlab.CellExampleApp();
cellout = (MWCellArray)obj.braille();
MWNumericArray item1 = (MWNumericArray)cellout[1];
MWNumericArray item2 = (MWNumericArray)cellout[2];
MWCharArray item3 = (MWCharArray)cellout[3];
Console.WriteLine("item1 is {0}", item1);
Console.WriteLine("item2 is {0}", item2);
Console.WriteLine("item3 is {0}", item3);
Console.ReadLine();
}emphasized text
}
}

(C#) Compiling class at runtime and calling methods from original code

I'm trying to compile code at runtime in C#, then from the compiled code call a function or initialize a class which is defined in the original code.
The code I currently have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace CTFGame
{
class Program
{
static void Main(string[] args)
{
string code = #"
using System;
namespace CTFGame
{
public class MyPlayer
{
public static void Main ()
{
Console.WriteLine(""Hello world"");
}
/*public void DoTurn ()
{
Program.SayHello();
}*/
}
}
";
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
if (results.Errors.HasErrors)
{
string errors = "";
foreach (CompilerError error in results.Errors)
{
errors += string.Format("Error #{0}: {1}\n", error.ErrorNumber, error.ErrorText);
}
Console.Write(errors);
}
else
{
Assembly assembly = results.CompiledAssembly;
Type program = assembly.GetType("CTFGame.MyPlayer");
MethodInfo main = program.GetMethod("Main");
main.Invoke(null, null);
}
}
public static void SayHello()
{
Console.WriteLine("I'm awesome ><");
}
}
}
Now, Running the runtime loaded method 'Main' is a success, and the message "Hello world" is printed. The problem starts here: in the original code I have a method called "SayHello". I want to call this method from my runtime loaded code.
If I uncomment the "DoTurn" method, a compiler error will show in runtime:
Error #CS0103: The name 'Program' does not exist in the current context
My question is - is this possible, and how?
Putting the runtime loaded code in the same namespace doesn't help (and that makes sense), so what is the correct way to do that?
Thanks.
Adding a reference to the current assembly solved the problem:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
//The next line is the addition to the original code
parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);
More about:
Compiling c# at runtime with user defined functions

CSharpCodeProvider Compilation Performance

Is CompileAssemblyFromDom faster than CompileAssemblyFromSource?
It should be as it presumably bypasses the compiler front-end.
CompileAssemblyFromDom compiles to a .cs file which is then run through the normal C# compiler.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
namespace CodeDomQuestion
{
class Program
{
private static void Main(string[] args)
{
Program p = new Program();
p.dotest("C:\\fs.exe");
}
public void dotest(string outputname)
{
CSharpCodeProvider cscProvider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.MainClass = null;
cp.GenerateExecutable = true;
cp.OutputAssembly = outputname;
CodeNamespace ns = new CodeNamespace("StackOverflowd");
CodeTypeDeclaration type = new CodeTypeDeclaration();
type.IsClass = true;
type.Name = "MainClass";
type.TypeAttributes = TypeAttributes.Public;
ns.Types.Add(type);
CodeMemberMethod cmm = new CodeMemberMethod();
cmm.Attributes = MemberAttributes.Static;
cmm.Name = "Main";
cmm.Statements.Add(new CodeSnippetExpression("System.Console.WriteLine('f'zxcvv)"));
type.Members.Add(cmm);
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(ns);
CompilerResults results = cscProvider.CompileAssemblyFromDom(cp, ccu);
foreach (CompilerError err in results.Errors)
Console.WriteLine(err.ErrorText + " - " + err.FileName + ":" + err.Line);
Console.WriteLine();
}
}
}
which shows errors in a (now nonexistent) temp file:
) expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17
; expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17
Invalid expression term ')' - c:\Documents and Settings\jacob\Local Settings\Tem p\x59n9yb-.0.cs:17
So I guess the answer is "no"
I've tried finding the ultimate compiler call earlier and I gave up. There's quite a number of layers of interfaces and virtual classes for my patience.
I don't think the source reader part of the compiler ends up with a DOM tree, but intuitively I would agree with you. The work necessary to transform the DOM to IL should be much less than reading C# source code.

Categories

Resources