Results 1 to 6 of 6

Thread: Scripting or executing .net code in run time

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Dec 2009
    Location
    sydney
    Posts
    265

    Scripting or executing .net code in run time

    Hello,

    i have a requirement in my program to calculate price based on cetain rules which varies depending on different paramters. these rules varies between items and are updated on regular basis and is not practical to hardcode in the actual system.

    Not sure if doable, but a good approach would be a text script which runs outside the program and returns a decimal value to main program

    and the only thing that comes to mind is python, it would write a price value into a text file or temp datatable which then is read by main program, this involves a learning curve as im not familiar with python

    any better suggestions? of a scripting language that can integrate with vb.net

    Thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: Scripting or executing .net code in run time

    What sort of rules do you mean? I would think that you could write VB code to read in records that represent the rules and process them based on type, operators, etc. I've done that sort of thing before for a web site that needed to validate uploaded files and the validation rules were stored in the database and could be added or edited after deployment.

    If you go for a script then it's not something that you would integrate specifically with your VB code, so the choice of language is yours. You'd probably call Process.Start to execute the script and then either call WaitForExit or handle the Exited event of the Process object to know when to proceed. Another option might be to use a FileSystemWatcher to watch a specific folder for the output file. If you do the latter, I would recommend writing the file with one name and then renaming it when you're done. That way, you can use the FSW to look for the rename, which ensures that the file isn't locked by the other process when you try to read it.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Dec 2009
    Location
    sydney
    Posts
    265

    Re: Scripting or executing .net code in run time

    Thanks for your reply, i will do some research about python

    it is for custom manufacturing, and end users will be distributors sales reps. plus there is an array of specifications to be defined by consumers. so the calculation will be driven by multiple aspects from all 3 parties.

    i have done similar work in the past using visual fox pro, which allowed code parsing during run time. and was pretty simple to modify the code in winform text editors and it just runs

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: Scripting or executing .net code in run time

    I guess the other option would be to write your app to use CodeDom to compile some additional code at run-time and then execute it.

  5. #5
    Frenzied Member
    Join Date
    May 2014
    Location
    Central Europe
    Posts
    1,372

    Re: Scripting or executing .net code in run time

    Quote Originally Posted by jmcilhinney View Post
    I guess the other option would be to write your app to use CodeDom to compile some additional code at run-time and then execute it.
    and this is how it works:
    Code:
        Private Function CompileCode(Code As String) As IScript
            Dim oParams As New CodeDom.Compiler.CompilerParameters
            oParams.GenerateInMemory = True
            oParams.TreatWarningsAsErrors = False
            oParams.WarningLevel = 4
            Dim sAssemblies() As String
    
            sAssemblies = "mscorlib.dll,System.dll,System.Windows.Forms.dll,System.Data.dll,System.Drawing.dll".Split(","c)
            oParams.ReferencedAssemblies.AddRange(sAssemblies)
            oParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location)
    
            Dim oVBProvider As CodeDom.Compiler.CodeDomProvider = CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic")
            Dim sImports As String = "Imports System,System.Windows.Forms,System.Collections.Generic,System.Drawing"
    
            Dim sb As New System.Text.StringBuilder
            With sb
                .AppendLine(sImports)
                .AppendLine("Namespace " & GetType(IScript).Namespace)
                .Append(Code & Environment.NewLine)
                .AppendLine("End Namespace")
            End With
    
            Dim oCompilerResults As CodeDom.Compiler.CompilerResults = oVBProvider.CompileAssemblyFromSource(oParams, sb.ToString)
    
            Dim oScript As IScript
            If oCompilerResults.Errors.Count > 0 Then
                Throw New Exception("Fehler beim Kompilieren des Codes!" & Environment.NewLine & oCompilerResults.Errors(0).ErrorText)
            Else
                Try
                    oScript = CType(oCompilerResults.CompiledAssembly.CreateInstance($"{GetType(IScript).Namespace}.Script"), IScript)
                Catch ex As Exception
                    Throw New Exception("Fehler beim Erstellen des Script Objekts!")
                End Try
            End If
            Return oScript
        End Function
    Code:
    Public Interface IScript
        Property ScriptHost As Object
        Function Run(Parameters As String) As String
    End Interface
    Code:
    class Script
    	Implements IScript
    
    	public Property ScriptHost as object implements IScript.ScriptHost
    
    	public Function Run(Parameters As String) As String Implements IScript.Run
                'your code here
    
    	end Function
    end class
    i am using this is some of my projects and it works really well apart from beeing a bit slow if many scripts get involved.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,041

    Re: Scripting or executing .net code in run time

    I would suggest a different approach. Can you say what the function would look like? For example, can you say which variables would be included and what the return type would be? If so, then you can declare a delegate type in a dll and reference that by the main project. You might have several different delegate types if there is more than one function. You might also have a simple interface which may be nothing more than this:

    Having done that, you can now set up a plugin system. The various different functions could be added to the main project by creating them in separate dlls that referenced the one dll with the delegate declarations. You would then load the dlls dynamically, use reflection to get the functions, and pass them to wherever they were needed.

    That's a rough outline. The actual work is pretty simple, though not commonly done. Interfaces might make even more sense in the common dll. You might have an interface that has a single function in it. The plugin dlls would just have a class that implements that interface. This would be an alternative to a delegate. The point is that your main program would be able to look at the plugins it had, get the alternatives from those plugins, and use whichever one was appropriate.

    By doing this, you would be able to swap out one function for another by copying/removing files in and out of some target folder. That would be safer than dynamically compiling code, because it could all be tested elsewhere. If you dynamically compile code, and the code has a bug, you have a dynamic mess.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width