My Instagram feed

My Instagram feed


Wrapping Web Service Proxy objects to Common Cargos using Serialization

In my previous post I described a way to wrap web service proxy objects to common cargo objects using reflection. This method works only for objects with only value type properties.

Update: The performance of this code may not be the best.

internal U wrapToCargoBySerialization<T, U>(T source, U target)
    UTF8Encoding encoding = new UTF8Encoding(true);

    XmlRootAttribute rootAttribute = new XmlRootAttribute();
    XmlSerializer xmlSerializerSource = new XmlSerializer(typeof(T), rootAttribute);
    MemoryStream stream = new MemoryStream();
    xmlSerializerSource.Serialize(stream, source);
    string xml = encoding.GetString(stream.ToArray());
    xml = xml.Replace("<?xml version=\"1.0\"?>", string.Empty);

    MemoryStream ms = new MemoryStream(encoding.GetBytes(xml));

    XmlSerializer xmlSerializerTarget = new XmlSerializer(typeof(U),rootAttribute);

    return (U)xmlSerializerTarget.Deserialize(ms);

Usage example:
CommonObjects.Customer cust;
cust = wrapToCargoBySerialization(wsCustomer, cust);

Note that I had to remove the <?xml … /> declaration before deserializing.

A prerequisite for using this method is that the objects have the same structure. To achieve this I simply copy the web service objects from the web reference to a common cargo project. The common objects are used for passing information between layers in the application.