Caliburn.micro design time data for WinRT - object reference not set to an instance of an object - xaml

I'm doing windows 8 app dev using the caliburn.micro MVVM framework.
I'm having issues with design time data. I've looked high and low through various blogs and what not to find an answer. No luck so far.
Here is a section from my view where I say use this view model for design time
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cal="using:Caliburn.Micro"
xmlns:vm="using:MyApp.SampleViewModels"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=vm:SampleNewsViewModel, IsDesignTimeCreatable=True}"
cal:Bind.AtDesignTime="True">
The d:DataContext... part is being underlined and saying "object reference not set to an instance of an object"
I have a view model with a default constructor
namespace MyApp.SampleViewModels
{
public sealed class SampleNewsViewModel
{
public SampleNewsViewModel()
{
Title = "News Title";
}
private string _title;
public string Title
{
get { return _title; }
set { _title = value; }
}
}
}
Pretty sure there's nothing wrong with my ViewModel (but I could be wrong).
I can't figure this out, any point in the right direction would be awesome.
cheers,
Lochana

First off, make sure you have got the namespaces configured correctly (this gives me a headache many times). Now with that out of our way, i can tell you to try too things:
Try to add these to your namespace declarations mc:Ignorable="d" and xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006".
If this alone didn't work then try to replace
Type=vm:SampleNewsViewModel with Type={x:Type
vm:SampleNewsViewModel and see if it works.

Oh man...I found the issue, and it's my fault.
In my design time view model, I had not initialized the list, and in the constructor, was trying to add items to it.
This fixed it
private List<NewsItem> _itemListView = new List<NewsItem>();
public List<NewsItem> ItemListView
{
get { return _itemListView; }
set { _itemListView = value; }
}
The lesson I learned here is that the error message "Object reference not set to an instance of an object" can mean you're view model is broken, even though it doesn't explicitly say. So for anyone starting out with caliburn.micro, unit test your design time view models to make sure they work as expected.

Related

Ignore the Binding initialization

The inital problem is coming from a personal project about the polyline of the Xamarin.Forms.Map where the initialization is realized by a binding from the XAML part..
Let me be clear by an example :
I have an object CustomMap.cs which inherit from Xamarin.Forms.Map (This file is in the PCL part -> CustomControl/CustomMap.cs)
public class CustomMap : Map, INotifyPropertyChanged
{
public static readonly BindableProperty PolylineAddressPointsProperty =
BindableProperty.Create(nameof(PolylineAddressPoints), typeof(List<string>), typeof(CustomMap), null);
public List<string> PolylineAddressPoints
{
get { return (List<string>)GetValue(PolylineAddressPointsProperty); }
set
{
SetValue(PolylineAddressPointsProperty, value);
this.GeneratePolylineCoordinatesInner();
}
}
// ...
}
As you can see, I have a bindable property with an assessor and the XAML doesn't seem to use this assessor..
So the MainPge.xaml part of the page, where the control is called, looks like that:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:control="clr-namespace:MapPolylineProject.CustomControl;assembly=MapPolylineProject"
x:Class="MapPolylineProject.Page.MainPage">
<ContentPage.Content>
<control:CustomMap x:Name="MapTest" PolylineAddressPoints="{Binding AddressPointList}"
VerticalOptions="Fill" HorizontalOptions="Fill"/>
</ContentPage.Content>
</ContentPage>
The MainPge.xaml.cs part:
public partial class MainPage : ContentPage
{
public List<string> AddressPointList { get; set; }
public MainPage()
{
base.BindingContext = this;
AddressPointList = new List<string>()
{
"72230 Ruaudin, France",
"72100 Le Mans, France",
"77500 Chelles, France"
};
InitializeComponent();
//MapTest.PolylineAddressPoints = AddressPointList;
}
}
So, everything is fine if I edit the PolylineAddressPoints from the object instance (if the commented part isnt' commented..), but if I init the value from the XAML (from the InitializeComponent();), it doesn't work, the SetValue, in the Set {}, of the CustomMap.PolylineAddressPoints, isn't called..
I then searched on the web about it and get something about the Dependency Properties? or something like that. So I tried some solutions but, from WPF, so some methods, such as DependencyProperty.Register();. So yeah, I can't find the way to solve my problem..
I also though about something, if DependencyProperty.Register(); would exists in Xamarin.Forms, then it means I would have to do it for each values? Because, if every value has to be set by a XAML binding logic, it would not work, I would have to register every value, doesn't it?
I'm sorry if I'm not clear, but I'm so lost about this problem.. Please, do not hesitate to ask for more details, thank in advance !
Finaly, the initial problem is that I'm trying to set a value of an object/control, from the XAML. Doing this by a Binding doesn't work, it seems like it ignored.. However, it does work if I do the following:
MapTest.PolylineAddressPoints = AddressPointList;
There are multiple questions in this:
Why is the property setter never called when using Xaml ?
Am I properly defining my BindableProperty ?
Why is my binding failing ?
Let me answer them in a different order.
Am I properly defining my BindableProperty ?
The BindableProperty declaration is right, but could be improved by using an IList<string>:
public static readonly BindableProperty PolylineAddressPointsProperty =
BindableProperty.Create(nameof(PolylineAddressPoints), typeof(IList<string>), typeof(CustomMap), null);
but the property accessor is wrong, and should only contains this:
public IList<string> PolylineAddressPoints
{
get { return (IList<string>)GetValue(PolylineAddressPointsProperty); }
set { SetValue(PolylineAddressPointsProperty, value); }
}
I'll tell you why while answering the next question. But you want to invoke a method when the property has changed. In order to do that, you have to reference a propertyChanged delegate to CreateBindableProperty, like this:
public static readonly BindableProperty PolylineAddressPointsProperty =
BindableProperty.Create(nameof(PolylineAddressPoints), typeof(IList<string>), typeof(CustomMap), null,
propertyChanged: OnPolyLineAddressPointsPropertyChanged);
And you have to declare that method too:
static void OnPolyLineAddressPointsPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
((CustomMap)bindable).OnPolyLineAddressPointsPropertyChanged((IList<string>)oldValue, (IList<string>)newValue);
}
void OnPolyLineAddressPointsPropertyChanged(IList<string> oldValue, IList<string> newValue)
{
GeneratePolylineCoordinatesInner();
}
Why is the property setter never called when using Xaml ?
The property, and the property accessors, are only meant to be invoked when accessing the property by code. C# code.
When setting a property with a BindablePrperty backing store from Xaml, the property accessors are bypassed and SetValue() is used directly.
When defining a Binding, both from code or from Xaml, property accessors are again bypassed and SetValue() is used when the property needs to be modified. And when SetValue() is invoked, the propertyChanged delegate is executed after the property has changed (to be complete here, propertyChanging is invoked before the property change).
You might wonder why bother defining the property if the bindable property is only used by xaml, or used in the context of Binding. Well, I said the property accessors weren't invoked, but they are used in the context of Xaml and XamlC:
a [TypeConverter] attribute can be defined on the property, and will be used
with XamlC on, the property signature can be used to infer, at compile time, the Type of the BindableProperty.
So it's a good habit to always declare property accessors for public BindableProperties. ALWAYS.
Why is my binding failing ?
As you're using CustomMap as both View and ViewModel (I won't tell the Mvvm Police), doing this in your constructor should be enough:
BindingContext = this; //no need to prefix it with base.
As you're doing it already, your Binding should work once you've modified the BindableProperty declaration in the way I explained earlier.

Expression Blend WP -> Create design time data from class. Issues with Generics

Im trying to create sample data for WP project in Expression Blend.
It works fine with simple classes, but not with custom generics classes. It can define structure of datasource, display correct structure of my ViewModel, but cannot generate values ie SampleData.xaml is empty.
How can I solve this, press some generate button or is there any other easy way to create design time data without writing everything manually?
I used a bit modified generic class NotifyTaskCompletion from here http://msdn.microsoft.com/en-us/magazine/dn605875.aspx and it is a root of problem. Here is result of generated data schema
The easiest thing to do is probably to create "dummy" types that are used by the designer. They would have the same public properties as your real types, but using concrete types and without any real code. They'd also have a different name. Since data-binding uses duck typing, the fact that the design-time object is a different type than the runtime object doesn't matter. For example, say your real class is:
public class GenericObject<T>
{
public T Thing { get; set; }
/* Lots of other complex code here... */
}
then you might also add:
#if DEBUG
public class GenericObjectDesigner
{
public string Thing { get; set; }
/* No need for any complex code */
}
#endif
Now in Blend, create a data source from the GenericObjectDesigner type and set the Thing property to be some string (eg, Lorum ipsum). You can now drag and drop that onto your design surface.
And in your actual code, you use the non-Designer version of the class, eg:
public MainPage()
{
InitializeComponent();
this.DataContext = new GenericObject<int> { Thing = 42 };
}
This will work fine as long as VS is in Debug mode. In Release mode, the app will still compile and run correctly, but you will see errors about GenericObjectDesigner not existing in your XAML files (you can safely ignore them).

Should a method on an object return a new copy of the object

I'm seeing code in our legacy system where the class's public methods, clone the object, do the state mutation and return a new copy of the object.
It just feels wrong but just wondering if anyone knows of a known good reason to do this. Otherwise if anyone knows of a really bad reason to do this can you help out. I just need to arm myself with some arguments to and for this situation before I go and propose a big change.
Thanks
Sample Code
public Class MyClass
{
public string MyProp { get; set; }
public MyClass Cancel()
{
var newObj = this.Clone();
newObj.Status = Status.Cancelled;
return newObj;
}
}
This is a typical pattern with immutable objects, like String in Java or .Net for instance. By returning a new object with the change, references to the old object don't see the state change. Being able to rely on an object not changing can be very useful. Immutable objects come with a cost, of course, that every state change requires allocating a new instance.
As MattDavey points out in a comment on the question, that sample code (assuming the missing bits added in) creates a class with mutable instances, because MyProp's set is public. So it seems to ensure immutablility for Status but not for MyProp, which would be fairly unusual. It's more typical for an instance to be immutable, or not, but not partially so. I assume that's a by-product of editing the code for the question, though...

Populating a property of type ObservableCollection in XAML with static resources

I have created a class that contains a property of type ObservableCollection. I am trying to create an instance of the class in XAML and fill this property with members. I keep getting an exception that class T can not be converted to ObservableCollection, but this exception only occurs when I am trying to populate the list with elements that were declared as static resources.
Anybody has an idea why?
The code is as follows:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mseg="clr-namespace:SegApp.Model.DataEntities.Segments;assembly=SegApp.Model.Silverlight">
<mseg:Dot xKey="d1"/>
<mseg:Dot xKey="d2"/>
<mseg:Dot xKey="d3"/>
<mseg:Dot xKey="d4"/>
<mseg:Segment xKey="seg1">
<mseg:Segment.Dots>
<StaticResource ResourceKey="d1"/>
<StaticResource ResourceKey="d2"/>
<StaticResource ResourceKey="d3"/>
<StaticResource ResourceKey="d4"/>
</mseg:Segment.Dots>
</mseg:Segment>
</ResourceDictionary>
The Class definition is:
public class Segment : Part
{
public ObservableCollection<Dot> Dots { get; set; }
public Segment()
{
Dots = new ObservableCollection<Dot>();
}
}
And the exception says:
"
Object of type bla.bla.bla.Dot can not
be converted to type
System.Collections.ObjectModel.ObservableCollection'1[bla.bla.bla.Dot]
"
Any ideas?
As is your code, each element of the collection must be a Dot, not a resource...
Each entry of the list in your xaml code must be something like
or perhaps try
somevalue
or
{staticResource xxx }
But there is still a problem. The 1st syntax is ok, the second can work if there is a simple content for Dot, but the 3rd can't run : tag means "create an instance of Dot". And a StaticResource means "create an instance of.. and give it a key".
So last syntax will certainly not work cause you can replace the instance created by the tag with the instance coming from the resource...
But give it a try. The main problem in your code is than you're trying to feel a collection of Dot with Resource, that can't work and the compiler is not ok.. try using tag to create entry. And then play a bit to see if you can refer the resources somewhere in these tags..
In order to use collections XAML syntax change your property and remove it's setter:
public class Segment : DependencyObject
{
private readonly ObservableCollection<Dot> _dots = new ObservableCollection<Dot>();
public ObservableCollection<Dot> Dots
{
get { return _dots; }
}
}

Do write-only properties have practical applications?

I don't know why I started thinking about this, but now I can't seem to stop.
In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax:
class WeirdClass
{
private void Hello(string name)
{
Console.WriteLine("Hello, {0}!", name);
}
public string Name
{
set { Hello(name); }
}
}
In other words, the property has a setter but no getter, it's write-only.
I guess I can't think of any reason why this should be illegal, but I've never actually seen it in the wild, and I've seen some pretty brilliant/horrifying code in the wild. It seems like a code smell; it seems like the compiler should be giving me a warning:
CS83417: Property 'Name' appears to be completely useless and stupid. Bad programmer! Consider replacing with a method.
But maybe I just haven't been doing this long enough, or have been working in too narrow a field to see any examples of the effective use of such a construct.
Are there real-life examples of write-only properties that either cannot be replaced by straight method calls or would become less intuitive?
My first reaction to this question was: "What about the java.util.Random#setSeed method?"
I think that write-only properties are useful in several scenarios. For example, when you don't want to expose the internal representation (encapsulation), while allowing to change the state of the object. java.util.Random is a very good example of such design.
Code Analysis (aka FxCop) does give you a diagnostic:
CA1044 : Microsoft.Design : Because
property 'WeirdClass.Name' is write-only,
either add a property getter with an
accessibility that is greater than or
equal to its setter or convert this
property into a method.
Write-only properties are actually quite useful, and I use them frequently. It's all about encapsulation -- restricting access to an object's components. You often need to provide one or more components to a class that it needs to use internally, but there's no reason to make them accessible to other classes. Doing so just makes your class more confusing ("do I use this getter or this method?"), and more likely that your class can be tampered with or have its real purpose bypassed.
See "Why getter and setter methods are evil" for an interesting discussion of this. I'm not quite as hardcore about it as the writer of the article, but I think it's a good thing to think about. I typically do use setters but rarely use getters.
I have code similar to the following in an XNA project. As you can see, Scale is write-only, it is useful and (reasonably) intuitive and a read property (get) would not make sense for it. Sure it could be replaced with a method, but I like the syntax.
public class MyGraphicalObject
{
public double ScaleX { get; set; }
public double ScaleY { get; set; }
public double ScaleZ { get; set; }
public double Scale { set { ScaleX = ScaleY = ScaleZ = value; } }
// more...
}
One use for a write-only property is to support setter dependency injection, which is typically used for optional parameters.
Let's say I had a class:
public class WhizbangService {
public WhizbangProvider Provider { set; private get; }
}
The WhizbangProvider is not intended to be accessed by the outside world. I'd never want to interact with service.Provider, it's too complex. I need a class like WhizbangService to act as a facade. Yet with the setter, I can do something like this:
service.Provider = new FireworksShow();
service.Start();
And the service starts a fireworks display. Or maybe you'd rather see a water and light show:
service.Stop();
service.Provider = new FountainDisplay(new StringOfLights(), 20, UnitOfTime.Seconds);
service.Start();
And so on....
This becomes especially useful if the property is defined in a base class. If you chose construction injection for this property, you'd need to write a constructor overload in any derived class.
public abstract class DisplayService {
public WhizbangProvider Provider { set; private get; }
}
public class WhizbangService : DisplayService { }
Here, the alternative with constructor injection is:
public abstract class DisplayService {
public WhizbangProvider Provider;
protected DisplayService(WhizbangProvider provider) {
Provider = provider ?? new DefaultProvider();
}
}
public class WhizbangService : DisplayService {
public WhizbangService(WhizbangProvider provider)
: base(provider)
{ }
}
This approach is messier in my opinion, because you need to some of the internal workings of the class, specifically, that if you pass null to the constructor, you'll get a reasonable default.
In MVP pattern it is common to write a property with a setter on the view (no need for a getter) - whenever the presenter sets it content the property will use that value to update some UI element.
See here for a small demonstration:
public partial class ShowMeTheTime : Page, ICurrentTimeView
{
protected void Page_Load(object sender, EventArgs e)
{
CurrentTimePresenter presenter = new CurrentTimePresenter(this);
presenter.InitView();
}
public DateTime CurrentTime
{
set { lblCurrentTime.Text = value.ToString(); }
}
}
The presenter InitView method simply sets the property's value:
public void InitView()
{
view.CurrentTime = DateTime.Now;
}
Making something write-only is usefulwhenever you're not supposed to read what you write.
For example, when drawing things onto the screen (this is precisely what the Desktop Window Manager does in Windows):
You can certainly draw to a screen, but you should never need to read back the data (let alone expect to get the same design as before).
Now, whether write-only properties are useful (as opposed to methods), I'm not sure how often they're used. I suppose you could imagine a situation with a "BackgroundColor" property, where writing to it sets the background color of the screen, but reading makes no sense (necessarily).
So I'm not sure about that part, but in general I just wanted to point out that there are use cases for situations in which you only write data, and never read it.
Although the .NET design guidelines recommend using a method ("SetMyWriteOnlyParameter") instead of a write-only property, I find write-only properties useful when creating linked objects from a serialised representation (from a database).
Our application represents oil-field production systems. We have the system as a whole (the "Model" object) and various Reservoir, Well, Node, Group etc objects.
The Model is created and read from database first - the other objects need to know which Model they belong to. However, the Model needs to know which lower object represents the Sales total. It makes sense for this information to be stored a Model property. If we do not want to have to do two reads of Model information, we need to be able to read the name of Sales object before its creation. Then, subsequently, we set the "SalesObject" variable to point to the actual object (so that, e.g., any change by the user of the name of this object does not cause problems)
We prefer to use a write-only property - 'SalesObjectName = "TopNode"' - rather than a method - 'SetSalesObjectName("TopNode") - because it seems to us that the latter suggests that the SalesObject exists.
This is a minor point, but enough to make us want to use a Write-Only property.
As far as I'm concerned, they don't. Every time I've used a write-only property as a quick hack I have later come to regret it. Usually I end up with a constructor or a full property.
Of course I'm trying to prove a negative, so maybe there is something I'm missing.
I can't stop thinking about this, either. I have a use case for a "write-only" property. I can't see good way out of it.
I want to construct a C# attribute that derives from AuthorizeAttribute for an ASP.NET MVC app. I have a service (say, IStore) that returns information that helps decide if the current user should be authorized. Constructor Injection won't work, becuase
public AllowedAttribute: AuthorizeAttribute
{
public AllowedAttribute(IStore store) {...}
private IStore Store { get; set; }
...
}
makes store a positional attribute parameter, but IStore is not a valid attribute parameter type, and the compiler won't build code that is annotated with it. I am forced to fall back on Property Setter Injection.
public AllowedAttribute: AuthorizeAttribute
{
[Inject] public IStore Store { private get; set; }
...
}
Along with all the other bad things about Property Setter instead of Constructor Injection, the service is a write-only property. Bad enough that I have to expose the setter to clients that shouldn't need to know about the implementation detail. It wouldn't do anybody any favors to let clients see the getter, too.
I think that the benefit of Dependency Injection trumps the guidelines against write-only properties for this scenario, unless I am missing something.
I just came across that situation when writing a program that reads data from a JSON database (Firebase). It uses Newtonsoft's Json.NET to populate the objects. The data are read-only, i.e., once loaded they won't change. Also, the objects are only deserialized and won't be serialized again. There may be better ways, but this solution just looks reasonable for me.
using Newtonsoft.Json;
// ...
public class SomeDatabaseClass
{
// JSON object contains a date-time field as string
[JsonProperty("expiration")]
public string ExpirationString
{
set
{
// Needs a custom parser to handle special date-time formats
Expiration = Resources.CustomParseDateTime(value);
}
}
// But this is what the program will effectively use.
// DateTime.MaxValue is just a default value
[JsonIgnore]
public DateTime Expiration { get; private set; } = DateTime.MaxValue;
// ...
}
No, I can' imagine any case where they can't be replaced, though there might people who consider them to be more readable.
Hypothetical case:
CommunicationDevice.Response = "Hello, World"
instead of
CommunicationDevice.SendResponse("Hello, World")
The major job would be to perform IO side-effects or validation.
Interestingly, VB .NET even got it's own keyword for this weird kind of property ;)
Public WriteOnly Property Foo() As Integer
Set(value As Integer)
' ... '
End Set
End Property
even though many "write-only" properties from outside actually have a private getter.
I recently worked on an application that handled passwords. (Note that I'm not claiming that the following is a good idea; I'm just describing what I did.)
I had a class, HashingPassword, which contained a password. The constructor took a password as an argument and stored it in a private attribute. Given one of these objects, you could either acquire a salted hash for the password, or check the password against a given salted hash. There was, of course, no way to retrieve the password from a HashingPassword object.
So then I had some other object, I don't remember what it was; let's pretend it was a password-protected banana. The Banana class had a set-only property called Password, which created a HashingPassword from the given value and stored it in a private attribute of Banana. Since the password attribute of HashingPassword was private, there was no way to write a getter for this property.
So why did I have a set-only property called Password instead of a method called SetPassword? Because it made sense. The effect was, in fact, to set the password of the Banana, and if I wanted to set the password of a Banana object, I would expect to do that by setting a property, not by calling a method.
Using a method called SetPassword wouldn't have had any major disadvantages. But I don't see any significant advantages, either.
I know this has been here for a long time, but I came across it and have a valid (imho) use-case:
When you post parameters to a webapi call from ajax, you can simply try to fill out the parameters class' properties and include validation or whatsoever.
public int MyFancyWepapiMethod([FromBody]CallParams p) {
return p.MyIntPropertyForAjax.HasValue ? p.MyIntPropertyForAjax.Value : 42;
}
public class CallParams
{
public int? MyIntPropertyForAjax;
public object TryMyIntPropertyForAjax
{
set
{
try { MyIntPropertyForAjax = Convert.ToInt32(value); }
catch { MyIntPropertyForAjax = null; }
}
}
}
On JavaScript side you can simply fill out the parameters including validation:
var callparameter = {
TryMyIntPropertyForAjax = 23
}
which is safe in this example, but if you handle userinput it might be not sure that you have a valid intvalue or something similar.