2009-02-26 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / ClientBase.cs
1 //
2 // generic ClientBase.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2005-2006 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.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;
36
37 namespace System.ServiceModel
38 {
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
42         {
43                 static InstanceContext initialContxt = new InstanceContext (null);
44 #if NET_2_1
45                 static readonly PropertyInfo dispatcher_main_property;
46                 static readonly MethodInfo dispatcher_begin_invoke_method;
47
48                 static ClientBase ()
49                 {
50                         foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies ()) {
51                                 if (ass.GetName ().Name != "System.Windows")
52                                         continue;
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 [])});
56                         }
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");
61                 }
62 #endif
63
64                 ChannelFactory<TChannel> factory;
65                 ChannelBase<TChannel> inner_channel;
66                 CommunicationState state;
67
68                 protected delegate IAsyncResult BeginOperationDelegate (object[] inValues, AsyncCallback asyncCallback, object state);
69                 protected delegate object[] EndOperationDelegate (IAsyncResult result);
70
71                 protected ClientBase ()
72                         : this (initialContxt)
73                 {
74                 }
75
76                 protected ClientBase (string endpointConfigurationName)
77                         : this (initialContxt, endpointConfigurationName)
78                 {
79                 }
80
81                 protected ClientBase (Binding binding, EndpointAddress remoteAddress)
82                         : this (initialContxt, binding, remoteAddress)
83                 {
84                 }
85
86                 protected ClientBase (string endpointConfigurationName, EndpointAddress remoteAddress)
87                         : this (initialContxt, endpointConfigurationName, remoteAddress)
88                 {
89                 }
90
91                 protected ClientBase (string endpointConfigurationName, string remoteAddress)
92                         : this (initialContxt, endpointConfigurationName, remoteAddress)
93                 {
94                 }
95
96                 protected ClientBase (InstanceContext instance)
97                         : this (instance, "*")
98                 {
99                 }
100
101                 protected ClientBase (InstanceContext instance, string endpointConfigurationName)
102                 {
103                         if (instance == null)
104                                 throw new ArgumentNullException ("instanceContext");
105                         if (endpointConfigurationName == null)
106                                 throw new ArgumentNullException ("endpointConfigurationName");
107
108                         Initialize (instance, endpointConfigurationName, null);
109                 }
110
111                 protected ClientBase (InstanceContext instance,
112                         string endpointConfigurationName, EndpointAddress remoteAddress)
113                 {
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");
120
121                         Initialize (instance, endpointConfigurationName, remoteAddress);
122                 }
123
124                 protected ClientBase (InstanceContext instance,
125                         string endpointConfigurationName, string remoteAddress)
126                 {
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");
133
134                         Initialize (instance, endpointConfigurationName, new EndpointAddress (remoteAddress));
135                 }
136
137                 protected ClientBase (InstanceContext instance,
138                         Binding binding, EndpointAddress remoteAddress)
139                 {
140                         if (instance == null)
141                                 throw new ArgumentNullException ("instanceContext");
142                         if (binding == null)
143                                 throw new ArgumentNullException ("binding");
144                         if (remoteAddress == null)
145                                 throw new ArgumentNullException ("remoteAddress");
146
147                         Initialize (instance, binding, remoteAddress);
148                 }
149
150                 internal ClientBase (ChannelFactory<TChannel> factory)
151                 {
152                         ChannelFactory = factory;
153                 }
154
155                 void Initialize (InstanceContext instance,
156                         string endpointConfigurationName, EndpointAddress remoteAddress)
157                 {
158                         ChannelFactory = new ChannelFactory<TChannel> (endpointConfigurationName, remoteAddress);
159                 }
160
161                 void Initialize (InstanceContext instance,
162                         Binding binding, EndpointAddress remoteAddress)
163                 {
164                         ChannelFactory = new ChannelFactory<TChannel> (binding, remoteAddress);
165                 }
166
167                 public ChannelFactory<TChannel> ChannelFactory {
168                         get { return factory; }
169                         private set {
170                                 factory = value;
171                                 factory.OwnerClientBase = this;
172                         }
173                 }
174
175 #if !NET_2_1
176                 public ClientCredentials ClientCredentials {
177                         get { return ChannelFactory.Credentials; }
178                 }
179 #endif
180
181                 public ServiceEndpoint Endpoint {
182                         get { return factory.Endpoint; }
183                 }
184
185                 public IClientChannel InnerChannel {
186                         get {
187                                 if (inner_channel == null)
188                                         // FIXME: "factory." might be extraneous.
189                                         inner_channel = (ChannelBase<TChannel>) (object) ChannelFactory.CreateChannel ();
190                                 return inner_channel;
191                         }
192                 }
193
194                 protected TChannel Channel {
195                         get { return (TChannel) (object) InnerChannel; }
196                 }
197
198                 public CommunicationState State {
199                         get { return InnerChannel.State; }
200                 }
201
202                 public void Abort ()
203                 {
204                         InnerChannel.Abort ();
205                 }
206
207                 public void Close ()
208                 {
209                         InnerChannel.Close ();
210                 }
211
212                 public void DisplayInitializationUI ()
213                 {
214                         InnerChannel.DisplayInitializationUI ();
215                 }
216
217 #if NET_2_1
218                 protected T GetDefaultValueForInitialization<T> ()
219                 {
220                         return default (T);
221                 }
222
223                 //IAsyncResult delegate_async;
224
225                 void RunCompletedCallback (SendOrPostCallback callback, InvokeAsyncCompletedEventArgs args)
226                 {
227                         object dispatcher = dispatcher_main_property.GetValue (null, null);
228                         if (dispatcher == null) {
229                                 callback (args);
230                                 return;
231                         }
232                         EventHandler a = delegate { callback (args); };
233                         dispatcher_begin_invoke_method.Invoke (dispatcher, new object [] {a, new object [] {this, new EventArgs ()}});
234                 }
235
236                 protected void InvokeAsync (BeginOperationDelegate beginOperationDelegate,
237                         object [] inValues, EndOperationDelegate endOperationDelegate,
238                         SendOrPostCallback operationCompletedCallback, object userState)
239                 {
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");
246
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
251                                 try {
252                                         results = endOperationDelegate (ar);
253                                 } catch (Exception ex) {
254                                         error = ex;
255                                 }
256                                 try {
257                                         if (operationCompletedCallback != null)
258                                                 RunCompletedCallback (operationCompletedCallback, new InvokeAsyncCompletedEventArgs (results, error, cancelled, userState));
259                                 } catch (Exception ex) {
260                                         Console.WriteLine ("Exception during operationCompletedCallback" + ex);
261                                         throw;
262                                 }
263                                 Console.WriteLine ("System.ServiceModel.ClientBase<TChannel>: web service invocation is successfully done.");
264                         };
265                         begin_async_result = beginOperationDelegate (inValues, cb, userState);
266                 }
267                 IAsyncResult begin_async_result;
268 #endif
269                 
270                 void IDisposable.Dispose ()
271                 {
272                         Close ();
273                 }
274
275                 protected virtual TChannel CreateChannel ()
276                 {
277                         return ChannelFactory.CreateChannel ();
278                 }
279
280                 public void Open ()
281                 {
282                         InnerChannel.Open ();
283                 }
284
285                 #region ICommunicationObject implementation
286
287                 IAsyncResult ICommunicationObject.BeginOpen (
288                         AsyncCallback callback, object state)
289                 {
290                         return InnerChannel.BeginOpen (callback, state);
291                 }
292
293                 IAsyncResult ICommunicationObject.BeginOpen (
294                         TimeSpan timeout, AsyncCallback callback, object state)
295                 {
296                         return InnerChannel.BeginOpen (timeout, callback, state);
297                 }
298
299                 void ICommunicationObject.EndOpen (IAsyncResult result)
300                 {
301                         InnerChannel.EndOpen (result);
302                 }
303
304                 IAsyncResult ICommunicationObject.BeginClose (
305                         AsyncCallback callback, object state)
306                 {
307                         return InnerChannel.BeginClose (callback, state);
308                 }
309
310                 IAsyncResult ICommunicationObject.BeginClose (
311                         TimeSpan timeout, AsyncCallback callback, object state)
312                 {
313                         return InnerChannel.BeginClose (timeout, callback, state);
314                 }
315
316                 void ICommunicationObject.EndClose (IAsyncResult result)
317                 {
318                         InnerChannel.EndClose (result);
319                 }
320
321                 void ICommunicationObject.Close (TimeSpan timeout)
322                 {
323                         InnerChannel.Close (timeout);
324                 }
325
326                 void ICommunicationObject.Open (TimeSpan timeout)
327                 {
328                         InnerChannel.Open (timeout);
329                 }
330
331                 event EventHandler ICommunicationObject.Opening {
332                         add { InnerChannel.Opening += value; }
333                         remove { InnerChannel.Opening -= value; }
334                 }
335                 event EventHandler ICommunicationObject.Opened {
336                         add { InnerChannel.Opened += value; }
337                         remove { InnerChannel.Opened -= value; }
338                 }
339                 event EventHandler ICommunicationObject.Closing {
340                         add { InnerChannel.Closing += value; }
341                         remove { InnerChannel.Closing -= value; }
342                 }
343                 event EventHandler ICommunicationObject.Closed {
344                         add { InnerChannel.Closed += value; }
345                         remove { InnerChannel.Closed -= value; }
346                 }
347                 event EventHandler ICommunicationObject.Faulted {
348                         add { InnerChannel.Faulted += value; }
349                         remove { InnerChannel.Faulted -= value; }
350                 }
351
352                 #endregion
353
354 #if NET_2_1
355                 protected
356 #else
357                 internal
358 #endif
359                 class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs
360                 {
361                         internal InvokeAsyncCompletedEventArgs (object [] results, Exception error, bool cancelled, object userState)
362                                 : base (error, cancelled, userState)
363                         {
364                                 Results = results;
365                         }
366
367                         public object [] Results { get; private set; }
368                 }
369
370 #if NET_2_1
371                 protected internal
372 #else
373                 internal
374 #endif
375                 class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel where T : class
376                 {
377                         ClientBase<T> client;
378                         ClientRuntimeChannel inner_channel;
379
380                         protected ChannelBase (ClientBase<T> client)
381                         {
382                                 this.client = client;
383                         }
384
385                         internal ClientRuntimeChannel Inner {
386                                 get {
387                                         if (inner_channel == null)
388                                                 inner_channel = new ClientRuntimeChannel (client.Endpoint.CreateRuntime (), client.ChannelFactory);
389                                         return inner_channel;
390                                 }
391                         }
392
393 #if !NET_2_1
394                         public object Invoke (string methodName, object [] args)
395                         {
396                                 var cd = client.Endpoint.Contract;
397                                 var od = cd.Operations.Find (methodName);
398                                 if (od == null)
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);
401                         }
402 #endif
403
404                         protected IAsyncResult BeginInvoke (string methodName, object [] args, AsyncCallback callback, object state)
405                         {
406                                 var cd = client.Endpoint.Contract;
407                                 var od = cd.Operations.Find (methodName);
408                                 if (od == null)
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);
411                         }
412
413                         protected object EndInvoke (string methodName, object [] args, IAsyncResult result)
414                         {
415                                 var cd = client.Endpoint.Contract;
416                                 var od = cd.Operations.Find (methodName);
417                                 if (od == null)
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);
420                         }
421
422                         #region ICommunicationObject
423
424                         IAsyncResult ICommunicationObject.BeginClose (AsyncCallback callback, object state)
425                         {
426                                 return Inner.BeginClose (callback, state);
427                         }
428
429                         IAsyncResult ICommunicationObject.BeginClose (TimeSpan timeout, AsyncCallback callback, object state)
430                         {
431                                 return Inner.BeginClose (timeout, callback, state);
432                         }
433
434                         void ICommunicationObject.Close ()
435                         {
436                                 Inner.Close ();
437                         }
438
439                         void ICommunicationObject.Close (TimeSpan timeout)
440                         {
441                                 Inner.Close (timeout);
442                         }
443
444                         IAsyncResult ICommunicationObject.BeginOpen (AsyncCallback callback, object state)
445                         {
446                                 return Inner.BeginOpen (callback, state);
447                         }
448
449                         IAsyncResult ICommunicationObject.BeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
450                         {
451                                 return Inner.BeginOpen (timeout, callback, state);
452                         }
453
454                         void ICommunicationObject.Open ()
455                         {
456                                 Inner.Open ();
457                         }
458
459                         void ICommunicationObject.Open (TimeSpan timeout)
460                         {
461                                 Inner.Open (timeout);
462                         }
463
464                         void ICommunicationObject.Abort ()
465                         {
466                                 Inner.Abort ();
467                         }
468
469                         void ICommunicationObject.EndClose (IAsyncResult result)
470                         {
471                                 Inner.EndClose (result);
472                         }
473
474                         void ICommunicationObject.EndOpen (IAsyncResult result)
475                         {
476                                 Inner.EndOpen (result);
477                         }
478
479                         CommunicationState ICommunicationObject.State {
480                                 get { return Inner.State; }
481                         }
482
483                         event EventHandler ICommunicationObject.Opened {
484                                 add { Inner.Opened += value; }
485                                 remove { Inner.Opened -= value; }
486                         }
487
488                         event EventHandler ICommunicationObject.Opening {
489                                 add { Inner.Opening += value; }
490                                 remove { Inner.Opening -= value; }
491                         }
492
493                         event EventHandler ICommunicationObject.Closed {
494                                 add { Inner.Closed += value; }
495                                 remove { Inner.Closed -= value; }
496                         }
497
498                         event EventHandler ICommunicationObject.Closing {
499                                 add { Inner.Closing += value; }
500                                 remove { Inner.Closing -= value; }
501                         }
502
503                         event EventHandler ICommunicationObject.Faulted {
504                                 add { Inner.Faulted += value; }
505                                 remove { Inner.Faulted -= value; }
506                         }
507
508                         #endregion
509
510                         #region IClientChannel
511
512                         public bool AllowInitializationUI {
513                                 get { return Inner.AllowInitializationUI; }
514                                 set { Inner.AllowInitializationUI = value; }
515                         }
516
517                         public bool DidInteractiveInitialization {
518                                 get { return Inner.DidInteractiveInitialization; }
519                         }
520
521                         public Uri Via {
522                                 get { return Inner.Via; }
523                         }
524
525                         public IAsyncResult BeginDisplayInitializationUI (
526                                 AsyncCallback callback, object state)
527                         {
528                                 return Inner.BeginDisplayInitializationUI (callback, state);
529                         }
530
531                         public void EndDisplayInitializationUI (
532                                 IAsyncResult result)
533                         {
534                                 Inner.EndDisplayInitializationUI (result);
535                         }
536
537                         public void DisplayInitializationUI ()
538                         {
539                                 Inner.DisplayInitializationUI ();
540                         }
541
542                         public void Dispose ()
543                         {
544                                 Inner.Dispose ();
545                         }
546
547                         public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived {
548                                 add { Inner.UnknownMessageReceived += value; }
549                                 remove { Inner.UnknownMessageReceived -= value; }
550                         }
551
552                         #endregion
553
554                         #region IContextChannel
555
556                         [MonoTODO]
557                         public bool AllowOutputBatching {
558                                 get { return Inner.AllowOutputBatching; }
559
560                                 set { Inner.AllowOutputBatching = value; }
561                         }
562
563                         [MonoTODO]
564                         public IInputSession InputSession {
565                                 get { return Inner.InputSession; }
566                         }
567
568                         public EndpointAddress LocalAddress {
569                                 get { return Inner.LocalAddress; }
570                         }
571
572                         [MonoTODO]
573                         public TimeSpan OperationTimeout {
574                                 get { return Inner.OperationTimeout; }
575                                 set { Inner.OperationTimeout = value; }
576                         }
577
578                         [MonoTODO]
579                         public IOutputSession OutputSession {
580                                 get { return Inner.OutputSession; }
581                         }
582
583                         public EndpointAddress RemoteAddress {
584                                 get { return Inner.RemoteAddress; }
585                         }
586
587                         [MonoTODO]
588                         public string SessionId {
589                                 get { return Inner.SessionId; }
590                         }
591
592                         #endregion
593
594                         #region IRequestChannel
595
596                         IAsyncResult IRequestChannel.BeginRequest (Message message, AsyncCallback callback, object state)
597                         {
598                                 return ((IRequestChannel) this).BeginRequest (message, client.Endpoint.Binding.SendTimeout, callback, state);
599                         }
600
601                         IAsyncResult IRequestChannel.BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
602                         {
603                                 return Inner.BeginRequest (message, timeout, callback, state);
604                         }
605
606                         Message IRequestChannel.EndRequest (IAsyncResult result)
607                         {
608                                 return Inner.EndRequest (result);
609                         }
610
611                         Message IRequestChannel.Request (Message message)
612                         {
613                                 return ((IRequestChannel) this).Request (message, client.Endpoint.Binding.SendTimeout);
614                         }
615
616                         Message IRequestChannel.Request (Message message, TimeSpan timeout)
617                         {
618                                 return Inner.Request (message, timeout);
619                         }
620
621                         EndpointAddress IRequestChannel.RemoteAddress {
622                                 get { return client.Endpoint.Address; }
623                         }
624
625                         Uri IRequestChannel.Via {
626                                 get { return Via; }
627                         }
628
629                         #endregion
630
631                         #region IOutputChannel
632
633                         IAsyncResult IOutputChannel.BeginSend (Message message, AsyncCallback callback, object state)
634                         {
635                                 return ((IOutputChannel) this).BeginSend (message, client.Endpoint.Binding.SendTimeout, callback, state);
636                         }
637
638                         IAsyncResult IOutputChannel.BeginSend (Message message, TimeSpan timeout, AsyncCallback callback, object state)
639                         {
640                                 return Inner.BeginSend (message, timeout, callback, state);
641                         }
642
643                         void IOutputChannel.EndSend (IAsyncResult result)
644                         {
645                                 Inner.EndSend (result);
646                         }
647
648                         void IOutputChannel.Send (Message message)
649                         {
650                                 ((IOutputChannel) this).Send (message, client.Endpoint.Binding.SendTimeout);
651                         }
652
653                         void IOutputChannel.Send (Message message, TimeSpan timeout)
654                         {
655                                 Inner.Send (message, timeout);
656                         }
657
658                         #endregion
659
660                         IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions {
661                                 get { return Inner.Extensions; }
662                         }
663
664                         TProperty IChannel.GetProperty<TProperty> ()
665                         {
666                                 return Inner.GetProperty<TProperty> ();
667                         }
668                 }
669         }
670 }