Files
Pilz/Pilz.Updating/Scripts/ScriptManager.vb
2019-09-30 16:18:53 +02:00

72 lines
2.2 KiB
VB.net

Imports System.CodeDom.Compiler
Imports System.Reflection
Imports Microsoft.CSharp
Imports Pilz.Updating.Model
Imports Pilz.Updating.Scripts
Namespace Scripts
Public Class ScriptManager
Public Property ApplicationPath As String
Public Property UpdatePackagePath As String
Public Sub New(applicationPath As String, updatePackagePath As String)
Me.ApplicationPath = applicationPath
Me.UpdatePackagePath = updatePackagePath
End Sub
Private Function CompileScript(script As Script) As CompilerResults
Dim provider As CodeDomProvider = Nothing
Dim params As New CompilerParameters
'Create code provider
Select Case script.Language
Case CodeLanguage.CSharp
provider = New CSharpCodeProvider
Case CodeLanguage.VB
provider = New VBCodeProvider
End Select
'Set general options
params.GenerateExecutable = False
params.GenerateInMemory = True
'Set references
params.ReferencedAssemblies.Add()
'Compile
Dim res As CompilerResults = provider.CompileAssemblyFromSource(params, script.Code)
Return res
End Function
Public Function CheckScriptForErrors(script As Script) As CompilerErrorCollection
Return CompileScript(script).Errors
End Function
Public Sub ExecuteScript(script As Script)
'Compile script
Dim res As CompilerResults = CompileScript(script)
If Not res.Errors.HasErrors Then
'Get Method
Dim mi As MethodInfo = res.CompiledAssembly.GetType("Program")?.GetMethod("Main")
If mi IsNot Nothing Then
'Create params
Dim params As New Dictionary(Of String, String) From {
{"ApplicationPath", ApplicationPath},
{"UpdatePackagePath", UpdatePackagePath}
}
'Execute method
mi.Invoke(Nothing, {params})
End If
End If
End Sub
End Class
End Namespace