Skip to content

Instantly share code, notes, and snippets.

@thaianhduc
Created October 16, 2018 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thaianhduc/35b7b9d809533b4c143e094176124346 to your computer and use it in GitHub Desktop.
Save thaianhduc/35b7b9d809533b4c143e094176124346 to your computer and use it in GitHub Desktop.
A simple implementation of WCF service where the architecture is based on Request/Response with a single endpoint
public static class BinaryDataContractSerializer
{
public static byte[] Serialize<T>(T obj) where T : class
{
if (obj == null)
return null;
var serializer = new DataContractSerializer(typeof(T));
using (var memStream = new MemoryStream())
{
using (var writer = XmlDictionaryWriter.CreateBinaryWriter(memStream))
{
serializer.WriteObject(writer, obj);
}
return memStream.ToArray();
}
}
public static T Deserialize<T>(Response response) where T : class
{
if (response == null)
return default(T);
var serializer = new DataContractSerializer(typeof(T));
using (var stream = new MemoryStream(response.SerializedData))
{
using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))
{
return (T)serializer.ReadObject(reader);
}
}
}
}
[DataContract]
public class Request
{
[DataMember]
public string Payload { get; set; }
}
[DataContract]
public class Response
{
[DataMember]
public byte[] SerializedData { get; set; }
[DataMember]
public string QualifiedAssemblyDataType { get; set; }
}
[DataContract]
public class DownloadFileResponse
{
[DataMember]
public byte[] Data { get; set; }
}
public class ServiceImpl
{
public Response Execute(Request request)
{
// Assuming the request is to read data from a file
byte[] data = File.ReadAllBytes(request.Payload);
var responseData = new DownloadFileResponse
{
Data = data
};
return new Response
{
QualifiedAssemblyDataType = typeof(DownloadFileResponse).AssemblyQualifiedName,
SerializedData = BinaryDataContractSerializer.Serialize(responseData)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment