4

A SQL Server Timestamp becomes a byte[] in a POCO object. The object gets serialized and the timestamp becomes a base 64 string.

An example is 'AAAAAAA2QDE='

When the object is posted back to the server, during Model Validation you get:

The value 'AAAAAAA2QDE=' is not valid for Byte.

I am using this value to check the state of the record to compare to the current record in SQL to see if someone else has updated it since this user has retrieved it (pretty normal).

But the string is not deserializing back to a byte array, it appears that it is trying to put it into a single byte.

This should be a very common issue. Any ideas?

Glenn D Orr
  • 156
  • 2
  • 5
  • Take a look here: http://stackoverflow.com/questions/669399/asp-net-mvc-how-do-i-keep-a-field-byte – ramsey_tm Dec 04 '13 at 22:50
  • That is a great example, but I am getting and returning data from a WebAPI project independent of the client consuming the data. In this case it is a knockoutjs based web application, but it could be an iPhone app. What I need is an example of how to get Json.net to deserialize the byte array back into it's original form. – Glenn D Orr Dec 05 '13 at 20:04

1 Answers1

5

We can map the SQL Column (via ORM like NHibernate...) or directly with ADO.NET to property of type byte[], but make this property protected/internal to the server. Instead this, we can have another string property doing conversion as needed:

protected virtual byte[] Timestamp { get; set; }
public virtual string Version
{
    get { return Timestamp.IsEmpty() ? null : Convert.ToBase64String(Timestamp); }
    set { Timestamp = value.IsEmpty() ? null : Convert.FromBase64String(value); }
}

The Timestamp is for internal processing, representing the real bytes, the Version is for a Client ... is well de/serialized.

An example with NHibernate here

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • I'm using POCO objects and Entity Framework. I would like for JSON.net to deserialize it correctly, thank you for the suggestion. – Glenn D Orr Dec 05 '13 at 20:01
  • Do not get me wrong. The above suggestion is fully following POCO. (check this http://stackoverflow.com/a/13632872/1679310). The point is, that string could be serialized or consumed almost by any tool (xml, url...) So, while we are working with timestamp in the native form of the DB engine (`byte[]`) we do hide that from the external world - publishing that as the base64. Not relying on the de/serializers ... formatters... but just a suggestion (working for me for many years;) – Radim Köhler Dec 06 '13 at 06:55