Serialize a derived class without access to base class - wpf

I need to serialize a derived class in my Windows Phone 7 Project for tombstoning state.
But I don't have access to the code to the base class - exposed by a Library -.
//don't have access to this class
public class A
{
public string member1 {get;set;}
}
[DataContract]
public class B : A
{
public B(){}; //CTOR
[DataMember]
public string member2 {get;set;}
}
When the system try to serialize (I save it to PhoneApplicationPage.State => so it's auto serializing) : it's not working, the exception (InvalidDataContractException) says "Type 'B' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type 'A' with DataContractAttribute or SerializableAttribute, or removing them from the derived type."
Should I implement a custom serializer ? How can I do that (in Windows Phone 7)

Rather than derive from the library class, you could have a member variable that of that type and expose the properties of the library class member via custom getters and setters:
[DataContract]
public class MyClass
{
BaseClass Wrapped { get; set; }
public MyClass()
{
Wrapped = new BaseClass( );
}
[DataMember]
public string member1
{
get { return Wrapped.member1; }
set { Wrapped.member1= value; }
}
}

Related

MetadataType Attribute are being ignored Telerik.AccessData.Core 2016.1.224 fluent mapping

I'm developing an asp.net core 1.0 (MVC 6) full framework 4.6.1 and I created a Class Library targeting framework 4.6.1 for Data Modeling using Telerik DataAccess core & fluent 2016.1.224.
I have some classes, one of them is:
namespace DataModel
{
public partial class Directory
{
private int _id;
public virtual int Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
private string _directoryId;
public virtual string DirectoryId
{
get
{
return this._directoryId;
}
set
{
this._directoryId = value;
}
}
private string _directoryFullName;
public virtual string DirectoryFullName
{
get
{
return this._directoryFullName;
}
set
{
this._directoryFullName = value;
}
}
I need to customize Dataannotations to set display name & validations for every property. According telerik documentation, I'm declaring another partial class for original generated fluent Directory class to decorate it with MetadataType, like following:
[MetadataType(typeof(Directory.DirectoryMetadata))]
public partial class Directory
{
internal sealed class DirectoryMetadata
{
public DirectoryMetadata()
{
}
[Display(Name = "Id Directorio")]
[Required()]
public string DirectoryId
{ get; set; }
[Display(Name = "Nombre Completo")]
[Required()]
public string DirectoryFullName
{ get; set; }
When I run asp.net core app, MetadataType is not working, no display name nor validator works. However, for some reason, decorating original generated fluent class works fine!:
public partial class Directory
{
private int _id;
public virtual int Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
private string _directoryId;
[Display(Name = "Id Directorio")]
[Required()]
public virtual string DirectoryId
{
get
{
return this._directoryId;
}
set
{
this._directoryId = value;
}
}
private string _directoryFullName;
[Display(Name = "Nombre Completo")]
[Required()]
public virtual string DirectoryFullName
{
get
{
return this._directoryFullName;
}
set
{
this._directoryFullName = value;
}
}
Both classes, Original and metadata are in the same namespace. In fact, declaring Directory metadata class into a separate file instead internal doesn't work also.
Please, need your help!
I've found solution by myself.
For Asp.Net core projects I had to use ModelMetadataTypeAttribute instead of MetadataTypeAttribute from Microsoft.AspNetCore.Mvc.Core assembly. Decorating a metadata class (buddy class) follows same methodology of using Display(...), DisplayName(...), same for validators. No matter if the buddy class (Metadata Class) is located external from or internal to the model class.
However using MetadataTypeAttribute directly with the model class instead of a buddy class, works perfectly!
The only explanation I could give about this divergence is related with the new emerging Microsoft Asp.Net core technology, relocation of DLL process and functionalities.

Raising OnPropertyChanged in the setter of each property vs Instance of Object

Information for the question:
I am trying to understand how to properly implement INotifyPropertyChanged on objects and collections.
First, here is my ViewModelBase class:
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertychanged([CallerMemberName] string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Consider that I have a class called Person:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
To use INotifyPropertyChanged, most examples that I have seen change the Person class to something like this:
public class Person
{
public int Id { get; set; }
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertychanged();
}
}
private string _age;
public string Age
{
get { return _age; }
set
{
_age = value;
OnPropertychanged();
}
}
}
It seems to work exactly the same when used a single time on an instance of the object (This might be useful if there are a lot of properties):
private Person _person;
public Person MyPerson
{
get { return _person; }
set
{
_person = value;
OnPropertychanged();
}
}
Actual question:
1 - Does it make a difference (aside from amounts of code) whether you call OnPropertychanged() on each individual property verses on an instance of an object? (Are both considered good practice?)
2 - If setting OnPropertychanged() on the object instance is good practice, am I correct to create an ObservableCollection like this?:
var PersonCollection = new ObservableCollection<MyPerson>();
1) Well, if you want to call it on object instance, then you need to do it every time you use your class like this in binding. When you implement OnNotifyPropertyChanged directly inside your class, you don't need to care about it later on...
2) Classes with INotifyPropertyChanged do not require Observable collections. This is however must when you are binding colection do some UI control (ListBox, ListView) and want to add/remove its elements. Observable collection will then make sure the UI gets updated.
The ObservableCollections object... When adding and removing from this collection the UI will be notified of the changes (Top Level). If you have an "ObservableCollection of Person" and you change a property on the one of the objects(Person) in the list the UI will not update unless your "Person" class implements the INotifyPropertyChanged interface, which can be put into a base class that all classes can inherit from like your example. I hope this helps a little.

How to change exported property through MEF?

I'm studying MEF, and try to use Export attribute to export a property, and import it in an other class.
But my problem is that I want to change this property and the other class can import a new value.
For example,
[Export]
public class A{
[Import("Notes")]
public string Description{get;set;}
}
[Export]
public class B{
[Export("Notes")]
public string Text{get;set;}
}
I want once I change the Text of class B, the A.Description can get changed too.
So, how can I implement this?
Any good idea?
This approach would work for most reference type but not with string which is immutable. This means that after you change the value of B.Text, the objects referenced by A.Description and B.Text will no longer be the same (you can use Object.ReferenceEquals to test this).
One way to do what you are after using MEF is to export/import a method instead of the property:
[Export]
public class A
{
public string Description { get { return GetDescription(); } }
[Import("GetNotes")]
Func<string> GetDescription;
}
[Export]
public class B
{
public string Text { get; set; }
[Export("GetNotes")]
string GetText()
{
return Text;
}
}
Finally note that there are other ways to do this. The most common in .NET is with events.

Protobuf-Net Silverlight: DataContract class has properties null or missing

This is one of the class definitions within a DLL I use in my WCF service.
[DataContract]
public class ScenarioXML
{
[DataMember(Order = 1)]
public long? TNRScenario { get; set; }
[DataMember(Order = 2)]
public long? TNRProject { get; set; }
[DataMember(Order = 3)]
public int? Priority { get; set; }
// ...
[DataMember(Order = 19)]
public List<ScenarioAssetXML> ScenarioAssets { get; set; }
[DataMember(Order = 20)]
public List<CalendarXML> Calendars { get; set; }
[DataMember(Order = 21)]
public ScenarioTriggerCollectionXML ScenarioTriggerCollection { get; set; }
}
I'm using DataContract instead of ProtoContract, so I can expose this class to a Silverlight project through a WSDL, and still use Protobuf-net for serialization.
Now, when I use the following code in my WCF service, the original "scenario" and the "restoredModel" are identical.
MemoryStream msTestString = new MemoryStream();
Serializer.Serialize<ScenarioXML>(msTestString, scenario);
string memento = Convert.ToBase64String(msTestString.ToArray());
byte[] byteAfter64 = Convert.FromBase64String(memento);
MemoryStream afterStream = new MemoryStream(byteAfter64);
ScenarioXML restoredModel = Serializer.Deserialize<ScenarioXML>(afterStream);
However, when I use the same code in Silverlight, the TNRScenario value is null.
Similarly, the TNRScenarioAsset property of the objects in the ScenarioAssets list are null.
[DataContract]
public class ScenarioAssetXML
{
[DataMember(Order = 1)]
public long? TNRScenarioAsset { get; set; }
[DataMember(Order = 2)]
public long? TNRScenario { get; set; }
[DataMember(Order = 3)]
public string Asset { get; set; }
[DataMember(Order = 4)]
public string Action { get; set; }
}
When I make the first property a string, it completely vanishes after (de)serialization. When I put a dummy bool as a first property, the bool is there, but the second property, in this case ScenarioAssets, is still null. There's something weird going on here...
Am I doing somethign wrong, or is this a bug?
Edit:
You're right Marc! The orders get messed up in the WSDL-generated code.
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ScenarioXML", Namespace="http://schemas.datacontract.org/2004/07/DataCollectionDLL")]
public partial class ScenarioXML : object, System.ComponentModel.INotifyPropertyChanged {
private System.Nullable<long> TNRScenarioField;
private System.Nullable<long> TNRProjectField;
private System.Nullable<int> PriorityField;
//...
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<long> TNRScenario {
get {
return this.TNRScenarioField;
}
set {
if ((this.TNRScenarioField.Equals(value) != true)) {
this.TNRScenarioField = value;
this.RaisePropertyChanged("TNRScenario");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(Order=1)]
public System.Nullable<long> TNRProject {
get {
return this.TNRProjectField;
}
set {
if ((this.TNRProjectField.Equals(value) != true)) {
this.TNRProjectField = value;
this.RaisePropertyChanged("TNRProject");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(Order=2)]
public System.Nullable<int> Priority {
get {
return this.PriorityField;
}
set {
if ((this.PriorityField.Equals(value) != true)) {
this.PriorityField = value;
this.RaisePropertyChanged("Priority");
}
}
}
//...
However, I'm not sure how to correctly implement that partial class? I created it in the WCF service, but that seems to confuse the compiler. Getting the following errors:
Error 6 'DataCollectionDLL.ScenarioXML' does not contain a definition for 'TNRScenario' and no extension method 'TNRScenario' accepting a first argument of type 'DataCollectionDLL.ScenarioXML' could be found (are you missing a using directive or an assembly reference?)
Error 2 Cannot convert type 'DataCollectionDLL.ScenarioXML [c:\Projects\Flowcontrol 1.7.1.1\flowcontrolFC.Web\Libraries\DataCollectionDLL.dll]' to 'DataCollectionDLL.ScenarioXML [C:\Projects\Flowcontrol 1.7.1.1\flowcontrolFC.Web\DAL\DataCollectionClasses\ScenarioXML.cs(31)]'
Then tried it in the Silverlight project, which compiles fine but that doesn't solve the problem. Results are the same.
The partial class I created:
namespace DataCollectionDLL
{
[ProtoContract]
[ProtoPartialMember(1, "TNRScenario")]
[ProtoPartialMember(2, "TNRProject")]
[ProtoPartialMember(3, "Priority")]
//...
[ProtoPartialMember(21, "ScenarioTriggerCollection")]
partial class ScenarioXML
{
}
}
It sounds like you used WSDL-generated proxies; that can confuse things a little bit, because protobuf-net really really cares what the numbers are, and WSDL can sometimes play fast and loose with those. It would really help if I could see the WSDL-generated proxy classes (in the .designer.cs), but I'm going to assume this is the problem. Fortunately, most code-generators use partial class, so you can add your own partial class in a separate file to add extra information into the same type, in particular: more attributes. For example:
namespace The.Same.Namespace
{
[ProtoContract]
[ProtoPartialMember(1, "TNRScenario")]
[ProtoPartialMember(2, "TNRProject")]
// ...
[ProtoPartialMember(21, "ScenarioTriggerCollection")]
partial class ScenarioXML { }
}
This will get merged by the compiler into the ScenarioXML class, and should allow protobuf-net to use the correct numeric identifiers for each property.

MVVM with aggregated model classes - how to wrap in ViewModels?

I'm currently trying to create a small application using the MVVM pattern. However I don't really know how to correctly wrap up aggregated Model classes in my ViewModel. From what little I know about MVVM, you're not supposed to expose Models in your ViewModel as properties or else you could directly bind to the Model from your View. So it seems I have to wrap the nested Model in another ViewModel, but this imposes some problems while synching Model and ViewModel later on.
So how do you do that efficiently?
I'll give a short example. Let's suppose I have the following model classes:
public class Bar
{
public string Name { get; set; }
}
public class Foo
{
public Bar NestedBar { get; set; }
}
Now I create two ViewModel classes accordingly, wrapping the Models, but run into problems with the FooViewModel:
public class BarViewModel
{
private Bar _bar;
public string Name
{
get { return _bar.Name; }
set { _bar.Name = value; }
}
}
public class FooViewModel
{
private Foo _foo;
public BarViewModel Bar
{
get { return ???; }
set { ??? = value; }
}
}
Now what do I do with the Bar-property of FooViewModel? For "get" to work I need to return a BarViewModel instance. Do I create a new field of that type in FooViewModel and just wrap the _foo.NestedBar object in there? Changes to that field's properties should propagate down to the underlying Bar instance, right?
What if I need to assign another BarViewModel instance to that property, like so:
foo.Bar = new BarViewModel();
Now that won't propagate down to the model, which still holds the old instance of type Bar. I'd need to create a new Bar object based on the new BarViewModel and assing it to _foo, but how do you do that elegantly? It's pretty trivial in this sample, but if Bar is much more complex with lots of properties, that'll be a lot of typing... not to mention it'd be very prone to errors, if you forget to set one of the properties.
#Goblin
There are some flaws with your code: e.g. what if I get a list of Foo objects from database and I want to wrap each of them in an ObservableCollection?
then your Constructor of FooViewModel should accept the Foo model as parameter and not create it inside the Constructor!
Normally you do this to wrap a model into a viewmodel and put it the same time into a bindable Collection:
IEnumerable<Foo> foos = fooRepository.GetFoos();
foos.Select( m => viewmodelCollection.Add(new ViewModel(m,e.g.Service)));
The models properties are not copied to the ViewModel hell no!!! The ViewModel does delegate its properties to the model properties like:
public class FooViewModel
{
private Foo _foo;
public FooViewModel(Foo foo,IService service)
{
_foo = foo;
}
public string FoosName
{
get{return _foo.Name };
set
{
if(_foo.Name == value)
return;
_foo.Name = value;
this.NotifyPropertyChanged("FoosName");
}
}
}
And like Goblin said all UI-Specific interfaces like:
IDataErrorInfo
INotifyPropertyChanged
IEditableObject
etc...
are implemented the by the ViewModel ONLY.
My above answer only makes sense if you are doing DDD - if you are not - you can solve your problem like this - simply 'flattening' the model:
public class FooViewModel
{
private Foo _foo;
public string Name
{
get { return _foo.Name; }
set { _foo.Name = value; }
}
public string BarProperty
{
get { return _foo.Bar.Property; }
set { _foo.Bar.Property = value; }
}
}
Or you could do like I showed in the prior example - just ignore everything about Aggregates... should still work.
Okay - first things first - using the term Aggregate implies you are adhering to DDD? If you are - you are doing an encapsulation no-no :-). One Aggregate should never be allowed to edit another Aggregate. If what you have is that both are really Aggregate they would become associated (which is perfectly 'legal' in a DDD-sense - but then your propety on the FooViewModel wouldn't be of type BarViewModel, but rather type Bar. That way Bar would (as it should) be responsible for updating itself - and we only maintain the link in FooViewModel.
However, if what you are doing is AggregateRoot with a ValueType child - then here is what you could do given a slightly modified domain model:
public class Foo
{
public string SomeProperty { get; set; }
public Bar Bar { get; set; }
public void Save()
{
//Magically saves to persistent storage...
}
}
public class Bar
{
public Bar(string someOtherProperty)
{
SomeOtherProperty = someOtherProperty;
}
public string SomeOtherProperty { get; private set; }
}
And then for the ViewModels:
public class FooViewModel
{
private Foo _foo;
public FooViewModel()
{
Bar = new BarViewModel();
}
public BarViewModel Bar { get; private set; }
public void SetFoo(Foo foo)
{
_foo = foo;
SomeProperty = foo.SomeProperty;
Bar.SetBar(foo.Bar);
}
public string SomeProperty { get; set; }
public void SaveChanges()
{
_foo.SomeProperty = SomeProperty;
_foo.Bar = Bar.CreateUpdatedBar();
_foo.Save();
}
}
public class BarViewModel
{
public string SomeOtherProperty { get; set; }
public void SetBar(Bar bar)
{
SomeOtherProperty = bar.SomeOtherProperty;
}
public Bar CreateUpdatedBar()
{
return new Bar(SomeOtherProperty);
}
}
This way - the FooViewModel is now capable of controlling the BarViewModel (which does nothing but accept a valuetype - and create a new one when asked). This also solves a common UI-problem ('How do we edit an object that has no setters?' - answer: 'We don't - we create a new one'). A lot of fleshing out is missing (INotifyPropertyChanged, dirty-tracking etc., but those are easy if you get through this leap of thinking :-).
I hope this makes a wee bit of sense :-) Otherwise, I'll be happy to elaborate.

Resources