473,782 Members | 2,525 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

run function from string

Hi,

I've a question. I'm developing a windows application and for the
application i need to run functions and procedures that are stored in a
database.
Here is an example that i tried to get working.
How can i execute the function that is stored in the string expr ?

Expand|Select|Wrap|Line Numbers
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
  2. System.EventArgs) Handles Button1.Click
  3. Dim expr As String = "test2(10,25)"
  4. MessageBox.Show(expr)
  5. expr.run()
  6. End Sub
  7.  
  8. Function test2(ByVal i As Integer, ByVal x As Integer) As Boolean
  9. Dim y As Integer
  10. y = i + x
  11. Return y
  12. End Function
  13.  
Mar 6 '07 #1
3 1856
You will have to write code that parses the text and calls the appropriate
function.

--
HTH,

Kevin Spencer
Microsoft MVP

Help test our new betas,
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net

"Jan Heppen" <Ja*******@disc ussions.microso ft.comwrote in message
news:D1******** *************** ***********@mic rosoft.com...
Hi,

I've a question. I'm developing a windows application and for the
application i need to run functions and procedures that are stored in a
database.
Here is an example that i tried to get working.
How can i execute the function that is stored in the string expr ?

Expand|Select|Wrap|Line Numbers
  1.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
  2. System.EventArgs) Handles Button1.Click
  3.        Dim expr As String = "test2(10,25)"
  4.        MessageBox.Show(expr)
  5.        expr.run()
  6.    End Sub
  7.    Function test2(ByVal i As Integer, ByVal x As Integer) As Boolean
  8.        Dim y As Integer
  9.        y = i + x
  10.        Return y
  11.    End Function
  12.  

Mar 6 '07 #2
Imports System.Text.Reg ularExpressions
Imports System.Reflecti on

Module Module1
Class Expression
Private Shared methodRegex As Regex = New
Regex("^(?<Meth od>\w[\w\d_]+)\s*(\((?<Para meters>.*)\))?$ ",
RegexOptions.Co mpiled Or RegexOptions.Si ngleline)
Public Shared Function Run(ByVal obj As Object, ByVal expr As
String) As Object
Dim m As Match = methodRegex.Mat ch(expr)
Dim method As String = m.Groups("Metho d").Value
Dim parameters As String = m.Groups("Param eters").Value
Dim params As Object() = Nothing

Dim binding As BindingFlags = BindingFlags.In vokeMethod Or
BindingFlags.In stance Or BindingFlags.St atic Or BindingFlags.Pu blic Or
BindingFlags.No nPublic

Dim mi As MethodInfo = obj.GetType().G etMethod(method , binding)

If mi Is Nothing Then
Return Nothing
End If

If Not String.IsNullOr Empty(parameter s) Then
Dim stringParams As String() = parameters.Spli t(New String()
{","}, StringSplitOpti ons.RemoveEmpty Entries)
ReDim params(stringPa rams.Length - 1)

Dim parameterInfo As ParameterInfo() = mi.GetParameter s()

If params.Length <parameterInfo. Length Then
Return Nothing
End If

For Each pi As ParameterInfo In parameterInfo
params(pi.Posit ion) =
Convert.ChangeT ype(stringParam s(pi.Position), pi.ParameterTyp e)
Next
End If

Return mi.Invoke(obj, binding, Nothing, params,
Threading.Threa d.CurrentThread .CurrentCulture )
End Function
End Class

Sub Main()
Dim expr As String = "test2(10,2 5)"
Expression.Run( New TestClass, expr)
End Sub

Class TestClass
Public Function test2(ByVal i As Integer, ByVal x As Integer) As
Integer
Dim y As Integer
y = i + x
Return y
End Function
End Class
End Module
"Jan Heppen" wrote:
Hi,

I've a question. I'm developing a windows application and for the
application i need to run functions and procedures that are stored in a
database.
Here is an example that i tried to get working.
How can i execute the function that is stored in the string expr ?

Expand|Select|Wrap|Line Numbers
  1.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
  2. System.EventArgs) Handles Button1.Click
  3.         Dim expr As String = "test2(10,25)"
  4.         MessageBox.Show(expr)
  5.         expr.run()
  6.     End Sub
  7.     Function test2(ByVal i As Integer, ByVal x As Integer) As Boolean
  8.         Dim y As Integer
  9.         y = i + x
  10.         Return y
  11.     End Function
  12.  
Mar 6 '07 #3
I assume you already have the 'test2' function in the same class from where
you want to invoke it.
You can invoke the function in the expr as follows

Dim expr As String = "test2"

Dim obj As Object = Activator.Creat eInstance(Me.Ge tType(), New String() {})

Dim result As Object = Me.GetType.Invo keMember(expr,
Reflection.Bind ingFlags.Defaul t Or Reflection.Bind ingFlags.Invoke Method,
Nothing, Me, New Object() {10, 25})

MessageBox.Show (CType(result, Integer).ToStri ng())

Note that I have passed your parameters (10, 25) as the final parameter to
the InvokeMember function which is a param array. Also correct your test2
function, I think it is required to return an integer whereas the return
type is boolean.
--
Abdul Aleem
Blog: http://aleemkhan.wordpress.com

"Jan Heppen" <Ja*******@disc ussions.microso ft.comwrote in message
news:D1******** *************** ***********@mic rosoft.com...
Hi,

I've a question. I'm developing a windows application and for the
application i need to run functions and procedures that are stored in a
database.
Here is an example that i tried to get working.
How can i execute the function that is stored in the string expr ?

Expand|Select|Wrap|Line Numbers
  1.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
  2. System.EventArgs) Handles Button1.Click
  3.        Dim expr As String = "test2(10,25)"
  4.        MessageBox.Show(expr)
  5.        expr.run()
  6.    End Sub
  7.    Function test2(ByVal i As Integer, ByVal x As Integer) As Boolean
  8.        Dim y As Integer
  9.        y = i + x
  10.        Return y
  11.    End Function
  12.  

Mar 7 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3697
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people discuss how reflection does this, but I cannot find the syntax to do this. I have tried several code example off of gotdotnet and other articles. Can somebody please show me the code to do this?
3
14951
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
7
5196
by: Mike D. | last post by:
I have a problem with a dynamic library I am developing, but it is really more of a pointer issue than anything else. Hopefully someone here can lend me some assistance or insight into resolving this. Ok... here goes.... I have a function that passes a pointer to a string to another function. For example: int FunctionA ()
18
3356
by: James Radke | last post by:
Hello, We are currently using a user DLL that when working in VB 6.0 has a user defined type as a parameter. Now we are trying to use the same DLL from a vb.net application and are having some problems getting it to work and we don't know why. Basically the function is accepting the parameters, and then returning an error and never performing the update.
2
6329
by: pangel83 | last post by:
I've been trying for days to write a piece of VB.NET code that will read from winamp's memory space the paths of the files from the current winamp playlist. The GETPLAYLISTFILE command of the winamp API will only return a pointer to the position of the asked path. An article available on http://msmvps.com/ch21st/archive/2004/02/26.aspx provides a VB6 implementation of this, using the ReadProcessMemory Windows API command, but something...
4
7698
by: Paul | last post by:
Anyone have code that emulates the Nz function in Microsoft Access? In Access it is: Nz(Value as variant, Optional ValueIfNull as Variant) as Variant
2
5332
by: f rom | last post by:
----- Forwarded Message ---- From: Josiah Carlson <jcarlson@uci.edu> To: f rom <etaoinbe@yahoo.com>; wxpython-users@lists.wxwidgets.org Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: 1>make_buildinfo.obj : error LNK2019: unresolved external symbol __imp__RegQueryValueExA@24 referenced in function _make_buildinfo2 Ask on python-list@python.org . - Josiah
28
4336
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
20
9007
by: Andrew Morton | last post by:
Is it possible to have two function declarations which take the same parameters but return different types depending on how the function is used? function f(x) as string ' return a string end function function f(x) as string() ' return an array of strings end function
9
2685
by: =?Utf-8?B?RGFya21hbg==?= | last post by:
Hi, I am wondering how you multi-dimension an array function? My declared function looks like this: Public Function GetCustomerList(ByVal Val1 As String, ByVal Val2 As Long, ByVal Val3 As String) As String() Previously I dimensioned a single dimension Array to the size I wanted and
0
9641
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9944
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.