Wed Feb 24 15:47:16 CET 2010 Paolo Molaro <lupus@ximian.com>
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / DuplexClientRuntimeChannel.cs
1 //
2 // DuplexClientRuntimeChannel.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2009 Novell, Inc.  http://www.novell.com
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28 using System;
29 using System.Reflection;
30 using System.ServiceModel.Channels;
31 using System.ServiceModel.Description;
32 using System.ServiceModel.Dispatcher;
33 using System.ServiceModel.Security;
34 using System.Threading;
35 using System.Xml;
36
37 namespace System.ServiceModel
38 {
39         internal class DuplexClientRuntimeChannel
40                 : ClientRuntimeChannel, IDuplexContextChannel
41         {
42                 public DuplexClientRuntimeChannel (ServiceEndpoint endpoint,
43                         ChannelFactory factory, EndpointAddress remoteAddress, Uri via)
44                         : base (endpoint, factory, remoteAddress, via)
45                 {
46                         var cd = ContractDescription.GetContract (endpoint.Contract.CallbackContractType);
47                         var se = new ServiceEndpoint (cd, factory.Endpoint.Binding, remoteAddress);
48                         var ed = new EndpointDispatcher (remoteAddress, cd.Name, cd.Namespace);
49                         ed.InitializeServiceEndpoint (true, null, se);
50                         Runtime.CallbackDispatchRuntime = ed.DispatchRuntime;
51                 }
52
53                 public bool AutomaticInputSessionShutdown {
54                         get { throw new NotImplementedException (); }
55                         set { throw new NotImplementedException (); }
56                 }
57
58                 InstanceContext callback_instance;
59
60                 public InstanceContext CallbackInstance {
61                         get { return callback_instance; }
62                         set {
63                                 callback_instance = value;
64                                 Runtime.CallbackDispatchRuntime.InstanceContextProvider = new CallbackInstanceContextProvider (callback_instance);
65                         }
66                 }
67
68                 Action<TimeSpan> session_shutdown_delegate;
69
70                 public void CloseOutputSession (TimeSpan timeout)
71                 {
72                         throw new NotImplementedException ();
73                 }
74
75                 public IAsyncResult BeginCloseOutputSession (TimeSpan timeout, AsyncCallback callback, object state)
76                 {
77                         if (session_shutdown_delegate == null)
78                                 session_shutdown_delegate = new Action<TimeSpan> (CloseOutputSession);
79                         return session_shutdown_delegate.BeginInvoke (timeout, callback, state);
80                 }
81
82                 public void EndCloseOutputSession (IAsyncResult result)
83                 {
84                         session_shutdown_delegate.EndInvoke (result);
85                 }
86
87                 // listener loop manager
88
89                 bool loop;
90
91                 TimeSpan receive_timeout;
92                 bool receive_synchronously = true; // FIXME
93
94                 IAsyncResult loop_result;
95                 AutoResetEvent loop_handle = new AutoResetEvent (false);
96                 AutoResetEvent finish_handle = new AutoResetEvent (false);
97
98                 protected override void OnOpen (TimeSpan timeout)
99                 {
100                         loop = true;
101                         base.OnOpen (timeout);
102                         receive_timeout = TimeSpan.FromSeconds (10);
103                 }
104
105                 protected override void OnOpened ()
106                 {
107                         base.OnOpened ();
108                         loop_result = new Action<IInputChannel> (ProcessRequestOrInput).BeginInvoke (DuplexChannel, null, null);
109                 }
110
111                 protected override void OnClose (TimeSpan timeout)
112                 {
113                         DateTime start = DateTime.Now;
114                         base.OnClose (timeout);
115                         loop = false;
116                         if (!loop_handle.WaitOne (timeout - (DateTime.Now - start)))
117                                 throw new TimeoutException ();
118                         if (!finish_handle.WaitOne (timeout - (DateTime.Now - start)))
119                                 throw new TimeoutException ();
120                 }
121
122                 void ProcessRequestOrInput (IInputChannel input)
123                 {
124                         while (true) {
125                                 if (!loop)
126                                         return;
127
128                                 if (receive_synchronously) {
129                                         Message msg;
130                                         if (input.TryReceive (receive_timeout, out msg))
131                                                 ProcessInput (input, msg);
132                                 } else {
133                                         input.BeginTryReceive (receive_timeout, TryReceiveDone, input);
134                                         loop_handle.WaitOne (receive_timeout);
135                                 }
136                         }
137                 }
138
139                 void TryReceiveDone (IAsyncResult result)
140                 {
141                         try {
142                                 Message msg;
143                                 var input = (IInputChannel) result.AsyncState;
144                                 if (input.EndTryReceive (result, out msg)) {
145                                         loop_handle.Set ();
146                                         ProcessInput (input, msg);
147                                 }
148                         } catch (Exception ex) {
149                                 // FIXME: rather log it
150                                 Console.WriteLine ("Error at duplex client receiver side");
151                                 Console.WriteLine (ex);
152                                 loop = false;
153                         }
154                 }
155
156                 void ProcessInput (IInputChannel input, Message message)
157                 {
158                         try {
159                                 if (!MessageMatchesEndpointDispatcher (message, Runtime.CallbackDispatchRuntime.EndpointDispatcher))
160                                         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));
161                                 new InputOrReplyRequestProcessor (Runtime.CallbackDispatchRuntime, input).ProcessInput (message);
162                         } catch (Exception ex) {
163                                 // FIXME: log it.
164                                 Console.WriteLine (ex);
165                         } finally {
166                                 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
167                                 if (loop && input.State != CommunicationState.Closed)
168                                         ProcessRequestOrInput (input);
169                         }
170                 }
171
172                 bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
173                 {
174                         // FIXME: no need to filter address? It'd be mostly anonymous URI though.
175
176                         return endpoint.ContractFilter.Match (req);
177                 }
178         }
179 }