2 // DuplexClientRuntimeChannel.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2009 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;
31 using System.Reflection;
32 using System.ServiceModel.Channels;
33 using System.ServiceModel.Description;
34 using System.ServiceModel.Dispatcher;
35 using System.ServiceModel.Security;
36 using System.Threading;
39 namespace System.ServiceModel.MonoInternal
41 #if DISABLE_REAL_PROXY
42 // FIXME: This is a quick workaround for bug #571907
45 class DuplexClientRuntimeChannel
46 : ClientRuntimeChannel, IDuplexContextChannel
48 public DuplexClientRuntimeChannel (ServiceEndpoint endpoint,
49 ChannelFactory factory, EndpointAddress remoteAddress, Uri via)
50 : base (endpoint, factory, remoteAddress, via)
52 var ed = new EndpointDispatcher (remoteAddress, endpoint.Contract.Name, endpoint.Contract.Namespace);
53 ed.InitializeServiceEndpoint (true, null, endpoint);
54 Runtime.CallbackDispatchRuntime = ed.DispatchRuntime;
57 public bool AutomaticInputSessionShutdown {
58 get { throw new NotImplementedException (); }
59 set { throw new NotImplementedException (); }
62 InstanceContext callback_instance;
64 public InstanceContext CallbackInstance {
65 get { return callback_instance; }
67 callback_instance = value;
68 Runtime.CallbackDispatchRuntime.InstanceContextProvider = new CallbackInstanceContextProvider (callback_instance);
72 Action<TimeSpan> session_shutdown_delegate;
74 public void CloseOutputSession (TimeSpan timeout)
76 throw new NotImplementedException ();
79 public IAsyncResult BeginCloseOutputSession (TimeSpan timeout, AsyncCallback callback, object state)
81 if (session_shutdown_delegate == null)
82 session_shutdown_delegate = new Action<TimeSpan> (CloseOutputSession);
83 return session_shutdown_delegate.BeginInvoke (timeout, callback, state);
86 public void EndCloseOutputSession (IAsyncResult result)
88 session_shutdown_delegate.EndInvoke (result);
91 // listener loop manager
95 TimeSpan receive_timeout;
96 bool receive_synchronously = true; // FIXME
98 IAsyncResult loop_result;
99 AutoResetEvent loop_handle = new AutoResetEvent (false);
100 AutoResetEvent finish_handle = new AutoResetEvent (false);
101 AutoResetEvent receive_reply_handle = new AutoResetEvent (false);
103 protected override void OnOpen (TimeSpan timeout)
106 base.OnOpen (timeout);
107 receive_timeout = TimeSpan.FromSeconds (10);
110 protected override void OnOpened ()
113 loop_result = new Action<IInputChannel> (ProcessRequestOrInput).BeginInvoke (DuplexChannel, null, null);
116 protected override void OnClose (TimeSpan timeout)
118 DateTime start = DateTime.Now;
119 base.OnClose (timeout);
121 if (!loop_handle.WaitOne (timeout - (DateTime.Now - start)))
122 throw new TimeoutException ();
123 if (!finish_handle.WaitOne (timeout - (DateTime.Now - start)))
124 throw new TimeoutException ();
127 void ProcessRequestOrInput (IInputChannel input)
133 if (receive_synchronously) {
135 if (input.TryReceive (receive_timeout, out msg))
136 ProcessInput (input, msg);
138 input.BeginTryReceive (receive_timeout, TryReceiveDone, input);
139 loop_handle.WaitOne (receive_timeout);
144 void TryReceiveDone (IAsyncResult result)
148 var input = (IInputChannel) result.AsyncState;
149 if (input.EndTryReceive (result, out msg)) {
151 ProcessInput (input, msg);
153 } catch (Exception ex) {
154 // FIXME: rather log it
155 Console.WriteLine ("Error at duplex client receiver side");
156 Console.WriteLine (ex);
161 void ProcessInputCore (IInputChannel input, Message message)
163 bool isReply = message != null && Contract.Operations.Any (od => (od.DeclaringContract.CallbackContractType == od.DeclaringContract.ContractType || !od.InCallbackContract) && od.Messages.Any (md => md.Action == message.Headers.Action));
165 if (ReplyHandlerQueue.Count > 0) {
167 var h = ReplyHandlerQueue.Dequeue ();
174 if (message.IsFault) {
176 var mf = MessageFault.CreateFault (message, 0x10000);
177 if (FaultConverter.GetDefaultFaultConverter (message.Version).TryCreateException (message, mf, out ex)) // FIXME: get maxMessageSize somehow
180 throw new FaultException (mf);
183 if (!MessageMatchesEndpointDispatcher (message, Runtime.CallbackDispatchRuntime.EndpointDispatcher))
184 throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' with action '{1}' which is not reachable in this service contract", message.Headers.To, message.Headers.Action));
185 new InputOrReplyRequestProcessor (Runtime.CallbackDispatchRuntime, input).ProcessInput (message);
188 void ProcessInput (IInputChannel input, Message message)
191 ProcessInputCore (input, message);
192 } catch (Exception ex) {
194 Console.WriteLine (ex);
196 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
197 if (loop && input.State != CommunicationState.Closed)
198 ProcessRequestOrInput (input);
202 bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
204 // FIXME: no need to filter address? It'd be mostly anonymous URI though.
206 return endpoint.ContractFilter.Match (req);
209 internal override Message RequestCorrelated (Message msg, TimeSpan timeout, IOutputChannel channel)
211 DateTime startTime = DateTime.Now;
213 ManualResetEvent wait = new ManualResetEvent (false);
214 Action<Message> handler = delegate (Message reply) {
218 ReplyHandlerQueue.Enqueue (handler);
219 channel.Send (msg, timeout);
220 if (ret == null && !wait.WaitOne (timeout - (DateTime.Now - startTime)))
221 throw new TimeoutException ();
225 internal Queue<Action<Message>> ReplyHandlerQueue = new Queue<Action<Message>> ();