views:

54

answers:

3

I have the following serialization method shown below. The problem is that I am attempting to pass a class to it that contains a property of type Binary. The serialization is failing because of this property type. Is there any way I can serialize a class with a property of type Binary?

    private string Serialize<TEntity>(TEntity instance)
    {
        string retStr = "";
        XmlSerializer xs = new XmlSerializer(typeof(TEntity));
        System.IO.StringWriter writer = new System.IO.StringWriter();
        xs.Serialize(writer, instance);
        retStr = writer.ToString();
        writer.Close();

        return retStr;
    }

Here is the portion of the class that represents the Binary property.

    /// <summary>
    /// Row version number
    /// </summary>
    [DataMember(Order = 5)]
    public System.Data.Linq.Binary VersionNumber { get; set; }
A: 

While not a total solution to your problem, please try the following code:

private string Serialize<TEntity>(TEntity instance)
{
    try
    {
        XmlSerializer xs = new XmlSerializer(typeof(TEntity));
        using (System.IO.StringWriter writer = new System.IO.StringWriter())
        {
            xs.Serialize(writer, instance);
            return writer.ToString();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        throw;
    }
} 
John Saunders
@John - I don't mean to be ignorant but what is this code supposed to accomplish? It's basically what I'm doing now.
Randy Minder
@Randy: it's what you were doing incorrectly, and if you get an exception, it grabs it for you to post here.
John Saunders
A: 

Disclaimer: I am not an expert on WCF nor serialization, and the solution below is hacky at best and has only undergone brief verification.

public class HasBinaryProperty
{
    public byte[] versionBytes;

    public HasBinaryProperty()
    {//ignore this used it to test the serialization of the class briefly
        Random rand = new Random();
        byte[] bytes = new byte[20];
        rand.NextBytes(bytes);
        this.VersionNumber = new Binary(bytes);
    }

    [XmlIgnore]
    public Binary VersionNumber
    {
        get
        {
            return new Binary(this.versionBytes);
        }
        set
        {
            this.versionBytes = value.ToArray();
        }
    }
}
RedDeckWins
+1  A: 

Why not just convert the System.Linq.Binary to byte[]? Internally both are same, except System.Linq.Binary is immutable. Also Binary class doesn't have a default constructor hence the serialization fails.

Further reading:

Vivek