AutoRefreshOnObservable only works once. Why? - wpf

I'm working on a small programm where i'm evaluating if reactive ui is the right framework for another project. So far so good... At the moment i'm a little bit lost in a DynamicData related function. I'm trying to execute a command in the MainViewWindow every time a combo box in a ReactiveUserControl is changed. All my Models are extending ReactiveObject and the Properties are set up with the RaiseAndSetIfChanged setter.
In my ReactiveUserControl ViewModel I invoke my Command SaveImage from the ReactiveUserControl ViewModel as it is described here:
https://reactiveui.net/docs/handbook/message-bus/#ways-to-avoid-using-messagebus
Defining the ObservableCollection
public ObservableCollection<FileViewModel> VisibleFiles { get; protected set; }
Initialize the Collection, Files is a SourceList
WatchFiles = ReactiveCommand.Create(() =>
{
VisibleFiles = new ObservableCollection<FilesViewModel>(Files.Items);
VisibleFiles.ToObservableChangeSet().AutoRefreshOnObservable(doc => doc.SaveImage).Select(_ => WhenAnyFileChanged()).Switch().Subscribe<FilesViewModel>(x => {
Console.WriteLine("HOORAY");
});
});
private IObservable<FilesViewModel> WhenAnyFileChanged()
{
return VisibleFiles.Select(x => x.SaveFile.Select(_ => x )).Merge();
}
The First time a combo box changed it gets evaluated correct. I get the "Hooray". But every time after that there is no output. If I invoke the Watch Files Command again it is again working once.
Why is this happening, and how can i solve it to print every time a file changed the "Hooray" ? I can see, that the ObservableCollection detects the change, and also the Command in the ReactiveUserControl is invoked on the change. But the WhenAnyFileChanged Method doesn't return the changed element after the first invokation.
Hopefully it is understandable what I'm trying to achieve, an what's the problem.
Update: I don't know why, but if i check the ChangeSet in the Select() i get TotalChanges 10 at initialisation, which is right. Then with my first working change TotalChanges is 0 but is evaluated right. On my next attempt on changing i still get 0 TotalChanges but also no correct evaluation in WhenAnyFileChanged().
Refreshes() is 1 on every change.
Update 2: Changing AutoRefreshOnObservable() to AutoRefresh() brings the desired functionality.

I copied the original message bus example and wrote a unit test to see whether the code behaves as expected. I can confirm the issue you are seeing is present in the example. The following code only fires once.
public MainViewModel()
{
OpenDocuments = new ObservableCollection<DocumentViewModel>();
OpenDocuments
.ToObservableChangeSet()
.AutoRefreshOnObservable(document => document.Close)
.Select(_ => WhenAnyDocumentClosed())
.Switch()
.Subscribe(x => OpenDocuments.Remove(x), ex=>{},()=>{});
}
IObservable<DocumentViewModel> WhenAnyDocumentClosed()
{
return OpenDocuments
.Select(x => x.Close.Select(_ => x))
.Merge();
}
And here's the test to prove it. It fails on the second attempt to remove.
[Fact]
public void MyTest()
{
//I added an id field to help with diagnostics / testing
_mainViewModel.OpenDocuments.Count.Should().Be(4);
_mainViewModel.OpenDocuments.Any(dvm => dvm.Id == "1").Should().BeTrue();
_mainViewModel.OpenDocuments[0].Close.Execute().Subscribe();
_mainViewModel.OpenDocuments.Count.Should().Be(3);
_mainViewModel.OpenDocuments.Any(dvm => dvm.Id == "1").Should().BeFalse();
_mainViewModel.OpenDocuments[0].Close.Execute().Subscribe();
_mainViewModel.OpenDocuments.Count.Should().Be(2);
_mainViewModel.OpenDocuments.Any(dvm => dvm.Id == "2").Should().BeFalse();
}
I am unsure why this fails, but the most optimal fix is to make use of Dynamic Data's MergeMany operator which is similar to Rx's Merge but automatically wires observables when items are added to the underlying list and unwires them when items are removed. The fix is:
public class MainViewModel : ReactiveObject
{
public ObservableCollection<DocumentViewModel> OpenDocuments { get;}
public MainViewModel()
{
OpenDocuments = new ObservableCollection<DocumentViewModel>();
OpenDocuments
.ToObservableChangeSet()
.MergeMany(x => x.Close.Select(_ => x))
.Subscribe(x => OpenDocuments.Remove(x));
}
}
Running the same unit tests pass.
The code with unit test is available in this gist

Related

Events generated through ReactiveCommand run in unexpected order

I have a problem where I see events running after I expect all events to be completed. But that happens only when the method called is called by a ReactiveCommand.
I have a viewmodel that has one property and a calculated property:
public class ViewModel : ReactiveObject
{
private int _property;
private readonly ObservableAsPropertyHelper<int> _calculatedProperty;
public ViewModel()
{
Command = new DelegateCommand(x => Test("Command"));
ReactiveCommand = ReactiveCommand.Create(() => Test("ReactiveCommand"));
this.WhenAnyValue(x => x.Property)
.Do(x => Console.WriteLine($"CalculatedProperty will be set to {x}"))
.ToProperty(this, x => x.CalculatedProperty, out _calculatedProperty);
this.WhenAnyValue(x => x.CalculatedProperty)
.Subscribe(v => Console.WriteLine($"CalculatedProperty was set to {v}"));
}
public void Test(string method)
{
Console.WriteLine($"Begin {method}");
Property++;
Console.WriteLine($"End {method}");
}
public int Property
{
get => _property;
set => this.RaiseAndSetIfChanged(ref _property, value);
}
public int CalculatedProperty => _calculatedProperty.Value;
public ICommand Command { get; }
public ReactiveCommand ReactiveCommand { get; }
}
I have a window with 2 buttons, one bound to the Command and one to the ReactiveCommand (and one button with an oldfashioned clickhandler which behaves identical to the Command).
When I click the Command button, the outputted text is as I expect:
Begin Command
CalculatedProperty will be set to 1
CalculatedProperty was set to 1
End Command
However when I click the ReactiveCommand-button I get this:
Begin ReactiveCommand
CalculatedProperty will be set to 2
End ReactiveCommand
CalculatedProperty was set to 2
The calculated property event firing after the End-message is being run. This causes problems in my code and I do not understand why this happens. I've been investigating and playing with sending in schedulers in the ReactiveCommand.Create method, looking at SynchronizationContexts but all my experiments haven't worked out.
Why is this happening and what can I do to stop it?
Be due to the fact that by default ReactiveCommand will issue the commands onto the Main Thread dispatcher for ReactiveCommand.Create(() => action)
Your Delegate command is just running it straight away without going through the dispatcher which is similar functionality to what ImmediateScheduler would do.
You could pass the ImmediateScheduler.Default to the second parameter of the ReactiveCommand.Create()
I found out that the ToProperty method also takes in a scheduler. When I changed the:
.ToProperty(this, x => x.CalculatedProperty, out _calculatedProperty);
to:
.ToProperty(this, x => x.CalculatedProperty, out _calculatedProperty,
scheduler: ImmediateScheduler.Instance);
it worked as I intended. Not sure if this is intended behaviour or some kind of bug. It certainly was unexpected for me.

Windows 10 Universal App - ListView Update from Background Thread

I have a strange problem here. We develop a Windows 10 Universal App and now I want to update my listview when I add new value. But unfortunately it wont work and I dont really know why. When I add new value it won't update my list view.
The data comes from a background-thread (REST-Request against Server) and therefore I know, I should use something that runs the "add-functionality" on the UI-Thread.
First of all I declared a IProgress and my collection:
private List<dtoGemeinde> _listeGemeinden = new List<dtoGemeinde>();
public List<dtoGemeinde> GemeindenCollection
{
get { return this._listeGemeinden; }
}
IProgress<dtoGemeinde> prog;
prog = new Progress<dtoGemeinde>(UpdateListViewUI);
This is the "UpdateListViewUI" method:
public void UpdateListViewUI(dtoGemeinde dto)
{
_listeGemeinden.Add(dto);
this.listViewGemeinden.ItemsSource = GemeindenCollection;
}
And this is the callback method which is called when the background thread, which loads the data from the server, is finished:
public async void onCallBackGemeinden(List<dtoGemeinde> listeGemeinden)
{
if (listeGemeinden != null && listeGemeinden.Count > 0)
{
this.progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
foreach (dtoGemeinde dto in listeGemeinden)
{
await listViewGemeinden.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => prog.Report(dto));
}
}
else
{
await new MessageDialog("Data cant be load", "Error").ShowAsync();
}
}
ObservableCollection instead of List usually works fine if need to bind a ListView and be able to see the updates, if this doesn't work any underlying class might need to implement the INotifyChanged pattern to update any properties within the collection if needed.

MVVM RelayCommand CanExecute

I'm implementing an RelayCommand with an execute and an canExecute part. The RelayCommand works when it is without the canExecute part, however when I add the canExecute part, the command locks the button. The RelayCommand only checks whether or not the button can be executed as long as the CanExecute part is true. Once the canExecute part becomes false, the button can no longer be clicked, even if it is supposed to. How do I make sure that every time I click on the button it controls whether or not it can be executed, and doesn't lock it forever, once it cannot be executed?
RedoCommand = new RelayCommand(undoRedoController.Redo,undoRedoController.CanRedo);
public bool CanRedo()
{
redoStack.Count();
redoStack.Any();
return redoStack.Any();
}
public void Redo()
{
if (redoStack.Count() <= 0) throw new InvalidOperationException();
IUndoRedoCommand command = redoStack.Pop();
undoStack.Push(command);
command.Execute();
}
public class UndoRedoController
{
private static UndoRedoController controller = new UndoRedoController();
private readonly Stack<IUndoRedoCommand> undoStack = new Stack<IUndoRedoCommand>();
private readonly Stack<IUndoRedoCommand> redoStack = new Stack<IUndoRedoCommand>();
private UndoRedoController() { }
public static UndoRedoController GetInstance() { return controller; }
There has been a hiatus with MVVMLight due to the fact that after the .NET 4.5 update the CommandManager no longer fires the can execute check. This has since been solved. Instead of including the GalaSoft.MvvmLight.Command namespace you should use the GalaSoft.MvvmLight.CommandWpf namespace. The RelayCommand defined in that namespace is still checking the CanExecute function that you pass to the command.
Took me about a day to find out what the hell was going wrong in my application. I hope this will help some of you.
Here is a blog post by the developer explanining why this is necessary.
For some reason you have to do the following:
public RelayCommand RedoCommand{
get;
set;
}
you can also put private before set optional, depending on your access level. Then you do
RedoCommand = new RelayCommand(() => undoRedoController.Redo(), () => undoRedoController.CanRedo());
Now your able to call RedoCommand.RaiseCanExecuteChanged();
And everything works.
If you are using an unpatched .net 4.5. Microsoft broke the .CanExecute event.
http://connect.microsoft.com/VisualStudio/feedback/details/753666/net-4-0-application-commands-canexecute-not-updating-in-4-5
If you are using the RelayCommand from http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030 and are not raising the CanExecuteChanged event when redoStack changes.
(Answering from a Silverlight perspective so assuming this will help you.)
Are you doing a RedoCommand.RaiseCanExecuteChanged() anywhere? Once whatever condition you are monitoring changes, you'll need to raise this command manually.
EDIT
Since you are using MVVM Light.. Heres sample code:
RedoCommand = new RelayCommand(undoRedoController.Redo,undoRedoController.CanRedo);
public bool CanRedo()
{
redoStack.Count();
redoStack.Any();
return redoStack.Any();
}
public void Redo()
{
if (redoStack.Count() <= 0) throw new InvalidOperationException();
IUndoRedoCommand command = redoStack.Pop();
undoStack.Push(command);
command.Execute();
// At this point, your stacks have changed; that is, the stacks
// may or may not contain items. Thus, raise the commands CanExecute part
// which will in turn enable/disable the commands based on the functions
// return value
RedoCommand.RaiseCanExecuteChanged();
// assuming you could possibly have an UndoCommand somewhere
UndoCommand.RaiseCanExecuteChanged();
}

Create a new ICommand object in the ViewModel

Both ICommand objects are bound to a ViewModel.
The first approach seems to be used often.
But the second one saves some lines of code but would it not create everytime a new ICommand object when the Binding is refreshed so its a waste of resources?!
private LightCommand _deleteDocumentCommand;
public LightCommand DeleteDocumentCommand
{
get { return _deleteDocumentCommand ?? (_deleteDocumentCommand = new LightCommand(() => DeleteDocument(), () => CanDeleteDocument)); }
}
public LightCommand DeleteDocumentCommand
{
get { return new LightCommand(() => DeleteDocument(), () => CanDeleteDocument); }
}
Yes your 2nd method creates a new command every time the command is referenced, but I also find your 1st method rather hard to read.
My preferred way to make a command in the ViewModel is
private LightCommand _deleteDocumentCommand;
public LightCommand DeleteDocumentCommand
{
get
{
if (_deleteDocumentCommand == null)
{
_deleteDocumentCommand = new LightCommand(
() => DeleteDocument(), () => CanDeleteDocument);
}
return _deleteDocumentCommand;
}
}
It might be more lines of code, but it is easy to read and understand. Besides, usually all my public Properties/Commands are generated by macros and dumped into a #region Properties area that stays collapsed the entire time I work with the ViewModel, so I don't have to scroll through pages of get/set methods.
yes it would. You are better off instantiating it once, so that you have something like this:
LightCommand DeleteCommand { get; set;}
and then in our VM instantiation you assign to it. Or you could use your first example.
I assume you're looking for verification, and that's correct:
Everytime the Binding is refreshed, (or the command is called), a new object is instantiated. It looks like a clear waste of resources.

Unit test WPF Bindings

I am trying to unit test my WPF databindings using the test suit provided by Microsoft Team System. I would like to be able to test the bindings without showing the window because most of my tests will be for user controls and not actually on a window. Is this possible or is there a better way to do it? The code below works if I show the window, but if I don't, the bindings don't update.
Window1_Accessor target = new Window1_Accessor();
UnitTestingWPF.Window1_Accessor.Person p = new UnitTestingWPF.Window1_Accessor.Person() { FirstName = "Shane" };
Window1 window = (target.Target as Window1);
window.DataContext = p;
//window.Show(); //Only Works when I actually show the window
//Is it possible to manually update the binding here, maybe? Is there a better way?
Assert.AreEqual("Shane", target.textBoxFirstName.Text); //Fails if I don't Show() the window because the bindings aren't updated
While looking for a solution to convert WPF binding errors into exception, I figured out that it can also be used in a unit test project.
The technique is very simple:
Derive a TraceListener that throws instead of logging
Add that listener to PresentationTraceSources.DataBindingSource
Please see the complete solution on GitHub, it includes a unit test project.
Shane, if what you're really worried about is a binding breaking silently, you should look at redirecting the binding traces to somewhere you can examine. I'd start here:
http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx
Other than that, I agree with Gishu that bindings aren't good candidates for unit testing, mainly due to the automagic going on that Gishu mentioned in the "Epilogue". Instead focus on making sure the underlying class behaves correctly.
Note, too, that you can get even more robust traces using the PresentationTraceSources class:
http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.aspx
Hope that helps!
Eyeball it.
This kind of declarative markup rarely breaks.. unless someone goes in manual and screws it up. Even then, you can fix it within minutes. IMHO the cost of writing such tests far outweigh the benefits.
Update[Dec3,08]: Alrighty then.
The test is just testing that the textbox has the value "FirstName" as the Path property of the binding. If I change/refactor FirstName to JustName in the actual data source object, the test would still pass since it is testing against an anonymous type. (Green test when code broken - TDD Antipattern: The Liar)
If your aim is to verify that FirstName has been specified in XAML,
Assert.AreEqual("FirstName", txtBoxToProbe.GetBindingExpression(TextBox.TextProperty).ParentBinding.Path.Path);
If you really must catch broken bindings via unit tests (and don't want to show the UI), use the real data source... struggled for a while and came up with this.
[Test]
public void TestTextBoxBinding()
{
MyWindow w = new MyWindow();
TextBox txtBoxToProbe = w.TextBox1;
Object obDataSource = w; // use 'real' data source
BindingExpression bindingExpr = BindingOperations.GetBindingExpression(txtBoxToProbe, TextBox.TextProperty);
Binding newBind = new Binding(bindingExpr.ParentBinding.Path.Path);
newBind.Source = obDataSource;
txtBoxToProbe.SetBinding(TextBox.TextProperty, newBind);
Assert.AreEqual("Go ahead. Change my value.", txtBoxToProbe.Text);
}
Epilogue:
There's some real covert stuff happening in the call to Window.Show(). It somehow magically sets up the DataItem property after which data binding starts working.
// before show
bindingExpr.DataItem => null
bindingExpr.Status => BindingStatus.Unattached
// after show
bindingExpr.DataItem => {Actual Data Source}
bindingExpr.Status => BindingStatus.Active
Once the Binding is Active, I guess you can force textbox updates via code like this..
txtBoxToProbe.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
Once again, I voice my reluctance against this approach. Getting NUnit to run in STA was a pain..
Combining advice I came across in a number of SO posts I wrote the following class which works very well to test WPF bindings.
public static class WpfBindingTester
{
/// <summary>load a view in a hidden window and monitor it for binding errors</summary>
/// <param name="view">a data-bound view to load and monitor for binding errors</param>
public static void AssertBindings(object view)
{
using (InternalTraceListener listener = new InternalTraceListener())
{
ManualResetEventSlim mre = new ManualResetEventSlim(false);
Window window = new Window
{
Width = 0,
Height = 0,
WindowStyle = WindowStyle.None,
ShowInTaskbar = false,
ShowActivated = false,
Content = view
};
window.Loaded += (_, __) => mre.Set();
window.Show();
mre.Wait();
window.Close();
Assert.That(listener.ErrorMessages, Is.Empty, listener.ErrorMessages);
}
}
/// <summary>Is the test running in an interactive session. Use with Assume.That(WpfBindingTester.IsAvailable) to make sure tests only run where they're able to</summary>
public static bool IsAvailable { get { return Environment.UserInteractive && Process.GetCurrentProcess().SessionId != 0; } }
private class InternalTraceListener : TraceListener
{
private readonly StringBuilder _errors = new StringBuilder();
private readonly SourceLevels _originalLevel;
public string ErrorMessages { get { return _errors.ToString(); } }
static InternalTraceListener() { PresentationTraceSources.Refresh(); }
public InternalTraceListener()
{
_originalLevel = PresentationTraceSources.DataBindingSource.Switch.Level;
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
PresentationTraceSources.DataBindingSource.Listeners.Add(this);
}
public override void Write(string message) {}
public override void WriteLine(string message) { _errors.AppendLine(message); }
protected override void Dispose(bool disposing)
{
PresentationTraceSources.DataBindingSource.Listeners.Remove(this);
PresentationTraceSources.DataBindingSource.Switch.Level = _originalLevel;
base.Dispose(disposing);
}
}
}
you can try Guia.
With it you can unit-test your UserControl and check if the data binding is correct. You have to show the window though.
Here is an example. It starts a new instance of your UserControl and sets its DataContext and then checks if the textbox is set to the right value.
[TestMethod]
public void SimpleTest()
{
var viewModel = new SimpleControlViewModel() {TextBoxText = "Some Text"};
customControl = CustomControl.Start<SimpleUserControl>((control) => control.DataContext = viewModel);
Assert.AreEqual("Some Text", customControl.Get<TextBox>("textbox1").Value);
customControl.Stop();
}

Resources