Issue with MVVMLight ViewModelBase public parameterless constructor in inherited base class for WP7 Tombstoning - serialization

I am handling tombstoning in Wp7 by dumping my ViewModel into the PhoneApplicationService state (see this link for more info).
My ViewModel (VM) inherits from the MVVM Light Toolkit (ViewModelBase) which has a protected parameterless constructor only.
This causes the serilization to fail with:
"The type 'GalaSoft.MvvmLight.ViewModelBase' cannot be deserialized in partial trust because it does not have a public parameterless constructor."
Excuse my ignorance but serialization is new to me - I think I understand why it's failing, but I am trying to think of ways around it. For example, can I mark the entire base class as non-serilizable or ignored like I do certain fields in classes ([IgnoreDataMember])? I don't need to store anything that is in this class.
Is there anyway around this? I don't want to edit the source of that assembly to mark it public instead of protected.

Public default constructors in abstract classes are frowned upon by StyleCop, which is why I made the ViewModelBase one protected. As you found out, this however causes issues with serialization. This issue is more acute in WP7 where it is tempting to dump the whole vm in serialization for safe keeping.
Right now, the only fix I can propose is to implement your own viewmodelbase class. I will consider changing the constructor to public in a future release.
Cheers,
Laurent

Related

Is there a solution to "Cannot access '<init>': it is private in XYZ?

I included a library I'd like to use, but in accessing to one of its classes I get the error message,
"Cannot access '<init>': it is private in [class name]
Is there something I can do to rectify this on my side, or am I just stuck to not use the package?
The error means the constructor is private. Given your comment, I'm assuming you're using a library. If this is the case, you'll have to find a different way to initialize it. Some libraries have factories or builders for classes, so look up any applicable documentation (if it is a library or framework). Others also use the singleton pattern, or other forms of initialization where you, the developer, don't use the constructor directly.
If, however, it is your code, remove private from the constructor(s). If it's internal and you're trying to access it outside the module, remove internal. Remember, the default accessibility is public. Alternatively, you can use the builder pattern, factory pattern, or anything similar yourself if you want to keep the constructor private or internal.
I came across this issue when trying to extend a sealed class in another file. Without seeing the library code it is hard to know if that is also what you are attempting to do.
The sealed classes have the following unique features:
A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself.
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their constructors are private by default).
Classes that extend subclasses of a sealed class (indirect inheritors) can be placed anywhere, not necessarily in the same file.
For more info, have a read at https://www.ericdecanini.com/2019/10/14/kotlins-sealed-class-enums-on-steroids/
Hopefully, this will help others new to Kotlin who are also encountering this issue.
Class constructors are package-private by default. Just add the public keyword before declaring the constructor.
By default constructor is public so need to remove internal keyword.

Modify Property Code At Runtime in VB.NET

Let say I have the following classes,
Public Class Base
Public Event PropertyChanged()
Sub New()
.....
End Sub
End Class
Public Class Other
Inherits Base
Public Property X As String
End Class
If I wanted to say, alter the code definition of the automatic property X (at runtime, perhaps in Sub New), such that I could throw the PropertyChanged event, how could I go about doing that?
Edit: Its seems that the Postsharp is an available tool that does the functionality I'm exploring, but I wanted my question to be more academic than practical. So, how could I implement the code injection at compile time or runtime myself?
I guess you are looking for AOP. A very nice technology that IMHO isn't mature on the dotnet platform. I believe, correct me if I am wrong, that Postsharp is the best known AOP framework. It isn't gratis though for production; installing and playing (and possibly F/OSS) is gratis. Also check this post for more info.
The answer is simple: you can't. Once a type is loaded, you can't change its code.
If you want to implement INotifyPropertyChanged without writing the same code for each property, there are several ways.
One of them is making the property MustOverride (abstract in C#) and then creating another class at runtime which implements it at runtime (for example using Castle DynamicProxy).
Another one is using AOP to rewrite the code after compilation (but before it's run) using something like PostSharp.
Also have a look at Implementing INotifyPropertyChanged - does a better way exist?, for an overview of other options.

NHibernate and IoC IInterceptor

I have been trying to implement a solution similar to what Ayende posts in his MSDN article, Building a Desktop To-Do Application with NHibernate. Fortunately, Skooletz wrote a similar article that follows up what I am trying to accomplish with his 3 part blog post on NHibernate interceptor magic tricks (1, 2, 3). I am having trouble getting my POCO object's parametered constructor to be called by NHibernate when instantiating the object.
When I remove the protected parameterless constructor, NHibernate complains with an InvalidProxyTypeException: "The following types may not be used as proxies:
YourNamespace.YourClass: type should have a visible (public or protected) no-argument constructor". If I then add in the protected default constructor, NHibernate no longer complains, but the dependency (in the overloaded constructor) is never called causing the application to barf with a NullReferenceException at runtime when the dependency is not satisfied.
public MyClass
{
IRequiredDependency dependency;
public MyClass(IRequiredDependency dependency)
{
this.dependency = dependency;
}
protected MyClass() {}
}
I just can't seem to get NHibernate to call the overloaded constructor. Any thoughts?
In the configuration of the IoC container, you have to declare your type with the dependency in addition to the dependency itself.
container.RegisterType<IRequiredDependency, RequiredDependency>();
container.RegisterType<MyClass, MyClass>();
I missed that little tidbit from Pablo's post (where he registers the Invoice class in addition to its dependency, IInvoiceTotalCalculator) as I am using Unity instead of Windsor.
One additional note: I found is that if you would like to have any other overloaded constructors, make them internal, leave the default constructor as protected and have only a single public constructor that contains your dependencies. This tidbit helped tighten up some of my API design for the classes.

Interface reference variables

I am going over some OO basics and trying to understand why is there a use of Interface reference variables.
When I create an interface:
public interface IWorker
{
int HoneySum { get; }
void getHoney();
}
and have a class implement it:
public class Worker : Bee, IWorker
{
int honeySum = 15;
public int HoneySum { get { return honeySum; } }
public void getHoney()
{
Console.WriteLine("Worker Bee: I have this much honey: {0}", HoneySum);
}
}
why do people use:
IWorker worker = new Worker();
worker.getHoney();
instead of just using:
Worker worker3 = new Worker();
worker3.getHoney();
whats the point of a interface reference variable when you can just instatiate the class and use it's methods and fields that way?
If your code knows what class will be used, you are right, there is no point in having an interface type variable. Just like in your example. That code knows that the class that will be instantiated is Worker, because that code won't magically change and instantiate anything else than Worker. In that sense, your code is coupled with the definition and use of Worker.
But you might want to write some code that works without knowing the class type. Take for example the following method:
public void stopWorker(IWorker worker) {
worker.stop(); // Assuming IWorker has a stop() method
}
That method doesn't care about the specific class. It would handle anything that implements IWorker.
That is code you don't have to change if you want later to use a different IWorker implementation.
It's all about low coupling between your pieces of code. It's all about maintainability.
Basically it's considered good programming practice to use the interface as the type. This allows different implementations of the interface to be used without effecting the code. I.e. if the object being assigned was passed in then you can pass in anything that implements the interface without effecting the class. However if you use the concrete class then you can only passin objects of that type.
There is a programming principle I cannot remember the name of at this time that applies to this.
You want to keep it as generic as possible without tying to specific implementation.
Interfaces are used to achieve loose coupling between system components. You're not restricting your system to the specific concrete IWorker instance. Instead, you're allowing the consumer to specify which concrete implementation of IWorker they'd like to use. What you get out of it is loosely dependent components and better flexibility.
One major reason is to provide compatibility with existing code. If you have existing code that knows how to manipulate objects via some particular interface, you can instantly make your new code compatible with that existing code by implementing that interface.
This kind of capability becomes particularly important for long-term maintenance. You already have an existing framework, and you typically want to minimize changes to other code to fit your new code into the framework. At least in the ideal case, you do this by writing your new code to implement some number of existing interfaces. As soon as you do, the existing code that knows how to manipulate objects via those interfaces can automatically work with your new class just as well as it could with the ones for which it was originally designed.
Think about interfaces as protocols and not classes i.e. does this object implement this protocol as distinct from being a protocol? For example can my number object be serialisable? Its class is a number but it might implement an interface that describes generally how it can be serialised.
A given class of object may actually implement many interfaces.

No parameterless constructer defined for this object when putting EnabledDelete=true on LinqDataSource

If I have a LinqDataSource without EnabledDelete, EnabledUpdate, EnabledInsert, it works fine, but as soon as I add those properties to the data source, I get the error:
No parameterless constructor defined for this object.
Here is an answer that helped me solve the issue from the MSDN forums:
LinqDataSource requires a default constructor on the DataContext. If you are working in a web application or website project, the Linq to SQL designer should have created a default constructor and connection string for you when you dragged tables from the database onto the design surface.
Did you create your DataContext and drag tables onto the design surface from a webapp or website project? Open the Lib.NorthwindDataContext class that was generated and see if it has the default constructor.
If you really want, you could also use LinqDataSource without the default constructor by handling the ContextCreating event and providing your own context instance.
As the error indicates, you need to provide a parameterless constructor for the class.
public class MyClass
{
public MyClass()
{
// This is the parameterless constructor
}
// rest of the class members goes here.
}
The system requires a parameterless constructor when it is required to create instances of a class automatically. It cannot determine the meaning of the parameters of your other constructors so it depends on this constructor.
Even if your constructor does nothing it will still work, though you may want it to provide useful defaults for your class properties.