Concord (VS debugger) method chaining question - visual-studio-debugging

I try to uinderstand how method chaining (calling previous or default implementation) works (https://github.com/Microsoft/ConcordExtensibilitySamples/wiki/Component-discovery-and-configuration) but still have many doubts.
DkmExample seems to be dispatcher, but how this class is defined ? Can I define such class ?
Concord interfaces (Microsoft.VisualStudio.Debugger.ComponentInterfaces) do not pass dispatcher in their methods, so how it can be added in implementation ? Do any Concord interface can be chained this way ?
can anyone show how to implement method chaining in https://github.com/microsoft/ConcordExtensibilitySamples/tree/master/HelloWorld/Cs (show how to call default implementation), or provide other real exapmle ?
Thanks in advance

In the Method Chaining Example IDkmExample represents an interface that is part of the Concord API. This is the interface you, as the developer, are implementing. In the method call itself, DkmExample is not the dispatcher but rather a dispatcher object that the dispatcher knows how to handle. These are defined by the dispatcher and cannot be defined externally.
The method chaining example is there to show that if the implementation does not want to handle the call of the interface method, then it can call the method of the same name on the dispatcher object (first item in the API method signature), passing in all the parameters that are taken by the method signature minus the dispatcher object itself. This will allow the dispatcher to pass the call, based on filtering and priority, to the next implementation of the interface that it can find.
For a concrete example, we can look at the following block from the Microsoft.VisualStudio.Debugger.Engine.xml from the microsoft.visualstudio.debugger.engine nuget package:
<member name="M:Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmStartDebuggingOperations.LaunchDebuggedProcess(Microsoft.VisualStudio.Debugger.Start.DkmProcessLaunchRequest)">
<summary>
Causes the debug monitor to create a new process under the debugger. The process
should be left suspended until ResumeDebuggedProcess is called. The debug monitor
must wait for ResumeDebuggedProcess before creating the DkmProcess object since
it needs the UniqueProcessId value from the AD7 Layer.
Note that this method may only be called in response to the Visual Studio
debugger package requesting a launch. Components that wish to launch another
process under the debugger should send a custom event to a visual studio package.
From a package, a launch can be requested through the
IVsDebugger.LaunchDebugTargets API.
</summary>
<param name="request">
[In] DkmProcessLaunchRequest is used to describe the process that debugger should
launch.
</param>
<returns>
[Out] DkmLaunchedProcessInfo is returned from APIs that launch a process.
</returns>
</member>
The interface we are overriding is IDkmStartDebuggingOperations and the method is LaunchDebuggedProcess which in the implementation will take a DkmProcessLaunchRequest, which is a dispatcher object. If the implementation does not want to handle the call, it can call the next implementation by taking the dispatcher object and calling the method of the same name on it, passing the necessary parameters.
For example:
internal class MyStartDebuggingOperations : IDkmStartDebuggingOperations
{
public DkmLaunchedProcessInfo LaunchDebuggedProcess(DkmProcessLaunchRequest request)
{
if (/* custom check that this class is to handle it */)
{
// Handle custom implementation here
}
else
{
// This calls the base implementation
return request.LaunchDebuggedProcess();
}
}
}

Related

Silverlight hangs on Prism's EventAggregator Subscribe method

I am using Prism's event aggregator in Silverlight and am having a hard time with Subscribe. When the code hits the Subscribe method it just hangs and never makes it to the next line of code. If I break up the code, _eventAggregator.GetEvent() seems to return a valid instance of the event. The code definitely hangs on "Subscribe". What could I be doing wrong here? The JobCompletedEvent is declared in another library (which is a dependency for this library).
public void CallMeWhenTheJobIsDone(Action callback)
{
if (_jobIsRunning)
_eventAggregator.GetEvent<JobCompletedEvent>().Subscribe((e) => callback(), ThreadOption.UIThread);
else
callback();
}
public class JobCompletedEvent: Microsoft.Practices.Prism.Events.CompositePresentationEvent<JobCompleted>
{ }
public class JobCompleted
{
}
1) Why you using if (_jobIsRunning) ?? You calling callback in any case.
2) Prism will only bring you the event - and according to your question - Prism IS rising and passing the event to you - so it's not a Prism question - it seems that whatever called by callback is not working.
So we need to see more on what is called by callback and another thing: in Prism case you calling the callback on ThreadOption.UIThread ThreadPool so - double check if any other thread already lock the UI thread when you calling callback
My problem is that I should not have used an anonymous method in my subscribe. Prism does not seem to support it. Some are calling this a bug in Prism, I agree :) Not only can you not use an anonymous method but the method must be public.
Some references I found googling
http://greenicicleblog.com/2010/04/28/prism-event-aggregator-more-leaky-than-it-seems/
Execute same Prism Command from different ViewModels
I suspect this is in the Prism docs somewhere, I guess I just blew by it. If I set keepSubscriberReferenceAlice it works with the private method or anonymous method (which does make some sense now that I think about it). The funny thing is that in my sandbox project I cannot even compile with an anonymous method which uses privately scoped code. My live project allows it to compile but fails at runtime.
Edit:
Yup, it is in the docs
http://msdn.microsoft.com/en-us/library/ff921122%28v=pandp.40%29.aspx
Big yellow box 2/3 of the way down the page.

Asynchronous WCF Services in WPF - events

I am using WCF services asynchronously in a WPF application. So I have class with all the web service. The view models call the method in this proc, which in-turn calls the web service.
So the view Model code looks like this:
WebServiceAgent.GetProductByID(SelectedProductID, (s, e)=>{States = e.Result;});
And the WebService agent looks like:
public static void GetProductByID(int ProductID, EventHandler<GetProductListCompletedEventArgs> callback)
{
Client.GetProductByIDCompleted += callback;
Client.GetProductByIDAsync(ProductID);
}
Is this a good approach? I am using MVVM light toolkit. So the View Model static, so in the lifetime of the application, the view model stays. But each time the view model calls this WebServiceAgent, I think I am registering an event. But that event is not being unregistered.
Is this a problem. Lets say the view Model is called for 20 - 30 times. I am inserting some kind of memory leak?
Some helpful information, based on the mistakes I learned from myself:
The Client object seems to be re-used all the time. When not unregisering event handlers, they will stack up when future invokations of the same operations finish and you'll get unpredictable results.
The States = e.Result statement is executed on the event handler's thread, which is not the UI dispatcher thread. When updating lists or complex properties this will cause problems.
In general not unregistering event handlers when they are invoked is a bad idea as it will indeed cause hard to find memory leaks.
You should probably refactor to create or re-use a clean client, wrap the viewmodel callback inside another callback that will take care of unregistering itself, cleaning up the client, and invoking the viewmodel's callback on the main dispatcher thread.
If you think all this is tedious, check out http://blogs.msdn.com/b/csharpfaq/archive/2010/10/28/async.aspx and http://msdn.microsoft.com/en-us/vstudio/async.aspx. In the next version of C# an async keyword will be introduced to make this all easier. A CTP is available already.
Event handlers are death traps and you will leak them if you do not "unsubscribe" with "-=".
One way to avoid is to use RX (Reactive Extensions) that will manage your event subscriptions. Take a look at http://msdn.microsoft.com/en-us/data/gg577609 and specifically creating Observable by using Observable.FromEvent or FromAsync http://rxwiki.wikidot.com/101samples.
This is unfortunaltely not a good approach.
I learned this the hard way in silverlight.
Your WebserviceAgent is probably a long-life object, whereas the model or view is probably short-life
Events give references, and in this case the webservice agent, and wcf client a reference to the model. A long lifeobject has a reference to a short life object, this means the short life object will not be collected, and so will have a memory leak.
As Pieter-Bias said, the async functionality will make this easier.
Have you looked at RIA services? This is the exact problem that RIA services was designed to solve
Yes, the event handlers are basically going to cause a leak unless removed. To get the near-single line equivalent of what you're expressing in your code, and to remove handlers you're going to need an instance of some sort of class that represents the full lifecycle of the call and does some housekeeping.
What I've done is create a Caller<TResult> class that uses an underlying WCF client proxy following this basic pattern:
create a Caller instance around an existing or new client proxy (the proxy's lifecycle is outside of the scope of the call to be made (so you can use a new short-lived one or an existing long-lived one).
use one of Caller's various CallAsync<TArg [,...]> overloads to specify the async method to call and the intended callback to call upon completion. This method will choose the async method that also takes a state parameter. The state parameter will be the Caller instance itself.
I say intended because the real handler that will be wired up will do a bit more housekeeping. The real callback is what will be called at the end of the async call, and will
check that ReferenceEquals(e.UserState, this) in your real handler
if not true, immediately return (the event was not intended to be the result of this particular call and should be ignored; this is very important if your proxy is long lived)
otherwise, immediately remove the real handler
call your intended, actual callback with e.Result
Modify Caller's real handler as needed to execute the intended callback on the right thread (more important for WPF than Silverlight)
The above implementation should also have separate handlers for cases where e.Error is non-null or e.Cancelled is true. This gives you the advantage of not checking these cases in your intended callback. Perhaps your overloads take in optional handlers for those cases.
At any rate, you end up cleaning up handlers aggressively at the expense of some per-call wiring. It's a bit expensive per-call, but with proper optimization ends up being far less expensive than the over-the-wire WCF call anyway.
Here's an example of a call using the class (you'll note I use method groups in many cases to increase the readability, though HandleStuff could have been result => use result ). The first method group is important, because CallAsync gets the owner of that delegate (i.e. the service instance), which is needed to call the method; alternatively the service could be passed in as a separate parameter).
Caller<AnalysisResult>.CallAsync(
// line below could also be longLivedAnalyzer.AnalyzeSomeThingsAsync
new AnalyzerServiceClient().AnalyzeSomeThingsAsync,
listOfStuff,
HandleAnalyzedStuff,
// optional handlers for error or cancelled would go here
onFailure:TellUserWhatWentWrong);

WPF: how to marshall data to user control from another domain

I have to use functionality that is in another application domain. The result should be displayed in user control.
I have something like that:
var instance = domain.CreateInstanceFromAndUnwrap(...);
instance.Foo(myWpfUserControl as ICallback);
Foo(ICallback itf) {
itf.SetData("...");
}
WpfUserControl.SetData(string data)
{
if (!Dispatcher.CheckAccess())
Dispatcher.Invoke(...)
...
}
I had to put [Serializable] attribute onto WpfUserControll class and implement serialization contructor as well as ISerializable interface but now i receive exception:
The calling thread must be STA because many UI components require this
that is raised from UserControl() constructor
What shall I do to avoid this ?
Thank you in advance !
==============================
Solution
as #Al noticed, my user control have to be serialized when it comes to cross-application-domain calls. Now i pass proxy, that implements ICallback interface. Proxy was marked with Serializable attribute.
Proxy implementation should have absolutely no knowledge about user control as there should be an attempt to deserialize user control instance once again. When I tried to abstract proxy from user control via interface it didn't help. When i tried to pass interface to proxy (that was implemented by user control) - same exception occured.
Finally I decoupled proxy and user control with queue/semaphor. Queue was monitored by a worker thread that deligated calls to user control
p.s. this queue should be inherited from "MarshalByObjectRef".
If the exception is coming from the constructor, it means that you're not creating this control instance from the UI thread. This can be fine but you have to make sure the Thread is an STA thread by calling .SetApartmentState(ApartmentState.STA) on the thread object before the thread is started.
This also means you have to have access to the thread object before its started so you cant do this on a threadpool thread.
The best way to avoid the problem though is probably to create the control on the main UI thread and then assign the Text value using the Dispatcher (or a Task on the UiScheduler). That way you'll also avoid problems if the main thread needs to set, get or bind to the control, as that would cause a cross thread exception if the control was created on another thread
i'd advice against seriealizing the control this way if possible. doing that will generate a new object that is not attatched to any panels or some such, and the original control would not be updated. sadly you cant inheirit from MarshalByRefObject that would eliminate serialization since it would only pass a reference to the other domain.
If you can, call Foo separately and then pass the result to SetData in the original Appdomain

Event Aggregation...What exactly is going on?

I have often times wondered about it but now that I have encountered a piece of logic that incorporates it, I thought I should go ahead and get some help on deciphering the fundamentals. The problem is as follows, I am looking at a WPF application that is utilizing the Composite Application Library. Within the source of the application I came across the following line of code in the Presentation of a view. For the sake of convinience I will call it Presentation A:
private void OnSomethingChanged(SomeArgumentType arguement)
{
UnityImplementation.EventAggregator.GetEvent<EventA>().Publish(null);
}
When I saw the method Publish in the above given method, my gut told me there must be a Subscribe somewhere and in another class, I will call it Presentation B there was the following:
UnityImplementation.EventAggregator.GetEvent(Of EventA).Subscribe(AddressOf OnSomeEventA)
There was a private function in the same class called OnSomeEventA that had some logic in it.
My question here is that how is everything wired over here? What exactly is achieved by the 'Publish' 'Subscribe' here? When 'something' changes, how does the compiler know it has to follow the logic in OnSomethingChanged that will 'Publish' an event that is 'Subscribed' by another class where the logic of the event handler has been described? It will be great to understand the underlying wiring of this process.
Thanks
The first time GetEvent<T> is called for each event (identified by the type parameter T) the EventAggregator creates an empty list of methods to call when that event is published. Typically, this will happen immediately before the first call to Publish or Subscribe (as in your examples).
Then:
Whenever Subscribe is called a method is added to the list.
Whenever Publish is called it walks through the list and makes those calls.
So, the call to Publish() in Presentation A results in all of the methods that have been registered by calling Subscribe being called, which in your example would include Presentation B's OnSomeEventA method.
Try setting a breakpoint in the OnSomeEventA method and take a look at the stack, and don't forget the source is available, too!

Command Pattern & parameter design

My understanding of the Command Pattern is that you simply have 1 virtual method 'execute()', and all dependencies that an implementation might have are put in the constructor or through setter injection in the implementation (like discussed here).
However, in the WPF implementation of the pattern, I noticed they are passing a generic argument to the execute() function (explained here).
This seems like a pollution of the interface to me, what would have been the motivation to add a generic parameter to the execute() function?
The canonical command pattern is usually illustrated with nice self-contained commands. In that any information needed by the command is stashed away within the Command object instance (typically via a parameterized constructor).
However in some cases, the parameters needed for Execute may not be available at command-creation time (are known only at runtime). e.g. Imagine a SignOutCommand( username ). The username is determined when the user clicks on the SignOut button after signing in first.
So username is passed in as a generic parameter to Command.Execute(); Each command is free to define its input and cast accordingly e.g. an arbitrary command can require 5 parameters as an object[].
It's for databinding. When you bind the command to every object in a list, for example, the current instance is sent to the execute method so that you don't have to keep track of the current instance yourself.
That said, I don't think that the WPF command notion is an implementation of the command pattern, they just share terminology.
The reason behind that parameter is the isolation between the creator of the command - who know what command needs to be executed, and the caller - who knows when a command need to be executed.
In certain commands some of the information that needed for the execution is not available to the creator. The caller the fills in the blank by passing a parameter to execute. An example: The creator creates a command that filters a list of records according to some criteria. The list is not available at the creation site, as there are many kinds of lists in the application.
The caller will specify which list needs to be filtered by passing at as a parameter.
We use a bit changed command pattern, so that in addition to Execute method we have two properties Request and Response and we parametrize them using polymorphism.
What's wrong with:
public class DeleteCommand : BaseCommand
{
private Dictionary<string, object> parameters;
public DeleteCommand(Dictionary<string, object> parameters)
{
this.parameters = parameters;
}
public void Execute()
{
var person = (Person)parameters["Person"];
var salary = System.Convert.ToDouble(parameters["Salary"]);
// etc.
}
}
Now if you have a controller that collects parameters you can pass those through to your commands.

Resources