ClientRuntimeChannel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //
  2. // ClientRuntimeChannel.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 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.Reflection;
  30. using System.ServiceModel.Channels;
  31. using System.ServiceModel.Description;
  32. using System.ServiceModel.Dispatcher;
  33. using System.ServiceModel.Security;
  34. using System.Threading;
  35. using System.Xml;
  36. namespace System.ServiceModel.MonoInternal
  37. {
  38. // FIXME: This is a quick workaround for bug #571907
  39. public class ClientRuntimeChannel
  40. : CommunicationObject, IClientChannel
  41. {
  42. ClientRuntime runtime;
  43. EndpointAddress remote_address;
  44. ContractDescription contract;
  45. MessageVersion message_version;
  46. TimeSpan default_open_timeout, default_close_timeout;
  47. IChannel channel;
  48. IChannelFactory factory;
  49. OperationContext context;
  50. #region delegates
  51. readonly ProcessDelegate _processDelegate;
  52. delegate object ProcessDelegate (MethodBase method, string operationName, object [] parameters);
  53. readonly RequestDelegate requestDelegate;
  54. delegate Message RequestDelegate (Message msg, TimeSpan timeout);
  55. readonly SendDelegate sendDelegate;
  56. delegate void SendDelegate (Message msg, TimeSpan timeout);
  57. #endregion
  58. public ClientRuntimeChannel (ServiceEndpoint endpoint,
  59. ChannelFactory channelFactory, EndpointAddress remoteAddress, Uri via)
  60. : this (endpoint.CreateRuntime (), endpoint.Contract, channelFactory.DefaultOpenTimeout, channelFactory.DefaultCloseTimeout, null, channelFactory.OpenedChannelFactory, endpoint.Binding.MessageVersion, remoteAddress, via)
  61. {
  62. }
  63. public ClientRuntimeChannel (ClientRuntime runtime, ContractDescription contract, TimeSpan openTimeout, TimeSpan closeTimeout, IChannel contextChannel, IChannelFactory factory, MessageVersion messageVersion, EndpointAddress remoteAddress, Uri via)
  64. {
  65. this.runtime = runtime;
  66. this.remote_address = remoteAddress;
  67. runtime.Via = via;
  68. this.contract = contract;
  69. this.message_version = messageVersion;
  70. default_open_timeout = openTimeout;
  71. default_close_timeout = closeTimeout;
  72. _processDelegate = new ProcessDelegate (Process);
  73. requestDelegate = new RequestDelegate (Request);
  74. sendDelegate = new SendDelegate (Send);
  75. // default values
  76. AllowInitializationUI = true;
  77. OperationTimeout = TimeSpan.FromMinutes (1);
  78. if (contextChannel != null)
  79. channel = contextChannel;
  80. else {
  81. var method = factory.GetType ().GetMethod ("CreateChannel", new Type [] {typeof (EndpointAddress), typeof (Uri)});
  82. channel = (IChannel) method.Invoke (factory, new object [] {remote_address, Via});
  83. this.factory = factory;
  84. }
  85. }
  86. public ContractDescription Contract {
  87. get { return contract; }
  88. }
  89. public ClientRuntime Runtime {
  90. get { return runtime; }
  91. }
  92. IRequestChannel RequestChannel {
  93. get { return channel as IRequestChannel; }
  94. }
  95. IOutputChannel OutputChannel {
  96. get { return channel as IOutputChannel; }
  97. }
  98. internal IDuplexChannel DuplexChannel {
  99. get { return channel as IDuplexChannel; }
  100. }
  101. #region IClientChannel
  102. bool did_interactive_initialization;
  103. public bool AllowInitializationUI { get; set; }
  104. public bool DidInteractiveInitialization {
  105. get { return did_interactive_initialization; }
  106. }
  107. public Uri Via {
  108. get { return runtime.Via; }
  109. }
  110. class DelegatingWaitHandle : WaitHandle
  111. {
  112. public DelegatingWaitHandle (IAsyncResult [] results)
  113. {
  114. this.results = results;
  115. }
  116. IAsyncResult [] results;
  117. protected override void Dispose (bool disposing)
  118. {
  119. if (disposing)
  120. foreach (var r in results)
  121. r.AsyncWaitHandle.Close ();
  122. }
  123. public override bool WaitOne ()
  124. {
  125. foreach (var r in results)
  126. r.AsyncWaitHandle.WaitOne ();
  127. return true;
  128. }
  129. public override bool WaitOne (int millisecondsTimeout)
  130. {
  131. return WaitHandle.WaitAll (ResultWaitHandles, millisecondsTimeout);
  132. }
  133. WaitHandle [] ResultWaitHandles {
  134. get {
  135. var arr = new WaitHandle [results.Length];
  136. for (int i = 0; i < arr.Length; i++)
  137. arr [i] = results [i].AsyncWaitHandle;
  138. return arr;
  139. }
  140. }
  141. #if !MOONLIGHT
  142. public override bool WaitOne (int millisecondsTimeout, bool exitContext)
  143. {
  144. return WaitHandle.WaitAll (ResultWaitHandles, millisecondsTimeout, exitContext);
  145. }
  146. public override bool WaitOne (TimeSpan timeout, bool exitContext)
  147. {
  148. return WaitHandle.WaitAll (ResultWaitHandles, timeout, exitContext);
  149. }
  150. #endif
  151. }
  152. class DisplayUIAsyncResult : IAsyncResult
  153. {
  154. public DisplayUIAsyncResult (IAsyncResult [] results)
  155. {
  156. this.results = results;
  157. }
  158. IAsyncResult [] results;
  159. internal IAsyncResult [] Results {
  160. get { return results; }
  161. }
  162. public object AsyncState {
  163. get { return null; }
  164. }
  165. WaitHandle wait_handle;
  166. public WaitHandle AsyncWaitHandle {
  167. get {
  168. if (wait_handle == null)
  169. wait_handle = new DelegatingWaitHandle (results);
  170. return wait_handle;
  171. }
  172. }
  173. public bool CompletedSynchronously {
  174. get {
  175. foreach (var r in results)
  176. if (!r.CompletedSynchronously)
  177. return false;
  178. return true;
  179. }
  180. }
  181. public bool IsCompleted {
  182. get {
  183. foreach (var r in results)
  184. if (!r.IsCompleted)
  185. return false;
  186. return true;
  187. }
  188. }
  189. }
  190. public IAsyncResult BeginDisplayInitializationUI (
  191. AsyncCallback callback, object state)
  192. {
  193. OnInitializationUI ();
  194. IAsyncResult [] arr = new IAsyncResult [runtime.InteractiveChannelInitializers.Count];
  195. int i = 0;
  196. foreach (var init in runtime.InteractiveChannelInitializers)
  197. arr [i++] = init.BeginDisplayInitializationUI (this, callback, state);
  198. return new DisplayUIAsyncResult (arr);
  199. }
  200. public void EndDisplayInitializationUI (
  201. IAsyncResult result)
  202. {
  203. DisplayUIAsyncResult r = (DisplayUIAsyncResult) result;
  204. int i = 0;
  205. foreach (var init in runtime.InteractiveChannelInitializers)
  206. init.EndDisplayInitializationUI (r.Results [i++]);
  207. did_interactive_initialization = true;
  208. }
  209. public void DisplayInitializationUI ()
  210. {
  211. OnInitializationUI ();
  212. foreach (var init in runtime.InteractiveChannelInitializers)
  213. init.EndDisplayInitializationUI (init.BeginDisplayInitializationUI (this, null, null));
  214. did_interactive_initialization = true;
  215. }
  216. void OnInitializationUI ()
  217. {
  218. if (!AllowInitializationUI && runtime.InteractiveChannelInitializers.Count > 0)
  219. throw new InvalidOperationException ("AllowInitializationUI is set to false but the client runtime contains one or more InteractiveChannelInitializers.");
  220. }
  221. public void Dispose ()
  222. {
  223. Close ();
  224. }
  225. public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived;
  226. #endregion
  227. #region IContextChannel
  228. [MonoTODO]
  229. public bool AllowOutputBatching { get; set; }
  230. public IInputSession InputSession {
  231. get {
  232. ISessionChannel<IInputSession> ch = RequestChannel as ISessionChannel<IInputSession>;
  233. ch = ch ?? OutputChannel as ISessionChannel<IInputSession>;
  234. if (ch != null)
  235. return ch.Session;
  236. var dch = OutputChannel as ISessionChannel<IDuplexSession>;
  237. return dch != null ? dch.Session : null;
  238. }
  239. }
  240. public EndpointAddress LocalAddress {
  241. get {
  242. var dc = OperationChannel as IDuplexChannel;
  243. return dc != null ? dc.LocalAddress : null;
  244. }
  245. }
  246. [MonoTODO]
  247. public TimeSpan OperationTimeout { get; set; }
  248. public IOutputSession OutputSession {
  249. get {
  250. ISessionChannel<IOutputSession> ch = RequestChannel as ISessionChannel<IOutputSession>;
  251. ch = ch ?? OutputChannel as ISessionChannel<IOutputSession>;
  252. if (ch != null)
  253. return ch.Session;
  254. var dch = OutputChannel as ISessionChannel<IDuplexSession>;
  255. return dch != null ? dch.Session : null;
  256. }
  257. }
  258. public EndpointAddress RemoteAddress {
  259. get { return RequestChannel != null ? RequestChannel.RemoteAddress : OutputChannel.RemoteAddress; }
  260. }
  261. public string SessionId {
  262. get { return OutputSession != null ? OutputSession.Id : InputSession != null ? InputSession.Id : null; }
  263. }
  264. #endregion
  265. // CommunicationObject
  266. protected internal override TimeSpan DefaultOpenTimeout {
  267. get { return default_open_timeout; }
  268. }
  269. protected internal override TimeSpan DefaultCloseTimeout {
  270. get { return default_close_timeout; }
  271. }
  272. protected override void OnAbort ()
  273. {
  274. channel.Abort ();
  275. if (factory != null) // ... is it valid?
  276. factory.Abort ();
  277. }
  278. Action<TimeSpan> close_delegate;
  279. protected override IAsyncResult OnBeginClose (
  280. TimeSpan timeout, AsyncCallback callback, object state)
  281. {
  282. if (close_delegate == null)
  283. close_delegate = new Action<TimeSpan> (OnClose);
  284. return close_delegate.BeginInvoke (timeout, callback, state);
  285. }
  286. protected override void OnEndClose (IAsyncResult result)
  287. {
  288. close_delegate.EndInvoke (result);
  289. }
  290. protected override void OnClose (TimeSpan timeout)
  291. {
  292. DateTime start = DateTime.Now;
  293. channel.Close (timeout);
  294. }
  295. Action<TimeSpan> open_callback;
  296. protected override IAsyncResult OnBeginOpen (
  297. TimeSpan timeout, AsyncCallback callback, object state)
  298. {
  299. if (open_callback == null)
  300. open_callback = new Action<TimeSpan> (OnOpen);
  301. return open_callback.BeginInvoke (timeout, callback, state);
  302. }
  303. protected override void OnEndOpen (IAsyncResult result)
  304. {
  305. if (open_callback == null)
  306. throw new InvalidOperationException ("Async open operation has not started");
  307. open_callback.EndInvoke (result);
  308. }
  309. protected override void OnOpen (TimeSpan timeout)
  310. {
  311. if (runtime.InteractiveChannelInitializers.Count > 0 && !DidInteractiveInitialization)
  312. throw new InvalidOperationException ("The client runtime is assigned interactive channel initializers, and in such case DisplayInitializationUI must be called before the channel is opened.");
  313. if (channel.State == CommunicationState.Created)
  314. channel.Open (timeout);
  315. }
  316. // IChannel
  317. IChannel OperationChannel {
  318. get { return channel; }
  319. }
  320. public T GetProperty<T> () where T : class
  321. {
  322. return OperationChannel.GetProperty<T> ();
  323. }
  324. // IExtensibleObject<IContextChannel>
  325. IExtensionCollection<IContextChannel> extensions;
  326. public IExtensionCollection<IContextChannel> Extensions {
  327. get {
  328. if (extensions == null)
  329. extensions = new ExtensionCollection<IContextChannel> (this);
  330. return extensions;
  331. }
  332. }
  333. #region Request/Output processing
  334. public IAsyncResult BeginProcess (MethodBase method, string operationName, object [] parameters, AsyncCallback callback, object asyncState)
  335. {
  336. if (context != null)
  337. throw new InvalidOperationException ("another operation is in progress");
  338. context = OperationContext.Current;
  339. return _processDelegate.BeginInvoke (method, operationName, parameters, callback, asyncState);
  340. }
  341. public object EndProcess (MethodBase method, string operationName, object [] parameters, IAsyncResult result)
  342. {
  343. context = null;
  344. if (result == null)
  345. throw new ArgumentNullException ("result");
  346. if (parameters == null)
  347. throw new ArgumentNullException ("parameters");
  348. // FIXME: the method arguments should be verified to be
  349. // identical to the arguments in the corresponding begin method.
  350. return _processDelegate.EndInvoke (result);
  351. }
  352. public object Process (MethodBase method, string operationName, object [] parameters)
  353. {
  354. try {
  355. return DoProcess (method, operationName, parameters);
  356. } catch (Exception ex) {
  357. Console.Write ("Exception in async operation: ");
  358. Console.WriteLine (ex);
  359. throw;
  360. }
  361. }
  362. object DoProcess (MethodBase method, string operationName, object [] parameters)
  363. {
  364. if (AllowInitializationUI)
  365. DisplayInitializationUI ();
  366. OperationDescription od = SelectOperation (method, operationName, parameters);
  367. if (State != CommunicationState.Opened)
  368. Open ();
  369. if (!od.IsOneWay)
  370. return Request (od, parameters);
  371. else {
  372. Output (od, parameters);
  373. return null;
  374. }
  375. }
  376. OperationDescription SelectOperation (MethodBase method, string operationName, object [] parameters)
  377. {
  378. string operation;
  379. if (Runtime.OperationSelector != null)
  380. operation = Runtime.OperationSelector.SelectOperation (method, parameters);
  381. else
  382. operation = operationName;
  383. OperationDescription od = contract.Operations.Find (operation);
  384. if (od == null)
  385. throw new Exception (String.Format ("OperationDescription for operation '{0}' was not found in its internally-generated contract.", operation));
  386. return od;
  387. }
  388. void Output (OperationDescription od, object [] parameters)
  389. {
  390. ClientOperation op = runtime.Operations [od.Name];
  391. Send (CreateRequest (op, parameters), OperationTimeout);
  392. }
  393. object Request (OperationDescription od, object [] parameters)
  394. {
  395. ClientOperation op = runtime.Operations [od.Name];
  396. object [] inspections = new object [runtime.MessageInspectors.Count];
  397. Message req = CreateRequest (op, parameters);
  398. for (int i = 0; i < inspections.Length; i++)
  399. inspections [i] = runtime.MessageInspectors [i].BeforeSendRequest (ref req, this);
  400. Message res = Request (req, OperationTimeout);
  401. if (res.IsFault) {
  402. MessageFault fault = MessageFault.CreateFault (res, runtime.MaxFaultSize);
  403. if (fault.HasDetail && fault is MessageFault.SimpleMessageFault) {
  404. MessageFault.SimpleMessageFault simpleFault = fault as MessageFault.SimpleMessageFault;
  405. object detail = simpleFault.Detail;
  406. Type t = detail.GetType ();
  407. Type faultType = typeof (FaultException<>).MakeGenericType (t);
  408. object [] constructorParams = new object [] { detail, fault.Reason, fault.Code, fault.Actor };
  409. FaultException fe = (FaultException) Activator.CreateInstance (faultType, constructorParams);
  410. throw fe;
  411. }
  412. else {
  413. // given a MessageFault, it is hard to figure out the type of the embedded detail
  414. throw new FaultException(fault);
  415. }
  416. }
  417. for (int i = 0; i < inspections.Length; i++)
  418. runtime.MessageInspectors [i].AfterReceiveReply (ref res, inspections [i]);
  419. if (op.DeserializeReply)
  420. return op.GetFormatter ().DeserializeReply (res, parameters);
  421. else
  422. return res;
  423. }
  424. #region Message-based Request() and Send()
  425. // They are internal for ClientBase<T>.ChannelBase use.
  426. internal Message Request (Message msg, TimeSpan timeout)
  427. {
  428. if (RequestChannel != null)
  429. return RequestChannel.Request (msg, timeout);
  430. else {
  431. DateTime startTime = DateTime.Now;
  432. OutputChannel.Send (msg, timeout);
  433. return ((IDuplexChannel) OutputChannel).Receive (timeout - (DateTime.Now - startTime));
  434. }
  435. }
  436. internal IAsyncResult BeginRequest (Message msg, TimeSpan timeout, AsyncCallback callback, object state)
  437. {
  438. return requestDelegate.BeginInvoke (msg, timeout, callback, state);
  439. }
  440. internal Message EndRequest (IAsyncResult result)
  441. {
  442. return requestDelegate.EndInvoke (result);
  443. }
  444. internal void Send (Message msg, TimeSpan timeout)
  445. {
  446. OutputChannel.Send (msg, timeout);
  447. }
  448. internal IAsyncResult BeginSend (Message msg, TimeSpan timeout, AsyncCallback callback, object state)
  449. {
  450. return sendDelegate.BeginInvoke (msg, timeout, callback, state);
  451. }
  452. internal void EndSend (IAsyncResult result)
  453. {
  454. sendDelegate.EndInvoke (result);
  455. }
  456. #endregion
  457. Message CreateRequest (ClientOperation op, object [] parameters)
  458. {
  459. MessageVersion version = message_version;
  460. if (version == null)
  461. version = MessageVersion.Default;
  462. Message msg;
  463. if (op.SerializeRequest)
  464. msg = op.GetFormatter ().SerializeRequest (
  465. version, parameters);
  466. else {
  467. if (parameters.Length != 1)
  468. throw new ArgumentException (String.Format ("Argument parameters does not match the expected input. It should contain only a Message, but has {0} parameters", parameters.Length));
  469. if (!(parameters [0] is Message))
  470. throw new ArgumentException (String.Format ("Argument should be only a Message, but has {0}", parameters [0] != null ? parameters [0].GetType ().FullName : "null"));
  471. msg = (Message) parameters [0];
  472. }
  473. context = context ?? OperationContext.Current;
  474. if (context != null) {
  475. // CopyHeadersFrom does not work here (brings duplicates -> error)
  476. foreach (var mh in context.OutgoingMessageHeaders) {
  477. int x = msg.Headers.FindHeader (mh.Name, mh.Namespace, mh.Actor);
  478. if (x >= 0)
  479. msg.Headers.RemoveAt (x);
  480. msg.Headers.Add ((MessageHeader) mh);
  481. }
  482. msg.Properties.CopyProperties (context.OutgoingMessageProperties);
  483. }
  484. if (OutputSession != null)
  485. msg.Headers.MessageId = new UniqueId (OutputSession.Id);
  486. msg.Properties.AllowOutputBatching = AllowOutputBatching;
  487. if (msg.Version.Addressing.Equals (AddressingVersion.WSAddressing10)) {
  488. if (msg.Headers.MessageId == null)
  489. msg.Headers.MessageId = new UniqueId ();
  490. if (msg.Headers.ReplyTo == null)
  491. msg.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
  492. if (msg.Headers.To == null)
  493. msg.Headers.To = RemoteAddress.Uri;
  494. }
  495. return msg;
  496. }
  497. #endregion
  498. }
  499. }