How to call an event directly in a sub in vb.net - events

I try to implement a C# program in VB.NET and I've stuck on a point. I would like to get the exact equivalent. I could not find out how to pass an event to a sub or function in the following way. So the part which I cannot do in vb.net is var mediaOpenedHandler = MediaOpened;. In VB you cannot pass an event like this. If I write in VB: Dim mediaOpenedHandler = MediaOpened then it says "'Public Event MediaOpened()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event." So how can I get exactly the same result. Thanks in advance.
public abstract class MediaPlayerBase : WorkDispatcherObject
{
…
public event Action MediaOpened;
…
protected void InvokeMediaOpened()
{
var mediaOpenedHandler = MediaOpened;
if (mediaOpenedHandler != null)
mediaOpenedHandler();
}
}

of the top of my head, it is literally just
RaiseEvent mediaOpenedHandler()

I found the answer myself here Event handler raising method convention. So basically as hermiod answered you just use RaiseEvent in VB. In C# they have to use this local assignment for this purpose: "In a multi-threaded application, you could get a null reference exception if the caller unregisters from the event. The assignment to a local variable protects against this." In VB the RaiseEvent handles this internally.

Related

Late binding with COM objects (flexgrid) is 2 times slower than early binding

Public Function gridloop(MSFG1 As Object) As Long
For i= 0 To MSFG1.rows - 1
A = MSFG1.TextMatrix(i,1)
Next
End Function
The above code is 2 times slower than below
Public Function gridloop(MSFG1 As MSHFlexGrid) As Long
Public Function gridloop(MSFG1 As MSFlexGrid) As Long
Any solution to speed-up?
Not a lot of details in the question, I presume you have two (or more?) different controls where you're trying to essentially overload your gridloop function so it'll work with multiple types of controls?
The following might provide a performance improvement. I have not tested this, not even confirmed that it is free of compile errors. Idea is to determine the control type, then assign it to a variable of a matching type, then the references to the methods and properties might be early bound (thus faster).
Public Function gridloop(MSFG1 as Object) as Long
Dim myMSHFlexGrid As MSHFlexGrid
Dim myMSFlexGrid As MSFlexGrid
Dim i As Integer
Dim A As Long
If TypeOf MSFG1 Is MSHFlexGrid Then
Set myMSHFlexGrid = MSFG1
For i = 0 To myMSHFlexGrid.rows - 1
A = myMSHFlexGrid.TextMatrix(i,1)
Next
ElseIf TypeOf MSFG1 Is MSFlexGrid Then
Set myMSFlexGrid = MSFG1
For i = 0 To myMSFlexGrid.rows - 1
A = myMSFlexGrid.TextMatrix(i,1)
Next
End If
End Function
Alternative is to define two gridloop functions, one for each type. A form of manual overloading.
Public Function gridloop_MSHFlexGrid(MSFG1 As MSHFlexGrid) As Long
Public Function gridloop_MSFlexGrid(MSFG1 As MSFlexGrid) As Long
Advantage to this is that trying to call one of the gridloop functions with an 'incorrect' control will result in a compile error - catching a problem early that could otherwise require spending some significant time performing runtime debugging.
Building on MarkL's answer, you could use actual VB interface overloading to get what you want.
The idea would be to create an interface exposing whatever properties or functions you need on the grids, and then create two classes, each one implementing that interface and internally manipulating the actual grid.
This wrappering substitutes for the fact that the two grid types do not intrinsically share a common interface. (I looked in the IDL using OLEView).
You can then use the interface as the type in every location you currently are using Object to stand in for the actual grid class. If the interface is comprehensive AND its methods / properties are named appropriately then you would not need to make any other code changes.
Sample (pseudo)code...
Interface:
'In file for interface IGridWrapper
Function Rows
End Function
Function TextMatrix(i as Integer, j as Integer)
End Function
'Any others...
Wrapper class 1:
' In file for class "MSFlexGridWrapper"
Implements IGridWrapper
Private m_grid as MSFlexGrid
Sub Init(MSFlexGrid grid)
Set m_grid = grid
End Sub
Function IGridWrapper_Rows
IGridWrapper_RowCount = m_grid.Count
End Function
Function IGridWrapper_Textmatrix(i as Integer, j as Integer)
'etc.
End Function
'Any others...
Wrapper class 2:
' In file for class "MSHFlexGridWrapper"
Implements IGridWrapper
Private m_grid as MSHFlexGrid
Sub Init(MSHFlexGrid grid)
Set m_grid = grid
End Sub
Function IGridWrapper_Rows
IGridWrapper_RowCount = m_grid.Count
End Function
Function IGridWrapper_Textmatrix(i as Integer, j as Integer)
'etc.
End Function
'Any others...
Code using the wrappers:
Public Function gridloop(MSFG1 As IGridWrapper) As Long
(Note - none of this has been put through a compiler for exact syntax checking)
The basic reason that late binding (binds at runtime) is slower than early binding (binds at compile time) is that you have to use the iDispatch interface's GetIDsOfNames and Invoke methods to access properties in the object's interface, rather than accessing them directly from the vtable. For more information, have a look at this.
The reason that DaveInCaz's and MarkL's suggestions will probably speed things up is that they are ways to allow your gridloop function to accept a type that can be bound early rather than an Object type. DaveInCaz's solution is also a fine example of a practical application of polymorphism.

What is the difference between Sub and Function in VB6?

I am going through some old VB code and I run into function definitions like these -
Private Function ExistingCustomer(Index As Integer, Customer As String) As Integer
Private Sub cmdCustomerList_Click()
What's the difference?
Function returns value, Sub doesn't. It's that simple.
A function can also be used in an expression. A Subroutine cannot.
Functions can lend to the readability of your code better than a subroutine.
Here's an example of how a function can increase readability:
If AccountIsLocked("JJones") then Msgbox("This account is locked")
this function would be defined somewhere
public function AccountIsLocked(UserId as string) as boolean
dim usr = uow.AccountRepository.UserInfo(UserId)
return usr.locked
end function
Here's the same example but coded with a subroutine:
CheckIfAccountLocked("JJones")
and elsewhere this sub is defined:
public sub CheckIfAccountLocked(UserId)
if uow.AccountRepository.UserInfo(UserId).locked then
msgbox("Account is locked")
end if
end sub
Also note that checking the value is separated from the action -- this contributes to separation of duties. The function would lend toward re-usability.
With VB6 there are some odd rules governing parenthesis. If there are no parameters to a sub then the parenthesis are not needed (I think Visual Studio might remove the parenthesis). One way around this is to add the keyword "Call" before your sub.
Call CheckIfAccountLocked()
vs
CheckIfAccountLocked
In function we can return values as boolean, string and other data data types.
but sub does not return any thing.
it just executes code and instruction that we give. These are also regarded as methods
Sub is also used in control's events and these events also not return any value.
for example the click event of a command button:
Private sub cmd_click()
end sub
They are both sections to write code however a function must return a value. For example if you had a program in which a complicated mathematical procedure needs to be executed a number of times you would simply make a function and have the complicated maths code in there and any time you need to do the calculation you can just call the function. Hope this helped not sure if I explained it well.
What is the difference between Sub and Function in VB6?
"sub" can perform some action.
"sub" returns no value.
Example:
Form_Load()
"function" can also perform some action but it also returns some value to point from which it was called.
that is, "Functions return a value, often based on a variable"
Example:
Val(), FormatPercentage().
function in vb
a function must return some value/s
Syntax :
private function fun_name(argument/s(optional)) as return_type(integer,string..)
return value
end function
fun_name(arguments(optional) ) is enough for function call
sub in vb
a sub need not to be return any value/s
Syntax :
private sub sub_name(argument/s(optional))
end sub
sub_name(arguments(optional) ) is enough for function call
A function holds data and code. But a subroutine contains only code, but not data.
Syntax of functions will be Function...End function and for Sub will be Sub...End Sub.
Functions may or may not have objects but sub doesn't have objects
Functions are re-usable where Sub doesn't
Functions can return values but sub doesn't
Functions may have object repository but sub doesn't
Extension of functions is .qfl where for sub it's .vba

How to call a function with function name reference to a string value in VB

I have this algorithm that I want to implement on VB6.
Sub Main()
dim stringVal1 as string, stringVal2 as string
dim getOne as boolean
stringVal1 = "FunctOne"
stringVal2 = "FunctTwo"
if getOne then
'Call Function with function name assigned to stringVal1 ... how to call the function here?**
else
'Call Function with function name assigned to stringVal1 ... how to call the function here?**
end if
End Sub
Function FunctOne()
Msgbox "I'm function one"
End Function
Function FunctTwo()
Msgbox "I'm function two"
End Function
Can this be done in VB6?
Generally, such code patterns point to errors in your software design.
In the rare cases where this is really needed, CallByName accomplishes this.
Example:
Call CallByName(Me, "NameOfFunction", vbMethod, arguments)
It would help if you give more information about why you're needing to call functions by the string representation of their name. Could you not simply re-write your code like this:
If getOne Then
Call FuncOne()
Else
Call FuncTwo()
End If
Generally, you don't want to actually dispatch based on Strings. This is error-prone (as you have to be really sure at run time that your String has the function name you want), and really unnecessary. The way to do this sort of thing where you want to be able to "pass in" the method that you want to use would be to use the polymorphism that VB has, and use a separate Class for each implementation.
In the Class Module that you use for your interface, say named MyInterface:
Public Sub DoStuff()
End Sub
Then, create two Class Modules, one for each possible implementation of the Interface:
In MyClassOne:
Implements MyInterface
Public Sub MyInterface_DoStuff()
Msgbox "I'm function one"
End Sub
Then, in MyClassTwo, the same thing but with your other implementation:
Implements MyInterface
Public Sub MyInterface_DoStuff()
Msgbox "I'm function two"
End Sub
To use it, you just need to pass in which implementation you want to use:
Private Sub UseInterface(WhichThingToUse as MyInterface)
WhichThingToUse.DoStuff
End Sub
Rather than using a String variable to store which method to use, you need to instead store a New MyClassOne or a New MyClassTwo. You don't show how your getOne variable gets set, but whatever the logic is for it, you just need to change to store an instance of MyInterface instead, and just use that directly.
For further reading in the MSDN library:
How Visual Basic Provides Polymorphism
Creating and Implementing an Interface
Creating Interfaces for Use With the Implements Statement
Implements Statement reference

VB6 ADO Connection - How to Check if in Transaction?

Is there any way to tell, using just the ADODB.Connection object, whether or not it is currently involved in a transaction?
I'd love to be able to test this on the connect object itself, without relying on keeping a boolean next to it updated.
The BeginTrans method can be used as a function that returns the nesting level of the transaction. If you create a property to store this you can check it where ever you need to to see if it is greater than 0. When you commit or rollback you will need to decrement the property yourself.
Private m_TransLevel As Long
Public Property Get TransactionLevel() As Long
TransactionLevel = m_TransLevel
End Property
Public Property Let TransactionLevel(vLevel As Long)
m_TransLevel = vLevel
End Property
Public Sub SaveMyData()
TransactionLevel = adoConnection.BeginTrans()
...
End Sub
You could also adapt the return value to work inside a function that returns True/False if the level > 1. I don't like this as well, but it would look something like this (without error handling)
Public Function IsConnectionInsideTransaction(ByVal vADOConnection as ADOBD.Connection) As Boolean
Dim intLevel As Integer
If vADOConnection.State = AdStateOpen Then
intLevel = vADOConnection.BeginTrans()
IsConnectionInsideTransaction = (intLevel > 1)
vADOConnection.RollbackTrans
End If
End Function
If you're connecting to an Microsoft SQL Server and can count on it to respond fast enough (i.e. it's not on the other side of the planet) you can perform the query:
SELECT ##TRANCOUNT
It looks like you can check the ADO state. http://msdn.microsoft.com/en-us/library/ms675068%28v=VS.85%29.aspx
You probably already know this other part but I'll post it anyway.
This explains how the transactions work with ADO in VB.
http://support.microsoft.com/kb/198024
You can't unless you track it yourself. The connection object doesn't have a property dealing with transaction state. You'll have to have your proc set a flag in another table/settings area if you HAVE to have it (which can be problematic if unhandled errors occur and the state flag ever gets "stuck" with an invalid status, you need come up with a valid "timeout" or override to ignore/kill/overwrite the previous).

What's so great about Func<> delegate?

Sorry if this is basic but I was trying to pick up on .Net 3.5.
Question: Is there anything great about Func<> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc<> with the exact 5 overloads and even more.
eg: public delegate TResult MyFunc<TResult>() and a combo of various overloads...
The thought came up as I was trying to understand Func<> delegates and hit upon the following scenario:
Func<int,int> myDelegate = (y) => IsComposite(10);
This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?
So am I justified in saying that Func<> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func<>" delegates to suit our own needs?
Thanks,
The greatness lies in establishing shared language for better communication.
Instead of defining your own delegate types for the same thing (delegate explosion), use the ones provided by the framework. Anyone reading your code instantly grasps what you are trying to accomplish.. minimizes the time to 'what is this piece of code actually doing?'
So as soon as I see a
Action = some method that just does something and returns no output
Comparison = some method that compares two objects of the same type and returns an int to indicate order
Converter = transforms Obj A into equivalent Obj B
EventHandler = response/handler to an event raised by some object given some input in the form of an event argument
Func = some method that takes some parameters, computes something and returns a result
Predicate = evaluate input object against some criteria and return pass/fail status as bool
I don't have to dig deeper than that unless it is my immediate area of concern. So if you feel the delegate you need fits one of these needs, use them before rolling your own.
Disclaimer: Personally I like this move by the language designers.
Counter-argument : Sometimes defining your delegate may help communicate intent better. e.g. System.Threading.ThreadStart over System.Action. So it’s a judgment call in the end.
The Func family of delegates (and their return-type-less cousins, Action) are not any greater than anything else you'd find in the .NET framework. They're just there for re-use so you don't have to redefine them. They have type parameters to keep things generic. E.g., a Func<T0,bool> is the same as a System.Predicate<T> delegate. They were originally designed for LINQ.
You should be able to just use the built-in Func delegate for any value-returning method that accepts up to 4 arguments instead of defining your own delegate for such a purpose unless you want the name to reflect your intention, which is cool.
Cases where you would absolutely need to define your delegate types include methods that accept more than 4 arguments, methods with out, ref, or params parameters, or recursive method signatures (e.g., delegate Foo Foo(Foo f)).
In addition to Marxidad's correct answer:
It's worth being aware of Func's related family, the Action delegates. Again, these are types overloaded by the number of type parameters, but declared to return void.
If you want to use Func/Action in a .NET 2.0 project but with a simple route to upgrading later on, you can cut and paste the declarations from my version comparison page. If you declare them in the System namespace then you'll be able to upgrade just by removing the declarations later - but then you won't be able to (easily) build the same code in .NET 3.5 without removing the declarations.
Decoupling dependencies and unholy tie-ups is one singular thing that makes it great. Everything else one can debate and claim to be doable in some home-grown way.
I've been refactoring slightly more complex system with an old and heavy lib and got blocked on not being able to break compile time dependency - because of the named delegate lurking on "the other side". All assembly loading and reflection didn't help - compiler would refuse to just cast a delegate() {...} to object and whatever you do to pacify it would fail on the other side.
Delegate type comparison which is structural at compile time turns nominal after that (loading, invoking). That may seem OK while you are thinking in terms of "my darling lib is going to be used forever and by everyone" but it doesn't scale to even slightly more complex systems. Fun<> templates bring a degree of structural equivalence back into the world of nominal typing . That's the aspect you can't achieve by rolling out your own.
Example - converting:
class Session (
public delegate string CleanBody(); // tying you up and you don't see it :-)
public static void Execute(string name, string q, CleanBody body) ...
to:
public static void Execute(string name, string q, Func<string> body)
Allows completely independent code to do reflection invocation like:
Type type = Type.GetType("Bla.Session, FooSessionDll", true);
MethodInfo methodInfo = type.GetMethod("Execute");
Func<string> d = delegate() { .....} // see Ma - no tie-ups :-)
Object [] params = { "foo", "bar", d};
methodInfo.Invoke("Trial Execution :-)", params);
Existing code doesn't notice the difference, new code doesn't get dependence - peace on Earth :-)
One thing I like about delegates is that they let me declare methods within methods like so, this is handy when you want to reuse a piece of code but you only need it within that method. Since the purpose here is to limit the scope as much as possible Func<> comes in handy.
For example:
string FormatName(string pFirstName, string pLastName) {
Func<string, string> MakeFirstUpper = (pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
};
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
It's even easier and more handy when you can use inference, which you can if you create a helper function like so:
Func<T, TReturn> Lambda<T, TReturn>(Func<T, TReturn> pFunc) {
return pFunc;
}
Now I can rewrite my function without the Func<>:
string FormatName(string pFirstName, string pLastName) {
var MakeFirstUpper = Lambda((string pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
});
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
Here's the code to test the method:
Console.WriteLine(FormatName("luis", "perez"));
Though it is an old thread I had to add that func<> and action<> also help us use covariance and contra variance.
http://msdn.microsoft.com/en-us/library/dd465122.aspx

Resources