WCF Extensibility – Transport Channels – Request channels, part 2
This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page .
This is the part 2 of 3 of a “mini-series” inside the main series. For the other parts, here’s the list.
- Transport Channels – Request Channels, part 1: Basic, synchronous-only IRequestChannel implementation
- Transport Channels – Request Channels, part 2: Service model support for the sample
- Transport Channels – Request Channels, part 3: Asynchronous support for the channel
Continuing where I left off on the previous post, let’s jump right back into the scenario. This post, although having “Transport Channels” in the title, is more about the WCF Runtime pieces required for the scenario to work (I’ll finish the transport with asynchronous support in the next post), but I think it’s interesting to see that we don’t have to change anything in the transport to provide a better experience for the client. You can think of this as a review for most of the runtime pieces (at least from the client side).
Real world scenario: consuming a JSON-RPC service
What we ended up was a simple transport channel which could make synchronous requests to the service, but we needed to create the message ourselves. Before we get back to the transport channel, let’s make the client a little more user-friendly, by implementing the pieces needed to let us use a typed proxy to call the service.
And just to get it out of the way, the usual disclaimer: this is a sample for illustrating the topic of this post, this is not production-ready code. I tested it for a few contracts and it worked, but I cannot guarantee that it will work for all scenarios (please let me know if you find a bug or something missing). I really kept the error checking to a minimum (especially in the “simple service” project and in many other helper functions whose inputs should be sanitized), to make the sample small.
Back to code. What we want in the end of the post is to be able to use an interface like the one below to call the operations in the service. That looks just like a “normal” WCF service contract.
- [ServiceContract]
- public interface ITypedTest
- {
- [OperationContract]
- int Add(int x, int y);
- [OperationContract]
- int Subtract(int x, int y);
- [OperationContract]
- int Multiply(int x, int y);
- [OperationContract]
- int Divide(int x, int y);
- }
The main component we need for this is a message formatter, more specifically an IClientMessageFormatter implementation. That’s the component which knows how to convert between the Message object and the typed CLR parameters for the operations. So let’s start with it. In order to deal with the JSON, I’m using the NewtonSoft Json.NET library, a popular JSON library in the community. Since all JSON-RPC requests have an ID, and this ID must be unique per session, I’m using a simple counter which gets incremented every time a new request gets made.
To serialize the request, the code first creates the wrapper JObject instance to which we add the method (operation) name, the parameters (serializing the objects using the Json.NET serializer) and the request id. We then call a helper method to serialize the JObject into a Message object (more on the helper in a moment). To deserialize the reply, we again use the helper to convert from the message object into a JObject instance, then we use the serializer to extract the result of the operation.
- class JsonRpcMessageFormatter : IClientMessageFormatter
- {
- private OperationDescription operation;
- private static int nextId = 0;
- public JsonRpcMessageFormatter(OperationDescription operation)
- {
- this.operation = operation;
- }
- public object DeserializeReply(Message message, object[] parameters)
- {
- JObject json = JsonRpcHelpers.DeserializeMessage(message);
- return JsonConvert.DeserializeObject(
- json[JsonRpcConstants.ResultKey].ToString(),
- this.operation.Messages[1].Body.ReturnValue.Type);
- }
- public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
- {
- JObject json = new JObject();
- json.Add(JsonRpcConstants.MethodKey, this.operation.Name);
- JArray methodParams = new JArray();
- json.Add(JsonRpcConstants.ParamsKey, methodParams);
- for (int i = 0; i < parameters.Length; i++)
- {
- methodParams.Add(null);
- }
- foreach (MessagePartDescription part in this.operation.Messages[0].Body.Parts)
- {
- object paramValue = parameters[part.Index];
- if (paramValue != null)
- {
- methodParams[part.Index] = JToken.FromObject(paramValue);
- }
- }
- json.Add(JsonRpcConstants.IdKey, new JValue(Interlocked.Increment(ref nextId)));
- return JsonRpcHelpers.SerializeMessage(json, null);
- }
The serialize / deserialize helpers are shown below. The serialize method writes out the JObject instance into a bytes, then creates a “raw” message based on those bytes. It also stores the original JObject instance in the message properties – this will be useful in the next runtime piece. Also, the serialize method will copy information from any previous message. Again, not very interesting at the client formatter level, but will be useful in the future. The deserialize method first checks if the message properties contain an instance of the JObject used to create it, thus short-circuiting the evaluation if it had already been done. If not, it will read the “raw” message into an array of bytes, then load it using the Json.NET classes into a new JObject instance.
- public static Message SerializeMessage(JObject json, Message previousMessage)
- {
- using (MemoryStream ms = new MemoryStream())
- {
- using (StreamWriter sw = new StreamWriter(ms))
- {
- using (JsonTextWriter jtw = new JsonTextWriter(sw))
- {
- json.WriteTo(jtw);
- jtw.Flush();
- sw.Flush();
- Message result = Message.CreateMessage(MessageVersion.None, null, new RawBodyWriter(ms.ToArray()));
- �� if (previousMessage != null)
- {
- result.Properties.CopyProperties(previousMessage.Properties);
- result.Headers.CopyHeadersFrom(previousMessage.Headers);
- previousMessage.Close();
- }
- result.Properties[JsonRpcConstants.JObjectMessageProperty] = json;
- return result;
- }
- }
- }
- }
- public static JObject DeserializeMessage(Message message)
- {
- if (message.Properties.ContainsKey(JsonRpcConstants.JObjectMessageProperty))
- {
- return (JObject)message.Properties[JsonRpcConstants.JObjectMessageProperty];
- }
- else
- {
- JObject json = null;
- byte[] bytes = null;
- using (XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents())
- {
- bodyReader.ReadStartElement("Binary");
- bytes = bodyReader.ReadContentAsBase64();
- }
- using (MemoryStream ms = new MemoryStream(bytes))
- {
- using (StreamReader sr = new StreamReader(ms))
- {
- using (JsonTextReader jtr = new JsonTextReader(sr))
- {
- json = JObject.Load(jtr);
- }
- }
- }
- if (json == null)
- {
- throw new ArgumentException("Message must be a JSON object");
- }
- return json;
- }
- }
And the formatter is done. Next step: since we need to have a correlation between a request and a response in the JSON-RPC messages, we need to validate that the response “id” is the same as the request “id”. Also, the response may contain an error, and we want to surface that error as an exception to the client. For that, let’s use a message inspector (or more specifically, an IClientMessageInspector). As the request is about to be sent, the inspector stores the request id and returns it; that value will be then passed as a parameter (correlationState) to the AfterReceiveReply method. In that method the code retrieves the id of the reply, then validates that it’s the same as the request id, throwing an exception otherwise. That method also checks whether there is an error in the reply. If so, it convers it into an exception and throws it to the client. Notice that we use the message property “cache” shown in the formatter / helper in this method as well.
- class JsonRpcClientMessageInspector : IClientMessageInspector
- {
- public void AfterReceiveReply(ref Message reply, object correlationState)
- {
- JObject json = GetJObjectPreservingMessage(ref reply);
- int replyId = json["id"].Value<int>();
- int requestId = (int)correlationState;
- if (replyId != requestId)
- {
- throw new CommunicationException("Reply does not correspond to the request!");
- }
- if (json[JsonRpcConstants.ErrorKey].Type != JTokenType.Null)
- {
- throw new CommunicationException("Error from the service: " + json[JsonRpcConstants.ErrorKey].ToString());
- }
- }
- public object BeforeSendRequest(ref Message request, IClientChannel channel)
- {
- JObject json = GetJObjectPreservingMessage(ref request);
- return json["id"].Value<int>();
- }
- static JObject GetJObjectPreservingMessage(ref Message message)
- {
- JObject json;
- if (message.Properties.ContainsKey(JsonRpcConstants.JObjectMessageProperty))
- {
- json = (JObject)message.Properties[JsonRpcConstants.JObjectMessageProperty];
- }
- else
- {
- json = JsonRpcHelpers.DeserializeMessage(message);
- message = JsonRpcHelpers.SerializeMessage(json, message);
- }
- return json;
- }
- }
Now we need something to hook the formatter and inspector to the client runtime. Time then for an enpdoint behavior, which is shown below. A message inspector is added to the client runtime, and for all operations in the contract, if it’s now an “untyped” operation (like we had before), we add our formatter to it.
- public class JsonRpcEndpointBehavior : IEndpointBehavior
- {
- public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
- {
- clientRuntime.MessageInspectors.Add(new JsonRpcClientMessageInspector());
- foreach (OperationDescription operation in endpoint.Contract.Operations)
- {
- if (!JsonRpcHelpers.IsUntypedMessage(operation))
- {
- ClientOperation clientOperation = clientRuntime.Operations[operation.Name];
- clientOperation.SerializeRequest = true;
- clientOperation.DeserializeReply = true;
- clientOperation.Formatter = new JsonRpcMessageFormatter(operation);
- }
- }
- }
- }
And now we can use that nice typed interface to call our simple service:
- ChannelFactory<ITypedTest> typedFactory = new ChannelFactory<ITypedTest>(binding, address);
- typedFactory.Endpoint.Behaviors.Add(new JsonRpcEndpointBehavior());
- ITypedTest typedProxy = typedFactory.CreateChannel();
- Console.WriteLine("Calling Add");
- int result = typedProxy.Add(5, 8);
- Console.WriteLine(" ==> Result: {0}", result);
- Console.WriteLine();
- Console.WriteLine("Calling Multiply");
- result = typedProxy.Multiply(5, 8);
- Console.WriteLine(" ==> Result: {0}", result);
- Console.WriteLine();
- Console.WriteLine("Calling Divide (throws)");
- try
- {
- result = typedProxy.Divide(5, 0);
- Console.WriteLine(" ==> Result: {0}", result);
- }
- catch (Exception e)
- {
- Console.WriteLine("Error: {0}", e);
- }
And that’s the end of the detour through the WCF runtime in the post about channels.
Coming up
Back to the transport channel, we’ll add support for asynchronous calling on it. Be prepared for a lot of asynchronous spaghetti. You’ve been warned.