Merge branch 'master' of github.com:mono/mono
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / ServiceHostBase.cs
1 //
2 // ServiceHostBase.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.Collections.ObjectModel;
31 using System.Linq;
32 using System.ServiceModel.Channels;
33 using System.ServiceModel.Configuration;
34 using System.ServiceModel.Description;
35 using System.ServiceModel.Dispatcher;
36 using System.ServiceModel.Security;
37 using System.Reflection;
38 using System.Threading;
39
40 namespace System.ServiceModel
41 {
42         public abstract partial class ServiceHostBase
43                 : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
44         {
45                 // It is used for mapping a ServiceHostBase to HttpChannelListener precisely.
46                 internal static ServiceHostBase CurrentServiceHostHack;
47
48                 ServiceCredentials credentials;
49                 ServiceDescription description;
50                 UriSchemeKeyedCollection base_addresses;
51                 TimeSpan open_timeout, close_timeout, instance_idle_timeout;
52                 List<InstanceContext> contexts;
53                 ReadOnlyCollection<InstanceContext> exposed_contexts;
54                 ChannelDispatcherCollection channel_dispatchers;
55                 IDictionary<string,ContractDescription> contracts;
56                 int flow_limit = int.MaxValue;
57                 IExtensionCollection<ServiceHostBase> extensions;
58
59                 protected ServiceHostBase ()
60                 {
61                         open_timeout = DefaultOpenTimeout;
62                         close_timeout = DefaultCloseTimeout;
63
64                         credentials = new ServiceCredentials ();
65                         contexts = new List<InstanceContext> ();
66                         exposed_contexts = new ReadOnlyCollection<InstanceContext> (contexts);
67                         channel_dispatchers = new ChannelDispatcherCollection (this);
68                 }
69
70                 public event EventHandler<UnknownMessageReceivedEventArgs>
71                         UnknownMessageReceived;
72
73                 internal void OnUnknownMessageReceived (Message message)
74                 {
75                         if (UnknownMessageReceived != null)
76                                 UnknownMessageReceived (this, new UnknownMessageReceivedEventArgs (message));
77                         else
78                                 // FIXME: better be logged
79                                 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));
80                 }
81
82                 public ReadOnlyCollection<Uri> BaseAddresses {
83                         get {
84                                 if (base_addresses == null)
85                                         base_addresses = new UriSchemeKeyedCollection ();
86                                 return new ReadOnlyCollection<Uri> (base_addresses.InternalItems);
87                         }
88                 }
89
90                 internal Uri CreateUri (string scheme, Uri relativeUri)
91                 {
92                         Uri baseUri = base_addresses.Contains (scheme) ? base_addresses [scheme] : null;
93
94                         if (relativeUri == null)
95                                 return baseUri;
96                         if (relativeUri.IsAbsoluteUri)
97                                 return relativeUri;
98                         if (baseUri == null)
99                                 return null;
100                         var s = relativeUri.ToString ();
101                         if (s.Length == 0)
102                                 return baseUri;
103                         var l = baseUri.LocalPath;
104                         var r = relativeUri.ToString ();
105
106                         if (l.Length > 0 && l [l.Length - 1] != '/' && r [0] != '/')
107                                 return new Uri (String.Concat (baseUri.ToString (), "/", r));
108                         else
109                                 return new Uri (String.Concat (baseUri.ToString (), r));
110                 }
111
112                 public ChannelDispatcherCollection ChannelDispatchers {
113                         get { return channel_dispatchers; }
114                 }
115
116                 public ServiceAuthorizationBehavior Authorization {
117                         get;
118                         private set;
119                 }
120
121                 public ServiceCredentials Credentials {
122                         get { return credentials; }
123                 }
124
125                 public ServiceDescription Description {
126                         get { return description; }
127                 }
128
129                 protected IDictionary<string,ContractDescription> ImplementedContracts {
130                         get { return contracts; }
131                 }
132
133                 public IExtensionCollection<ServiceHostBase> Extensions {
134                         get {
135                                 if (extensions == null)
136                                         extensions = new ExtensionCollection<ServiceHostBase> (this);
137                                 return extensions;
138                         }
139                 }
140
141                 protected internal override TimeSpan DefaultCloseTimeout {
142                         get { return DefaultCommunicationTimeouts.Instance.CloseTimeout; }
143                 }
144
145                 protected internal override TimeSpan DefaultOpenTimeout {
146                         get { return DefaultCommunicationTimeouts.Instance.OpenTimeout; }
147                 }
148
149                 public TimeSpan CloseTimeout {
150                         get { return close_timeout; }
151                         set { close_timeout = value; }
152                 }
153
154                 public TimeSpan OpenTimeout {
155                         get { return open_timeout; }
156                         set { open_timeout = value; }
157                 }
158
159                 public int ManualFlowControlLimit {
160                         get { return flow_limit; }
161                         set { flow_limit = value; }
162                 }
163
164                 protected void AddBaseAddress (Uri baseAddress)
165                 {
166                         if (base_addresses == null)
167                                 throw new InvalidOperationException ("Base addresses must be added before the service description is initialized");
168                         base_addresses.Add (baseAddress);
169                 }
170
171                 public ServiceEndpoint AddServiceEndpoint (
172                         string implementedContract, Binding binding, string address)
173                 {
174                         return AddServiceEndpoint (implementedContract,
175                                 binding,
176                                 new Uri (address, UriKind.RelativeOrAbsolute));
177                 }
178
179                 public ServiceEndpoint AddServiceEndpoint (
180                         string implementedContract, Binding binding,
181                         string address, Uri listenUri)
182                 {
183                         Uri uri = new Uri (address, UriKind.RelativeOrAbsolute);
184                         return AddServiceEndpoint (
185                                 implementedContract, binding, uri, listenUri);
186                 }
187
188                 public ServiceEndpoint AddServiceEndpoint (
189                         string implementedContract, Binding binding,
190                         Uri address)
191                 {
192                         return AddServiceEndpoint (implementedContract, binding, address, null);
193                 }
194
195                 public ServiceEndpoint AddServiceEndpoint (
196                         string implementedContract, Binding binding,
197                         Uri address, Uri listenUri)
198                 {
199                         EndpointAddress ea = new EndpointAddress (BuildAbsoluteUri (address, binding));
200                         ContractDescription cd = GetContract (implementedContract, binding.Namespace == "http://schemas.microsoft.com/ws/2005/02/mex/bindings");
201                         if (cd == null)
202                                 throw new InvalidOperationException (String.Format ("Contract '{0}' was not found in the implemented contracts in this service host.", implementedContract));
203                         return AddServiceEndpointCore (cd, binding, ea, listenUri);
204                 }
205
206 #if NET_4_0
207                 public virtual void AddServiceEndpoint (ServiceEndpoint endpoint)
208                 {
209                         if (endpoint == null)
210                                 throw new ArgumentNullException ("endpoint");
211
212                         ThrowIfDisposedOrImmutable ();
213
214                         if (endpoint.Address == null)
215                                 throw new ArgumentException ("Address on the argument endpoint is null");
216                         if (endpoint.Contract == null)
217                                 throw new ArgumentException ("Contract on the argument endpoint is null");
218                         if (endpoint.Binding == null)
219                                 throw new ArgumentException ("Binding on the argument endpoint is null");
220
221                         if (!ImplementedContracts.Values.Any (cd => cd.ContractType == endpoint.Contract.ContractType) &&
222                             endpoint.Binding.Namespace != "http://schemas.microsoft.com/ws/2005/02/mex/bindings") // special case
223                                 throw new InvalidOperationException (String.Format ("Contract '{0}' is not implemented in this service '{1}'", endpoint.Contract.Name, Description.Name));
224
225                         Description.Endpoints.Add (endpoint);
226                 }
227 #endif
228
229                 Type PopulateType (string typeName)
230                 {
231                         Type type = Type.GetType (typeName);
232                         if (type != null)
233                                 return type;
234                         foreach (ContractDescription cd in ImplementedContracts.Values) {
235                                 type = cd.ContractType.Assembly.GetType (typeName);
236                                 if (type != null)
237                                         return type;
238                         }
239                         return null;
240                 }
241
242                 ContractDescription mex_contract, help_page_contract;
243
244                 ContractDescription GetContract (string name, bool mexBinding)
245                 {
246                         // FIXME: not sure if they should really be special cases.
247                         switch (name) {
248                         case "IHttpGetHelpPageAndMetadataContract":
249                                 if (help_page_contract == null)
250                                         help_page_contract = ContractDescription.GetContract (typeof (IHttpGetHelpPageAndMetadataContract));
251                                 return help_page_contract;
252                         case "IMetadataExchange":
253                                 // this is certainly looking special (or we may 
254                                 // be missing something around ServiceMetadataExtension).
255                                 // It seems .NET WCF has some "infrastructure"
256                                 // endpoints. .NET ServiceHost fails to Open()
257                                 // if it was added only IMetadataExchange 
258                                 // endpoint (and you'll see the word
259                                 // "infrastructure" in the exception message).
260                                 if (mexBinding && Description.Behaviors.Find<ServiceMetadataBehavior> () == null)
261                                         break;
262                                 if (mex_contract == null)
263                                         mex_contract = ContractDescription.GetContract (typeof (IMetadataExchange));
264                                 return mex_contract;
265                         }
266
267                         Type type = PopulateType (name);
268                         if (type == null)
269                                 return null;
270
271                         foreach (ContractDescription cd in ImplementedContracts.Values) {
272                                 // This check is a negative side effect of the above match-by-name design.
273                                 if (cd.ContractType == typeof (IMetadataExchange))
274                                         continue;
275
276                                 if (cd.ContractType == type ||
277                                     cd.ContractType.IsSubclassOf (type) ||
278                                     type.IsInterface && cd.ContractType.GetInterface (type.FullName) == type)
279                                         return cd;
280                         }
281                         return null;
282                 }
283
284                 internal Uri BuildAbsoluteUri (Uri address, Binding binding)
285                 {
286                         if (!address.IsAbsoluteUri) {
287                                 // Find a Base address with matching scheme,
288                                 // and build new absolute address
289                                 if (!base_addresses.Contains (binding.Scheme))
290                                         throw new InvalidOperationException (String.Format ("Could not find base address that matches Scheme {0} for endpoint {1}", binding.Scheme, binding.Name));
291
292                                 Uri baseaddr = base_addresses [binding.Scheme];
293
294                                 if (!baseaddr.AbsoluteUri.EndsWith ("/") && address.OriginalString.Length > 0) // with empty URI it should not add '/' to possible file name of the absolute URI
295                                         baseaddr = new Uri (baseaddr.AbsoluteUri + "/");
296                                 address = new Uri (baseaddr, address);
297                         }
298                         return address;
299                 }
300
301                 internal ServiceEndpoint AddServiceEndpointCore (
302                         ContractDescription cd, Binding binding, EndpointAddress address, Uri listenUri)
303                 {
304                         if (listenUri != null)
305                                 listenUri = BuildAbsoluteUri (listenUri, binding);
306
307                         foreach (ServiceEndpoint e in Description.Endpoints)
308                                 if (e.Contract == cd && e.Binding == binding && e.Address == address && e.ListenUri.Equals (listenUri))
309                                         return e;
310                         ServiceEndpoint se = new ServiceEndpoint (cd, binding, address);
311                         // FIXME: should we reject relative ListenUri?
312                         se.ListenUri = listenUri ?? address.Uri;
313                         Description.Endpoints.Add (se);
314                         return se;
315                 }
316
317                 protected virtual void ApplyConfiguration ()
318                 {
319                         if (Description == null)
320                                 throw new InvalidOperationException ("ApplyConfiguration requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation");
321
322                         ServiceElement service = GetServiceElement ();
323                         
324                         if (service != null)
325                                 ApplyServiceElement (service);
326
327                         // TODO: consider commonBehaviors here
328
329                         // ensure ServiceAuthorizationBehavior
330                         Authorization = Description.Behaviors.Find<ServiceAuthorizationBehavior> ();
331                         if (Authorization == null) {
332                                 Authorization = new ServiceAuthorizationBehavior ();
333                                 Description.Behaviors.Add (Authorization);
334                         }
335
336                         // ensure ServiceDebugBehavior
337                         ServiceDebugBehavior debugBehavior = Description.Behaviors.Find<ServiceDebugBehavior> ();
338                         if (debugBehavior == null) {
339                                 debugBehavior = new ServiceDebugBehavior ();
340                                 Description.Behaviors.Add (debugBehavior);
341                         }
342                 }
343                 
344                 void ApplyServiceElement (ServiceElement service)
345                 {
346                         //base addresses
347                         HostElement host = service.Host;
348                         foreach (BaseAddressElement baseAddress in host.BaseAddresses) {
349                                 AddBaseAddress (new Uri (baseAddress.BaseAddress));
350                         }
351
352                         // behaviors
353                         ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors [service.BehaviorConfiguration];
354                         if (behavior != null) {
355                                 foreach (var bxe in behavior) {
356                                         IServiceBehavior b = (IServiceBehavior) bxe.CreateBehavior ();
357                                         Description.Behaviors.Add (b);
358                                 }
359                         }
360                         else if (!String.IsNullOrEmpty (service.BehaviorConfiguration))
361                                 throw new ArgumentException (String.Format ("Service behavior configuration '{0}' was not found", service.BehaviorConfiguration));
362
363                         // services
364                         foreach (ServiceEndpointElement endpoint in service.Endpoints) {
365                                 ServiceEndpoint se;
366
367 #if NET_4_0
368                                 var binding = String.IsNullOrEmpty (endpoint.Binding) ? null : ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
369
370                                 if (!String.IsNullOrEmpty (endpoint.Kind)) {
371                                         var contract = String.IsNullOrEmpty (endpoint.Contract) ? null : GetContract (endpoint.Contract, false);
372                                         se = ConfigUtil.ConfigureStandardEndpoint (contract, endpoint);
373                                         if (se.Binding == null)
374                                                 se.Binding = binding;
375                                         if (se.Address == null && se.Binding != null) // standard endpoint might have empty address
376                                                 se.Address = new EndpointAddress (CreateUri (se.Binding.Scheme, endpoint.Address));
377                                         if (se.Binding == null && se.Address != null) // look for protocol mapping
378                                                 se.Binding = GetBindingByProtocolMapping (se.Address.Uri);
379
380                                         AddServiceEndpoint (se);
381                                 }
382                                 else {
383                                         if (binding == null && endpoint.Address != null) // look for protocol mapping
384                                                 binding = GetBindingByProtocolMapping (endpoint.Address);
385                                         se = AddServiceEndpoint (endpoint.Contract, binding, endpoint.Address);
386                                 }
387 #else
388                                 var binding = ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
389                                 se = AddServiceEndpoint (endpoint.Contract, binding, endpoint.Address);
390 #endif
391
392                                 // endpoint behaviors
393                                 EndpointBehaviorElement epbehavior = ConfigUtil.BehaviorsSection.EndpointBehaviors [endpoint.BehaviorConfiguration];
394                                 if (epbehavior != null)
395                                         foreach (var bxe in epbehavior) {
396                                                 IEndpointBehavior b = (IEndpointBehavior) bxe.CreateBehavior ();
397                                                 se.Behaviors.Add (b);
398                                 }
399                         }
400                 }
401
402 #if NET_4_0
403                 Binding GetBindingByProtocolMapping (Uri address)
404                 {
405                         ProtocolMappingElement el = ConfigUtil.ProtocolMappingSection.ProtocolMappingCollection [address.Scheme];
406                         if (el == null)
407                                 return null;
408                         return ConfigUtil.CreateBinding (el.Binding, el.BindingConfiguration);
409                 }
410 #endif
411
412                 private ServiceElement GetServiceElement() {
413                         Type serviceType = Description.ServiceType;
414                         if (serviceType == null)
415                                 return null;
416
417                         return ConfigUtil.ServicesSection.Services [serviceType.FullName];                      
418                 }
419
420                 protected abstract ServiceDescription CreateDescription (
421                         out IDictionary<string,ContractDescription> implementedContracts);
422
423                 protected void InitializeDescription (UriSchemeKeyedCollection baseAddresses)
424                 {
425                         this.base_addresses = baseAddresses;
426                         IDictionary<string,ContractDescription> retContracts;
427                         description = CreateDescription (out retContracts);
428                         contracts = retContracts;
429
430                         ApplyConfiguration ();
431                 }
432
433                 protected virtual void InitializeRuntime ()
434                 {
435                         //First validate the description, which should call all behaviors
436                         //'Validate' method.
437                         ValidateDescription ();
438                         
439                         //Build all ChannelDispatchers, one dispatcher per user configured EndPoint.
440                         //We must keep thet ServiceEndpoints as a seperate collection, since the user
441                         //can change the collection in the description during the behaviors events.
442                         ServiceEndpoint[] endPoints = new ServiceEndpoint[Description.Endpoints.Count];
443                         Description.Endpoints.CopyTo (endPoints, 0);
444                         var builder = new DispatcherBuilder (this);
445                         foreach (ServiceEndpoint se in endPoints) {
446                                 var commonParams = new BindingParameterCollection ();
447                                 foreach (IServiceBehavior b in Description.Behaviors)
448                                         b.AddBindingParameters (Description, this, Description.Endpoints, commonParams);
449
450                                 var channel = builder.BuildChannelDispatcher (Description.ServiceType, se, commonParams);
451                                 if (!ChannelDispatchers.Contains (channel))
452                                         ChannelDispatchers.Add (channel);
453                         }
454
455                         //After the ChannelDispatchers are created, and attached to the service host
456                         //Apply dispatching behaviors.
457                         //
458                         // This behavior application order is tricky: first only
459                         // ServiceDebugBehavior and ServiceMetadataBehavior are
460                         // applied, and then other service behaviors are applied.
461                         // It is because those two behaviors adds ChannelDispatchers
462                         // and any other service behaviors must be applied to
463                         // those newly populated dispatchers.
464                         foreach (IServiceBehavior b in Description.Behaviors)
465                                 if (b is ServiceMetadataBehavior || b is ServiceDebugBehavior)
466                                         b.ApplyDispatchBehavior (Description, this);
467                         foreach (IServiceBehavior b in Description.Behaviors)
468                                 if (!(b is ServiceMetadataBehavior || b is ServiceDebugBehavior))
469                                         b.ApplyDispatchBehavior (Description, this);
470
471                         builder.ApplyDispatchBehaviors ();
472                 }
473
474                 private void ValidateDescription ()
475                 {
476                         foreach (IServiceBehavior b in Description.Behaviors)
477                                 b.Validate (Description, this);
478                         foreach (ServiceEndpoint endPoint in Description.Endpoints)
479                                 endPoint.Validate ();
480
481 #if NET_4_0
482                         // In 4.0, it seems that if there is no configured ServiceEndpoint, infer them from the service type.
483                         if (Description.Endpoints.Count == 0) {
484                                 foreach (Type iface in Description.ServiceType.GetInterfaces ())
485                                         if (iface.GetCustomAttributes (typeof (ServiceContractAttribute), true).Length > 0)
486                                                 foreach (var baddr in BaseAddresses) {
487                                                         if (!baddr.IsAbsoluteUri)
488                                                                 continue;
489                                                         var binding = GetBindingByProtocolMapping (baddr);
490                                                         if (binding == null)
491                                                                 continue;
492                                                         AddServiceEndpoint (iface.FullName, binding, baddr);
493                                                 }
494                         }
495 #endif
496
497                         if (Description.Endpoints.FirstOrDefault (e => e.Contract != mex_contract && !e.IsSystemEndpoint) == null)
498                                 throw new InvalidOperationException ("The ServiceHost must have at least one application endpoint (that does not include metadata exchange endpoint) defined by either configuration, behaviors or call to AddServiceEndpoint methods.");
499                 }
500
501                 [MonoTODO]
502                 protected void LoadConfigurationSection (ServiceElement element)
503                 {
504                         ServicesSection services = ConfigUtil.ServicesSection;
505                 }
506
507                 [MonoTODO]
508                 protected override sealed void OnAbort ()
509                 {
510                 }
511
512                 Action<TimeSpan> close_delegate;
513                 Action<TimeSpan> open_delegate;
514
515                 protected override sealed IAsyncResult OnBeginClose (
516                         TimeSpan timeout, AsyncCallback callback, object state)
517                 {
518                         if (close_delegate != null)
519                                 close_delegate = new Action<TimeSpan> (OnClose);
520                         return close_delegate.BeginInvoke (timeout, callback, state);
521                 }
522
523                 protected override sealed IAsyncResult OnBeginOpen (
524                         TimeSpan timeout, AsyncCallback callback, object state)
525                 {
526                         if (open_delegate == null)
527                                 open_delegate = new Action<TimeSpan> (OnOpen);
528                         return open_delegate.BeginInvoke (timeout, callback, state);
529                 }
530
531                 protected override void OnClose (TimeSpan timeout)
532                 {
533                         DateTime start = DateTime.Now;
534                         ReleasePerformanceCounters ();
535                         List<ChannelDispatcherBase> l = new List<ChannelDispatcherBase> (ChannelDispatchers);
536                         foreach (ChannelDispatcherBase e in l) {
537                                 try {
538                                         TimeSpan ts = timeout - (DateTime.Now - start);
539                                         if (ts < TimeSpan.Zero)
540                                                 e.Abort ();
541                                         else
542                                                 e.Close (ts);
543                                 } catch (Exception ex) {
544                                         Console.WriteLine ("ServiceHostBase failed to close the channel dispatcher:");
545                                         Console.WriteLine (ex);
546                                 }
547                         }
548                 }
549
550                 protected override sealed void OnOpen (TimeSpan timeout)
551                 {
552                         DateTime start = DateTime.Now;
553                         InitializeRuntime ();
554                         for (int i = 0; i < ChannelDispatchers.Count; i++) {
555                                 // Skip ServiceMetadataExtension-based one. special case.
556                                 for (int j = i + 1; j < ChannelDispatchers.Count; j++) {
557                                         var cd1 = ChannelDispatchers [i];
558                                         var cd2 = ChannelDispatchers [j];
559                                         if (cd1.IsMex || cd2.IsMex)
560                                                 continue;
561                                         // surprisingly, some ChannelDispatcherBase implementations have null Listener property.
562                                         if (cd1.Listener != null && cd2.Listener != null && cd1.Listener.Uri.Equals (cd2.Listener.Uri))
563                                                 throw new InvalidOperationException ("Two or more service endpoints with different Binding instance are bound to the same listen URI.");
564                                 }
565                         }
566
567                         var waits = new List<ManualResetEvent> ();
568                         foreach (var cd in ChannelDispatchers) {
569                                 var wait = new ManualResetEvent (false);
570                                 cd.Opened += delegate { wait.Set (); };
571                                 waits.Add (wait);
572                                 cd.Open (timeout - (DateTime.Now - start));
573                         }
574
575                         WaitHandle.WaitAll (waits.ToArray ());
576                 }
577
578                 protected override void OnEndClose (IAsyncResult result)
579                 {
580                         if (close_delegate == null)
581                                 throw new InvalidOperationException ("Async close operation has not started");
582                         close_delegate.EndInvoke (result);
583                 }
584
585                 protected override sealed void OnEndOpen (IAsyncResult result)
586                 {
587                         if (open_delegate == null)
588                                 throw new InvalidOperationException ("Aync open operation has not started");
589                         open_delegate.EndInvoke (result);
590                 }
591
592                 protected override void OnOpened ()
593                 {
594                         base.OnOpened ();
595                 }
596
597                 [MonoTODO]
598                 protected void ReleasePerformanceCounters ()
599                 {
600                 }
601
602                 void IDisposable.Dispose ()
603                 {
604                         Close ();
605                 }
606         }
607
608         /// <summary>
609         ///  Builds ChannelDispatchers as appropriate to service the service endpoints. 
610         /// </summary>
611         partial class DispatcherBuilder
612         {
613                 ServiceHostBase host;
614
615                 public DispatcherBuilder (ServiceHostBase host)
616                 {
617                         this.host = host;
618                 }
619
620                 Dictionary<Binding,ChannelDispatcher> built_dispatchers = new Dictionary<Binding,ChannelDispatcher> ();
621                 Dictionary<ServiceEndpoint, EndpointDispatcher> ep_to_dispatcher_ep = new Dictionary<ServiceEndpoint, EndpointDispatcher> ();
622
623                 internal static Action<ChannelDispatcher> ChannelDispatcherSetter;
624
625                 internal ChannelDispatcher BuildChannelDispatcher (Type serviceType, ServiceEndpoint se, BindingParameterCollection commonParams)
626                 {
627                         //Let all behaviors add their binding parameters
628                         AddBindingParameters (commonParams, se);
629                         
630                         // See if there's an existing channel that matches this endpoint
631                         var version = se.Binding.GetProperty<MessageVersion> (commonParams);
632                         if (version == null)
633                                 throw new InvalidOperationException ("At least one BindingElement in the Binding must override GetProperty method to return a MessageVersion and no prior binding element should return null instead of calling GetInnerProperty method on BindingContext.");
634
635                         ChannelDispatcher cd = FindExistingDispatcher (se);
636                         EndpointDispatcher ep;
637                         if (cd != null) {
638                                 ep = cd.InitializeServiceEndpoint (serviceType, se);
639                         } else {
640                                 // Use the binding parameters to build the channel listener and Dispatcher.
641                                 lock (HttpTransportBindingElement.ListenerBuildLock) {
642                                         ServiceHostBase.CurrentServiceHostHack = host;
643                                         IChannelListener lf = BuildListener (se, commonParams);
644                                         cd = new ChannelDispatcher (lf, se.Binding.Name);
645                                         cd.MessageVersion = version;
646                                         if (ChannelDispatcherSetter != null) {
647                                                 ChannelDispatcherSetter (cd);
648                                                 ChannelDispatcherSetter = null;
649                                         }
650                                         ServiceHostBase.CurrentServiceHostHack = null;
651                                 }
652                                 ep = cd.InitializeServiceEndpoint (serviceType, se);
653                                 built_dispatchers.Add (se.Binding, cd);
654                         }
655                         ep_to_dispatcher_ep[se] = ep;
656                         return cd;
657                 }
658                 
659                 ChannelDispatcher FindExistingDispatcher (ServiceEndpoint se)
660                 {
661                         return built_dispatchers.FirstOrDefault ((KeyValuePair<Binding,ChannelDispatcher> p) => se.Binding == p.Key).Value;
662                 }
663
664                 internal void ApplyDispatchBehaviors ()
665                 {
666                         foreach (KeyValuePair<ServiceEndpoint, EndpointDispatcher> val in ep_to_dispatcher_ep)
667                                 ApplyDispatchBehavior (val.Value, val.Key);
668                 }
669                 
670                 private void ApplyDispatchBehavior (EndpointDispatcher ed, ServiceEndpoint endPoint)
671                 {
672                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
673                                 b.ApplyDispatchBehavior (endPoint.Contract, endPoint, ed.DispatchRuntime);
674                         foreach (IEndpointBehavior b in endPoint.Behaviors)
675                                 b.ApplyDispatchBehavior (endPoint, ed);
676                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
677                                 foreach (IOperationBehavior b in operation.Behaviors)
678                                         b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
679                         }
680
681                 }
682
683                 private void AddBindingParameters (BindingParameterCollection commonParams, ServiceEndpoint endPoint) {
684
685                         commonParams.Add (ChannelProtectionRequirements.CreateFromContract (endPoint.Contract));
686
687                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
688                                 b.AddBindingParameters (endPoint.Contract, endPoint, commonParams);
689                         foreach (IEndpointBehavior b in endPoint.Behaviors)
690                                 b.AddBindingParameters (endPoint, commonParams);
691                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
692                                 foreach (IOperationBehavior b in operation.Behaviors)
693                                         b.AddBindingParameters (operation, commonParams);
694                         }
695                 }
696
697                 static IChannelListener BuildListener (ServiceEndpoint se,
698                         BindingParameterCollection pl)
699                 {
700                         Binding b = se.Binding;
701                         if (b.CanBuildChannelListener<IReplySessionChannel> (pl))
702                                 return b.BuildChannelListener<IReplySessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
703                         if (b.CanBuildChannelListener<IReplyChannel> (pl))
704                                 return b.BuildChannelListener<IReplyChannel> (se.ListenUri, "", se.ListenUriMode, pl);
705                         if (b.CanBuildChannelListener<IInputSessionChannel> (pl))
706                                 return b.BuildChannelListener<IInputSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
707                         if (b.CanBuildChannelListener<IInputChannel> (pl))
708                                 return b.BuildChannelListener<IInputChannel> (se.ListenUri, "", se.ListenUriMode, pl);
709
710                         if (b.CanBuildChannelListener<IDuplexChannel> (pl))
711                                 return b.BuildChannelListener<IDuplexChannel> (se.ListenUri, "", se.ListenUriMode, pl);
712                         if (b.CanBuildChannelListener<IDuplexSessionChannel> (pl))
713                                 return b.BuildChannelListener<IDuplexSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
714                         throw new InvalidOperationException ("None of the listener channel types is supported");
715                 }
716         }
717 }