2009-06-13

The blog is moving

The blog is moving to http://blogs.microsoft.co.il/blogs/bnaya/
new post will publish to its new location

2009-05-30

Generics instantiation using MEF

This post will discuss techniques of instantiating generics types at runtime.

You can download the code sample here.

Generics has lots of benefits (which is not the subject of this post).
In order to gain most of the generics benefits you should instantiate the generics at design time whenever it possible.
But using generics long enough you come across needs of instantiate the generics at runtime (mostly because there is scenarios when you don’t know the exact type of T at design time.

How can you instantiate generics at runtime?

you can instantiate it at runtime using reflection, as the following code demonstrate (but it is very expensive instantiation technique):

public class MyGenericType<T> {
public MyGenericType ( T instance ) {
this.Instance = instance;
}
public T Instance { get; set; }
public static object Create ( object body ) {
Type gnType = typeof (MyGenericType<>);
Type[] typeArgs = { body.GetType () };
Type genericType = gnType.MakeGenericType (typeArgs);
object o = Activator.CreateInstance (
genericType, body);
return o ;
}
}

The above code has simple generics class with static Create method which use reflection in order to instantiate the class

How can we improve it?

We can use the factory or DI (dependency injection).
Factory code will look something like the following code:

public static object Create ( object body ) {
if (body is string)
return new MyGenericType<string> (body as string);
if (body is DataTable)
return new MyGenericType<DataTable> (body as DataTable);
throw new NotImplementedException()
}

The problem is this, writing hardcoded factory case extensibility problem which require recompilation whenever new type should added and cross reference conflict in-case that the new type locate in dll that already reference our assembly.
So obviously you can use DI to solve the problem (which is good acceptable solution)

Taking it one step further

I choose different approach which is using the newly MEF technology for addressing this problem by Exporting the factories as MEF export parts.
The following code assume that you are familiar with the MEF fundamentals (if not you should read this post):

[Export (typeof(MyFactory))]
[PartExportsInherited]
public abstract class MyFactory {
public abstract object Create(object bodyOfMsgBase);
public abstract bool CanHandle<T> ();
}
public class MyFactoryOfDataTable: MyFactory  {
public override object Create ( object bodyOfMsgBase ) {
return new MyGenericType<DataTable>(bodyOfMsgBase as DataTable);
}

public override bool CanHandle<T> () {
return typeof (DataTable) == typeof (T);
}
}

You can later consume the factory as demonstrate in the following code:

var container = new CompositionContainer (
new AssemblyCatalog(Assembly.GetExecutingAssembly()));

ICollection<MyFactory> aPlugIns=container.GetExportedObjects<MyFactory>();
var plugIn = (from item in aPlugIns
where item.CanHandle<string>()
select item).SingleOrDefault();
var instance = plugIn.Create (“Hellow world”);

Summary
We so that creating generics at runtime is possible but it can be costly using reflection.

You can download the code sample here.

2009-05-23

Serialize generics list part 2

This post is the 3rd of series on serialization in WCF.

The post is taking the previous post concept one step ahead by wrapping the List<T> as serializable type

Downloads available here

Jump into the code

see the theory in the previous post

[XmlRoot (Namespace = "htp://...")]
public class GenListCustom<T>:List<T>,IXmlSerializable {
private static readonly string ITEM_ELEMENT_NAME=
typeof (T).Name;

XmlSchema IXmlSerializable.GetSchema() {
throw new NotImplementedException();
}

void IXmlSerializable.ReadXml(XmlReader reader){
var ser=new DataContractSerializer(typeof(T));

while(reader.Name == ITEM_ELEMENT_NAME){
var item = (T)ser.ReadObject(reader);
this.Add (item);
}
}

void IXmlSerializable.WriteXml ( XmlWriter writer ) {
var ser = new DataContractSerializer (typeof (T));

writer.WriteStartElement ("Items", "htp://...");
foreach (var item in this) {
ser.WriteObject (writer, item);
}
writer.WriteEndElement ();
}
}

Actually this class is identical to the class on our previous post with one exception, it use T instead of CompositeType.

WCF and generics collections

Unfortunately WCF does not always handling well generics collections of complex types (despite the fact that it can be serialized using Data Contract serialization).

In those case you may use the the technique of having the collection as composite type and using property decorated with DataMember attribute in order to serialize the collection (as discuss in Serialize generics list part 1)

Summary

I used post reuse pattern :-) leaving the theory in the previous post, but after reading the previous post I believe it’s kind of straight forward.

Downloads available here

Previous Posts

del.icio.us Tags:

Serialize generics list part 1

This post is the second of series on serialization in WCF (previous post).

The topic of this post is dealing with writing data contract that inherit from type that does not decorated with the DataContract attribute (in our case List<T>).

Downloads available here

Why shouldn’t it work?

consider the following type declaration:

[DataContract]
public class ListCustom: List<CompositeType> {…}

The above code will not pass the data contract serialization because List<T> does not decorated with DataContract attribute

What can we do about it?

We can certainly refactor the class to composite pattern which will look like the following:

[DataContract]
public class ListCustom{
private List<CompositeType> m_aItems =
new List<CompositeType> ();

[DataMember]
private CompositeType[] Values {
get {
if (m_aItems == null)
m_aItems = new List<CompositeType> ();
return m_aItems.ToArray ();
}
set {
if (m_aItems == null)
m_aItems = new List<CompositeType> ();
m_aItems.AddRange (value);
}
}
}

This is simple work around but we have to refactor the code and lose the inheritance benefits.

Can we serialize none decorated types?

The answer is yes, and this is how we do it.

It is not the simplest task if you don’t familiar with xml serialization, but I will try to explain it.

Data contract serialization do know to serialize types that implement xml serialization, so it give us the option to instruct the serializer how to serialize the base type which is not decorated with DataContract attribute.

Please read the code and I will explain it latter:

[XmlRoot (Namespace = "http://...")]
public class ListCustom: List<CompositeType>, IXmlSerializable {
XmlSchema IXmlSerializable.GetSchema () {
throw new NotImplementedException ();
}
void IXmlSerializable.ReadXml ( XmlReader reader ) {
var ser = new DataContractSerializer (typeof (CompositeType));
...
while (reader.Name == "CompositeType") {
var item = ser.ReadObject (reader) as CompositeType;
this.Add (item);
}
}

void IXmlSerializable.WriteXml ( XmlWriter writer ) {
var ser = new DataContractSerializer (typeof (CompositeType));

writer.WriteStartElement ("Items", "http://...");
foreach (var item in this) {
ser.WriteObject (writer, item);
}
writer.WriteEndElement ();
}
}

What’s in the code?

  • Instead of decorating the class with DataContract attribute we decorating it with XmlRoot attribute.
  • We implementing IXmlSerializable so we can customize the serialization processing
  • You can ignore GetSchema
  • The serialization process is using ReadXml for deserialization and WriteXml for serialization.
    you can just copy and paste the code pattern all it’s doing is using XmlReader and XmlWriter combine with DataContractSerializer in order to inject or fetch the list item to or from the xml stream.

Summary

We saw that we can keep our functionality in term of inheritance of none serializable type and still serialize it with data contract serialization.

Downloads available here

Part 2 will take it one step further and use

class ListCustom<T>: List<T>

Following Posts

Previous Posts

Flexible Serializer Provider

This post is the first of a series.
Each post of this series will take the concept one step ahead.

Code sample download available here

What in this post?

this post will discuss the technique of writing reusable type that can be serialize both by Data Contract serialization and Xml serialization and be later deserialize by the other.

Why should we care about it?

  • This technique is the base line for following posts in this series which talk about serializing inherits generics list.
  • Some .NET technologies (like the compact framework) does not support Data Contract serialization, so it is needed in order to achieve reusable business entity.

How to write flexible serializable entity?

[DataContract(Namespace="http://…", Name="CompositeType")]
[XmlRoot(Namespace="http://…", ElementName="CompositeType")]
public class CompositeType {
[DataMember (Order = 1)]
[XmlElement (IsNullable = true, Order = 1)]
public string StringValue { get; set; }


[DataMember (Order = 2)]
[XmlElement (DataType = "base64Binary", Order = 2)]
public byte[] BytesValue{ get; set; }
}

Lets talk about it :)

  • The class should be decorated with both DataContract and XmlRoot attributes and it is important to set the namespace (otherwise you won’t be able to serialize with one technique and deserialize with the other)
  • Properties should be decorated with both DataMember and XmlElement attribute given correlated order

Summary

Simple scenarios can be adjust with little addition of xml serialization attribute to your data contract entities (remember to assign the namespace)

The sample code is available here

the following post will discuss how to serialize collections

Following Posts

Previous Posts

del.icio.us Tags:

2009-05-16

MEF introduction

The MEF team declare the MEF as

“The Managed Extensibility Framework (MEF) is a new library in .NET that enables greater reuse of applications and components. Using MEF, .NET applications can make the shift from being statically compiled to dynamically composed.”

you can download the MEF bits in here

SO what is the MEF and why do you want it?

Lets start with what !(MAF)
MEF is not another DI (dependency injection), you should think of MEF as plug-ins infrastructure rather then being DI.

Actually you can consider MEF as very flexible plug-ins discovery mechanism.

How does it work?

The essence of MEF paradigm is built upon the idea of needs and part that can be founds (in order of satisfying the needs).

You can think of it as having Guilds that publish its policy (shoemaker, tailor, ext…), and Peoples that declaring their professions, the MEF infrastructure apply the role of matching the Peoples to their suitable Guilds.

image

The above diagram present institutions (University and software company) that has specific need (in terms of human segments),
and peoples that apply to one or more of the segments.
the MEF framework role is to satisfy the institution needs by discovering the people which apply the right segments.

The MEF terminology: institutions will be declare as Import and the peoples will be declare as Export Parts

Where does MEF looking for the for its Export Parts?

MEF is looking for export parts in Catalogs there is built-in catalogs (like Directory, Assembly, Types) and you definitely can build your own.

Code samples:

You can download the sample here (VS 2008 SP1)

the following are very light snippets of how it will look

// property that declare its needs for university related peoples
[Import (typeof (IUniversityRelated))]
public IEnumerable<PeopleBase> Peoples { get; private set; }
// class that decorate export part for university
[Export (typeof (IUniversityRelated))]
public class Student: PeopleBase, IUniversityRelated
// asking the MEF to compose the right export parts
// in order of satisfying the imports

private static CompositionContainer s_container =
new CompositionContainer (new AggregateCatalog ());
static void Main ( string[] args ) {

// here the MEF magic matching game occur
s_container.Compose (new CompositionBatch ());

Summary

MEF is very friendly plug-ins framework which help you to get greater extensibility with less efforts and more consistency.
It is very simple decoration module which having supper light dependencies.I hope you find this post useful, I'm having intensions to write future post which will cover the MEF in more details including some advance technique.

About

Bnaya Eshet C.T.O and co-founder of Wise Mobility

2009-02-14

WCF – serialize the unserializable

Introduction

WCF serialization rely on the Data Contract and Data Member decoration

This post discuss one simple trick that available in cases that you having your own data contract that holding data members that does not been decorated for the WCF serialization

This trick will work as long as you reuse the same assembly of the data contract both on the client and service sides

There some other techniques for advance serialization which will beyond the scope of this post

you can find the post code in here

Our Test Case

In our test case we will have data contract that has data member of type DataTable

Note: you do not need this trick for typed data table, it does serialized well

Having the following service:

[ServiceContract]
public interface IMyService
{
[OperationContract]
CustomEntity GetData ();
}

[DataContract]
public class CustomEntity
{
[DataMember]
public DataTable Table { get; set; }
}

Notice that we try to have data contract that having data member which does not design to be serialized using WCF serialization (because DataTable does not decorate with data contract attribute)

The trick is very simple and it can be assign for any similar cases
it simply using the data contract serialization processing with little twist

We will serialize the DataTable indirectly using private data member which won’t expose by our Custom Entity API so the consumer of our Custom Entity won’t e aware of it, still the WCF will use it during the serialization process

Steps needed to achieve our goal

  1. Remove the data member decoration from the Table property
  2. Add custom private data member that will handle the serialization process
    1. We need one member to serialize the DataTable schema
    2. And other member to serialize the DataTable data (the data deserialization must occur after the schema deserialization completed)

Our data contract should look like the following one

[DataContract]
public class CustomEntity
{
[DataMember (Order=0)]
private byte[] TableSchemaSerialization
{
get
{
// the folowing operation will occur during the WCF serializing
var srm = new MemoryStream ();
this.Table.WriteXmlSchema (srm);
return srm.ToArray ();
}
set
{
// the folowing operation will occur during the WCF deserializing
this.Table = new DataTable ();
var srm = new MemoryStream (value);
this.Table.ReadXmlSchema (srm);
}
}

[DataMember (Order=1)]
private byte[] TableDataSerialization
{
get
{
// the folowing operation will occur during the WCF serializing
var srm = new MemoryStream ();
this.Table.WriteXml (srm);
return srm.ToArray ();
}
set
{
// the folowing operation will occur during the WCF deserializing
var srm = new MemoryStream (value);
this.Table.ReadXml (srm);
}
}

//[DataMember]
public DataTable Table { get; set; }
}

Conclusion

As long as we reusing the data contract at both service and client sides

We can build our data contract to intercept the serialization process without changing the data contract API

2009-02-02

WCF Serialization

Some words before we start
I intend to start blog series of .NET technical blogs
I encourage you to add comments whether the post content meeting your expectation
I will try to keep the post short and technical.

So with that said lets dive into this post topic.
As you may know while passing complex type as parameter for WCF will be serialized using DataContractSerializer.

One thing you should notice about this serialization process is that unlike XmlSerializer it will not call the constructor or field initialization.

So if you declare the following contract
[DataContract]
public class MyCompositeType
{
private Guid m_id1 = Guid.NewGuid (); // will not happens during serialization
public MyCompositeType () // will not happens during serialization
{
Id2 = Guid.NewGuid ();
}
public Guid Id1
{
get { return m_id1; }
}
public Guid Id2 { get; private set; }

[DataMember]
public string StringValue { get; set; }
}

So do not expect that the ids (which is not data member) be initialized on the other side of the serialization process

The code sample for this post is available here

If we having the following service implementation:
public MyCompositeType GetDataUsingDataContract ( MyCompositeType composite )
{
composite.StringValue += " : " + composite.Id1.ToString () +
" : " + composite.Id2.ToString ();
return composite;
}

And we call it from the client like this:
static void Main ( string[] args )
{
MyProxy.SampleServiceClient svc = new MyProxy.SampleServiceClient ();
var composite = new MyCompositeType { StringValue = "Test" };

Console.WriteLine ("Id1 = {0} \nId2 = {1}",
composite.Id1.ToString (), composite.Id2.ToString ());

var response = svc.GetDataUsingDataContract (composite);

Console.WriteLine (response.StringValue);
Console.WriteLine ("Id1 = {0} \nId2 = {1}",
response.Id1.ToString (), response.Id2.ToString ());

Console.ReadLine ();
}

The ids will be initialized to none empty Guid only on the client side
Both at the server and the response ids will be empry