Wednesday, 7 August 2013

Deserializing SQL varbinary in form of XML to C# byte[]

Deserializing SQL varbinary in form of XML to C# byte[]

I'm working on a small proof of concept project, in which the client sends
an image file in a byte[] format and the server inserts the data to the
database in Image column, which is VarBinary(MAX). This part works fine,
however, I'm having issues trying to convert the data back into a byte
array and sending it to the client.
In the database, there is a stored procedure which is responsible for
getting data and returning it in XML:
SELECT
...
asset.Image AS 'Image'
FROM ASSETS AS asset
WHERE asset.Id = @Id
FOR XML PATH('Asset')
A sample query result looks like this (the actual value for Image is
actually a lot longer than this, but I shortened it to make it more
readable):
<Asset>
...
<Image>/9j/4AAQSkZJRgABAQEAYABgAAD/2wB</Image>
</Asset>
And in the code, I have a generic method which deserializes this XML into
its corresponding object:
internal static T ExecuteQuery<T>(StoredProcedures storedProcedure,
ParameterList parameters)
{
using (var connection = GetSqlConnection())
{
using (var command = new
SqlCommand(storedProcedure.ToString(), connection))
{
command.CommandType =
System.Data.CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
command.Parameters.Add(new
SqlParameter(parameter.Key.ToString(),
parameter.Value));
}
connection.Open();
var data = command.ExecuteScalar();
return DeserializeXml<T>(data.ToString());
}
}
The Asset type (which is what I'm passing it to this generic method has
several properties, one of which is Image:
public class Asset
{
public Asset()
{
}
...
[DataMember]
[XmlElement("Image")]
public byte[] Image { get; set; }
}
Now when I execute the program, I get this error:
There is an error in XML document
It seems like the deserializer is having issues with the VarBinary value
(it used to work fine before I added this Image property). Any ideas why
this could be happening? Do I need to use a memory stream to convert the
data back?

No comments:

Post a Comment