Using Moq at Blend design time - wpf

This might be a bit out there, but suppose I want to use Moq in a ViewModel to create some design time data, like so:
public class SomeViewModel
{
public SomeViewModel(ISomeDependency dependency)
{
if (IsInDesignMode)
{
var mock = new Mock<ISomeDependency>();
dependency = mock.Object; // this throws!
}
}
}
The mock could be set up to do some stuff, but you get the idea.
My problem is that at design-time in Blend, this code throws an InvalidCastException, with the message along the lines of "Unable to cast object of type 'Castle.Proxies.ISomeDependencyProxy2b3a8f3188284ff0b1129bdf3d50d3fc' to type 'ISomeDependency'." While this doesn't necessarily look to be Moq related but Castle related, I hope the Moq example helps ;)
Any idea why that is?
Thanks!

I'm having a similar issue, except that the cast is coming from a dynamically generated assembly (Blend_RuntimeGeneratedTypesAssembly) type that is masquerading as one of my types.
For no apparent reason.
Which is driving me CRAZY.

I used to think that I needed to do this sort of trick but after much experiementing and searching about, discovered that Blend 4 now can create design time sample datacontexts based on an existing class.
This effectively gives you a dummy class that looks just like your VM class so that you can add your binding etc.
It works well enough that this is the technique we now recommend.
A possible disadvantage with this is that if you need your real VM to perform some sort of interactivity then the proxy of course can't do that - you'd have to manually change values, or swap to another design time object. But in practice, I've rarely encountered this scenario. Most of the time, you set the state of the VM and then take ages getting the look right.

Update: released on github: https://github.com/GeniusCode/GeniusCode.Components.DynamicDuck
I also ran into a similar problem when trying to use castle to mock viewmodels at design time. We wrote our own msil duck / mock library, and it works well for that purpose.
I blogged about it here: http://blogs.geniuscode.net/JeremiahRedekop/?p=255
We are working to release the library under MS-PL and deploy on GitHub.

Related

Deprecation of TableRegistry::get()

I'd like to ask what are your thought on deprecation of the TableRegistry::get() static call in CakePHP 3.6?
In my opinion it was not a good idea.
First of all, using LocatorAwareTrait is wrong on many levels. Most important, using traits in such way can break the Single Responsibility and Separation of Concerns principles. In addition some developers don't want to use traits as all because they thing that it breaks the object oriented design pattern. They prefer delegation.
I prefer to use delegation as well with combination of flyweight/singleton approach. I know that the delegation is encapsulated by the LocatorAwareTrait but the only problem is that it exposes the (get/set)TableLocator methods that can be used incorrectly.
In other words if i have following facade:
class Fruits {
use \Cake\ORM\Locator\LocatorAwareTrait;
public function getApples() { ... }
public function getOranges() { ... }
...
}
$fruits = new Fruits();
I don't want to be able to call $fruits->getTableLocator()->get('table') outside of the scope of Fruits.
The other thing you need to consider when you make such changes is the adaptation of the framework. Doing TableRegistry::getTableLocator()->get('table') every time i need to access the model is not the best thing if i have multiple modules in my application that move beyond simple layered architecture.
Having flyweight/singleton class like TableRegistry with property get to access desired model just makes the development more straight forward and life easier.
Ideally, i would just like to call TR::get('table'), although that breaks the Cake's coding standards. (I've created that wrapper for myself anyways to make my app bullet proof from any similar changes)
What are your thoughts?

How do I implement IActivationForViewFetcher for a child UserControl?

I've just added ReactiveUI to an existing code base. Of course, for the first control I tried it with I hit a snag. I'm using it with a UserControl embedded in a TabControl. The code looks something like this:
public partial class TabPageControl : UserControl, IViewFor<TestViewModel>
{
public TabPageControl()
{
InitializeComponent();
ViewModel = new TestViewModel();
this.WhenActivated(dispose =>
{
dispose(this.Bind( ... ));
dispose(this.BindCommand( ... ));
});
}
}
When I run the app, I get the following error message:
Don't know how to detect when TabPageControl
is activated/deactivated, you may need to implement
IActivationForViewFetcher
So, how do I implement IActivationForViewFetcher? I'm not sure what I'm supposed to do with GetAffinityForView. I'm assuming in GetActivationForView I need to check to see if the UserControl is the currently visible inside the TabControl?
Although I would like to understand how to implement the methods for IActivationForViewFetcher (especially the part where I identify that a control is in the VisualTree) - the real cause of my problem was that my main assembly didn't have the appropriate references (the controls are in a class assembly).
I'm assuming (because I've skimmed the ReactiveUI source) ReactiveUI.Winforms.Registrations needs to be instantiated by the main assembly - which includes registering ActivationForViewFetcher.
Incidentally, the class library is written in C# and the main assembly is VB.NET. So I'm not sure whether this contributed to the problem.
At least it's working now!
I don't if this will ever help anybody, since this thread is so old.
What solved my issue was having ReactiveUI.WPF,ReactiveUI.WinForms, CefSharp.WPF and CefSharp.WinForms NuGet references on all the projects/plugins that were running on the App.
My suspicion is that when ReactiveUI/CefSharp is initialized and it doesn't contain all the info/files it needs, it will not possible to add them later on runtime. But this is just guessing based on my experience.
I know it's an old thread, but just to save other developers time when facing this problem.
My solution was to add the following code in the entrypoint of the project that makes use of ReactiveUi and ReactiveUi.Wpf.
var reactiveUiWpfName = typeof(ReactiveUI.Wpf.Registrations).Assembly.FullName;
Assembly.Load(reactiveUiWpfName);
Of course, it was just required because I couldn't reference ReactiveUi or ReactiveUi.Wpf in my application startup project due to the project specifications, otherwise this error wouldn't appear anyway.
(Please, observe that, in your case you should use ReactiveUi.Winforms in the places I've used ReactiveUi.Wpf)

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.

How does the Silverlight testing framework's EnqueueConditional work?

So let's say I have a test that looks something like
[TestMethod]
[Asynchronous]
public void MyTest() {
MyObject m = new MyObject();
m.DoAsyncStuff();
EnqueueConditional(() => m.TaskComplete);
EnqueueCallback(() => Assert.IsTrue(m.ValidState));
EnqueueTestComplete();
}
How does EnqueueConditional work? Assume MyObject has no property change notifiers or anything. I'm assuming EnqueueConditional polls the variable periodically? But I'm not sure.
That's precisely what it does. It polls the m.TaskComplete variable multiple times a second (I'm not sure how many). It's a hack, and you wouldn't want it in production code, but it works for a testing framework, and it sure as heck simplifies a lot of other code.
For example, in production code, you'd probably want to make MyObject implement INotifyPropertyChanged, and then use Reactive Extensions to subscribe to the INPC notifications. But that would be a lot of extra work for the sort of simple conditionals that are everywhere in testing code, and I think that Jeff Wilcox made the right call in how he implemented this, however hacky it might be.

What are the Pros and Cons of having Multiple Inheritance?

What are the pros and cons of having multiple inheritance?
And why don't we have multiple inheritance in C#?
UPDATE
Ok so it is currently avoided because of the issue with clashes resolving which parent method is being called etc. Surely this is a problem for the programmer to resolve. Or maybe this could be resolve simularly as SQL where there is a conflict more information is required i.e. ID might need to become Sales.ID to resolve a conflict in the query.
Here is a good discussion on the pitfalls of multiple inheritance:
Why should I avoid multiple inheritance in C++?
Here is a discussion from the C# team on why they decided not to allow multiple inheritance:
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85562.aspx
http://dotnetjunkies.com/WebLog/unknownreference/archive/2003/09/04/1401.aspx
It's just another tool in the toolbox. Sometimes, it is exactly the right tool. If it is, having to find a workaround because the language actually prohibits it is a pain and leads to good opportunities to screw it up.
Pros and cons can only be found for a concrete case. I guess that it's quite rare to actually fit a problem, but who are the language designers to decide how I am to tackle a specific problem?
I will give a pro here based on a C++ report-writer I've been converting to REALbasic (which has interfaces but only single-inheritance).
Multiple inheritance makes it easier to compose classes from small mixin base classes that implement functionality and have properties to remember state. When done right, you can get a lot of reuse of small code without having to copy-and-paste similar code to implement interfaces.
Fortunately, REALbasic has extends methods which are like the extension methods recently added to C# in C# 3.0. These help a bit with the problem, especially as they can be applied to arrays. I still ended up with some class hierarchies being deeper as a result of folding in what were previously multiply-inherited classes.
The main con is that if two classes have a method with the same name, the new subclass doesn't know which one to call.
In C# you can do a form of multiple inheritance by including instances of each parent object within the child.
class MyClass
{
private class1 : Class1;
private class2: Class2;
public MyClass
{
class1 = new Class1;
class2 = new Class2;
}
// Then, expose whatever functionality you need to from there.
}
When you inherit from something you are asserting that your class is of that (base) type in every way except that you may implement something slightly differently or add something to it, its actually extremely rare that your class is 2 things at once. Usually it just has behavour common to 2 or more things, and a better way to describe that generally is to have your class implement multiple interfaces. (or possibly encapsulation, depending on your circumstances)
It's one of those help-me-to-not-shoot-myself-in-the-foot quirks, much like in Java.
Although it is nice to extend fields and methods from multiple sources (imagine a Modern Mobile Phone, which inherits from MP3 Players, Cameras, Sat-Navs, and the humble Old School Mobile Phone), clashes cannot be resolved by the compiler alone.

Resources