2 // generic ClientBase.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2005-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;
30 using System.ComponentModel;
31 using System.Reflection;
32 using System.ServiceModel.Channels;
33 using System.ServiceModel.Description;
34 using System.ServiceModel.Dispatcher;
35 using System.Threading;
37 namespace System.ServiceModel
39 [MonoTODO ("It somehow rejects classes, but dunno how we can do that besides our code wise.")]
40 public abstract class ClientBase<TChannel>
41 : IDisposable, ICommunicationObject where TChannel : class
43 static InstanceContext initialContxt = new InstanceContext (null);
45 static readonly PropertyInfo dispatcher_main_property;
46 static readonly MethodInfo dispatcher_begin_invoke_method;
50 foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies ()) {
51 if (ass.GetName ().Name != "System.Windows")
53 Type dispatcher_type = ass.GetType ("System.Windows.Threading.Dispatcher", true);
54 dispatcher_main_property = dispatcher_type.GetProperty ("Main", BindingFlags.NonPublic | BindingFlags.Static);
55 dispatcher_begin_invoke_method = dispatcher_type.GetMethod ("BeginInvoke", new Type [] {typeof (Delegate), typeof (object [])});
57 if (dispatcher_main_property == null)
58 throw new SystemException ("Dispatcher.Main not found");
59 if (dispatcher_begin_invoke_method == null)
60 throw new SystemException ("Dispatcher.BeginInvoke not found");
64 ChannelFactory<TChannel> factory;
65 ChannelBase<TChannel> inner_channel;
66 CommunicationState state;
68 protected delegate IAsyncResult BeginOperationDelegate (object[] inValues, AsyncCallback asyncCallback, object state);
69 protected delegate object[] EndOperationDelegate (IAsyncResult result);
71 protected ClientBase ()
72 : this (initialContxt)
76 protected ClientBase (string endpointConfigurationName)
77 : this (initialContxt, endpointConfigurationName)
81 protected ClientBase (Binding binding, EndpointAddress remoteAddress)
82 : this (initialContxt, binding, remoteAddress)
86 protected ClientBase (string endpointConfigurationName, EndpointAddress remoteAddress)
87 : this (initialContxt, endpointConfigurationName, remoteAddress)
91 protected ClientBase (string endpointConfigurationName, string remoteAddress)
92 : this (initialContxt, endpointConfigurationName, remoteAddress)
96 protected ClientBase (InstanceContext instance)
97 : this (instance, "*")
101 protected ClientBase (InstanceContext instance, string endpointConfigurationName)
103 if (instance == null)
104 throw new ArgumentNullException ("instanceContext");
105 if (endpointConfigurationName == null)
106 throw new ArgumentNullException ("endpointConfigurationName");
108 Initialize (instance, endpointConfigurationName, null);
111 protected ClientBase (InstanceContext instance,
112 string endpointConfigurationName, EndpointAddress remoteAddress)
114 if (instance == null)
115 throw new ArgumentNullException ("instanceContext");
116 if (endpointConfigurationName == null)
117 throw new ArgumentNullException ("endpointConfigurationName");
118 if (remoteAddress == null)
119 throw new ArgumentNullException ("remoteAddress");
121 Initialize (instance, endpointConfigurationName, remoteAddress);
124 protected ClientBase (InstanceContext instance,
125 string endpointConfigurationName, string remoteAddress)
127 if (instance == null)
128 throw new ArgumentNullException ("instanceContext");
129 if (remoteAddress == null)
130 throw new ArgumentNullException ("endpointAddress");
131 if (endpointConfigurationName == null)
132 throw new ArgumentNullException ("endpointConfigurationName");
134 Initialize (instance, endpointConfigurationName, new EndpointAddress (remoteAddress));
137 protected ClientBase (InstanceContext instance,
138 Binding binding, EndpointAddress remoteAddress)
140 if (instance == null)
141 throw new ArgumentNullException ("instanceContext");
143 throw new ArgumentNullException ("binding");
144 if (remoteAddress == null)
145 throw new ArgumentNullException ("remoteAddress");
147 Initialize (instance, binding, remoteAddress);
150 internal ClientBase (ChannelFactory<TChannel> factory)
152 ChannelFactory = factory;
155 void Initialize (InstanceContext instance,
156 string endpointConfigurationName, EndpointAddress remoteAddress)
158 ChannelFactory = new ChannelFactory<TChannel> (endpointConfigurationName, remoteAddress);
161 void Initialize (InstanceContext instance,
162 Binding binding, EndpointAddress remoteAddress)
164 ChannelFactory = new ChannelFactory<TChannel> (binding, remoteAddress);
167 public ChannelFactory<TChannel> ChannelFactory {
168 get { return factory; }
171 factory.OwnerClientBase = this;
176 public ClientCredentials ClientCredentials {
177 get { return ChannelFactory.Credentials; }
181 public ServiceEndpoint Endpoint {
182 get { return factory.Endpoint; }
185 public IClientChannel InnerChannel {
187 if (inner_channel == null)
188 // FIXME: "factory." might be extraneous.
189 inner_channel = (ChannelBase<TChannel>) (object) ChannelFactory.CreateChannel ();
190 return inner_channel;
194 protected TChannel Channel {
195 get { return (TChannel) (object) InnerChannel; }
198 public CommunicationState State {
199 get { return InnerChannel.State; }
204 InnerChannel.Abort ();
209 InnerChannel.Close ();
212 public void DisplayInitializationUI ()
214 InnerChannel.DisplayInitializationUI ();
218 protected T GetDefaultValueForInitialization<T> ()
223 //IAsyncResult delegate_async;
225 void RunCompletedCallback (SendOrPostCallback callback, InvokeAsyncCompletedEventArgs args)
227 object dispatcher = dispatcher_main_property.GetValue (null, null);
228 if (dispatcher == null) {
232 EventHandler a = delegate { callback (args); };
233 dispatcher_begin_invoke_method.Invoke (dispatcher, new object [] {a, new object [] {this, new EventArgs ()}});
236 protected void InvokeAsync (BeginOperationDelegate beginOperationDelegate,
237 object [] inValues, EndOperationDelegate endOperationDelegate,
238 SendOrPostCallback operationCompletedCallback, object userState)
240 if (beginOperationDelegate == null)
241 throw new ArgumentNullException ("beginOperationDelegate");
242 if (endOperationDelegate == null)
243 throw new ArgumentNullException ("endOperationDelegate");
244 //if (delegate_async != null)
245 // throw new InvalidOperationException ("Another async operation is in progress");
247 AsyncCallback cb = delegate (IAsyncResult ar) {
248 object [] results = null;
249 Exception error = null;
250 bool cancelled = false; // FIXME: fill it in case it is cancelled
252 results = endOperationDelegate (ar);
253 } catch (Exception ex) {
257 if (operationCompletedCallback != null)
258 RunCompletedCallback (operationCompletedCallback, new InvokeAsyncCompletedEventArgs (results, error, cancelled, userState));
259 } catch (Exception ex) {
260 Console.WriteLine ("Exception during operationCompletedCallback" + ex);
263 Console.WriteLine ("System.ServiceModel.ClientBase<TChannel>: web service invocation is successfully done.");
265 begin_async_result = beginOperationDelegate (inValues, cb, userState);
267 IAsyncResult begin_async_result;
270 void IDisposable.Dispose ()
275 protected virtual TChannel CreateChannel ()
277 return ChannelFactory.CreateChannel ();
282 InnerChannel.Open ();
285 #region ICommunicationObject implementation
287 IAsyncResult ICommunicationObject.BeginOpen (
288 AsyncCallback callback, object state)
290 return InnerChannel.BeginOpen (callback, state);
293 IAsyncResult ICommunicationObject.BeginOpen (
294 TimeSpan timeout, AsyncCallback callback, object state)
296 return InnerChannel.BeginOpen (timeout, callback, state);
299 void ICommunicationObject.EndOpen (IAsyncResult result)
301 InnerChannel.EndOpen (result);
304 IAsyncResult ICommunicationObject.BeginClose (
305 AsyncCallback callback, object state)
307 return InnerChannel.BeginClose (callback, state);
310 IAsyncResult ICommunicationObject.BeginClose (
311 TimeSpan timeout, AsyncCallback callback, object state)
313 return InnerChannel.BeginClose (timeout, callback, state);
316 void ICommunicationObject.EndClose (IAsyncResult result)
318 InnerChannel.EndClose (result);
321 void ICommunicationObject.Close (TimeSpan timeout)
323 InnerChannel.Close (timeout);
326 void ICommunicationObject.Open (TimeSpan timeout)
328 InnerChannel.Open (timeout);
331 event EventHandler ICommunicationObject.Opening {
332 add { InnerChannel.Opening += value; }
333 remove { InnerChannel.Opening -= value; }
335 event EventHandler ICommunicationObject.Opened {
336 add { InnerChannel.Opened += value; }
337 remove { InnerChannel.Opened -= value; }
339 event EventHandler ICommunicationObject.Closing {
340 add { InnerChannel.Closing += value; }
341 remove { InnerChannel.Closing -= value; }
343 event EventHandler ICommunicationObject.Closed {
344 add { InnerChannel.Closed += value; }
345 remove { InnerChannel.Closed -= value; }
347 event EventHandler ICommunicationObject.Faulted {
348 add { InnerChannel.Faulted += value; }
349 remove { InnerChannel.Faulted -= value; }
359 class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs
361 internal InvokeAsyncCompletedEventArgs (object [] results, Exception error, bool cancelled, object userState)
362 : base (error, cancelled, userState)
367 public object [] Results { get; private set; }
375 class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel where T : class
377 ClientBase<T> client;
378 ClientRuntimeChannel inner_channel;
380 protected ChannelBase (ClientBase<T> client)
382 this.client = client;
385 internal ClientRuntimeChannel Inner {
387 if (inner_channel == null)
388 inner_channel = new ClientRuntimeChannel (client.Endpoint.CreateRuntime (), client.ChannelFactory);
389 return inner_channel;
394 public object Invoke (string methodName, object [] args)
396 var cd = client.Endpoint.Contract;
397 var od = cd.Operations.Find (methodName);
399 throw new ArgumentException (String.Format ("Operation '{0}' not found in the service contract '{1}' in namespace '{2}'", methodName, cd.Name, cd.Namespace));
400 return Inner.Process (od.SyncMethod, methodName, args);
404 protected IAsyncResult BeginInvoke (string methodName, object [] args, AsyncCallback callback, object state)
406 var cd = client.Endpoint.Contract;
407 var od = cd.Operations.Find (methodName);
409 throw new ArgumentException (String.Format ("Operation '{0}' not found in the service contract '{1}' in namespace '{2}'", methodName, cd.Name, cd.Namespace));
410 return Inner.BeginProcess (od.BeginMethod, methodName, args, callback, state);
413 protected object EndInvoke (string methodName, object [] args, IAsyncResult result)
415 var cd = client.Endpoint.Contract;
416 var od = cd.Operations.Find (methodName);
418 throw new ArgumentException (String.Format ("Operation '{0}' not found in the service contract '{1}' in namespace '{2}'", methodName, cd.Name, cd.Namespace));
419 return Inner.EndProcess (od.EndMethod, methodName, args, result);
422 #region ICommunicationObject
424 IAsyncResult ICommunicationObject.BeginClose (AsyncCallback callback, object state)
426 return Inner.BeginClose (callback, state);
429 IAsyncResult ICommunicationObject.BeginClose (TimeSpan timeout, AsyncCallback callback, object state)
431 return Inner.BeginClose (timeout, callback, state);
434 void ICommunicationObject.Close ()
439 void ICommunicationObject.Close (TimeSpan timeout)
441 Inner.Close (timeout);
444 IAsyncResult ICommunicationObject.BeginOpen (AsyncCallback callback, object state)
446 return Inner.BeginOpen (callback, state);
449 IAsyncResult ICommunicationObject.BeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
451 return Inner.BeginOpen (timeout, callback, state);
454 void ICommunicationObject.Open ()
459 void ICommunicationObject.Open (TimeSpan timeout)
461 Inner.Open (timeout);
464 void ICommunicationObject.Abort ()
469 void ICommunicationObject.EndClose (IAsyncResult result)
471 Inner.EndClose (result);
474 void ICommunicationObject.EndOpen (IAsyncResult result)
476 Inner.EndOpen (result);
479 CommunicationState ICommunicationObject.State {
480 get { return Inner.State; }
483 event EventHandler ICommunicationObject.Opened {
484 add { Inner.Opened += value; }
485 remove { Inner.Opened -= value; }
488 event EventHandler ICommunicationObject.Opening {
489 add { Inner.Opening += value; }
490 remove { Inner.Opening -= value; }
493 event EventHandler ICommunicationObject.Closed {
494 add { Inner.Closed += value; }
495 remove { Inner.Closed -= value; }
498 event EventHandler ICommunicationObject.Closing {
499 add { Inner.Closing += value; }
500 remove { Inner.Closing -= value; }
503 event EventHandler ICommunicationObject.Faulted {
504 add { Inner.Faulted += value; }
505 remove { Inner.Faulted -= value; }
510 #region IClientChannel
512 public bool AllowInitializationUI {
513 get { return Inner.AllowInitializationUI; }
514 set { Inner.AllowInitializationUI = value; }
517 public bool DidInteractiveInitialization {
518 get { return Inner.DidInteractiveInitialization; }
522 get { return Inner.Via; }
525 public IAsyncResult BeginDisplayInitializationUI (
526 AsyncCallback callback, object state)
528 return Inner.BeginDisplayInitializationUI (callback, state);
531 public void EndDisplayInitializationUI (
534 Inner.EndDisplayInitializationUI (result);
537 public void DisplayInitializationUI ()
539 Inner.DisplayInitializationUI ();
542 public void Dispose ()
547 public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived {
548 add { Inner.UnknownMessageReceived += value; }
549 remove { Inner.UnknownMessageReceived -= value; }
554 #region IContextChannel
557 public bool AllowOutputBatching {
558 get { return Inner.AllowOutputBatching; }
560 set { Inner.AllowOutputBatching = value; }
564 public IInputSession InputSession {
565 get { return Inner.InputSession; }
568 public EndpointAddress LocalAddress {
569 get { return Inner.LocalAddress; }
573 public TimeSpan OperationTimeout {
574 get { return Inner.OperationTimeout; }
575 set { Inner.OperationTimeout = value; }
579 public IOutputSession OutputSession {
580 get { return Inner.OutputSession; }
583 public EndpointAddress RemoteAddress {
584 get { return Inner.RemoteAddress; }
588 public string SessionId {
589 get { return Inner.SessionId; }
594 #region IRequestChannel
596 IAsyncResult IRequestChannel.BeginRequest (Message message, AsyncCallback callback, object state)
598 return ((IRequestChannel) this).BeginRequest (message, client.Endpoint.Binding.SendTimeout, callback, state);
601 IAsyncResult IRequestChannel.BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
603 return Inner.BeginRequest (message, timeout, callback, state);
606 Message IRequestChannel.EndRequest (IAsyncResult result)
608 return Inner.EndRequest (result);
611 Message IRequestChannel.Request (Message message)
613 return ((IRequestChannel) this).Request (message, client.Endpoint.Binding.SendTimeout);
616 Message IRequestChannel.Request (Message message, TimeSpan timeout)
618 return Inner.Request (message, timeout);
621 EndpointAddress IRequestChannel.RemoteAddress {
622 get { return client.Endpoint.Address; }
625 Uri IRequestChannel.Via {
631 #region IOutputChannel
633 IAsyncResult IOutputChannel.BeginSend (Message message, AsyncCallback callback, object state)
635 return ((IOutputChannel) this).BeginSend (message, client.Endpoint.Binding.SendTimeout, callback, state);
638 IAsyncResult IOutputChannel.BeginSend (Message message, TimeSpan timeout, AsyncCallback callback, object state)
640 return Inner.BeginSend (message, timeout, callback, state);
643 void IOutputChannel.EndSend (IAsyncResult result)
645 Inner.EndSend (result);
648 void IOutputChannel.Send (Message message)
650 ((IOutputChannel) this).Send (message, client.Endpoint.Binding.SendTimeout);
653 void IOutputChannel.Send (Message message, TimeSpan timeout)
655 Inner.Send (message, timeout);
660 IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions {
661 get { return Inner.Extensions; }
664 TProperty IChannel.GetProperty<TProperty> ()
666 return Inner.GetProperty<TProperty> ();