2 // HttpRequestChannel.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2006 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.Generic;
32 using System.Net.Security;
33 using System.ServiceModel;
34 using System.ServiceModel.Description;
35 using System.ServiceModel.Security;
36 using System.Threading;
38 namespace System.ServiceModel.Channels
40 internal class HttpRequestChannel : RequestChannelBase
42 HttpChannelFactory<IRequestChannel> source;
44 WebRequest web_request;
46 // FIXME: supply maxSizeOfHeaders.
47 int max_headers = 0x10000;
51 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
52 EndpointAddress address, Uri via)
53 : base (factory, address, via)
55 this.source = factory;
58 public int MaxSizeOfHeaders {
59 get { return max_headers; }
62 public MessageEncoder Encoder {
63 get { return source.MessageEncoder; }
68 public override Message Request (Message message, TimeSpan timeout)
70 return EndRequest (BeginRequest (message, timeout, null, null));
73 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
75 Message message = result.Message;
76 TimeSpan timeout = result.Timeout;
77 // FIXME: is distination really like this?
78 Uri destination = message.Headers.To;
79 if (destination == null) {
80 if (source.Source.ManualAddressing)
81 throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
83 destination = Via ?? RemoteAddress.Uri;
86 web_request = HttpWebRequest.Create (destination);
87 web_request.Method = "POST";
88 web_request.ContentType = Encoder.ContentType;
90 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
91 web_request.Timeout = (int) timeout.TotalMilliseconds;
94 // There is no SOAP Action/To header when AddressingVersion is None.
95 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
96 message.Version.Addressing.Equals (AddressingVersion.None)) {
97 if (message.Headers.Action != null) {
98 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
99 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
103 // apply HttpRequestMessageProperty if exists.
104 bool suppressEntityBody = false;
106 string pname = HttpRequestMessageProperty.Name;
107 if (message.Properties.ContainsKey (pname)) {
108 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
109 web_request.Headers.Add (hp.Headers);
110 web_request.Method = hp.Method;
111 // FIXME: do we have to handle hp.QueryString ?
112 if (hp.SuppressEntityBody)
113 suppressEntityBody = true;
117 if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
118 MemoryStream buffer = new MemoryStream ();
119 Encoder.WriteMessage (message, buffer);
121 if (buffer.Length > int.MaxValue)
122 throw new InvalidOperationException ("The argument message is too large.");
125 web_request.ContentLength = (int) buffer.Length;
128 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
130 result.CompletedSynchronously &= r.CompletedSynchronously;
131 using (Stream s = web_request.EndGetRequestStream (r))
132 s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
133 web_request.BeginGetResponse (GotResponse, result);
134 } catch (Exception ex) {
135 result.Complete (ex);
139 web_request.BeginGetResponse (GotResponse, result);
143 void GotResponse (IAsyncResult result)
145 HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
146 channelResult.CompletedSynchronously &= result.CompletedSynchronously;
151 res = web_request.EndGetResponse (result);
152 resstr = res.GetResponseStream ();
153 } catch (WebException we) {
156 Console.WriteLine (we);
159 // The response might contain SOAP fault. It might not.
160 resstr = res.GetResponseStream ();
161 } catch (WebException we2) {
163 Console.WriteLine (we2);
166 channelResult.Complete (we2);
172 using (var responseStream = resstr) {
173 MemoryStream ms = new MemoryStream ();
174 byte [] b = new byte [65536];
178 n = responseStream.Read (b, 0, 65536);
183 ms.Seek (0, SeekOrigin.Begin);
185 channelResult.Response = Encoder.ReadMessage (
186 //responseStream, MaxSizeOfHeaders);
187 ms, MaxSizeOfHeaders, res.ContentType);
189 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
190 ret = buf.CreateMessage ();
191 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
192 w.Formatting = System.Xml.Formatting.Indented;
193 buf.CreateMessage ().WriteMessage (w);
196 channelResult.Complete ();
198 } catch (Exception ex) {
199 channelResult.Complete (ex);
205 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
207 ThrowIfDisposedOrNotOpen ();
209 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
210 BeginProcessRequest (result);
214 public override Message EndRequest (IAsyncResult result)
217 throw new ArgumentNullException ("result");
218 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
220 throw new InvalidOperationException ("Wrong IAsyncResult");
227 protected override void OnAbort ()
229 if (web_request != null)
230 web_request.Abort ();
236 protected override void OnClose (TimeSpan timeout)
238 if (web_request != null)
239 web_request.Abort ();
243 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
245 throw new NotImplementedException ();
248 protected override void OnEndClose (IAsyncResult result)
250 throw new NotImplementedException ();
255 protected override void OnOpen (TimeSpan timeout)
259 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
261 throw new NotImplementedException ();
264 protected override void OnEndOpen (IAsyncResult result)
266 throw new NotImplementedException ();
269 class HttpChannelRequestAsyncResult : IAsyncResult
271 public Message Message {
275 public TimeSpan Timeout {
279 AsyncCallback callback;
280 ManualResetEvent wait;
283 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
285 CompletedSynchronously = true;
288 this.callback = callback;
291 wait = new ManualResetEvent (false);
294 public Message Response {
298 public WaitHandle AsyncWaitHandle {
302 public object AsyncState {
306 public void Complete ()
311 public void Complete (Exception ex)
316 // If we've already stored an error, don't replace it
321 if (callback != null)
325 public bool CompletedSynchronously {
329 public bool IsCompleted {
333 public void WaitEnd ()
337 const bool exit_context =
339 false; // MonoTouch doesn't support any remoting feature
344 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
345 // Is the current request cancelled and an exception thrown? If so we need to pass the
346 // exception to the Complete () method and allow the result to complete 'normally'.
347 if (!wait.WaitOne (Timeout, exit_context))
348 throw new TimeoutException ();