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.Collections.ObjectModel;
31 using System.ServiceModel.Channels;
32 using System.ServiceModel.Configuration;
33 using System.ServiceModel.Description;
34 using System.ServiceModel.Dispatcher;
35 using System.ServiceModel.Security;
36 using System.Reflection;
38 namespace System.ServiceModel
40 public abstract partial class ServiceHostBase
41 : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
43 ServiceCredentials credentials;
44 ServiceDescription description;
45 UriSchemeKeyedCollection base_addresses;
46 TimeSpan open_timeout, close_timeout, instance_idle_timeout;
47 ServiceThrottle throttle;
48 List<InstanceContext> contexts;
49 ReadOnlyCollection<InstanceContext> exposed_contexts;
50 ChannelDispatcherCollection channel_dispatchers;
51 IDictionary<string,ContractDescription> contracts;
52 int flow_limit = int.MaxValue;
53 IExtensionCollection<ServiceHostBase> extensions;
55 protected ServiceHostBase ()
57 open_timeout = DefaultOpenTimeout;
58 close_timeout = DefaultCloseTimeout;
60 credentials = new ServiceCredentials ();
61 throttle = new ServiceThrottle ();
62 contexts = new List<InstanceContext> ();
63 exposed_contexts = new ReadOnlyCollection<InstanceContext> (contexts);
64 channel_dispatchers = new ChannelDispatcherCollection (this);
67 public event EventHandler<UnknownMessageReceivedEventArgs>
68 UnknownMessageReceived;
70 internal void OnUnknownMessageReceived (Message message)
72 if (UnknownMessageReceived != null)
73 UnknownMessageReceived (this, new UnknownMessageReceivedEventArgs (message));
75 // FIXME: better be logged
76 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));
79 public ReadOnlyCollection<Uri> BaseAddresses {
80 get { return new ReadOnlyCollection<Uri> (base_addresses.InternalItems); }
83 internal Uri CreateUri (string sheme, Uri relatieUri) {
84 Uri baseUri = base_addresses.Contains (sheme) ? base_addresses [sheme] : null;
86 if (relatieUri == null)
88 if (relatieUri.IsAbsoluteUri)
92 return new Uri (baseUri, relatieUri);
95 public ChannelDispatcherCollection ChannelDispatchers {
96 get { return channel_dispatchers; }
99 public ServiceAuthorizationBehavior Authorization {
105 public ServiceCredentials Credentials {
106 get { return credentials; }
109 public ServiceDescription Description {
110 get { return description; }
113 protected IDictionary<string,ContractDescription> ImplementedContracts {
114 get { return contracts; }
118 public IExtensionCollection<ServiceHostBase> Extensions {
120 if (extensions == null)
121 extensions = new ExtensionCollection<ServiceHostBase> (this);
126 protected internal override TimeSpan DefaultCloseTimeout {
127 get { return DefaultCommunicationTimeouts.Instance.CloseTimeout; }
130 protected internal override TimeSpan DefaultOpenTimeout {
131 get { return DefaultCommunicationTimeouts.Instance.OpenTimeout; }
134 public TimeSpan CloseTimeout {
135 get { return close_timeout; }
136 set { close_timeout = value; }
139 public TimeSpan OpenTimeout {
140 get { return open_timeout; }
141 set { open_timeout = value; }
144 public int ManualFlowControlLimit {
145 get { return flow_limit; }
146 set { flow_limit = value; }
149 public ServiceEndpoint AddServiceEndpoint (
150 string implementedContract, Binding binding, string address)
152 return AddServiceEndpoint (implementedContract,
154 new Uri (address, UriKind.RelativeOrAbsolute));
157 public ServiceEndpoint AddServiceEndpoint (
158 string implementedContract, Binding binding,
159 string address, Uri listenUri)
161 Uri uri = new Uri (address, UriKind.RelativeOrAbsolute);
162 return AddServiceEndpoint (
163 implementedContract, binding, uri, listenUri);
166 public ServiceEndpoint AddServiceEndpoint (
167 string implementedContract, Binding binding,
170 return AddServiceEndpoint (implementedContract, binding, address, address);
173 public ServiceEndpoint AddServiceEndpoint (
174 string implementedContract, Binding binding,
175 Uri address, Uri listenUri)
177 EndpointAddress ea = BuildEndpointAddress (address, binding);
178 ContractDescription cd = GetContract (implementedContract);
180 throw new InvalidOperationException (String.Format ("Contract '{0}' was not found in the implemented contracts in this service host.", implementedContract));
181 return AddServiceEndpointCore (cd, binding, ea, listenUri);
184 Type PopulateType (string typeName)
186 Type type = Type.GetType (typeName);
189 foreach (ContractDescription cd in ImplementedContracts.Values) {
190 type = cd.ContractType.Assembly.GetType (typeName);
197 ContractDescription GetContract (string name)
199 //FIXME: hack hack hack
200 ImplementedContracts ["IHttpGetHelpPageAndMetadataContract"] =
201 ContractDescription.GetContract (typeof (IHttpGetHelpPageAndMetadataContract));
203 // FIXME: As long as I tried, *only* IMetadataExchange
204 // is the exception case that does not require full
205 // type name. Hence I treat it as a special case.
206 if (name == ServiceMetadataBehavior.MexContractName) {
207 if (!Description.Behaviors.Contains (typeof (ServiceMetadataBehavior)) && Array.IndexOf (Description.ServiceType.GetInterfaces (), typeof (IMetadataExchange)) < 0)
208 throw new InvalidOperationException (
209 "Add ServiceMetadataBehavior to the ServiceHost to add a endpoint for IMetadataExchange contract.");
211 ImplementedContracts [ServiceMetadataBehavior.MexContractName] =
212 ContractDescription.GetContract (typeof (IMetadataExchange));
214 foreach (ContractDescription cd in ImplementedContracts.Values)
215 if (cd.ContractType == typeof (IMetadataExchange))
220 Type type = PopulateType (name);
222 foreach (ContractDescription cd in ImplementedContracts.Values) {
223 // FIXME: This check is a negative side effect
224 // of the above hack.
225 if (cd.ContractType == typeof (IMetadataExchange))
234 if (cd.ContractType == type ||
235 cd.ContractType.IsSubclassOf (type) ||
236 type.IsInterface && cd.ContractType.GetInterface (type.FullName) == type)
242 internal EndpointAddress BuildEndpointAddress (Uri address, Binding binding)
244 if (!address.IsAbsoluteUri) {
245 // Find a Base address with matching scheme,
246 // and build new absolute address
247 if (!base_addresses.Contains (binding.Scheme))
248 throw new InvalidOperationException (String.Format ("Could not find base address that matches Scheme {0} for endpoint {1}", binding.Scheme, binding.Name));
250 Uri baseaddr = base_addresses [binding.Scheme];
252 if (!baseaddr.AbsoluteUri.EndsWith ("/"))
253 baseaddr = new Uri (baseaddr.AbsoluteUri + "/");
254 address = new Uri (baseaddr, address);
256 return new EndpointAddress (address);
259 internal ServiceEndpoint AddServiceEndpointCore (
260 ContractDescription cd, Binding binding, EndpointAddress address, Uri listenUri)
262 foreach (ServiceEndpoint e in Description.Endpoints)
263 if (e.Contract == cd)
265 ServiceEndpoint se = new ServiceEndpoint (cd, binding, address);
266 se.ListenUri = listenUri.IsAbsoluteUri ? listenUri : new Uri (address.Uri, listenUri);
267 Description.Endpoints.Add (se);
272 protected virtual void ApplyConfiguration ()
274 if (Description == null)
275 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");
277 ServiceElement service = GetServiceElement ();
279 //TODO: Should we call here LoadServiceElement ?
280 if (service != null) {
283 HostElement host = service.Host;
284 foreach (BaseAddressElement baseAddress in host.BaseAddresses) {
285 this.base_addresses.Add (new Uri (baseAddress.BaseAddress));
289 foreach (ServiceEndpointElement endpoint in service.Endpoints) {
290 // FIXME: consider BindingName as well
291 ServiceEndpoint se = AddServiceEndpoint (
293 ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration),
294 endpoint.Address.ToString ());
297 // TODO: use EvaluationContext of ServiceElement.
298 ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors.Find (service.BehaviorConfiguration);
299 if (behavior != null) {
300 for (int i = 0; i < behavior.Count; i++) {
301 BehaviorExtensionElement bxel = behavior [i];
302 IServiceBehavior b = (IServiceBehavior) behavior [i].CreateBehavior ();
304 Description.Behaviors.Add (b);
308 // TODO: consider commonBehaviors here
310 // ensure ServiceAuthorizationBehavior
311 Authorization = Description.Behaviors.Find<ServiceAuthorizationBehavior> ();
312 if (Authorization == null) {
313 Authorization = new ServiceAuthorizationBehavior ();
314 Description.Behaviors.Add (Authorization);
317 // ensure ServiceDebugBehavior
318 ServiceDebugBehavior debugBehavior = Description.Behaviors.Find<ServiceDebugBehavior> ();
319 if (debugBehavior == null) {
320 debugBehavior = new ServiceDebugBehavior ();
321 Description.Behaviors.Add (debugBehavior);
325 private ServiceElement GetServiceElement() {
326 Type serviceType = Description.ServiceType;
327 if (serviceType == null)
330 return ConfigUtil.ServicesSection.Services [serviceType.FullName];
333 internal ContractDescription GetContract (string name, string ns)
335 foreach (ContractDescription d in ImplementedContracts.Values)
336 if (d.Name == name && d.Namespace == ns)
341 protected abstract ServiceDescription CreateDescription (
342 out IDictionary<string,ContractDescription> implementedContracts);
344 protected void InitializeDescription (UriSchemeKeyedCollection baseAddresses)
346 this.base_addresses = baseAddresses;
347 IDictionary<string,ContractDescription> retContracts;
348 description = CreateDescription (out retContracts);
349 contracts = retContracts;
351 ApplyConfiguration ();
354 protected virtual void InitializeRuntime ()
356 //First validate the description, which should call all behaviors
358 ValidateDescription ();
360 //Build all ChannelDispatchers, one dispatcher per user configured EndPoint.
361 //We must keep thet ServiceEndpoints as a seperate collection, since the user
362 //can change the collection in the description during the behaviors events.
363 Dictionary<ServiceEndpoint, ChannelDispatcher> endPointToDispatcher = new Dictionary<ServiceEndpoint,ChannelDispatcher>();
364 ServiceEndpoint[] endPoints = new ServiceEndpoint[Description.Endpoints.Count];
365 Description.Endpoints.CopyTo (endPoints, 0);
366 foreach (ServiceEndpoint se in endPoints) {
367 ChannelDispatcher channel = BuildChannelDispatcher (se);
368 ChannelDispatchers.Add (channel);
369 endPointToDispatcher[se] = channel;
372 //After the ChannelDispatchers are created, and attached to the service host
373 //Apply dispatching behaviors.
374 foreach (IServiceBehavior b in Description.Behaviors)
375 b.ApplyDispatchBehavior (Description, this);
377 foreach(KeyValuePair<ServiceEndpoint, ChannelDispatcher> val in endPointToDispatcher)
378 foreach (var ed in val.Value.Endpoints)
379 ApplyDispatchBehavior (ed, val.Key);
382 private void ValidateDescription ()
384 foreach (IServiceBehavior b in Description.Behaviors)
385 b.Validate (Description, this);
386 foreach (ServiceEndpoint endPoint in Description.Endpoints)
387 endPoint.Validate ();
390 private void ApplyDispatchBehavior (EndpointDispatcher ed, ServiceEndpoint endPoint)
392 foreach (IContractBehavior b in endPoint.Contract.Behaviors)
393 b.ApplyDispatchBehavior (endPoint.Contract, endPoint, ed.DispatchRuntime);
394 foreach (IEndpointBehavior b in endPoint.Behaviors)
395 b.ApplyDispatchBehavior (endPoint, ed);
396 foreach (OperationDescription operation in endPoint.Contract.Operations) {
397 foreach (IOperationBehavior b in operation.Behaviors)
398 b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
403 internal ChannelDispatcher BuildChannelDispatcher (ServiceEndpoint se)
405 var commonParams = new BindingParameterCollection ();
406 foreach (IServiceBehavior b in Description.Behaviors)
407 b.AddBindingParameters (Description, this, Description.Endpoints, commonParams);
409 return new DispatcherBuilder ().BuildChannelDispatcher (Description.ServiceType, se, commonParams);
413 protected void LoadConfigurationSection (ServiceElement element)
415 ServicesSection services = ConfigUtil.ServicesSection;
418 void DoOpen (TimeSpan timeout)
420 foreach (var cd in ChannelDispatchers) {
422 // This is likely hack.
423 if (cd is ChannelDispatcher)
424 ((ChannelDispatcher) cd).StartLoop ();
429 protected override sealed void OnAbort ()
433 Action<TimeSpan> close_delegate;
434 Action<TimeSpan> open_delegate;
436 protected override sealed IAsyncResult OnBeginClose (
437 TimeSpan timeout, AsyncCallback callback, object state)
439 if (close_delegate != null)
440 close_delegate = new Action<TimeSpan> (OnClose);
441 return close_delegate.BeginInvoke (timeout, callback, state);
444 protected override sealed IAsyncResult OnBeginOpen (
445 TimeSpan timeout, AsyncCallback callback, object state)
447 if (open_delegate == null)
448 open_delegate = new Action<TimeSpan> (OnOpen);
449 return open_delegate.BeginInvoke (timeout, callback, state);
452 protected override void OnClose (TimeSpan timeout)
454 DateTime start = DateTime.Now;
455 ReleasePerformanceCounters ();
456 List<ChannelDispatcherBase> l = new List<ChannelDispatcherBase> (ChannelDispatchers);
457 foreach (ChannelDispatcherBase e in l) {
459 TimeSpan ts = timeout - (DateTime.Now - start);
460 if (ts < TimeSpan.Zero)
464 } catch (Exception ex) {
465 Console.WriteLine ("ServiceHostBase failed to close the channel dispatcher:");
466 Console.WriteLine (ex);
471 protected override sealed void OnOpen (TimeSpan timeout)
473 InitializeRuntime ();
477 protected override void OnEndClose (IAsyncResult result)
479 if (close_delegate == null)
480 throw new InvalidOperationException ("Async close operation has not started");
481 close_delegate.EndInvoke (result);
484 protected override sealed void OnEndOpen (IAsyncResult result)
486 if (open_delegate == null)
487 throw new InvalidOperationException ("Aync open operation has not started");
488 open_delegate.EndInvoke (result);
491 protected override void OnOpened ()
496 protected void ReleasePerformanceCounters ()
500 void IDisposable.Dispose ()
506 class SyncMethodInvoker : IOperationInvoker
508 readonly MethodInfo _methodInfo;
509 public SyncMethodInvoker (MethodInfo methodInfo) {
510 _methodInfo = methodInfo;
513 #region IOperationInvoker Members
515 public bool IsSynchronous {
519 public object [] AllocateParameters () {
520 return new object [_methodInfo.GetParameters ().Length];
523 public object Invoke (object instance, object [] parameters)
525 return _methodInfo.Invoke (instance, parameters);
528 public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state) {
529 throw new NotSupportedException ();
532 public object InvokeEnd (object instance, out object [] outputs, IAsyncResult result) {
533 throw new NotSupportedException ();
539 class AsyncMethodInvoker : IOperationInvoker
541 readonly MethodInfo _beginMethodInfo, _endMethodInfo;
542 public AsyncMethodInvoker (MethodInfo beginMethodInfo, MethodInfo endMethodInfo) {
543 _beginMethodInfo = beginMethodInfo;
544 _endMethodInfo = endMethodInfo;
547 #region IOperationInvoker Members
549 public bool IsSynchronous {
550 get { return false; }
553 public object [] AllocateParameters () {
554 return new object [_beginMethodInfo.GetParameters ().Length - 2 + _endMethodInfo.GetParameters().Length-1];
557 public object Invoke (object instance, object [] parameters) {
558 throw new NotImplementedException ("Can't invoke async method synchronously");
559 //BUGBUG: need to differentiate between input and output parameters.
560 IAsyncResult asyncResult = InvokeBegin(instance, parameters, delegate(IAsyncResult ignore) { }, null);
561 asyncResult.AsyncWaitHandle.WaitOne();
562 return InvokeEnd(instance, out parameters, asyncResult);
565 public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state) {
566 if (inputs.Length + 2 != _beginMethodInfo.GetParameters ().Length)
567 throw new ArgumentException ("Wrong number of input parameters");
568 object [] fullargs = new object [_beginMethodInfo.GetParameters ().Length];
569 Array.Copy (inputs, fullargs, inputs.Length);
570 fullargs [inputs.Length] = callback;
571 fullargs [inputs.Length + 1] = state;
572 return (IAsyncResult) _beginMethodInfo.Invoke (instance, fullargs);
575 public object InvokeEnd (object instance, out object [] outputs, IAsyncResult asyncResult) {
576 outputs = new object [_endMethodInfo.GetParameters ().Length - 1];
577 object [] fullargs = new object [_endMethodInfo.GetParameters ().Length];
578 fullargs [outputs.Length] = asyncResult;
579 object result = _endMethodInfo.Invoke (instance, fullargs);
580 Array.Copy (fullargs, outputs, outputs.Length);
589 partial class DispatcherBuilder
591 internal ChannelDispatcher BuildChannelDispatcher (Type serviceType, ServiceEndpoint se, BindingParameterCollection commonParams)
593 //Let all behaviors add their binding parameters
594 AddBindingParameters (commonParams, se);
595 //User the binding parameters to build the channel listener and Dispatcher
596 IChannelListener lf = BuildListener (se, commonParams);
597 ChannelDispatcher cd = new ChannelDispatcher (
598 lf, se.Binding.Name);
599 cd.InitializeServiceEndpoint (serviceType, se);
603 private void AddBindingParameters (BindingParameterCollection commonParams, ServiceEndpoint endPoint) {
605 commonParams.Add (ChannelProtectionRequirements.CreateFromContract (endPoint.Contract));
607 foreach (IContractBehavior b in endPoint.Contract.Behaviors)
608 b.AddBindingParameters (endPoint.Contract, endPoint, commonParams);
609 foreach (IEndpointBehavior b in endPoint.Behaviors)
610 b.AddBindingParameters (endPoint, commonParams);
611 foreach (OperationDescription operation in endPoint.Contract.Operations) {
612 foreach (IOperationBehavior b in operation.Behaviors)
613 b.AddBindingParameters (operation, commonParams);
617 static IChannelListener BuildListener (ServiceEndpoint se,
618 BindingParameterCollection pl)
620 Binding b = se.Binding;
621 if (b.CanBuildChannelListener<IReplySessionChannel> (pl))
622 return b.BuildChannelListener<IReplySessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
623 if (b.CanBuildChannelListener<IReplyChannel> (pl))
624 return b.BuildChannelListener<IReplyChannel> (se.ListenUri, "", se.ListenUriMode, pl);
625 if (b.CanBuildChannelListener<IInputSessionChannel> (pl))
626 return b.BuildChannelListener<IInputSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
627 if (b.CanBuildChannelListener<IInputChannel> (pl))
628 return b.BuildChannelListener<IInputChannel> (se.ListenUri, "", se.ListenUriMode, pl);
630 if (b.CanBuildChannelListener<IDuplexChannel> (pl))
631 return b.BuildChannelListener<IDuplexChannel> (se.ListenUri, "", se.ListenUriMode, pl);
632 if (b.CanBuildChannelListener<IDuplexSessionChannel> (pl))
633 return b.BuildChannelListener<IDuplexSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
634 throw new InvalidOperationException ("None of the listener channel types is supported");