In Visual Basic .NET, how can I list and call all class functions with a given custom attribute? - vb.net

I have a Windows Forms / Visual Basic .NET application which basically acts as an editor. One of the functions it should provide its users with is the ability to run a set of rules on their current project and report any problems it finds. These rules will all be run by a BackgroundWorker object living in a form, so execution progress can be reported.
My strategy for implementing this is to give the form a bunch of private instance methods which take in the user's project data (contained in, say, a ProjectData object), run whatever check is needed at that step, and return an object containing displayable information about the test and whether it passed or failed. (Let's call this class CheckResult for discussion purposes). So, just to be clear, all of these methods would have a signature along the lines of:
Private Function SomeCheckToRun(data As ProjectData) As CheckResult
I could just define all these methods as usual and manually list them out one-by-one to be called in the BackgroundWorker's DoWork event handler, but that approach seems like it would get tedious for a potentially large number of checks. It would be nice if I could just define each method I want to run and have it decorated as such, so that a loop could automatically find each such method definition and run it.
What I'm thinking I would like to do instead is to define a custom attribute class used to indicate which instance methods are meant to be run as checks (maybe called CheckToRunAttribute), then use reflection somehow to get a list of all these methods currently implemented in the form and execute each one in sequence, perhaps by setting up a delegate to run for each one. The number of these methods in total, and how many have been executed so far, can be used by the BackgroundWorker to indicate overall progress.
So far, the structure of my code would look something like the following in my mind:
Private Sub MyBackgroundWorker_DoWork(sender As Object, e As DoWorkEventArgs) Handles MyBackgroundWorker.DoWork
' TODO: Get a list of all the <CheckToRun()> methods here,
' run each one in a loop, and report progress after each one.
End Sub
' Further down...
<CheckToRun()>
Private Function SomeCheckToRun(data As ProjectData) As CheckResult
' Check code in here.
End Function
<CheckToRun()>
Private Function AnotherCheckToRun(data As ProjectData) As CheckResult
' Check code in here.
End Function
<CheckToRun()>
Private Function YetAnotherCheckToRun(data As ProjectData) As CheckResult
' Check code in here.
End Function
' And so on...
This is not something I have much experience with doing though. I know about the Type.GetMethods() function, how to write custom attributes, and the Func(T, TResult) delegate, but I'm not sure how to put it all together for what I want.
tl;dr: Given a class with multiple private instance functions following the same signature and all marked with the same custom attribute, how can I count how many there are and then run each one?

You can use Reflection to list all the methods with your custom attribute. This is a Linq solution:
Dim methods = Me.GetType.GetMethods(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)_
.Where(Function(m) m.GetCustomAttributes(GetType(CheckToRun), False)_
.Length > 0).ToArray()
And then run them like:
For Each method As Reflection.MethodInfo In methods
method.Invoke(Me, New Object() {methodParams})
Next

Related

VB.NET 2019 Open a form from another form

I know this appears to be a rather common topic and should have been resolved from earlier posts. But what I am experiencing still does not seem to have a solution online:
I have a form called ExpenseEntry in which there is a sub procedure called Public Sub OpenVoucher.
I want to call this sub from another form for which I use the following code:
Dim ExpForm As New ExpenseEntry
ExpForm.Show()
ExpForm.OpenVoucher()
While this works well enough, the problem is everytime I click the button, a new window of ExpenseEntry is launched. As per how I have designed the application, repeat windows is not permissible and only one window should be available at a time.
I have tried various methods to restrict more than one form such as by using a variable to control the form but that gives rise to other issues.
If I use Application.OpenForms but still does not resolve the issue.
I have earlier queried in this regard in the following link:
Textbox not refreshing
I am using VB.NET 2019 which does not allow the launch of default instance of a form like Form.Show. I know this is bad practice but it was easier to manage with that till VB.NET 2017.
Now by creating a form variable and launching that creates an infinite loop where I cannot have just one instance of a form running on a single thread.
The really simple way to handle this is to use the default instance of the form type. In VB, since 2005, each form type has a default instance that you can access via the type name. Read here for more info. In your case, you can do this:
'Display the form if it is not already displayed.
ExpenseEntry.Show()
'Activate the form if it is already displayed.
ExpenseEntry.Activate()
'Do the deed.
ExpenseEntry.OpenVouncher()
That said, default instances are a bit dodgy. They do enable beginners to access forms from anywhere in their project under certain circumstances but they also have limitations that can cause issues. Most importantly though, they help to prevent you learning proper OOP by treating forms differently to other types. If you want to do this the way a proper developer would then simply declare a variable to refer to the current instance of the form:
Private expenseEntryDialogue As ExpenseEntry
When it's time to use the form, you simply check whether that variable refers to a usable instance and use it if it does, otherwise create a new one:
If expenseEntryDialogue Is Nothing OrElse expenseEntryDialogue.IsDisposed Then
expenseEntryDialogue = New ExpenseEntry
End If
expenseEntryDialogue.Show()
expenseEntryDialogue.Activate()
expenseEntryDialogue.OpenVoucher()
A third option would be to implement your own singleton, i.e. a type that can only ever have a single instance. You probably wouldn't do that in VB, given that the default instance is basically a thread-specific singleton and does more automatically but, if you wanted to, you could do this:
Public Class ExpenseEntry
Private Shared _instance As ExpenseEntry
'The one and only instance of the type.
Public Shared ReadOnly Property Instance As ExpenseEntry
Get
If _instance Is Nothing OrElse _instance.IsDisposed Then
_instance = New ExpenseEntry
End If
Return _instance
End Get
End Property
'The constructor is private to prevent external instantiation.
Private Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
End Class
and then this:
ExpenseEntry.Instance.Show()
ExpenseEntry.Instance.Activate()
ExpenseEntry.Instance.OpenVoucher()

Reference to a non-shared member requires an object reference in VB.net

I have a VB.net program that I got from someone else. It is comprised of a main form and 6 other modules (all .vb files). These files all have a "VB" icon next to them in the Explorer pane. I am trying to make a call to a sub-routine in one of the modules from the main form. My line of code is:
QuoteMgr.StartGettingQuotesLevel2(sSym)
where QuoteMgr is the name of the module and StartGettingQuotesLevel2(sSym) is the name of the sub-routine. When I enter this, I get the error message:
Reference to a non-shared member requires an object reference.
The sub-routine is defined in the QuoteMgr Module as follows:
Public Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
What is strange is when I enter:
QuoteMgr.
(the name of the module with a period), it does not show me all the sub-routines and functions in the module. It only shows:
Update_Level1
Update_Level12
Update_Level2
These are Public Const in the module.
Can you tell me what I need to do?
What the compiler is trying to tell you with this error message
Reference to a non-shared member requires an object reference
is that the StartGettingQuotesLevel2 subroutine is an instance method not a shared or class method, see a more detailed explanation here
To call an instance method, you need to have an object instance to call it on. In your case, an object instance of the class type QuoteMgr. Like in the example below:
' create a new QuoteMgr object instance
Dim myQuoteMgr As QuoteMgr = New QuoteMgr()
' call its instance method with "abc" as its oSymbol argument.
myQuoteMgr.StartGettingQuotesLevel2("abc")
It is possible that you only want a single QuoteMgr object instance to be created and used by your main form. In that case, you can make it a member variable of your main form and create it once.
Public Partial Class MainForm
' Create it as a private member variable of the main form
Private m_QuoteMgr As QuoteMgr = New QuoteMgr()
' Use it when "some" button is pressed
Private Sub btnSome_Click(sender As Object, e As EventArgs) Handles btnSome.Click
m_QuoteMgr.StartGettingQuotesLevel2(txtSymbol.Text)
' And possibly do something with the results.
End Sub
End Class
Also, if instances of your QuoteMgr class depend on other object instances for their tasks, you will have to supply these to the constructor method of the QuoteMgr class as the arguments for its constructor's method parameters. Constructors (Sub New(...)) look like this:
Public Class QuoteMgr
' This is a constructor that takes two arguments
' - oMainSymbol: a string value
' - oKernel: an instance of the type Kernel
Public Sub New(oMainSymbol As String, ByRef oKernel As Kernel)
' ....
End Sub
End Class
That means, that when you create a QuoteMgr instance, you have to call its constructor method with the things it need, for example
' There must be an instance of Kernel created somewhere.
Dim myKernel As Kernel = ....
' create a new QuoteMgr object instance with these arguments:
' - oMainSymbol = "SYMABC"
' - oKernel = myKernel
Dim myQuoteMgr As QuoteMgr = New QuoteMgr("SYMABC", myKernel)
Some other recommendations
The explanations I have provided, are about basic VB.NET language features (e.g. the terms highlighted in bold). I suggest that before you make any changes to the code you have, you (1) make a backup of it, and (2) try to read a tutorial and practice on something smaller.
The compiler is (virtually) always right. When it gives you an error message, read it carefully, it will indicate the line where something is wrong and a message that tells you what it needs or is missing.
It is not the purpose of Stack Overflow to provide tutorials or code. It is a Q&A site where the best questions and answers deal with specific, delineated programming problems, for which succinct answers are possible.
Right click your application and go to Properties.
Make sure your application type is "Windows Forms Application".
It means that the routine you are trying to call needs to reference an instance of the form to access the routine. You can either reference an instance as Alex says, or you can make the routine 'Shared', so it doesn't need an instance. To do this, change the definition in QuoteMgr.vb to
Friend Shared Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
Switching it to `Shared' may start showing compiler errors, if the routine accesses form controls or module-level variables. These will need to be added to the parameter list.

Reference to a non-shared member requires reference

I am updating some code from a vb6 application to VB.NET.
I have a problem that occurs when I try to open a form from the main form.
It calls this function:
Public Sub optDrawSafeFile_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optDrawSafeFile.CheckedChanged
If eventSender.Checked Then
'--------------------------------------------------------------------------------
' JRL 11-03-06
' change the enables
UpdateGUI((False))
cboProject.SelectedIndex = frmMain.cboProjects.SelectedIndex
SelectJob()
End If
End Sub
And when it goes to execute this line:
cboProject.SelectedIndex = frmMain.cboProjects.SelectedIndex
It blows up and says this:
frmMain is declared like this:
How can I fix this error?
TL;DR
It is described in more detail in this video.
Short answer: change frmMain to My.Forms.frmMain.
cboProject.SelectedIndex = My.Forms.frmMain.cboProjects.SelectedIndex
Long answer:
In VB6, referencing a form by its name allowed you to access it both as a class and an instance of that class. The instance that you access in this manner is called the default instance. This is not possible in VB.NET. However, VB.NET includes a dynamically generated class, My.Forms, that provides functionality similar to that of default instances.
See http://msdn.microsoft.com/en-us/library/ms379610%28v=vs.80%29.aspx#vbmy_topic3 for more information about My.Forms and the "My" namespace.
A better and more object-oriented way to handle this, however, would be to pass the instance of the main form to the constructor of the frmAddMethod form and store it in an instance field.
So, within the class definition in frmAddMethod.vb:
Sub New(ByVal mainForm As frmMain)
_mainForm = mainForm
End Sub
Private _mainForm as frmMain
And when you create the frmAddMethod instance from frmMain, pass in "Me" to the constructor:
Dim addMethodForm as new frmAddMethod(Me)
"Me" is the instance of the class from which a non-shared class method was called.
This will allow you to use the _mainForm class field to access the instance of the main form from non-shared methods of frmAddMethod.
*Edited to recommend My.Forms instead of DefInstance per Plutonix's comment.
Nothing is "blowing up", your program is not crashing. Using a type name, like frmMain, where an object reference is expected is something that the VB.NET compiler allows. Specifically for the Form class, an appcompat hack for VB6 code. It is the debugger that doesn't think much of it. It merely gives you a diagnostic on your watch expression since it doesn't have the same appcompat hack as the compiler does. So doesn't know what to display.
You can use My.Forms instead to get the active form object reference. So make your watch expression:
My.Forms.frmMain.cboProjects.SelectedIndex
Only do this when you are single-stepping the code, it will still go wrong if you use Debug + Break All to break into the program. Setting a watch expression on Me.cboProject is otherwise the obvious workaround in this specific case.

vb.net Invoke and Inheritance Design

this is my first post here.
I like to have some advice on designing a new module for our software.
It's written in vb6 and i want to rewrite it in vb.net. So I want to refactor it.
It does the following:
We got many templates for OpenOffice Documents. (about 300)
Each one has an unique identifier which is in a database and comes as the input.
Dending on this number i want to create the document. e.g. calc or writer or later something else.
Then call a method named doc[template_num] or sth.
I read about invoking methods. I think this as a good way to dynamically call methods by number. Tried to do this. I think I understood now how it works.
But I dont know how to handle the document type.
I want to reuse big parts of code due to all calc documents are created equal at the beginning. But filling the cells is just bit diffrent.
I dont know how to inherit and do method calls with invoke.
Maybe someone has a little code snip for me which can explain this to.
Or maybe some other good idea how to handle this problem.
I am thankful for any new thought on this.
You could, of course, just have a giant Select Case block, like this:
Public Sub CreateDoc(templateNum As Integer)
Select Case templateNum
Case 1
CreateDoc1()
Case 2
CreateDoc2()
Case 3
CreateDoc3()
End Select
End Sub
If you had a fairly small number of case statements that would probably be the better, simpler method. If however, as you described, you have many different possible ID's to look for, then that becomes impractical and I can appreciate your desire to invoke the correct method without a big Select Case block.
However, before I get into that, I feel like I should give you another option. Perhaps you don't really need to have that many different methods. Is it possible, for instance, that half of the template ID's actually all need to be handled in the same way, and the only difference is the template file name that needs to be different. If so, it is conceivable that the Select Case block wouldn't need to be that big. For instance:
Public Sub CreateDoc(templateNum As Integer)
Select Case templateNum
Case 1 To 100
CreateWriterDoc(GetTemplateFilePath(templateNum))
Case 101 To 200
CreateCalcDoc(GetTemplateFilePath(templateNum))
End Select
End Sub
Private Sub CreateWriterDoc(templateFilePath As String)
' Launch Writer with given template file
End Sub
Private Sub CreateCalcDoc(templateFilePath As String)
' Launch Calc with given template file
End Sub
Private Function GetTemplateFilePath(templateNum As Integer) As String
' Retrieve template file path for given ID
' (from DB, Array, List, Dictionary, etc.) and return it
End Sub
To me, that seems like a much simpler solution, if such a thing is possible. If not--if you really have entirely different logic which needs to be executed for each template ID, then there are several ways to do it. The first option would be to create a list of delegates which point to the appropriate method to call for each ID. For instance, you could store them in an array, like this:
Dim createDocDelegates() As Action =
{
AddressOf CreateDoc1,
AddressOf CreateDoc2,
AddressOf CreateDoc3
}
So now, those three delegates are indexed by number (0 through 2) in an array. You can invoke them by number, like this:
createDocDelegates(1).Invoke() ' Calls CreateDoc2
Or, if your ID's aren't sequential, you may want to use a Dictionary(Of Integer, Action), instead, like this:
Dim createDocDelegates As New Dictionary(Of Integer, Action)()
createDocDelegates.Add(1, AddressOf CreateDoc1)
createDocDelegates.Add(7, AddressOf CreateDoc7)
createDocDelegates.Add(20, AddressOf CreateDoc20)
Then you can call one by ID, like this:
createDocDelegates(7).Invoke() ' Calls CreateDoc7
Another option would be to create an Interface for an object that creates a document, like this:
Public Interface IDocCreator
Sub CreateDoc()
End Interface
Then you could implement a separate class for each type of template (each implementing that same interface). For instance:
Public Class Doc1Creator
Implements IDocCreator
Public Sub CreateDoc() Implements IDocCreator
' Do work
End Sub
End Class
Public Class Doc2Creator
Implements IDocCreator
Public Sub CreateDoc() Implements IDocCreator
' Do different work
End Sub
End Class
Then, you can create a list of those objects, like this:
Dim docCreators() As IDocCreator =
{
New DocCreator1(),
New DocCreator2()
}
Or:
Dim docCreators As New Dictionary(Of Integer, IDocCreator)()
docCreators.Add(1, New DocCreator1())
docCreators.Add(7, New DocCreator7())
docCreators.Add(20, New DocCreator7())
Then you can call one like this:
docCreators(1).CreateDoc()
The IDocCreator approach is very similar to the Delegate approach. Neither is the right or wrong way to do it. It depends on your style, what you are comfortable with, and your requirements. The main advantage of the IDocCreator approach is that you could easily add more properties and methods to it in the future. For instance, lets say that you also want to somewhere store a user-friendly, descriptive name for each template. It would be very easy to add a ReadOnly Property Name As String property to the IDocCreator interface, but if you go the list-of-delegates route, that would be more difficult and sloppy.
In any of the above examples, however, you still have to add the complete list of methods or delegates somewhere. So, while it's slightly less ugly than a giant Select Case block, it may still not be enough. If so, the technology you need to use is called Reflection. The System.Reflection namespace contains much of the reflection-related functionality. Reflection allows you to dynamically access and invoke portions of your code. For instance, you can use reflection to get a list of all of the properties or methods that are defined by a given class. Or you can use reflection to get a list of types that are defined by your assembly. Using reflection, it would be possible to get a method, by string name, and then invoke it. So, for instance, if you want to call the "CreateDoc1" method on the current object, you could do it like this:
Me.GetType().GetMethod("CreateDoc1").Invoke(Me, {})
Since you are calling it by its string name, you could build the method name via concatenation:
Dim methodName As String = "CreateDoc" & templateNum.ToString()
Me.GetType().GetMethod(methodName).Invoke(Me, {})
However, if you are going to use the reflection approach, instead of using the name of the method, like that, it would be cleaner, in my opinion, to use a custom attribute to tag each method. For instance, you could create an attribute class which allows you to decorate your methods like this:
<CreateDocMethod(1)>
Public Sub CreateDoc1()
' ...
End Sub
Then, at run-time, you can use reflection to find all of the methods that have that particular attribute and then invoke the right one.
The reason that I saved the discussion on reflection for last is because it is not as efficient and it can lead to brittle code. As such, it's best to only use reflection as a last-resort. There's nothing wrong with reflection, if you really need it, but, as a general rule, if there is another reasonable way to do something, which doesn't require reflection, then you probably ought to be doing it that other way.

Pass function as a parameter in vb.net?

I have class that performs many similar yet different read/write operations to an excel file.
All of these operations are defined in separate functions. They all have to be contained within the same long block of code (code that checks and opens a file, saves, closes, etc). What is reasonable way to not have to duplicate this code each time?
The problem is that I can't just one method containing all of the shared code before I execute the code that is different for each method because that code must be contained within many layers of if, try, and for statements of the shared code.
Is it possible to pass a function as a parameter, and then just run that function inside the shared code? Or is there a better way to handle this?
Focusing on the actual question:
Is it possible to pass a function as a parameter
Yes. Use AddressOf TheMethod to pass the method into another method. The argument type must be a delegate whose signature matches that of the target method. Inside the method, you treat the parameter as if it were the actual method. Example:
Sub Foo()
Console.WriteLine("Foo!")
End Sub
Sub Bar()
Console.WriteLine("Bar!")
End Sub
Sub CallSomething(f As Action)
f()
End Sub
' … somewhere:
CallSomething(AddressOf Foo)
CallSomething(AddressOf Bar)
As I said, the actual parameter type depends on the signature of the method you’d like to pass. Use either Action(Of T) or Func(Of T) or a custom delegate type.
However, in many cases it’s actually appropriate to use an interface instead of a delegate, have different classes implement your interface, and pass objects of those different classes into your method.
Declare your parameter as Func(Of T) or Action(Of T).
Which one you should use depend on your methods signature. I could give you more precise answer if you gave us one.
You can also use a delegate so you can pass function/subs that have a certain signature.