2 // WebMessageFormatter.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 using System.Collections.Specialized;
30 using System.Reflection;
31 using System.Runtime.Serialization;
32 using System.Runtime.Serialization.Json;
33 using System.ServiceModel;
34 using System.ServiceModel.Channels;
35 using System.ServiceModel.Dispatcher;
36 using System.ServiceModel.Web;
39 namespace System.ServiceModel.Description
41 internal abstract class WebMessageFormatter
43 OperationDescription operation;
44 ServiceEndpoint endpoint;
45 QueryStringConverter converter;
46 WebHttpBehavior behavior;
48 WebAttributeInfo info = null;
50 public WebMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
52 this.operation = operation;
53 this.endpoint = endpoint;
54 this.converter = converter;
55 this.behavior = behavior;
59 void ApplyWebAttribute ()
61 MethodInfo mi = operation.SyncMethod ?? operation.BeginMethod;
63 object [] atts = mi.GetCustomAttributes (typeof (WebGetAttribute), false);
65 info = ((WebGetAttribute) atts [0]).Info;
66 atts = mi.GetCustomAttributes (typeof (WebInvokeAttribute), false);
68 info = ((WebInvokeAttribute) atts [0]).Info;
70 info = new WebAttributeInfo ();
72 template = info.BuildUriTemplate (Operation, GetMessageDescription (MessageDirection.Input));
75 public WebHttpBehavior Behavior {
76 get { return behavior; }
79 public WebAttributeInfo Info {
83 public OperationDescription Operation {
84 get { return operation; }
87 public QueryStringConverter Converter {
88 get { return converter; }
91 public ServiceEndpoint Endpoint {
92 get { return endpoint; }
95 public UriTemplate UriTemplate {
96 get { return template; }
99 protected WebContentFormat ToContentFormat (WebMessageFormat src)
102 case WebMessageFormat.Xml:
103 return WebContentFormat.Xml;
104 case WebMessageFormat.Json:
105 return WebContentFormat.Json;
107 throw new SystemException ("INTERNAL ERROR: should not happen");
110 protected void CheckMessageVersion (MessageVersion messageVersion)
112 if (messageVersion == null)
113 throw new ArgumentNullException ("messageVersion");
115 if (!MessageVersion.None.Equals (messageVersion))
116 throw new ArgumentException ("Only MessageVersion.None is supported");
119 protected MessageDescription GetMessageDescription (MessageDirection dir)
121 foreach (MessageDescription md in operation.Messages)
122 if (md.Direction == dir)
124 throw new SystemException ("INTERNAL ERROR: no corresponding message description for the specified direction: " + dir);
127 internal class RequestClientFormatter : WebClientMessageFormatter
129 public RequestClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
130 : base (operation, endpoint, converter, behavior)
135 internal class ReplyClientFormatter : WebClientMessageFormatter
137 public ReplyClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
138 : base (operation, endpoint, converter, behavior)
143 internal class RequestDispatchFormatter : WebDispatchMessageFormatter
145 public RequestDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
146 : base (operation, endpoint, converter, behavior)
151 internal class ReplyDispatchFormatter : WebDispatchMessageFormatter
153 public ReplyDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
154 : base (operation, endpoint, converter, behavior)
159 internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
161 protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
162 : base (operation, endpoint, converter, behavior)
166 public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
168 if (parameters == null)
169 throw new ArgumentNullException ("parameters");
170 CheckMessageVersion (messageVersion);
172 var c = new NameValueCollection ();
174 MessageDescription md = GetMessageDescription (MessageDirection.Input);
176 if (parameters.Length != md.Body.Parts.Count)
177 throw new ArgumentException ("Parameter array length does not match the number of message body parts");
179 for (int i = 0; i < parameters.Length; i++) {
180 var p = md.Body.Parts [i];
181 string name = p.Name.ToUpperInvariant ();
182 if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
183 UriTemplate.QueryValueVariableNames.Contains (name))
184 c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
186 // FIXME: bind as a message part
187 throw new NotImplementedException (String.Format ("parameter {0} is not contained in the URI template {1} {2} {3}", p.Name, UriTemplate, UriTemplate.PathSegmentVariableNames.Count, UriTemplate.QueryValueVariableNames.Count));
190 Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
192 Message ret = Message.CreateMessage (messageVersion, (string) null);
195 var hp = new HttpRequestMessageProperty ();
196 hp.Method = Info.Method;
197 // FIXME: set hp.SuppressEntityBody for some cases.
198 ret.Properties.Add (HttpRequestMessageProperty.Name, hp);
200 var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat));
201 ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
206 public object DeserializeReply (Message message, object [] parameters)
208 if (parameters == null)
209 throw new ArgumentNullException ("parameters");
210 CheckMessageVersion (message.Version);
212 string pname = WebBodyFormatMessageProperty.Name;
213 if (!message.Properties.ContainsKey (pname))
214 throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
215 var wp = (WebBodyFormatMessageProperty) message.Properties [pname];
216 MessageDescription md = GetMessageDescription (MessageDirection.Output);
218 XmlObjectSerializer serializer = null;
220 case WebContentFormat.Xml:
221 serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
223 case WebContentFormat.Json:
224 serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
226 case WebContentFormat.Raw:
228 throw new NotImplementedException ();
231 // FIXME: handle ref/out parameters
233 return serializer.ReadObject (message.GetReaderAtBodyContents (), false);
237 internal abstract class WebDispatchMessageFormatter : WebMessageFormatter, IDispatchMessageFormatter
239 protected WebDispatchMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
240 : base (operation, endpoint, converter, behavior)
244 public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
247 return SerializeReplyCore (messageVersion, parameters, result);
249 if (WebOperationContext.Current != null)
250 OperationContext.Current.Extensions.Remove (WebOperationContext.Current);
254 Message SerializeReplyCore (MessageVersion messageVersion, object [] parameters, object result)
256 if (parameters == null)
257 throw new ArgumentNullException ("parameters");
258 CheckMessageVersion (messageVersion);
260 MessageDescription md = GetMessageDescription (MessageDirection.Output);
263 // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> ();
264 // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null);
265 // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> ();
266 // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ());
268 WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
270 string mediaType = null;
271 XmlObjectSerializer serializer = null;
273 case WebMessageFormat.Xml:
274 serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
275 mediaType = "application/xml";
277 case WebMessageFormat.Json:
278 serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
279 mediaType = "application/json";
283 // FIXME: serialize ref/out parameters as well.
285 Message ret = Message.CreateMessage (MessageVersion.None, null, result, serializer);
287 // Message properties
289 var hp = new HttpResponseMessageProperty ();
290 // FIXME: get encoding from somewhere
291 hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";
293 // apply user-customized HTTP results via WebOperationContext.
294 WebOperationContext.Current.OutgoingResponse.Apply (hp);
296 // FIXME: fill some properties if required.
297 ret.Properties.Add (HttpResponseMessageProperty.Name, hp);
299 var wp = new WebBodyFormatMessageProperty (ToContentFormat (msgfmt));
300 ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
305 public void DeserializeRequest (Message message, object [] parameters)
307 if (parameters == null)
308 throw new ArgumentNullException ("parameters");
309 CheckMessageVersion (message.Version);
311 OperationContext.Current.Extensions.Add (new WebOperationContext (OperationContext.Current));
313 IncomingWebRequestContext iwc = WebOperationContext.Current.IncomingRequest;
315 Uri to = message.Headers.To;
316 UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
318 // not sure if it could happen
319 throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
320 iwc.UriTemplateMatch = match;
322 MessageDescription md = GetMessageDescription (MessageDirection.Input);
324 for (int i = 0; i < parameters.Length; i++) {
325 var p = md.Body.Parts [i];
326 string name = p.Name.ToUpperInvariant ();
327 parameters [i] = match.BoundVariables [name];