Created
October 16, 2018 15:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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