Serializing parent class fields using ServiceStack Redis/TextSerializer - serialization

I have two classes
public class ClassOne {
public Guid Id { get; set; }
}
public class ClassTwo : ClassOne {
}
When I send an instance of ClassTwo to Redis (using ServiceStack via its TypeSerializer) the superclass properties (e.g. Id) does not Serialize because it's on the parent class.
Is there a way to get this working?

Only abstract classes, interfaces or late-bound objects emit the necessary __type info required for inheritance to work. So if you must use inheritance (which is a bad idea in DTOs) change ClassOne to abstract.

Related

UML class diagram relation with mother class if every child class uses the same thing

I have two questions:
I have a Singleton class with a property Layout that I use in creating child objects of an abstract class (example below). The abstract class has an abstract method where the layout file is given as a variable. Do I connect that Singleton class to the abstract class or each child? The following example is written using pseudo-code:
public class SingletonClass
{
public static Instance;
public var[,] Layout;
}
public abstract class AbstractClass
{
public abstract void DoSomething(var[,] Layout);
}
public class ClassA : AbstractClass
{
public override void DoSomething(var[,] Layout) { some code }
}
public class ClassB : AbstractClass
{
public override void DoSomething(var[,] Layout) { some other code }
}
Is it even needed, or "cleaner", to give the Layout as variable in the method, or is it ok to just call Layout from the singleton class?
The following UML is an equivalent of your code
under the following assumptions: Instance and Layout are assumed to be attributes of analogous classes.
SingletonClass has two owned attributes (denoted by the big dots): public layout of type Layout and instance of type AbstractClass (it's abstract, hence the italics). The latter will later hold either an instance of the concrete ClassA or ClassB.
Whether or not the design is ok depends. Basically there's nothing wrong with this.

Simple Injector Property Injection

How do you perform property injection with Simple Injector.
The with Ninject you do is as per bellow:
[Inject]
public IUnitOfWork UnitOfWork { get; set; }
How can I do the equivalent to this with Simple Injector. I tried finding a solution online but had no luck.
Why do I want to use Property Injection?
I want to use property injection to set up unit of work in my base controller so that it will create a new unit of work OnActionExecuting and commit the changes OnResultExecuted. It also means I don't have to pass in the UoW with each new controller I create through the constructor.
Another option is to use the RegisterInitializer method:
container.RegisterInitializer<BaseControllerType>(controller =>
{
controller.UnitOfWork = container.GetInstance<IUnitOfWork>();
}
It keeps all configuration in your composition root and does not pollute your code base with all kinds of attributes.
Update: (as promised)
While this is a direct answer to your question I have to provide you with a better option, because the usage of a base class for this is a IMO not the correct design, for multiple reasons.
Abstract classes can become real PITA classes as they tend to grow towards a god class which has all kinds of cross cutting concerns
An abstract class, especially when used with property injection, hides the needed dependencies.
With focus on point 2. When you want to unit test a controller which inherits from the base controller, you have no way of knowing that this controller is dependent on IUnitOfWork. This you could solve by using constructor injection instead of property injection:
protected abstract class BaseController : Controller
{
protected readonly IUnitOfWork uoW;
protected BaseController (IUnitOfWork uoW)
{
this.uoW = uoW;
}
}
public class SomeController : BaseController
{
public SomeController(IUnitOfWork uoW) : base(uoW) { }
}
While this solves point 2, point 1 is still lurking. The main reason you're wanting this, as you say, is because you do not want to commit your changes in every Action method. Changes must just be saved by the context when the request is done. And thinking about design in this way is a good thing, because Saving changes is, or can be seen as a cross cutting concern and the way you're implementing this is more or less known as AOP.
If it's comes to AOP, especially if you're working with atomic actions in the action methods of your controllers, there is a far better, more SOLID and more flexible design possible which deals with this very nicely.
I'm referring to the Command/Handler pattern which is described in great detail here (also read this for the query part of your application).
With this patterns you don't inject a generic IUnitOfWork abstraction, but inject the specific needed ICommandHandler<TCommand> abstractions.
The action methods would fire the responsible commandhandler for this specific action. All commandhandlers can simple be decorated by a single open-generic SaveChangesCommandHandlerDecorator, 'ValidationDecorator', 'CheckPermissionsDecorator', etc...
A quick example:
public class MoveCustomerCommand
{
public int CustomerId;
public Address NewAddress;
}
public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Handle(MoveCustomerCommand command)
{
// retrieve customer from database
// change address
}
}
public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decoratee;
private readonly DbContext db;
public SaveChangesCommandHandlerDecorator(
ICommandHandler<TCommand> decoratee, DbContext db)
{
this.decoratee = decoratee;
this.db = db;
}
public void Handle(TCommand command)
{
this.decoratee.Handle(command);
this.db.SaveChanges();
}
}
// Register as
container.Register(typeof(ICommandHandler<>), new []{Assembly.GetExecutingAssembly() });
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(SaveChangesCommandHandlerDecorator<>));
// And use in controller as
public ActionResult MoveCustomer(int customerId, Address address)
{
var command = new MoveCustomerCommand
{ CustomerId = customerId, Address = address };
this.commandHandler.Handle(command);
return View(new ResultModel());
}
This keeps your controllers clean and let it do what it must do, namely be the layer between the business logic (the commandhandler implementation in this case) and the view.
Need to create the following:
First create the attribute class
[System.AttributeUsage(System.AttributeTargets.Property]
public class Inject : Attribute
{
}
Then create a custom property behavior
class PropertySelectionBehavior<TAttribute> : IPropertySelectionBehavior
where TAttribute : Attribute
{
public bool SelectProperty(Type type, PropertyInfo prop)
{
return prop.GetCustomAttributes(typeof(TAttribute)).Any();
}
}
Finally tell the container to use custom behavior
container.Options.PropertySelectionBehavior = new PropertySelectionBehavior<Inject>();
All that is left to do is decorate the property with the attribute
[Inject]
public IUnitOfWork UnitOfWork { get; set; }

Protobuf type inheritance with WCF

We have trouble with the protobuf-net type inheritance.
We have a base class like this:
[DataContract, ProtoContract]
public abstract class BaseClass : IBase
{
protected IBase()
{
RequestUID = Guid.NewGuid();
}
[DataMember(Order = 8000), ProtoMember(8000)]
public Guid ID { get; set; }
[DataMember(Order = 8001), ProtoMember(8001)]
public string User { get; set; }
}
And classes which inherits from BaseClass.
[DataContract, ProtoContract]
public class ConcreteClass : BaseClass
{
[DataMember(Order = 4), ProtoMember(4)]
public int? WorkItemId { get; set; }
}
(In future we are going to use only ProtoMember and ProtoContract.)
When the client and server starts we do following in both environments:
RuntimeTypeModel.Default[typeof(BaseClass)].AddSubType(50, typeof(ConcreteClass));
Now when we pass an instance of ConcreteClass to a WCF service operation we get exceptions:
BaseClass does not provide a public constructor. (Wrong type chosen for deserialization)
Or if we provide a public constructor for BaseClass it tries to cast the BaseClass object to ConcreteClass on the server. (Again wrong type)
And under some special circumstances (we don't know exactly when this happens) Protobuf tries to deserialize from OtherConcreteClass to ConcreteClass.
What are we doing wrong? The WCF behavior is register correctly. We had no problems with simple classes (no inheritance).
Is there and documentation how two configure the inheritance properly for WCF scenarios?
Thanks

Abstract classes in client lib, and concrete class in shared lib

How do I solve the serialization problem with abstract class defined in a shared client library, and concrete implementation in a server side library.
Interface in shared client library :
[ServiceContract(SessionMode=SessionMode.Required)]
[ServiceKnownType(typeof(SharedClient.Shape))]
public interface IMyInterface
{
void UploadDrawing(Drawing dr);
}
Concreate Drawing class in shared client library :
[DataContract]
[KnownType(typeof(SharedClient.Shape))]
public class Drawing
{
public Shape s;
}
Abstract class in shared client library :
[DataContract]
abstract public class Shape
{
[DataMember]
public abstract string Name;
}
Concrete class implementation in separate library which references the client library :
[DataContract]
public class Cirle : ClientLibrary.Shape
{
public override string Name { get; set; }
}
I keep getting the exception message:
There was an error while trying to serialize parameter
http://tempuri.org/:Drawing. The InnerException message was 'Type
'Circle' with data contract name
'Circle:http://schemas.datacontract.org/2004/07/' is not expected.
Consider using a DataContractResolver or add any types not known
statically to the list of known types - for example, by using the
KnownTypeAttribute attribute or by adding them to the list of known
types passed to DataContractSerializer.'. Please see InnerException
for more details.
KnownType works in other way. If you want to use KnownType attribute you must use it on the base class to define its child:
[DataContract]
[KnownType(typeof(Circle))]
abstract public class Shape
{
[DataMember]
public abstract string Name;
}
That will not be too much helpful in your case. Try to put ServiceKnownType with concrete class on your interface:
[ServiceContract(SessionMode=SessionMode.Required)]
[ServiceKnownType(typeof(Circle))]
public interface IMyInterface
{
void UploadDrawing(Drawing dr);
}
You doesn't have to define Shape as ServiceKnownType - it is already known because it is used in Drawing but WCF yet doesn't know the Circle type.

Adapter Pattern: Class Adapter vs Object Adapter

I have a few questions about the Adapter pattern. I understand that the class adapter inherits from the adaptee while the object adapter has the adaptee as an object rather than inheriting from it.
When would you use a class adapter over an object adapter and vice versa? Also, what are the trade-offs of using the class adapter and the trade-offs of the object adapter?
I can see one advantage for the object adapter, depending on your programming language: if the latter does not support multiple inheritance (such as Java, for instance), and you want to adapt several adaptees in one shot, you'll be obliged to use an object adapter.
Another point for object adapter is that you can have the wrapped adaptee live his life as wanted (instantiation notably, as long as you instantiate your adapter AFTER your adaptee), without having to specify all parameters (the part for your adapter AND the part for your adaptee because of the inheritance) when you instantiate your adapter. This approach appears more flexible to me.
Prefer to use composition, over inheritance
First say we have a user;
public interface IUser
{
public String Name { get; }
public String Surname { get; }
}
public class User : IUser
{
public User(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
}
Now, imagine that for any reason, youre required to have an adapter for the user class, we have then two aproaches, by inheritance, or by composite;
//Inheritance
public class UserAdapter1 : User
{
public String CompleteName { get { return base.Name + " " + base.Surname } }
}
//Composition
public class UserAdapter2
{
private IUser user;
public UserAdapter2(IUser user)
{
this.user = user;
}
public String CompleteName { get { return this.user.Name + " " + this.user.Surname; } }
}
You are totally ok, but just if the system don't grow... Imagine youre required to implement a SuperUser class, in order to deal with a new requirement;
public class SuperUser : IUser
{
public SuperUser(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
public Int32 SupernessLevel { get { return this.Name.Length * 100; } }
}
By using inheritance you would not be able to re-use your adapter class, messing up your code (as your would have to implement another adapter, inheriting from SuperUser that would do ECXATLY the same thing of the other class!!!)... Interface usage is all about uncopling, thats the main reason that I'm 99% likely to use them, of course, if the choice is up to me.
Class Adapter is plain old Inheritance, available in every object-oriented language, while Object Adapter is a classic form of an Adapter Design Pattern.
The biggest benefit of Object Adapter compared to Class Adapter ( and thus Inheritance ) is loose coupling of client and adaptee.
A class adapter uses multiple inheritance to adapt one interface to another: (depending on your programming language: Java & C# does not support multiple inheritance)
An object adapter depends on object composition:
Images Source: Design Pattern (Elements of Reusable Object-Oriented Software) book
class adapters adapts Adaptee to Target by committing to a specific Adapter class will not work when we want to adapt a class and its subclasses.
object adapters lets a single Adapter work with many Adaptees (the Adaptee and all adaptees hierarchy)
In addition to what renatoargh has mentioned in his answer I would like to add an advantage of class adapter.
In class adapter you can easily override the behavior of the adaptee if you need to because you are just subclassing it. And it is harder in Object adapter.
However advantages of object adapter usually outweighs this tiny advantage of class adapter.