How to find out the exact operation that is posted to Dispatcher - wpf

Is there a way where we can find out which UI element has posted an operation to the Dispatcher queue which eventually throws the event ,System.Windows.Threading.Dispatcher.CurrentDispatcher.Hooks.OperationPosted
Update : A private property DispatcherOperation.Name is showing what I need in the VS mouse-over in debugging mode. I just need to print this name to a logger for other debugging purposes. Is it possible to extract the Name dynamically.

Yes it is possible, while i give you a way to do it, i must warn you though, using reflection to get private or protected fields/properties/methods is never a good idea because first they are usually private for a reason and second of all if the signature or interface changes you code might break. But because you said it is just for debugging, this might be a valuable solution.
You can always use Reflection for these kind of things. First you need the Type and Instance of the object you want to read its private properties. Unfortunately i don't know if the Name you are looking for is a field or a property, but the overall procedure is similar. First get the property with GetProperty and then call GetValue on the returned PropertyInfo object. You might want to cache the PropertyInfo object to gain some speed while debug. You also need to use the correct BindingFlags again i don't know exactly how the field/property is described so i can't give you the exact code, but from here it should be easy to figure out.
Hope that helps.

Related

Correct way to add a (lagging) watermark to a source which already has timestamps

First up, I'm very new to stream processing, feel free to correct me where I misunderstand concepts :)
I'm using Apache Fink.
My source is a FlinkKafkaConsumer, which already adds timestamps which it takes from Kafka.
In my processing I want to be able to use a watermark (the why is out of scope for this question).
What I'm after is the watermark generation behaviour as provided by the abstract class BoundedOutOfOrdernessTimestampExtractor.
But this class only provides a:
public abstract long extractTimestamp(T element);
Which if you override it gives you the element, but not the timestamp originally provided by FlinkKafkaConsumer
The TimestampAssigner interface implemented by BoundedOutOfOrdernessTimestampExtractor does provide a public final long extractTimestamp(T element, long previousElementTimestamp), which does give you the previously assigned, in which case you could just re-use that. But this method is made final in BoundedOutOfOrdernessTimestampExtractor, and thus can't be used.
So my way of getting around this now is to copy/paste the source code of BoundedOutOfOrdernessTimestampExtractor, and rewrite it to use previousElementTimestamp as the timestamp.
My question is: Is this indeed the best way to go about this, or is there a (better) alternative?
I'm just surprised having to copy paste classes, I'm used to (spoiled by) frameworks designed so that such 'basic' functionality can be done with what's incuded. (Or mayby what I want is actually very esoteric :)

Keeping track of parameters using a Command Pattern and ICommand for Undo/Redo. Storing multiple commands?

I've been working on a WPF application that involves moving many shapes. It is mostly MVVM and relies heavily on commands. I had not worried about Undo/Redo until just recently. I don't think it will be too difficult since most of my changes involve commands that inherit a base class CommandBase that implements ICommand.
So far I have added another Interface named IUndoCommand that uses ICommand. I have added an Undo method that will perform the operations needed when an undo is called.
I will be using a stack for both Undo and Redo, but I'm running in to an issue with the parameters for the Execute/Undo methods. Is there a proper way to store these parameters of type object? Is it advisable to add a field/method to IUndoCommand? If so should I set it in the Execute method or in a constructor (if I even can.)
If not should I pass it as it's own object in the Stack?
Secondly, (although this can probably be it's own question) is there a better data structure to track multiple commands? I currently have a loop that runs multiple commands to move multiple selected shapes and would like to allow one undo to undo them all. I guess I could convert this to a command on it's own and pass commands to it, but again I'm new to this and would rather do it right.
Thanks for reading and any help would be greatly appreciated.
Sources:
Code Project
VisualStudioMagazine
StackOverFlow
Since the interface doesn't need access to the data (it should just need an Undo()/Redo() method pair, and potentially a flag for whether it can undo), it doesn't need to know about the parameters at all.
One option might be to make your implementation of IUndoCommand generic. You could then use this to store the parameter in a type-safe manner.
Your CommandBase class could then be generic, ie:
class CommandBase<T> : ICommand, IUndoCommand
{
// You could then store the parameter directly...
public T Parameter { get; private set; }
}

Is ReactiveUI Production Ready?

I've been looking into the feasability of using Reactive UI in production code. Some of the features are really appealing, but I have concerns about taking a dependency on this library. These include:
Whacky naming and conventions. For example, protected members starting with lower case, and the RaiseAndSetIfChanged method depends on your private member beginning with an underscore. I understand Paul Betts (ReactiveUI author) has a Ruby background, so I guess that's where the odd naming stems from. However, this will cause a real issue for me, since standard naming (as per Stylecop) is enforced throughout my project. Even if it wasn't enforced, I'd be concerned by the resultant inconsistency in naming that this will cause.
Lack of documentation/samples. There is some documentation and a lonely sample. However, the documentation is just a series of (old) blog posts and the sample is based on V2 of the library (it's now on V4).
Odd design, in parts. For example, logging is abstracted so as not to take a dependency on a specific logging framework. Fair enough. However, since I use log4net (and not NLog) I will need my own adapter. I think that will require me to implement IRxUIFullLogger, which has a metric crapload of methods in it (well over 50). I would have thought a far better approach would be to define a very simple interface and then provide extension methods within ReactiveUI to facilitate all the requisite overloads. In addition, there's this weird IWantsToRegisterStuff interface that the NLog assembly depends on, that I won't be able to depend on (because it's an internal interface). I'm hoping I don't need that...
Anyway, my concern here is the overall design of the library. Has anyone been bitten by this?
I'm already using MVVM Light extensively. I know Paul did a blog post where he explains you can technically use both, but my concern is more around maintainability. I suspect it would be horribly confusing having both intermingled in one's code base.
Does anyone have hands-on experience with using Reactive UI in production? If so, are you able to allay or address any of my above concerns?
Let's go through your concerns piece by piece:
#1. "Whacky naming and conventions."
Now that ReactiveUI 4.1+ has CallerMemberName, you don't have to use the conventions at all (and even then, you can override them via RxApp.GetFieldNameForPropertyFunc). Just write a property as:
int iCanNameThisWhateverIWant;
public int SomeProperty {
get { return iCanNameThisWhateverIWant; }
set { this.RaiseAndSetIfChanged(ref iCanNameThisWhateverIWant, value); }
}
#2. Lack of documentation/samples
This is legit, but here's some more docs / samples:
http://docs.reactiveui.net/ (this is the official ReactiveUI documentation, a work in progress but definitely where you want to start)
https://github.com/reactiveui/ReactiveUI.Samples
https://github.com/reactiveui/RxUI_QCon
https://github.com/play/play-windows
#3. "I would have thought a far better approach would be to define a very simple interface and then provide extension methods within ReactiveUI to facilitate all the requisite overloads"
Implement IRxUILogger instead, it has a scant two methods :) ReactiveUI will fill in the rest. IRxUIFullLogger is only there if you need it.
"In addition, there's this weird IWantsToRegisterStuff interface "
You don't need to know about this :) This is only for dealing with ReactiveUI initializing itself so that you don't have to have boilerplate code.
"I suspect it would be horribly confusing having both intermingled in one's code base."
Not really. Just think of it as "MVVM Light with SuperPowers".
I am answering as someone who has used ReactiveUI in a few production systems, has had issues with the way RxUI does stuff, and has submitted patches to try and fix issues I've had.
Disclaimer: I don't use all the features of RxUI. The reason being I don't agree with the way those features have been implemented. I'll detail my changes as I go.
Naming. I thought this was odd too. This ended up being one of the features I don't really use. I use PropertyChanged.Fody to weave in the change notification using AOP. As a result my properties look like auto properties.
Doco. Yes there could be more. Especially with the newer parts like routing. This possibly is a reason why I don't use all of RxUI.
Logging. I've had issues with this in the past. See pull request 69. At the end of the day I see RxUI as a very opinionated framework. If you don't agree with that opinion you can suggest changes, but that's all. Opinionated does not make it bad.
I use RxUI with Caliburn Micro. CM handles View-ViewModel location and binding, Screen and Conductors. I don't use CM's convention binding. RxUI handles Commands, and ViewModel INPC code, and allows me to react to property changes using Reactive instead of the traditional approaches. By keeping these things separate I find it much easier to mix the two together.
Does any of these issues have anything to do with being production ready? Nope. ReactiveUI is stable, has a decently sized user base, problems get solved quickly in the google group and Paul is receptive to discussion.
I use it in production and so far RxUI has been perfectly stable. The application has had problems with stability, some to do with EMS, others with an UnhandledException handler that was causing more problems than it was solving, but I've not had any problems with the ReactiveUI part of the application. However, I have had issues regarding the ObservableForProperty not firing at all, which I may have used incorrectly and did work consistently (incorrectly) in my test code as well as in the UI at run time.
-1. Paul explains that the _Upper is due to using reflection to get at the private field in your class. You can either use a block such as below to deal with the StyleCop and Resharper messages, which is easy to generate (from the Resharper SmartTag)
/// <summary>The xxx view model.</summary>
public class XXXViewModel : ReactiveObject
{
#pragma warning disable 0649
// ReSharper disable InconsistentNaming
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. ReactiveUI field.")]
private readonly bool _IsRunning;
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. ReactiveUI field.")]
private string _Name;
....
or change your properties from the full
/// <summary>Gets or sets a value indicating whether is selected.</summary>
public bool IsSelected
{
get { return _IsSelected; }
set { this.RaiseAndSetIfChanged(x => x.IsSelected, value); }
}
to its component parts such as
/// <summary>Gets or sets a value indicating whether is selected.</summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
this.RaisePropertyChanging(x => x.IsSelected);
_isSelected = value;
this.RaisPropertyChanged(x=>x.IsSelected);
}
}
}
This pattern is also useful where you don't actually supply a "simple" property accessor, but may require a more derived variant where setting one value affects multiple others.
-2. Yes the documentation isn't ideal but I found that after Rx, picking up the RxUI samples was quite easy. I also note that the jumps from 2->4 seem to have all come with the changes to support Windows 8/Windows 8 Phone, and having picked up ReactiveUI for a Windows Store App then the DotNet 4.5 support is excellent. i.e. use of [CallerName] now means that you simply this.RaiseAndSetIFChanged(value) no need for the expression.
-3. I haven't any feedback on the logging side as I've not elected to use it.
-4. I've not mixed and matched with others frameworks either.
There's also a list of other contributors to ReactiveUI 4.2 at http://blog.paulbetts.org/index.php/2012/12/16/reactiveui-4-2-is-released/, including Phil Haack.

Making actions get called in silverlight unit test with MOQ

Lets say I have this
_articlesService.SaveAsync(Model, AddressOf OnSaveCompleted)
The OnSaveCompleteMethod do a couple of things, obviously. Its a
Protected Overridable Sub OnSaveCompleted(ByVal asyncValidationResult As AsyncValidationResult)
In my unittest. I need to run a mocked SaveAsync, and have OnSaveCompleted called in anyway, because the method sends out events that I need to know have been sent.
Right now, the code just walks past that method, thus its never executed.
Need help solving this because I'm stuck right now.
If I understand your context right:
you have a class under test which uses an ArticlesService
your ArticlesService (a collaborating class) is responsible for sending some events
you want to verify that your class under test is behaving correctly
you want to do that by checking for the events.
If that's the case, you may be making your class responsible for more than it needs to be. You only need to verify that the ArticlesService was asked to SaveAsync. You don't need to worry about what the ArticlesService then went off and did.
Think of it this way. You are a Class-Under-Test. You have too much work to do, so you've asked some other people to help you. You have two choices. You can either chase them up, worrying about whether they're doing it right, or you can just trust them.
Rather than micro-managing classes, you can write a separate test which gives some examples of the way the ArticlesService will work, which will check that the ArticlesService is doing its job correctly. Your CUT's responsibility is to delegate that work effectively.
If you actually need the events to be raised so that your CUT can respond, that's a separate aspect of its behaviour, and you can do it with Moq's "Raise" method, documented in "Events", here:
http://code.google.com/p/moq/wiki/QuickStart
Edit: You can also use "CallBack", documented on the same link, to do stuff with the args being passed to you, including OnSaveCompleted. Not sure if it's going to help or not; it's tricky to see what you're doing without both the code and the failing test. Good luck anyway!
Close, but not exactly like that.
We don't actually send out an event in the ArticleService.
The method SaveAsync takes an Article to be saved, and a method to be called once the saving is complete.
The problem is that the "OnSaveCompleted"-method isnt being called. (This method exists in the View Model Base class, so the service isnt sending the event, the viewmodel is.).
But we have our own implementation of WCF-service proxies so this is probably what's messing with us, since we dont use the generated code.
Think we will have to rework our infrastructure on the services abit to solve this.
So it's a special case, just wanted to throw the question out just in case. :)
Thanks anyway for the answer.

Subclassing TDataset: InternalRefresh

What are you supposed to do in InternalRefresh when you subclassing TDataset in Delphi?
Fetch the data from the database again. The public interface to this is TDataSet.Refresh.
Note that TQuery's override of this just throws an exception. There's not a strict requirement to do anything useful here, if you don't care about supporting Refresh.

Resources