Back to our script editing dialog. In the handler procedure for the Ok button, we need to use the procedure we've just written to compile the source code. We'll start by getting the path to the assembly the compiler needs to reference - our interfaces assembly. This is easy since it's in the same directory as the running host application. Then we clear our "errors" listview and run the CompileScript
function.
[VB]
Dim results As CompilerResults
Dim reference As String
'Find reference
reference = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
If Not reference.EndsWith("\") Then reference &= "\"
reference &= "interfaces.dll"
'Compile script
lvwErrors.Items.Clear()
results = Scripting.CompileScript(ScriptSource, reference, _
Scripting.Languages.VB)
[C#]
CompilerResults results;
string reference;
// Find reference
reference = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
if (!reference.EndsWith(@"\"))
reference += @"\";
reference += "interfaces.dll";
// Compile script
lvwErrors.Items.Clear();
results = Scripting.CompileScript(ScriptSource, reference,
Scripting.Languages.VB);
Next we look at the Errors collection of our results. If it is empty, the compile succeeded. In this case, we use our FindInterface
method to instantiate the class from the assembly and store it, then return DialogResult.Ok
to the procedure that showed the script editor. If the Errors
collection is not empty, we iterate through it populating the listview with all the errors that occured during the compile.
[VB]
Dim err As CompilerError
Dim l As ListViewItem
'Add each error as a listview item with its line number
For Each err In results.Errors
l = New ListViewItem(err.ErrorText)
l.SubItems.Add(err.Line.ToString())
lvwErrors.Items.Add(l)
Next
MessageBox.Show("Compile failed with " & results.Errors.Count.ToString() & _
" errors.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Stop)
[C#]
ListViewItem l;
// Add each error as a listview item with its line number
foreach (CompilerError err in results.Errors)
{
l = new ListViewItem(err.ErrorText);
l.SubItems.Add(err.Line.ToString());
lvwErrors.Items.Add(l);
}
MessageBox.Show("Compile failed with " + results.Errors.Count.ToString() +
" errors.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
Comments