NSubstitute and mocking an object to fire an event - vb.net

I'm currently using NSubstitute as my mocking framework and over I'm doing reasonably well, with one exception that is...
I'm attempting to mock an interaction that calls an event from inside my mocked object, unfortunately I'm really struggling to do this. The setup is something like this...
Public Interface IMockObject
Event MyMockedEvent( someId as Integer )
Sub MyRoutineThatInvokesMyMockedEvent( someId as Integer)
End Interface
...so in my Unit Test I need to mock the 'MyRoutineThatInvokesMyMockedEvent' to receive the ID and then raise the 'MyMockedEvent'. So far I have come up with...
Dim mockedObject = Substitute.For(Of IMockObject)()
mockedObject.When(
Sub(x) x.MyRoutineThatInvokesMyMockedEvent( 999 )).Do(
Sub(y) 'RaiseTheEventHere )
...but I'm stuck on actually raising the event with the following not valid...
mockedObject.When(
Sub(x) x.MyRoutineThatInvokesMyMockedEvent( 999 )).Do(
Sub(y) RaiseEvent MyMockedEvent(999) )
...I do have a theory that this may not be possible in VB.NET (without creating a helper routine) but will gladly appreciate any help on how to achieve the above without the helper routine.

OK, found the answer. Or something like it.
The problem I believe is due to the event definition that is used - by reconfiguring the 'MyMockedEvent' to use its own 'MyMockedEventArgs' (inheriting from System.EventArgs) the event can be raised without it complaining about passing through an inappropriate type.
mockedObject.When(
Sub(x) x.MyRoutineThatInvokesMyMockedEvent( 999 )).Do(
Sub(y) RaiseEvent IMockObject.MyMockedEventEventHandler() )
But its here where my suspicions of VB.NET doing some black magic come into play as I'm aware that VB.NET with create the delegates for the event behind the scenes. Of course, the fact that Intellisense doesn't show the EventHandler doesn't particularly help either and I'm guessing I could manually code up the delegate but this approach seems quicker.
HTH

Related

MATLAB - objects not clearing when timers are involved

This is somewhat related to this question, but not quite.
I have two classes, FunctionWrapper and TimerWrapper:
classdef FunctionWrapper < handle
methods
function Fcn(obj)
disp('FunctionWrapper.Fcn was called!');
end
end
end
classdef TimerWrapper < handle
properties
Timer
end
methods
function obj = TimerWrapper(other_object)
obj.Timer = timer;
set(obj.Timer, 'Period', 1);
set(obj.Timer, 'ExecutionMode', 'fixedSpacing');
set(obj.Timer, 'TimerFcn', #(event, data) other_object.Fcn);
end
function start(obj)
start(obj.Timer);
end
function stop(obj)
stop(obj.Timer);
end
function delete(obj)
disp('destructor called!');
delete(obj.Timer);
end
end
end
Say I execute the following code in the Command Window:
>> F = FunctionWrapper;
>> T = TimerWrapper(F);
>> clear T %# T's destructor not called
>> timerfind %# just to verify that no, the destructor was never called
Timer Object: timer-1
Timer Settings
ExecutionMode: fixedSpacing
Period: 1
BusyMode: drop
Running: off
Callbacks
TimerFcn: #(event,data)other_object.Fcn
ErrorFcn: ''
StartFcn: ''
StopFcn: ''
What's going on here? I know that timer objects need to be manually deleted, but I thought that would be dealt with in the destructor for TimerWrapper. Without using Amro's ugly but straightforward workaround to overload the clear command, is there a way to clear T from the workspace? Furthermore, nothing is referring to T, so why does a reference to it exist? (The fact that the destructor is never called implies this fact.) Is this buried in the timer object itself?
If you type t = TimerWrapper; f = functions(t.Timer.TimerFcn); f.workspace(2), you'll see that the workspace of the anonymous function used for the callback contains a reference to the TimerWrapper object itself. So there's a kind of circular reference there which is not picked up by clear.
Given how you've set things up, you can remove T (and its underlying timer object) by calling the destructor explicitly and then calling clear.
T.delete
clear T
The difference between clear and delete is kind of confusing (to me, anyway). As you've found, clear doesn't explicitly call the destructor. It just removes the name T from the workspace. So T, and its underlying timer, still exist at that point. If they contained no references to things that still existed, MATLAB would then remove T properly, including calling its destructor. As it is, since the timer contains a reference (in its callback) to T, which still exists, the timer (and thus T as well) is not deleted.
You can find it (despite not having a name in the workspace) with timerfindall, and if you explicitly delete it yourself using
tmrs = timerfindall;
delete(tmrs);
you'll find that T is now properly gone.
I'm not so sure that this is a bug, although I find it pretty confusing, and the distinction between clear and delete could probably be documented better.
As to a workaround, I don't find it a big pain to explicitly call delete, although it's a bit more of a pain to clean things up if you accidentally call clear. I would think the suggestion in message #5 from the thread you linked to, rather than message #4, would be more general and robust.
I don't think you should overload clear in the way #Amro suggests in the separate thread you linked to: although this may work if you call clear T explicitly, you may still get into trouble if you call clear all, or clear variables. (I haven't tried it just now, but I believe these syntaxes of clear don't even loop over things in the workspace and call clear on each - instead they call the clear method of the internal MATLAB workspace object, and that's going to get confusing fast).
It seems as though this might be because the timer's callback is set to a non-default value. A proposed workaround (see message#4 of the linked thread) is to set the callback function only when the start method is called, then setting it to null when the stop method is called.

Why am I having to double cast here?

I have inheritance structure: Foo implements IGraphNode inherits IGraphItem.
Foo, IGraphItem/IGraphNode, and the implementation for IGraphItem/IGraphNode all reside in separate assemblies. I am using an inversion of control container, so the project I'm working in has a reference to the first two (Foo and IGraphItem/IGraphNode), but not the implementation of IGraphItem/IGraphNode. I also have Option Strict on as it is required for this project (turning if off didn't fix the problem). I'm using .NET 3.5.
I am passing a IGraphItem around and I have code that looks like this:
Public Sub ProcessItem(of IGraphItem)(item As IGraphItem)
If TypeOf item Is Foo Then
Dim f1 = CType(item, Foo) 'Compiler error
Dim f2 = DirectCast(item, Foo) 'Compiler error
'This is what I'm currently having to do. It works.
Dim f = CType(CType(item, IGraphNode), Foo)
'Do stuff
End If
End Sub
Any idea why I'm having to do this? I should add that TryCast works, but since we've just confirmed that item's type is Foo, I don't see why I can't DirectCast it. Shouldn't it just let me and throw an exception if I'm wrong? Is there a better way to accomplish what I'm trying to do?
Your original code compiles without a problem, even when target framework is 3.5.
The problem with your current code is that you've defined a generic method whereas IGraphItem is not the type of your interface but the generic type T which can be any type. But it cannot be another type than T and you're trying to cast it to type Foo.
If you would change your method signature to anything else it would work, for instance:
Public Sub ProcessItem(of IGraphItm)(item As IGraphItem)
I assume that you're somehow "shadowing" the type IGraphItem of your interface with the generic type IGraphItem in this method.
It would also work if you would explicitely tell the compiler that item As IGraphItem actually is a item As YourNamespace.IGraphItem.
I'm sure Jon or Eric could explain it better, but maybe it's helpful anyway ;)
This article might answer your question. If not, well, it's an excellent reading anyway.
http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx

Is this a UI-threading issue? Is there an easy way to fix it?

I am communicating with a USB-HID device. It will successfully complete hundreds of send-receive requests but occasionally get a Null Exception error.
Is this a threading issue?
FormMain.vb:
myHidDevice.transmitPacket(Packet)
myHidDevice.resetEvent.WaitOne(6)
If myHidDevice.rxDataReady = True then
' Life is good
MyHidDevicePort.vb
Public Sub DataReceivedHandler(ByVal sender as Object, dataReceived as DataReceivedEventArgs)
if dataReceived.data Is Nothing Then
Exit Sub
Else
Dim rDataPacket As List(Of Byte) = dataReceived.data.ToList()
For Each element in rDataPacket
rxData.dataPacket(i) = element
rxDataReady = True
resetEvent.Set()
MySensorClass.vb
Public Overrides Function processPacket(ByRef rxStruct as rStruct, ByVal txPacket()) as Boolean
....
Select Case rxStruct.dataPacket(4)
Case MOD_DISPLAY_SET_BRIGHTNESS
rxData(0) = rxStruct.dataPacket(5)
...
at the rxData.dataPacket(i) = element I will get a NullReference error every now and then. I could enclose it in a try/catch statement, but I'd like to fix the root problem if possible.
This device is communicating to microcontrollers, and it is possible that they won't always give a value... but my feeling is this is some sort of UI threading issue. When debugging, even though there is a null exception, many times there actually does seem to be data in dataReceived.data.ToList(). Is there an easy way to place the whole data processing routine on a thread separate from the UI?
Edit: Changed code to match answer and give more info on where it is used. Still get NullReferenceExceptions after about 1,000 completed send/receive requests to the HID device.
The dialog in the comments is too restricting, so I'll try this as an answer. Unfortunately, there still isn't enough code to give a full answer.
Some sample unknowns:
What is rxData (a custome class, part of the SDK, a struct)?
Where does i come from in the code sample rxData.dataPacket(i) = element, I don't see it decalred or incremented.
Why is the form waiting on myHidDevice.resetEvent.WaitOne(6) and what does it do once it thinks there is sucess?
How/when does processPacket get called?
What I can recommend in general is that access to shared state be wrapped in a SyncLock. And in your case, that includes both rxData and rxDataReady.
In your threaded event callback you need this:
SyncLock(syncRoot)
For Each element in rDataPacket
rxData.dataPacket(i) = element
next
rxDataReady = True
resetEvent.Set()
End SyncLock
And in your Main form where you are waiting for a response you need to wrap access to the ready flag as well:
SyncLock(myHidDevice.syncRoot)
If myHidDevice.rxDataReady = True then
' do something that consumes the data read in the thread
End If
End SyncLock
You have to watch for how long you hold the lock in the read and the write because you cannot be doing both at the same time.
Over all, I wouldn't be surprised if your code code be refactored a bit to make the thread issues easier to deal with. A blocking queue / colletion as you suggested might be a good idea. Just not enough is known of you design/code to give any more concrete advice.
If you know that there is a possibility that your object may be null, placing it inside of a try-catch block would be the incorrect way of handling this situation, as that would be considered coding by exception. Instead, do a null check on your object prior to setting it. e.g.
If Not dataReceived.data Is Nothing Then
Dim rDataPacket As List(Of Byte) = dataReceived.data.ToList()
End If
If your problem lyes with the individual array elements being null, you should also check them to ensure they exist before setting/accessing them.

Can I include a Generic type parameter in a lamba expression? (VB.NET 2010)

(Not really sure if I phrased the question correctly...)
I want to create a lambda expression that would take an Object, attempt to convert it to a passed-in Type, and print to the console whether it was successful or not.
At a glance, the lambda expression may seem a pretty silly way to accomplish this task, but I'd really like to know what I'm doing wrong, so I can better grow my skill set.
VS gives me a designer error about the second "T" in the expression below, telling me it isn't defined)
This is where I left off:
Sub MyMethod(ByVal param as Object)
Dim quickMethod = Sub (Of T)(o as Object)
Console.WriteLine(TryCast(o, T) IsNot Nothing)
End Sub
quickMethod(Of myClass1)(param)
quickMethod(Of myClass2)(param)
quickMethod(Of myClass3)(param)
quickMethod(Of myClass4)(param)
'further logic below... ;)
End Sub
I can't speak for VB specifically, but I'm not aware of any such concept in .NET delegates in general. While a delegate type can be generic, I don't believe you can leave a particular delegate instance "open" in a type parameter, to be provided by the caller. It's an interesting idea though.
Of course, you could easily write a generic method to do this, and that's probably the right way to go. It's an interesting situation where you could have a single-method interface expressing the desired functionality, but you can't express that as a delegate type. Hmm. Just for the sake of discussion, the interface could be something like this:
interface IConverter
{
bool IsConvertible<T>(object input);
}

How to pass a generic type not having a Interface to a Of T function

I have a following code which works fine
MsgBox(AddSomething(Of String)("Hello", "World"))
Public Function AddSomething(Of T)(ByVal FirstValue As T, ByVal SecondValue As T) As String
Return FirstValue.ToString + SecondValue.ToString
End Function
Now we are redesigning the application to work with parameters of different types which will be provided through XML
<SomeValues>
<Add Param1="Somedata" Param2="SomeData" MyType="String"/>
<Add Param1="Somedata" Param2="SomeData" MyType="MyBusinessObject"/>
</SomeValues>
If I try to provide the following it gives error as Of accepts only type
''''Get DetailsFromXml --- MyType,Param1,Param2
MsgBox(AddSomething(Of Type.GetType(MyType))(Param1,Param2))
How to solve this issue.
Edit
The above example is given to make the question simple. Actual issue is as follows
I am using SCSF of P&P.
Following is per view code which has to be written for each view
Private Sub tsStudentTableMenuClick()
Dim _StudentTableListView As StudentListView
_StudentTableListView = ShowViewInWorkspace(Of StudentListView)("StudentTable List", WorkspaceNames.RightWorkspace)
_StudentTableListView.Show()
End Sub
Now I want to show the views dynamically.
Public Sub ShowModalView(ByVal ViewName As String)
Dim _MasterListView As >>>EmployeeListView<<<<
_MasterListView = ShowViewInWorkspace(Of >>>EmployeeListView<<<)("Employee List", WorkspaceNames.RightWorkspace)
_MasterListView.Show()
End Sub
So the part shown using the arrows above has to be somehow dynamically provided.
The point of generics is to provide extra information at compile-time. You've only got that information at execution-time.
As you're using VB, you may be able to get away with turning Option Strict off to achieve late binding. I don't know whether you can turn it off for just a small piece of code - that would be the ideal, really.
Otherwise, and if you really can't get the information at compile-time, you'll need to call it with reflection - fetch the generic "blueprint" of the method, call MethodInfo.MakeGenericMethod and then invoke it.
I assume that the real method is somewhat more complicated? After all, you can call ToString() on anything...
(It's possible that with .NET 4.0 you'll have more options. You could certainly use dynamic in C# 4.0, and I believe that VB10 will provide the same sort of functionality.)
In .Net generics, you must be able to resolve to a specific type at compile time, so that it can generate appropriate code. Any time you're using reflection, you're resolving the type at run time.
In this case, you're always just calling the .ToString() method. If that's really all your code does, you could just change the parameter type to Object rather than use a generic method. If it's a little more complicated, you could also try requiring your parameters to implement some common interface that you will define.
If all you are doing is ToString, then making the parameters object instead would solve the problem in the simplest way. Otherwise you are going to have to bind the type at run-time, which in C# looks like:
System.Reflection.MethodInfo mi = GetType().GetMethod("AddSomething");
mi = mi.MakeGenericMethod(Type.GetType(MyType));
object result = mi.Invoke(this, new object[] { Param1, Param2 });
Because it involves reflection it won't be fast though... but I assume that's not a problem in this context.