Is it possible to access the My.Application object from a Form or Control object? - vb.net

I have a solution with several Projects in it. There is a Windows App project (called ImportClient), and a Class Library (Import.Library). The Import.Library has functions to perform data imports (I have other applications in the solution that also need to call it). But the interactive application, I want to be able to pass in some form controls, and have it update the GUI. No problem. But, I also want to execute a DoEvents() so that the loop execution doesn't hang other interaction to the app.
So, ImportClient has a reference to Import.Library. But I can't add a reference to ImportClient to the Import.Library, because the compiler complains about circular reference, etc. I don't know how else to define the My.Application object of ImportClient as a parameter to the data function in ImportLibrary.
(I realize this is a dumb question - problem is, for this project I have a tight timeline, and haven't learned how to do the BackgroundWorker process. If you think I could pick it up quickly, I'm open to some hints about how to update the progress bar on the GUI, and how to pause / cancel the background task.)

Application.DoEvents is a static method, you don't need an instance of Application to call it, so why not simply add a reference to System.Windows.Forms to access it?
I'd thoroughly recommend finding the time to learn about threading and asynchronous operations, Application.DoEvents is not the silver bullet for keeping your UI smooth...

Related

Threads vs. GUI in VB

The language I am talking about is VB.
I'm struggling with this problem for over three weeks, and still a solution is not in sight.
The problem is the following:
I have got an intense calculation running in a sub procedure, while modifying the GUI a lot in the process. After a short period of time, the application freezes and is "not responding". After the calculation is finished, everything suddenly snaps to the point I have modified it. Nothing special about that.
But if I now try to start the sub with a thread, so the application doesn't freeze anymore, I can't access the GUI, because "it isn't created by the thread itself".
How do I get around this??
More concretely: How do I access information about the GUI (especially width and height of a PictureBox) and modify the GUI (especially setting a BackgroundPicture in a PictureBox)?
Any help is appreciated. Thank you!
You need to read up on how to use the Dispatcher (MSDN Threading Model)
If only one thread can modify the UI, how do background threads interact with the user? A background thread can ask the UI thread to perform an operation on its behalf. It does this by registering a work item with the Dispatcher of the UI thread. The Dispatcher class provides two methods for registering work items: Invoke and BeginInvoke. Both methods schedule a delegate for execution. Invoke is a synchronous call – that is, it doesn’t return until the UI thread actually finishes executing the delegate. BeginInvoke is asynchronous and returns immediately.
Small snippit of code from example in msdn article link:
startStopButton.Dispatcher
.BeginInvoke(DispatcherPriority.Normal,
New NextPrimeDelegate(AddressOf CheckNextNumber))

Generate a Mock object with a Method which raises an event

I am working on a VB.NET project which requires the extensive used of Unit Tests but am having problems mocking on of the classes.
Here is a breakdown of the issue:
Using NUnit and Rhino Mock 3.6
VS2010 & VB.NET
I have an interface which contains a number of methods and an Event.
The class which implements that Interface raises the event when one of the methods is called.
When I mock the object in my tests I can stub methods and create/assert expectations on the methods with no problems.
How do I configure the mock object so that when a method is called the event is raised so that I can assert that is was raised?
I have found numerous posts using C# which suggest code like this
mockObject.MyEvent += null...
When I try this 'MyEvent' does not appear in Intellisense.
I'm obviously not configuring my test/mock correctly but with so few VB.NET examples out there I'm drawing a blank.
Sorry for my lack of VB syntax; I'm a C# guy. Also, I think you should be congratulated for writing tests at all, regardless of test first or test last.
I think your code needs refactoring. It sounds like you have an interface that requires implementations to contain an event, and then another class (which you're testing) depends on this interface. The code under test then executes the event when certain things happen.
The question in my mind is, "Why is it a publically exposed event?" Why not just a method that implementations can define? I suppose the event could have multiple delegates being added to it dynamically somewhere, but if that's something you really need, then the implementation should figure out how that works. You could replace the event with a pair of methods: HandleEvent([event parameters]) and AddEventListener(TheDelegateType listener). I think the meaning and usage of those should be obvious enough. If the implementation wants to use events internally, it can, but I feel like that's an implementation detail that users of the interface should not care about. All they should care about is adding their listener and that all the listeners get called. Then you can just assert that HandleEvent or AddEventListener were called. This is probably the simplest way to make this more testable.
If you really need to keep the event, then see here for information on mocking delegates. My advice would be to mock a delegate, add it to the event during set up, and then assert it was called. This might also be useful if you need to test that things are added to the event.
Also, I wouldn't rely on Intellisense too much. Mocking is done via some crafty IL code, I believe. I wouldn't count on Intellisense to keep up with members of its objects, especially when you start getting beyond normal methods.

Custom performance profiler for Objective C

I want to create a simple to use and lightweight performance profile framework for Objective C. My goal is to measure the bottlenecks of my application.
Just to mention that I am not a beginner and I am aware of Instruments/Time Profiler. This is not what I am looking for. Time Profiler is a great tool but is too developer oriented. I want a framework that can collect performance data from a QA or pre production users and even incorporate in a real production environment to gather the real data.
The main part of this framework is the ability to measure how much time was spent in Objective C message (I am going to profile only Objective C messages).
The easiest way is to start timer in the beginning of a message and stop it at the end. It is the simplest way but its disadvantage is that it is to tedious and error prone - if any message has more than 1 return path then it will require to add the "stop timer" code before each return.
I am thinking of using method swizzling (just to note that I am aware that Apple are not happy with method swizzling but these profiled builds will be used internally only - will not be uploaded on the App Store).
My idea is to mark each message I want to profile and to generate automatically code for the method swizzling method (maybe using macros). When started, the application will swizzle the original selector with the generated one. The generated one will just start a timer, will call the original method and then will stop the timer. So in general the swizzled method will be just a wrapper of the original one.
One of the problems of the above idea is that I cannot think of an easy way how to automatically generate the methods to use for swizzling.
So I greatly will appreciate if anyone has any ideas how to automate the whole process. The perfect scenario is just to write one line of code anywhere mentioning the class and the selector I want to profile and the rest to be generated automatically.
Also will be very thankful if you have any other idea (beside method swizzling) of how to measure the performance.
I came up with a solution that works for me pretty well. First just to clarify that I was unable to find out an easy (and performance fast) way to automatically generate the appropriate swizzled methods for arbitrary selectors (i.e. with arbitrary arguments and return value) using only the selector name. So I had to add the arguments types and the return value for each selector, not only the selector name. In reality it should be relatively easy to create a small tool that would be able to parse all source files and detect automatically what are the arguments types and the returned value of the selector which we want to profile (and prepare the swizzled methods) but right now I don't need such an automated solution.
So right now my solution includes the above ideas for method swizzling, some C++ code and macros to automate and minimize some coding.
First here is the simple C++ class that measures time
class PerfTimer
{
public:
PerfTimer(PerfProfiledDataCounter* perfProfiledDataCounter);
~PerfTimer();
private:
uint64_t _startTime;
PerfProfiledDataCounter* _perfProfiledDataCounter;
};
I am using C++ to use that the destructor will be executed when object has exited the current scope. The idea is to create PerfTimer in the beginning of each swizzled method and it will take care of measuring the elapsed time for this method
The PerfProfiledDataCounter is a simple struct that counts the number of execution and the whole elapsed time (so it may find out what is the average time spent).
Also I am creating for each class I'd like profile, a category named "__Performance_Profiler_Category" and to conforms to "__Performance_Profiler_Marker" protocol. For easier creating I am using some macros that automatically create such categories. Also I have a set of macros that take selector name, return type and arguments type and create selectors for each selector name.
For all of the above tasks, I've created a set of macros to help me. Also I have a single file with .mm extension to register all classes and all selectors I'd like to profile. On app start, I am using the runtime to retrieve all classes that conforms to "__Performance_Profiler_Marker" protocol (i.e. the registered ones) and search for selectors that are marked for profiling (these selectors starts with predefined prefix). Note that this .mm file is the only file that needs .mm extension and there is no need to change file extension for each class I want to profile.
Afterwards the code swizzles the original selectors with the profiled ones. In each profiled one, I just create PerfTimer and call the swizzled method.
In brief that is my idea which turned out to work pretty smoothly.

DLL Reflection?

Is something like this possible? If so, could you point me in the right direction for learning how?
applicationx tries to run the method start() in dll_one.dll
dll_one.dll runs the command
applicationx tries to run the method run() in dll_one.dll
dll_one.dll doesn't have a method run() and hasn't prepared for such an occurance.
dll_one.dll asks dll_two.dll if it has a run()
dll_two runs run()
Basically, I want it so if dllA doesn't have a method that the application is looking for, it asks dllB. This is assuming, as well, that ApplicationX and dllB don't know anything about dllA and dllA kind of just appeared out of nowhere (I want dlls dynamically like a patch to my applications without having to rewrite ALL of the methods, properties, etc. in the dll and have everything else just routed to the old dll).
Any ideas? Keep in mind, I'm using vb.net so a .net reference is appreciated.
It seems like you're asking for a plug-in architecture for your app (except that "patch" part is bothering me). If so, you can try MEF, which solves this exact problem.
The specific thing you ask for isn't possible. You can't have a non-existent method call automatically re-routed to a different dll. You can't "run the method run() in dll_one.dll" unless you've compiled that code, and it won't compile if the method doesn't exist. You also can't compile code against dllB and then drop dllA in and have it intercept method calls. Reflection could conceivably solve part of your problem, but you'd not want to base your code around calling all methods by reflection - it'd be horrendously unperformant and not very maintainable.
As Anton suggests, a plugin approach might work. However, this would rely on you being able to specify up-front the interface for your plugin, which sounds like it would contradict your original requirement.
Another problem: if you'd not deployed dllA until later, how would your ApplicationX know to call method start() in dll_one.dll anyway? You'd surely need to re-deploy at least the base application for that part to work.
These kinds of problem are often best solved by having a more specific set of requirements to work to: what functionality are you likely to want to extend or change in the future? Could you support a common set of interfaces that allow extensibility via plugins, or can you need to redeploy encapsulated chunks of your application with new functionality? Is there UI involved or is this just to change back-end logic? Questions like this could help to suggest more viable solutions.

intercepting the GetCustomUI callback in a VSTO3 addin

I've got a VSTO3 Word addin that makes use of custom ribbons and taskbars, etc.
Now, Office 2010 comes along and there's this nifty new BACKSTAGE concept, which I'd like to hook into. However, from what I can tell, doing it with VSTO requires Vsto 4, which requires VS2010, which isn't an option.
Soooo. I started looking online and have found all sorts of examples of, essentially, piggybacking the backstage XML onto whatever Ribbon xml I define and returning that as the value of GetCustomUI. All good, except if you're using VSTO3, there doesn't appear to be any way to "hook" into the call chain for GetCustomUI. It's all "automagically" handled for you by the OfficeRibbon and RibbonManage classes.
I know I +COULD+ convert the addin to a shared addin and just implement the IDTExtensibility interfaces directly. I'd lose all the vsto goodness (yeah, that's debatable) but I'd gain access to the GetCustomUI call.
Anyone every tried to get access to GetCustomUI +WHILE+ using VSTO though? Is it even possible?
I thought I could create a wrapper class for RibbonManager, but lo, MS has gone and done what looks to be some supreme violation of encapsulation. The RibbonManager implements the nice and easy IRibbonExtensibility interface, and yet, where that interface is passed around, they actually check the passed object to be sure it's of the actual type RibbonManager! Ugh, so much for any kind of wrapper.
Turns out it's possible, just not easy. You have to override the CreateRibbonExtensibilityObject method on connect, as well as the CreateRibbonObjects, and the RequestService methods.
Then, you have to create an object that wraps the built in VSTO RibbonManager object, and implements iReflect to intercept reflection INVOKE calls and forward them on to the underlying RibbonManager.
Finally, on the interceptor object, you have to also implement IRibbonExtensibility, then code up the GetCustomUI method of that interface.
once you do all that, your GetCustomUI will be called and passed in the full XML of the ribbons you've defined via VSTO, which you can then alter directly (in my case I needed to add backstage support), and then return that xml from the function.
definitely not straightforward, but it works.
If you want to edit XML ribbon at runtime in a VSTO app, I have created a simple solution here: Outlook 2007 ribbon customization in .NET using VS2010; insertBeforeMso dynamic function