ChannelDispatcher.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. //
  2. // ChannelDispatcher.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005,2009 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.ObjectModel;
  31. using System.Linq;
  32. using System.Reflection;
  33. using System.ServiceModel.Channels;
  34. using System.Threading;
  35. using System.Transactions;
  36. using System.ServiceModel;
  37. using System.ServiceModel.Description;
  38. using System.Net.Sockets;
  39. using System.Xml;
  40. using System.IO;
  41. namespace System.ServiceModel.Dispatcher
  42. {
  43. public class ChannelDispatcher : ChannelDispatcherBase
  44. {
  45. class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
  46. {
  47. public EndpointDispatcherCollection (ChannelDispatcher owner)
  48. {
  49. this.owner = owner;
  50. }
  51. ChannelDispatcher owner;
  52. protected override void ClearItems ()
  53. {
  54. foreach (var ed in this)
  55. ed.ChannelDispatcher = null;
  56. base.ClearItems ();
  57. }
  58. protected override void InsertItem (int index, EndpointDispatcher item)
  59. {
  60. item.ChannelDispatcher = owner;
  61. base.InsertItem (index, item);
  62. }
  63. protected override void RemoveItem (int index)
  64. {
  65. if (index < Count)
  66. this [index].ChannelDispatcher = null;
  67. base.RemoveItem (index);
  68. }
  69. protected override void SetItem (int index, EndpointDispatcher item)
  70. {
  71. item.ChannelDispatcher = owner;
  72. base.SetItem (index, item);
  73. }
  74. }
  75. ServiceHostBase host;
  76. string binding_name;
  77. Collection<IErrorHandler> error_handlers
  78. = new Collection<IErrorHandler> ();
  79. IChannelListener listener;
  80. internal IDefaultCommunicationTimeouts timeouts; // FIXME: remove internal
  81. MessageVersion message_version;
  82. bool receive_sync, include_exception_detail_in_faults,
  83. manual_addressing, is_tx_receive;
  84. int max_tx_batch_size;
  85. SynchronizedCollection<IChannelInitializer> initializers
  86. = new SynchronizedCollection<IChannelInitializer> ();
  87. IsolationLevel tx_isolation_level;
  88. TimeSpan tx_timeout;
  89. ServiceThrottle throttle;
  90. Guid identifier = Guid.NewGuid ();
  91. ManualResetEvent async_event = new ManualResetEvent (false);
  92. ListenerLoopManager loop_manager;
  93. SynchronizedCollection<EndpointDispatcher> endpoints;
  94. [MonoTODO ("get binding info from config")]
  95. public ChannelDispatcher (IChannelListener listener)
  96. : this (listener, null)
  97. {
  98. }
  99. public ChannelDispatcher (
  100. IChannelListener listener, string bindingName)
  101. : this (listener, bindingName, null)
  102. {
  103. }
  104. public ChannelDispatcher (
  105. IChannelListener listener, string bindingName,
  106. IDefaultCommunicationTimeouts timeouts)
  107. {
  108. if (listener == null)
  109. throw new ArgumentNullException ("listener");
  110. Init (listener, bindingName, timeouts);
  111. }
  112. private void Init (IChannelListener listener, string bindingName,
  113. IDefaultCommunicationTimeouts timeouts)
  114. {
  115. this.listener = listener;
  116. this.binding_name = bindingName;
  117. // IChannelListener is often a ChannelListenerBase
  118. // which implements IDefaultCommunicationTimeouts.
  119. this.timeouts = timeouts ?? listener as IDefaultCommunicationTimeouts ?? DefaultCommunicationTimeouts.Instance;
  120. endpoints = new EndpointDispatcherCollection (this);
  121. }
  122. internal EndpointDispatcher InitializeServiceEndpoint (Type serviceType, ServiceEndpoint se)
  123. {
  124. //Attach one EndpointDispacher to the ChannelDispatcher
  125. EndpointDispatcher ed = new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace);
  126. this.Endpoints.Add (ed);
  127. ed.InitializeServiceEndpoint (false, serviceType, se);
  128. return ed;
  129. }
  130. public string BindingName {
  131. get { return binding_name; }
  132. }
  133. public SynchronizedCollection<IChannelInitializer> ChannelInitializers {
  134. get { return initializers; }
  135. }
  136. protected internal override TimeSpan DefaultCloseTimeout {
  137. get { return timeouts.CloseTimeout; }
  138. }
  139. protected internal override TimeSpan DefaultOpenTimeout {
  140. get { return timeouts.OpenTimeout; }
  141. }
  142. public Collection<IErrorHandler> ErrorHandlers {
  143. get { return error_handlers; }
  144. }
  145. public SynchronizedCollection<EndpointDispatcher> Endpoints {
  146. get { return endpoints; }
  147. }
  148. [MonoTODO]
  149. public bool IsTransactedAccept {
  150. get { throw new NotImplementedException (); }
  151. }
  152. public bool IsTransactedReceive {
  153. get { return is_tx_receive; }
  154. set { is_tx_receive = value; }
  155. }
  156. public bool ManualAddressing {
  157. get { return manual_addressing; }
  158. set { manual_addressing = value; }
  159. }
  160. public int MaxTransactedBatchSize {
  161. get { return max_tx_batch_size; }
  162. set { max_tx_batch_size = value; }
  163. }
  164. public override ServiceHostBase Host {
  165. get { return host; }
  166. }
  167. public override IChannelListener Listener {
  168. get { return listener; }
  169. }
  170. public MessageVersion MessageVersion {
  171. get { return message_version; }
  172. set { message_version = value; }
  173. }
  174. public bool ReceiveSynchronously {
  175. get { return receive_sync; }
  176. set {
  177. ThrowIfDisposedOrImmutable ();
  178. receive_sync = value;
  179. }
  180. }
  181. public bool IncludeExceptionDetailInFaults {
  182. get { return include_exception_detail_in_faults; }
  183. set { include_exception_detail_in_faults = value; }
  184. }
  185. public ServiceThrottle ServiceThrottle {
  186. get { return throttle; }
  187. set { throttle = value; }
  188. }
  189. public IsolationLevel TransactionIsolationLevel {
  190. get { return tx_isolation_level; }
  191. set { tx_isolation_level = value; }
  192. }
  193. public TimeSpan TransactionTimeout {
  194. get { return tx_timeout; }
  195. set { tx_timeout = value; }
  196. }
  197. protected internal override void Attach (ServiceHostBase host)
  198. {
  199. this.host = host;
  200. var bl = listener as IChannelDispatcherBoundListener;
  201. if (bl != null)
  202. bl.ChannelDispatcher = this;
  203. }
  204. public override void CloseInput ()
  205. {
  206. if (loop_manager != null)
  207. loop_manager.CloseInput ();
  208. }
  209. protected internal override void Detach (ServiceHostBase host)
  210. {
  211. this.host = null;
  212. }
  213. protected override void OnAbort ()
  214. {
  215. if (loop_manager != null)
  216. loop_manager.Stop (TimeSpan.FromTicks (1));
  217. }
  218. Action<TimeSpan> open_delegate;
  219. Action<TimeSpan> close_delegate;
  220. protected override IAsyncResult OnBeginClose (TimeSpan timeout,
  221. AsyncCallback callback, object state)
  222. {
  223. if (close_delegate == null)
  224. close_delegate = new Action<TimeSpan> (OnClose);
  225. return close_delegate.BeginInvoke (timeout, callback, state);
  226. }
  227. protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
  228. AsyncCallback callback, object state)
  229. {
  230. if (open_delegate == null)
  231. open_delegate = new Action<TimeSpan> (OnOpen);
  232. return open_delegate.BeginInvoke (timeout, callback, state);
  233. }
  234. protected override void OnClose (TimeSpan timeout)
  235. {
  236. if (loop_manager != null)
  237. loop_manager.Stop (timeout);
  238. }
  239. protected override void OnClosed ()
  240. {
  241. if (host != null)
  242. host.ChannelDispatchers.Remove (this);
  243. base.OnClosed ();
  244. }
  245. protected override void OnEndClose (IAsyncResult result)
  246. {
  247. close_delegate.EndInvoke (result);
  248. }
  249. protected override void OnEndOpen (IAsyncResult result)
  250. {
  251. open_delegate.EndInvoke (result);
  252. }
  253. protected override void OnOpen (TimeSpan timeout)
  254. {
  255. if (Host == null || MessageVersion == null)
  256. throw new InvalidOperationException ("Service host is not attached to this ChannelDispatcher.");
  257. loop_manager.Setup (timeout);
  258. }
  259. protected override void OnOpening ()
  260. {
  261. base.OnOpening ();
  262. loop_manager = new ListenerLoopManager (this);
  263. }
  264. protected override void OnOpened ()
  265. {
  266. base.OnOpened ();
  267. StartLoop ();
  268. }
  269. void StartLoop ()
  270. {
  271. // FIXME: not sure if it should be filled here.
  272. if (ServiceThrottle == null)
  273. ServiceThrottle = new ServiceThrottle (this);
  274. loop_manager.Start ();
  275. }
  276. }
  277. // isolated from ChannelDispatcher
  278. class ListenerLoopManager
  279. {
  280. ChannelDispatcher owner;
  281. AutoResetEvent throttle_wait_handle = new AutoResetEvent (false);
  282. AutoResetEvent creator_handle = new AutoResetEvent (false);
  283. ManualResetEvent stop_handle = new ManualResetEvent (false);
  284. bool loop;
  285. Thread loop_thread;
  286. DateTime close_started;
  287. TimeSpan close_timeout;
  288. Func<IAsyncResult> channel_acceptor;
  289. List<IChannel> channels = new List<IChannel> ();
  290. AddressFilterMode address_filter_mode;
  291. List<ISession> sessions = new List<ISession> ();
  292. public ListenerLoopManager (ChannelDispatcher owner)
  293. {
  294. this.owner = owner;
  295. var sba = owner.Host != null ? owner.Host.Description.Behaviors.Find<ServiceBehaviorAttribute> () : null;
  296. if (sba != null)
  297. address_filter_mode = sba.AddressFilterMode;
  298. }
  299. public void Setup (TimeSpan openTimeout)
  300. {
  301. if (owner.Listener.State != CommunicationState.Created)
  302. throw new InvalidOperationException ("Tried to open the channel listener which is bound to ChannelDispatcher, but it is not at Created state");
  303. owner.Listener.Open (openTimeout);
  304. // It is tested at Open(), but strangely it is not instantiated at this point.
  305. foreach (var ed in owner.Endpoints)
  306. if (ed.DispatchRuntime.InstanceContextProvider == null && (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null))
  307. throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
  308. SetupChannelAcceptor ();
  309. }
  310. public void Start ()
  311. {
  312. if (loop_thread == null)
  313. loop_thread = new Thread (new ThreadStart (Loop));
  314. loop_thread.Start ();
  315. }
  316. Func<IAsyncResult> CreateAcceptor<TChannel> (IChannelListener l) where TChannel : class, IChannel
  317. {
  318. IChannelListener<TChannel> r = l as IChannelListener<TChannel>;
  319. if (r == null)
  320. return null;
  321. AsyncCallback callback = delegate (IAsyncResult result) {
  322. try {
  323. ChannelAccepted (r.EndAcceptChannel (result));
  324. } catch (Exception ex) {
  325. Logger.Error ("Exception during finishing channel acceptance.", ex);
  326. creator_handle.Set ();
  327. }
  328. };
  329. return delegate {
  330. try {
  331. return r.BeginAcceptChannel (callback, null);
  332. } catch (Exception ex) {
  333. Logger.Error ("Exception during accepting channel.", ex);
  334. throw;
  335. }
  336. };
  337. }
  338. void SetupChannelAcceptor ()
  339. {
  340. var l = owner.Listener;
  341. channel_acceptor =
  342. CreateAcceptor<IReplyChannel> (l) ??
  343. CreateAcceptor<IReplySessionChannel> (l) ??
  344. CreateAcceptor<IInputChannel> (l) ??
  345. CreateAcceptor<IInputSessionChannel> (l) ??
  346. CreateAcceptor<IDuplexChannel> (l) ??
  347. CreateAcceptor<IDuplexSessionChannel> (l);
  348. if (channel_acceptor == null)
  349. throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", l.GetType ()));
  350. }
  351. public void Stop (TimeSpan timeout)
  352. {
  353. if (loop_thread == null)
  354. return;
  355. close_started = DateTime.Now;
  356. close_timeout = timeout;
  357. loop = false;
  358. creator_handle.Set ();
  359. throttle_wait_handle.Set (); // break primary loop
  360. if (stop_handle != null) {
  361. stop_handle.WaitOne (timeout > TimeSpan.Zero ? timeout : TimeSpan.FromTicks (1));
  362. stop_handle.Close ();
  363. stop_handle = null;
  364. }
  365. if (owner.Listener.State != CommunicationState.Closed) {
  366. Logger.Warning (String.Format ("Channel listener '{0}' is not closed. Aborting.", owner.Listener.GetType ()));
  367. owner.Listener.Abort ();
  368. }
  369. if (loop_thread != null && loop_thread.IsAlive)
  370. loop_thread.Abort ();
  371. loop_thread = null;
  372. }
  373. void AddChannel (IChannel ch)
  374. {
  375. channels.Add (ch);
  376. var ich = ch as ISessionChannel<IInputSession>;
  377. if (ich != null && ich.Session != null) {
  378. lock (sessions) {
  379. var session = sessions.FirstOrDefault (s => s.Id == ich.Session.Id);
  380. if (session == null)
  381. sessions.Add (session);
  382. }
  383. }
  384. }
  385. void RemoveChannel (IChannel ch)
  386. {
  387. channels.Remove (ch); // zonbie, if exists
  388. var ich = ch as ISessionChannel<IInputSession>;
  389. if (ich != null && ich.Session != null)
  390. sessions.Remove (ich.Session);
  391. }
  392. public void CloseInput ()
  393. {
  394. foreach (var ch in channels.ToArray ()) {
  395. if (ch.State == CommunicationState.Closed)
  396. RemoveChannel (ch);
  397. else {
  398. try {
  399. ch.Close (close_timeout - (DateTime.Now - close_started));
  400. } catch (Exception ex) {
  401. // FIXME: log it.
  402. Logger.Error (String.Format ("Exception on closing channel ({0})", ch.GetType ()), ex);
  403. ch.Abort ();
  404. }
  405. }
  406. }
  407. }
  408. void Loop ()
  409. {
  410. try {
  411. LoopCore ();
  412. } catch (Exception ex) {
  413. Logger.Error (String.Format ("ListenerLoopManager caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener), ex);
  414. } finally {
  415. if (stop_handle != null)
  416. stop_handle.Set ();
  417. }
  418. }
  419. void LoopCore ()
  420. {
  421. loop = true;
  422. // FIXME: use WaitForChannel() for (*only* for) transacted channel listeners.
  423. // http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3faa4a5e-8602-4dbe-a181-73b3f581835e
  424. while (loop) {
  425. // FIXME: take MaxConcurrentCalls into consideration appropriately.
  426. while (loop && channels.Count < Math.Min (owner.ServiceThrottle.MaxConcurrentSessions, owner.ServiceThrottle.MaxConcurrentCalls)) {
  427. // FIXME: this should not be required, but saves multi-ChannelDispatcher case (Throttling enabled) for HTTP standalone listener...
  428. Thread.Sleep (100);
  429. channel_acceptor ();
  430. creator_handle.WaitOne (); // released by ChannelAccepted()
  431. }
  432. if (!loop)
  433. break;
  434. throttle_wait_handle.WaitOne (); // released by IChannel.Close()
  435. }
  436. try {
  437. owner.Listener.Close ();
  438. } catch (Exception ex) {
  439. Logger.Error (String.Format ("Exception while closing IChannelListener ({0})", owner.Listener.GetType ()), ex);
  440. } finally {
  441. // make sure to close both listener and channels.
  442. owner.CloseInput ();
  443. }
  444. }
  445. void ChannelAccepted (IChannel ch)
  446. {
  447. try {
  448. if (ch == null) // could happen when it was aborted
  449. return;
  450. if (!loop) {
  451. var dis = ch as IDisposable;
  452. if (dis != null)
  453. dis.Dispose ();
  454. return;
  455. }
  456. lock (channels)
  457. AddChannel (ch);
  458. ch.Opened += delegate {
  459. ch.Faulted += delegate {
  460. lock (channels)
  461. if (channels.Contains (ch))
  462. RemoveChannel (ch);
  463. throttle_wait_handle.Set (); // release loop wait lock.
  464. };
  465. ch.Closed += delegate {
  466. lock (channels)
  467. if (channels.Contains (ch))
  468. RemoveChannel (ch);
  469. throttle_wait_handle.Set (); // release loop wait lock.
  470. };
  471. };
  472. ch.Open ();
  473. } finally {
  474. creator_handle.Set ();
  475. }
  476. ProcessRequestOrInput (ch);
  477. }
  478. void ProcessRequestOrInput (IChannel ch)
  479. {
  480. var reply = ch as IReplyChannel;
  481. var input = ch as IInputChannel;
  482. if (reply != null) {
  483. if (owner.ReceiveSynchronously) {
  484. RequestContext rc;
  485. if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
  486. ProcessRequest (reply, rc);
  487. } else {
  488. reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
  489. }
  490. } else if (input != null) {
  491. if (owner.ReceiveSynchronously) {
  492. Message msg;
  493. if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
  494. ProcessInput (input, msg);
  495. } else {
  496. input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
  497. }
  498. }
  499. }
  500. void TryReceiveRequestDone (IAsyncResult result)
  501. {
  502. RequestContext rc;
  503. var reply = (IReplyChannel) result.AsyncState;
  504. if (reply.EndTryReceiveRequest (result, out rc))
  505. ProcessRequest (reply, rc);
  506. else
  507. reply.Close ();
  508. }
  509. void TryReceiveDone (IAsyncResult result)
  510. {
  511. Message msg;
  512. var input = (IInputChannel) result.AsyncState;
  513. if (input.EndTryReceive (result, out msg))
  514. ProcessInput (input, msg);
  515. else
  516. input.Close ();
  517. }
  518. void ProcessRequest (IReplyChannel reply, RequestContext rc)
  519. {
  520. try {
  521. var req = rc.RequestMessage;
  522. var ed = FindEndpointDispatcher (req);
  523. new InputOrReplyRequestProcessor (ed.DispatchRuntime, reply).ProcessReply (rc);
  524. } catch (Exception ex) {
  525. Message res;
  526. if (ProcessErrorWithHandlers (reply, ex, out res))
  527. return;
  528. if ((!(ex is SocketException)) &&
  529. (!(ex is XmlException)) &&
  530. (!(ex is IOException)))
  531. rc.Reply (res);
  532. reply.Close (owner.DefaultCloseTimeout); // close the channel
  533. } finally {
  534. if (rc != null)
  535. rc.Close ();
  536. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  537. if (loop && reply.State != CommunicationState.Closed)
  538. ProcessRequestOrInput (reply);
  539. }
  540. }
  541. bool ProcessErrorWithHandlers (IChannel ch, Exception ex, out Message res)
  542. {
  543. res = null;
  544. foreach (var eh in owner.ErrorHandlers)
  545. if (eh.HandleError (ex))
  546. return true; // error is handled appropriately.
  547. Logger.Error ("An error occured, to be handled", ex);
  548. foreach (var eh in owner.ErrorHandlers)
  549. eh.ProvideFault (ex, owner.MessageVersion, ref res);
  550. if (res == null) {
  551. var conv = ch.GetProperty<FaultConverter> () ?? FaultConverter.GetDefaultFaultConverter (owner.MessageVersion);
  552. if (!conv.TryCreateFaultMessage (ex, out res))
  553. res = Message.CreateMessage (owner.MessageVersion, new FaultCode ("Receiver"), ex.Message, owner.MessageVersion.Addressing.FaultNamespace);
  554. }
  555. return false;
  556. }
  557. void ProcessInput (IInputChannel input, Message message)
  558. {
  559. try {
  560. EndpointDispatcher candidate = null;
  561. candidate = FindEndpointDispatcher (message);
  562. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).ProcessInput (message);
  563. }
  564. catch (Exception ex) {
  565. Message dummy;
  566. ProcessErrorWithHandlers (input, ex, out dummy);
  567. } finally {
  568. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  569. if (loop && input.State != CommunicationState.Closed)
  570. ProcessRequestOrInput (input);
  571. }
  572. }
  573. EndpointDispatcher FindEndpointDispatcher (Message message) {
  574. EndpointDispatcher candidate = null;
  575. bool hasEndpointMatch = false;
  576. foreach (var endpoint in owner.Endpoints) {
  577. if (endpoint.AddressFilter.Match (message)) {
  578. hasEndpointMatch = true;
  579. if (!endpoint.ContractFilter.Match (message))
  580. continue;
  581. var newdis = endpoint;
  582. if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
  583. candidate = newdis;
  584. else if (candidate.FilterPriority == newdis.FilterPriority)
  585. throw new MultipleFilterMatchesException ();
  586. }
  587. }
  588. if (candidate == null && !hasEndpointMatch) {
  589. if (owner.Host != null)
  590. owner.Host.OnUnknownMessageReceived (message);
  591. // we have to return a fault to the client anyways...
  592. throw new EndpointNotFoundException ();
  593. }
  594. else if (candidate == null)
  595. // FIXME: It is not a good place to check, but anyways detach this error from EndpointNotFoundException.
  596. throw new ActionNotSupportedException (String.Format ("Action '{0}' did not match any operations in the target contract", message.Headers.Action));
  597. return candidate;
  598. }
  599. }
  600. }