Right now I am programming a multiplayer card game in Silverlight
I am wondering how to store a object best binary in a sql database.
I have a GameState Object which contains the current state of a game between two players. I want to store this object in a s开发者_运维知识库ql database that both player can access and change it anytime.
How would you do that with Silverlight + RIA Services? Especially the part where you serialize the object in Silverlight.
Thanks
I would do the serialization on the server side. Add an Invoke
operation to your RIA services domain context that accepts your GameState object. On the server side you can then use standard .NET serialization (personally I would recommend XML serialization instead of binary, but it shouldn't matter).
First, you can not possibly simply serialize something at the server. It must be serialized before it can be sent to the server. But it seems that perhaps you are making things too complicated/magical.
Given what you have said, I would start with by defining my GameState object (and any other object you need) inside the Entity Framework. Include any and all fields that are needed to save the state of the game. Then you should be able to have the framework create the needed tables.
Once you have done this, add a DomainService to the web project and when you compile the objects will then be available inside your Silverlight project.
Finally i decided to use XML serialization.
I found a great article about XML Serialization: http://www.ingebrigtsen.info/post/2008/11/29/Serialization-in-Silverlight.aspx
That's how it looks like in my Silverlight code:
public static class MySerializer
{
public static string Serialize<T>(T data)
{
using (var memoryStream = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(memoryStream, data);
memoryStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(memoryStream);
string content = reader.ReadToEnd();
return content;
}
}
public static T Deserialize<T>(string xml)
{
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
{
var serializer = new DataContractSerializer(typeof(T));
T theObject = (T)serializer.ReadObject(stream);
return theObject;
}
}
}
I've found the SharpSerializer package very easy to use for fast binary serlization in Silverlight: http://www.sharpserializer.com/en/index.html
精彩评论