Problems getting C# code to compile dynamically within application

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Here is what I am trying:


<div style="color:Black; background-color:White
<pre> <span style="color:Blue public

Script(<span style="color:Blue string

language)
{
<span style="color:Green // CSharp / VisualBasic

_codeProvider = CodeDomProvider.CreateProvider(language);
_icc = _codeProvider.CreateCompiler();
}

<span style="color:Blue private
ICodeCompiler _icc;
<span style="color:Blue private
CodeDomProvider _codeProvider;

<span style="color:Blue private
ScriptForm _scriptForm;
<span style="color:Blue public
ScriptForm ScriptF
{
<span style="color:Blue get
{ <span style="color:Blue return
_scriptForm; }
<span style="color:Blue set
{ _scriptForm = value; } }

<span style="color:Blue public
<span style="color:Blue void
Compile()
{
CompilerParameters parameters = <span style="color:Blue new
CompilerParameters();
parameters.GenerateExecutable = <span style="color:Blue false
;
CompilerResults results = _icc.CompileAssemblyFromSource(parameters, ScriptF.CompilerSource());

<span style="color:Blue if
(results.Errors.Count < 1)
{
results.CompiledAssembly.EntryPoint.Invoke(<span style="color:Blue new
<span style="color:Blue object
(), <span style="color:Blue new
<span style="color:Blue object
[0]);
}
<span style="color:Blue else

<span style="color:Blue foreach
(CompilerError CompErr <span style="color:Blue in
results.Errors)
{
<span style="color:Blue string
output = <span style="color:Blue string
.Format(<span style="color:#a31515 "Line number {0}, Error number {1}, Error text: n{2}"
, CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText);<br/>
ScriptF.CompilerOutput(output);
}
}
[/code]



The error I get is "object reference not set to an instance of an object" when I compile the following code:


<div style="color:Black; background-color:White
<pre><span style="color:Blue using
System;

<span style="color:Blue class
Script
{
<span style="color:Blue static
<span style="color:Blue public
<span style="color:Blue void
Main(<span style="color:Blue string
[] args)
{
<span style="color:Blue for
(<span style="color:Blue int
i = 0; i < args.Length; i++)
{
Console.WriteLine(args);
}
}
}
[/code]


I have also tried:

<pre>results.CompiledAssembly.EntryPoint.Invoke(<span style="color:blue null, null
);<br/>

[/code]

Any ideas?


View the full article
 
Back
Top