What's the practical way of serializing an instance of subclass by using DataContractSerializer? - wcf

What's the practical way of serializing an instance of subclass by using DataContractSerializer?
For example, here are the data types:
[DataContract]
public class Car
{
public Car()
{
Wheels = new Collection<Wheel>();
}
[DataMember]
public Collection<Wheel> Wheels { get; set; }
}
[DataContract]
public abstract class Wheel
{
[DataMember]
public string Name { get; set; }
}
[DataContract]
public class MichelinWheel : Wheel
{
[DataMember]
public string Wheel1Test { get; set; }
}
[DataContract]
public class BridgeStoneWheel : Wheel
{
[DataMember]
public string Wheel2Test { get; set; }
}
Then here is the code that creates a car with two differen wheels:
Car car = new Car();
MichelinWheel w1 = new MichelinWheel { Name = "o1", Wheel1Test = "o1 test" };
BridgeStoneWheel w2 = new BridgeStoneWheel { Name = "o2", Wheel2Test = "o2 test" };
car.Wheels.Add(w1);
car.Wheels.Add(w2);
Now if I try to serialize the car by using DataContractSerializer, I will get an exception that says MichelinWheel is not expected. And I have to modify the Wheel class like this to make it work:
[DataContract]
[KnownType(typeof(MichelinWheel))]
[KnownType(typeof(BridgeStoneWheel))]
public abstract class Wheel
{
[DataMember]
public string Name { get; set; }
}
But this approach is not practical, because I am not able to list all kinds of wheels before they are created. And changing the Wheel class every time after a new brand of wheel is created is also not practical, because they might by created in third-party code.
So, what is the practical approach of serializing an instance of a subclass when using DataContractSerializer?
Thanks

Check this article using DataContractResolver from WCF 4. You can also use KnownTypeAttribute with passing name of a method that will use reflection to get all types. Anyway service requires that all types are known before it starts.

There are several ways to make known types available to the service.
The simplest you have outlined above, but obviously this requires you to recompile when new types are added, and depending on your configuration can make it awkward to avoid circular dependencies.
You can also configure the KnownTypes:
through the service configuration file (service restart only required),
add them as service known types provided through a static method on the service interface which you could get through reflection as Ladislav Mrnka has indicated (you could probably reflect over all loaded assemblies and return all types that have the DataContact attribute on them as known types, but I couldn't find an example of that.)
implement your own way of getting them (perhaps through some bespoke configuration elements in the config file or just through a text file)

Related

loosing dataAnottation when upload model from database

I have a big database existing database to comunicate with, and I'm using EF 5.0 database first, the problem I'm having is that if I create any data decoration like [stringlength(50)] on the class and then the databases is uploaded, when I "upload from database" all data annotations are gone. How can I do to keep them?
It's very simple: You Can't! Because those codes are auto-generated and will be over written on each model update or change.
However you can achieve what you need through extending models. Suppose that EF generated the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:
First, add two classes some where (wherever you want, but it's better to be in Models) like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
then add what properties and attributes you want to the second class - NewsAttribs here. :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Notes:
1) The namespace of the generated entity class and your classes must be the same - here YourSolution.
2) your first class must be partial and its name must be the same as EF generated class.
Go through this and your attribs never been lost again ...
The accepted answer may work for standard data operations, but I am trying to validate the model prior to the call to DbSet.Add using TryValidateObject. With the accepted answer, it is still not picking up on the data annotations.
What did work for me I found in a .NET Runtime GitHub thread, as proposed by what I'm inferring is one of the .NET developers.
Basically, this is a bug, and you have to force the model to recognize the metadata decorations using TypeDescriptor.AddProviderTransparent . . .
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(News), typeof(NewsAttrib)), typeof(News));
Once I make this call, TryValidateObject recognizes the data annotations and returns false when any of the constraints are not met.
Here's the link. I little more than half-way down, there's a working code sample in a .zip file.
https://github.com/dotnet/runtime/issues/46678

RavenDB SaveChanges() not saving properties on derived class ([DataMember] used in other class)

I've recently upgraded to build 2230, and things are working just fine. However, I just updated the RavenDB .NET client assemblies and now I'm having this issue.
This code has been in place for a year or so. This is how I'm saving:
public void Save(EntityBase objectToSave)
{
using (IDocumentSession session = GetOptimisticSession())
{
session.Store(objectToSave, objectToSave.Etag);
session.SaveChanges();
}
}
And this is the object I'm saving.
public class InstallationEnvironment : EntityBase
{
public string Name { get; set; }
public int LogicalOrder { get; set; }
}
Now the base class:
public class EntityBase : NotifyPropertyChangedBase
{
public string Id { get; set; } // Required field for all objects with RavenDB.
}
The problem is that the base class property (Id) is getting persisted in RavenDB, but the derived properties (Name, LogicalOrder) are not.
Why would only the base class properties be saved in RavenDB?
Got it. Through trial and error, I noticed that one derived property was being saved (on a different class than the one shown in my question), and that property was decorated with the [DataMember] attribute. I just recently added it because I'm creating a WCF service for my app, and I started by using that attribute on one property for testing.
As Ayende states here, you have to use [DataMember] on all properties, or on none of them. If [DataMember] exists on a property, all others will be ignored.
Note: This was a problem for me even though [DataMember] was specified on a property in a different class. It seems like if I use [DataMember] anywhere, I have to use it for everything.

access wcf interface method from client

This is one of the classes in Interface file.
[DataContract]
public class ClassX
{
public ClassX()
{
ClassXParameters = new List<ClassXParameter>();
}
public void Add(string name, string value)
{
ClassXParameters.Add(new ClassXParameter() { Name = name, Value = value });
}
[DataMember]
public List<ClassXParameter> ClassXParameters { get; set; }
}
[DataContract]
public class ClassXParameter
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Value { get; set; }
}
on the client I'm trying to do something like this
ClassX classx = new ClassX();
classx.Add("testname", "testvalue");
But this .Add method is not even visible.
currently I'm doing
ClassX classx = new ClassX();
List<ClassXParameter> params = new List<ClassXParameter()>;
params.add(new ClassXParameter() {Name="testname", Value="testvalue"});
classx.ClassXParameters = params;
Is there anyway I can do what I'm trying to do?
Note: I am not sure why some of the text above are in bold.
If you autogenerate the client code from scratch, it will generate a new class, which contains those members and properties that are marked with DataContract.
If you have methods that you want available on the client, you can accomplish this by putting the DataContract types in an own assembly, which you reference from both the server and the client. When you generate the service reference you have to choose the option to reuse existing classes instead of generating new ones.
Often it is suitable to put data validation rules in the data contract classes property setters. Reusing the data contract assembly in the client will cause the data validation to occur directly on the client, without the need for a roundtrip. It also causes the error in a place where it is much easier to spot than if it is reported as deserialization error.
Data Contracts are for data only. Any methods will not be visible on the client.
The bold was because of the "-----".

Class Naming Conventions with Layered Architecture and Entity Framework

I'm designing a layered architecture (Service/Business Logic Layer, Data Access Layer) and am struggling with the intersection of a few problems.
Entity Framework 4.1 does not support interfaces directly
My Interfaces contain collections of other interfaces with read/write properties
This means using an implementing class won't work either, since it would still refers to another interface type
Example (please excuse the poorly written code, this is ad-hoc from my brain):
Data Access Layer
public interface IEmployer
{
string Name { get; set; }
ICollection<IEmployee> Employees { get; set; }
}
public interface IEmployee
{
string Name { get; set; }
}
public class Employer : IEmployer
{
public string Name { get; set; }
public ICollection<IEmployee> Employees { get; set; }
}
public class Employee : IEmployee
{
public string Name { get; set; }
}
public class DataManager
{
public IEmployer GetEmployer(string name) { ... }
public IEmployee CreateEmployeeObject(string name) { ... }
public void Save(IEmployer employer) { ... }
public void Save(IEmployee employee) { ... }
}
Service Layer
[DataContract]
public class Employee
{
[DataMember]
public string Name { get; set; }
}
public class HireService
{
public void HireNewEmployee(Employee newEmployee, string employerName)
{
DataManager dm = new DataManager();
IEmployer employer = dm.GetEmployer(employerName);
IEmployee employee = dm.CreateEmployeeObject(newEmployee.Name);
dm.Save(employee);
employer.Employees.Add(employee);
dm.Save(employer);
}
}
Without EF, the above works fine. The IEmployee type is used in the service layer, and does not conflict with the Employee data contract type. However, EF cannot use an interface, so I would be required to use class instead of an interface.
I see a few options:
Change IEmployer/IEmployee to classes, leaving the same names
Change IEmployer/IEmployee to classes, rename to EmployerDAL/EmployeeDAL
Change IEmployer/IEmployee to classes, rename to Employer/Employee, sprinkle using EmployerDL = DataLayer.Employer at the beginning of any service classes using it
What naming convention should I follow for class names which are defined in both the business and data layer?
Similar question to this: What's the naming convention for classes in the DataAccess Project? except that EF causes a problem with interfaces.
Actually the class defined in your DAL should be the one used in your business layer - those are your real domain objects. Classes exposed from your business layer are just data transfer objects so if you want to build any convention you should imho rename your data contracts.
Anyway the naming convention is something really subjective. Choose the way which best fits your needs and be consistent in that naming.

How can I pass a List<Interface> over WCF?

I have a WCF service where I am trying to return a List (where IWatchable is a custom interface I have built) in one of my operation contracts. When I test the service on the client the method returns an object[] instead of List<IWatchable>. Is it possible to return a List of IWatchable, since IWatchable is an interface with WCF?
Method:
public List<IWatchable> GetWorkload( Guid nodeId, int maximum )
IWatchable:
public interface IWatchable
{
string ActionName { get; set; }
Guid ActionReference { get; set; }
}
Hopefully a bit more info will be helpful...
I have a derived interface:
public interface IAMRAWatchable: IWatchable
And three concrete implementations from IAMRAWatchable:
public class InstrumentationWatch: IAMRAWatchable
public class OutputWatch: IAMRAWatchable
etc...
In my WCF method that returns List<IWatchable> I want to send an InstrumentationWatch and an OutputWatch to the client... Is this possible or am I going about this the wrong way?
Resolved
Thanks to John I found my solution. KnownType wasn't working since I was using List<IWatchable> - So I wrapped my list into a new class and added the attributes to it. I'll need to re-factor my code but for others who are interested here is the class:
[DataContract]
[KnownType( typeof( InstrumentationWatch ) )]
[KnownType( typeof( OutputWatch ) )]
public class WorkInfo
{
[DataMember]
public List<IWatchable> WorkQueue { get; set; }
}
and my WCF method:
public WorkInfo GetWorkload( Guid nodeId, int maximum )
An interface can never be serialized. It is only a description of behavior.
You can serialize objects which implement the interface, but you must tell WCF what their types are. See Data Contract Known Types.