I am using VB.Net with Visual Studio 2019 and have been attempting this for a couple days and have been unsuccessful with DoWork. I did do some research and while exploring more threads similar to this, they are 7-12 years old, and do not seem to cut it for me.
I did get an example from Import code from text VB.NET
I am trying to have the Codedom script read the text file and run the code from inside it.
I have a couple errors which I will explain after the below code.
The Textfile called deploythis.txt has MsgBox("Success")
inside it.
Imports System.CodeDom.Compiler
Imports System.IO
Imports System.Reflection
Public Class Form1
Public Interface IScript
Property Variable1 As String
Sub DoWork()
End Interface
Private Function GenerateScript(code As String) As IScript
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location)
parameters.ReferencedAssemblies.Add("System.Data.dll")
parameters.ReferencedAssemblies.Add("System.Xml.dll")
Dim interfaceNamespace As String = GetType(IScript).Namespace
Dim codeArray() As String = New String() {"Imports " & interfaceNamespace & Environment.NewLine & code}
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeArray)
If results.Errors.HasErrors Then
Throw New Exception("Failed to compile script")
Else
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End If
End Using
End Function
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dthis As String = "C:\deploythis.txt"
Dim script As IScript = GenerateScript(File.ReadAllText(dthis))
script.DoWork()
MessageBox.Show(script.Variable1)
End Sub
End Class
When running this script, the first error comes from results
. However it does not list an actual error, warning or message. Just highlights Throw New Exception("Failed to compile script")
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeArray)
If results.Errors.HasErrors Then
Throw New Exception("Failed to compile script")
Else
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End If
If I remove Throw New Exception("Failed to compile script")
from the if statement,
I result in a new error from script.DoWork()
, which says "Object reference not set to an instance of an object."
This error is actually a Warning which says Function GenerateScript doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
Thanks for your time.