1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
|
//
// ClientRuntimeChannel.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.Threading;
using System.Xml;
namespace System.ServiceModel.MonoInternal
{
#if DISABLE_REAL_PROXY
// FIXME: This is a quick workaround for bug #571907
public
#endif
interface IInternalContextChannel
{
ContractDescription Contract { get; }
OperationContext Context { set; }
object Process (MethodBase method, string operationName, object [] parameters);
IAsyncResult BeginProcess (MethodBase method, string operationName, object [] parameters, AsyncCallback callback, object asyncState);
object EndProcess (MethodBase method, string operationName, object [] parameters, IAsyncResult result);
}
#if DISABLE_REAL_PROXY
// FIXME: This is a quick workaround for bug #571907
public
#endif
class ClientRuntimeChannel
: CommunicationObject, IClientChannel, IInternalContextChannel
{
ClientRuntime runtime;
EndpointAddress remote_address;
ContractDescription contract;
MessageVersion message_version;
TimeSpan default_open_timeout, default_close_timeout;
IChannel channel;
IChannelFactory factory;
OperationContext context;
#region delegates
readonly ProcessDelegate _processDelegate;
delegate object ProcessDelegate (MethodBase method, string operationName, object [] parameters);
readonly RequestDelegate requestDelegate;
delegate Message RequestDelegate (Message msg, TimeSpan timeout);
readonly SendDelegate sendDelegate;
delegate void SendDelegate (Message msg, TimeSpan timeout);
#endregion
public ClientRuntimeChannel (ServiceEndpoint endpoint,
ChannelFactory channelFactory, EndpointAddress remoteAddress, Uri via)
: this (endpoint.CreateClientRuntime (null), endpoint.Contract, channelFactory.DefaultOpenTimeout, channelFactory.DefaultCloseTimeout, null, channelFactory.OpenedChannelFactory, endpoint.Binding.MessageVersion, remoteAddress, via)
{
}
public ClientRuntimeChannel (ClientRuntime runtime, ContractDescription contract, TimeSpan openTimeout, TimeSpan closeTimeout, IChannel contextChannel, IChannelFactory factory, MessageVersion messageVersion, EndpointAddress remoteAddress, Uri via)
{
if (runtime == null)
throw new ArgumentNullException ("runtime");
if (messageVersion == null)
throw new ArgumentNullException ("messageVersion");
this.runtime = runtime;
this.remote_address = remoteAddress;
if (runtime.Via == null)
runtime.Via = via ?? (remote_address != null ?remote_address.Uri : null);
this.contract = contract;
this.message_version = messageVersion;
default_open_timeout = openTimeout;
default_close_timeout = closeTimeout;
_processDelegate = new ProcessDelegate (Process);
requestDelegate = new RequestDelegate (Request);
sendDelegate = new SendDelegate (Send);
// default values
AllowInitializationUI = true;
OperationTimeout = TimeSpan.FromMinutes (1);
if (contextChannel != null)
channel = contextChannel;
else {
var method = factory.GetType ().GetMethod ("CreateChannel", new Type [] {typeof (EndpointAddress), typeof (Uri)});
try {
channel = (IChannel) method.Invoke (factory, new object [] {remote_address, Via});
this.factory = factory;
} catch (TargetInvocationException ex) {
if (ex.InnerException != null)
throw ex.InnerException;
else
throw;
}
}
}
public ContractDescription Contract {
get { return contract; }
}
public ClientRuntime Runtime {
get { return runtime; }
}
IRequestChannel RequestChannel {
get { return channel as IRequestChannel; }
}
IOutputChannel OutputChannel {
get { return channel as IOutputChannel; }
}
internal IDuplexChannel DuplexChannel {
get { return channel as IDuplexChannel; }
}
public OperationContext Context {
set { context = value; }
}
#region IClientChannel
bool did_interactive_initialization;
public bool AllowInitializationUI { get; set; }
public bool DidInteractiveInitialization {
get { return did_interactive_initialization; }
}
public Uri Via {
get { return runtime.Via; }
}
class DelegatingWaitHandle : WaitHandle
{
public DelegatingWaitHandle (IAsyncResult [] results)
{
this.results = results;
}
IAsyncResult [] results;
protected override void Dispose (bool disposing)
{
if (disposing)
foreach (var r in results)
r.AsyncWaitHandle.Close ();
}
public override bool WaitOne ()
{
foreach (var r in results)
r.AsyncWaitHandle.WaitOne ();
return true;
}
public override bool WaitOne (int millisecondsTimeout)
{
return WaitHandle.WaitAll (ResultWaitHandles, millisecondsTimeout);
}
WaitHandle [] ResultWaitHandles {
get {
var arr = new WaitHandle [results.Length];
for (int i = 0; i < arr.Length; i++)
arr [i] = results [i].AsyncWaitHandle;
return arr;
}
}
#if !MOONLIGHT
public override bool WaitOne (int millisecondsTimeout, bool exitContext)
{
return WaitHandle.WaitAll (ResultWaitHandles, millisecondsTimeout, exitContext);
}
public override bool WaitOne (TimeSpan timeout, bool exitContext)
{
return WaitHandle.WaitAll (ResultWaitHandles, timeout, exitContext);
}
#endif
}
class DisplayUIAsyncResult : IAsyncResult
{
public DisplayUIAsyncResult (IAsyncResult [] results)
{
this.results = results;
}
IAsyncResult [] results;
internal IAsyncResult [] Results {
get { return results; }
}
public object AsyncState {
get { return null; }
}
WaitHandle wait_handle;
public WaitHandle AsyncWaitHandle {
get {
if (wait_handle == null)
wait_handle = new DelegatingWaitHandle (results);
return wait_handle;
}
}
public bool CompletedSynchronously {
get {
foreach (var r in results)
if (!r.CompletedSynchronously)
return false;
return true;
}
}
public bool IsCompleted {
get {
foreach (var r in results)
if (!r.IsCompleted)
return false;
return true;
}
}
}
public IAsyncResult BeginDisplayInitializationUI (
AsyncCallback callback, object state)
{
OnInitializationUI ();
IAsyncResult [] arr = new IAsyncResult [runtime.InteractiveChannelInitializers.Count];
int i = 0;
foreach (var init in runtime.InteractiveChannelInitializers)
arr [i++] = init.BeginDisplayInitializationUI (this, callback, state);
return new DisplayUIAsyncResult (arr);
}
public void EndDisplayInitializationUI (
IAsyncResult result)
{
DisplayUIAsyncResult r = (DisplayUIAsyncResult) result;
int i = 0;
foreach (var init in runtime.InteractiveChannelInitializers)
init.EndDisplayInitializationUI (r.Results [i++]);
did_interactive_initialization = true;
}
public void DisplayInitializationUI ()
{
OnInitializationUI ();
foreach (var init in runtime.InteractiveChannelInitializers)
init.EndDisplayInitializationUI (init.BeginDisplayInitializationUI (this, null, null));
did_interactive_initialization = true;
}
void OnInitializationUI ()
{
if (!AllowInitializationUI && runtime.InteractiveChannelInitializers.Count > 0)
throw new InvalidOperationException ("AllowInitializationUI is set to false but the client runtime contains one or more InteractiveChannelInitializers.");
}
public void Dispose ()
{
Close ();
}
public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived;
#endregion
#region IContextChannel
[MonoTODO]
public bool AllowOutputBatching { get; set; }
public IInputSession InputSession {
get {
ISessionChannel<IInputSession> ch = RequestChannel as ISessionChannel<IInputSession>;
ch = ch ?? OutputChannel as ISessionChannel<IInputSession>;
if (ch != null)
return ch.Session;
var dch = OutputChannel as ISessionChannel<IDuplexSession>;
return dch != null ? dch.Session : null;
}
}
public EndpointAddress LocalAddress {
get {
var dc = OperationChannel as IDuplexChannel;
return dc != null ? dc.LocalAddress : null;
}
}
[MonoTODO]
public TimeSpan OperationTimeout { get; set; }
public IOutputSession OutputSession {
get {
ISessionChannel<IOutputSession> ch = RequestChannel as ISessionChannel<IOutputSession>;
ch = ch ?? OutputChannel as ISessionChannel<IOutputSession>;
if (ch != null)
return ch.Session;
var dch = OutputChannel as ISessionChannel<IDuplexSession>;
return dch != null ? dch.Session : null;
}
}
public EndpointAddress RemoteAddress {
get { return RequestChannel != null ? RequestChannel.RemoteAddress : OutputChannel.RemoteAddress; }
}
public string SessionId {
get { return OutputSession != null ? OutputSession.Id : InputSession != null ? InputSession.Id : null; }
}
#endregion
// CommunicationObject
protected internal override TimeSpan DefaultOpenTimeout {
get { return default_open_timeout; }
}
protected internal override TimeSpan DefaultCloseTimeout {
get { return default_close_timeout; }
}
protected override void OnAbort ()
{
channel.Abort ();
if (factory != null) // ... is it valid?
factory.Abort ();
}
Action<TimeSpan> close_delegate;
protected override IAsyncResult OnBeginClose (
TimeSpan timeout, AsyncCallback callback, object state)
{
if (close_delegate == null)
close_delegate = new Action<TimeSpan> (OnClose);
return close_delegate.BeginInvoke (timeout, callback, state);
}
protected override void OnEndClose (IAsyncResult result)
{
close_delegate.EndInvoke (result);
}
protected override void OnClose (TimeSpan timeout)
{
DateTime start = DateTime.Now;
if (channel.State == CommunicationState.Opened)
channel.Close (timeout);
}
Action<TimeSpan> open_callback;
protected override IAsyncResult OnBeginOpen (
TimeSpan timeout, AsyncCallback callback, object state)
{
if (open_callback == null)
open_callback = new Action<TimeSpan> (OnOpen);
return open_callback.BeginInvoke (timeout, callback, state);
}
protected override void OnEndOpen (IAsyncResult result)
{
if (open_callback == null)
throw new InvalidOperationException ("Async open operation has not started");
open_callback.EndInvoke (result);
}
protected override void OnOpen (TimeSpan timeout)
{
if (runtime.InteractiveChannelInitializers.Count > 0 && !DidInteractiveInitialization)
throw new InvalidOperationException ("The client runtime is assigned interactive channel initializers, and in such case DisplayInitializationUI must be called before the channel is opened.");
if (channel.State == CommunicationState.Created)
channel.Open (timeout);
}
// IChannel
IChannel OperationChannel {
get { return channel; }
}
public T GetProperty<T> () where T : class
{
if (typeof (T) == typeof (MessageVersion))
return (T) (object) message_version;
return OperationChannel.GetProperty<T> ();
}
// IExtensibleObject<IContextChannel>
IExtensionCollection<IContextChannel> extensions;
public IExtensionCollection<IContextChannel> Extensions {
get {
if (extensions == null)
extensions = new ExtensionCollection<IContextChannel> (this);
return extensions;
}
}
#region Request/Output processing
public IAsyncResult BeginProcess (MethodBase method, string operationName, object [] parameters, AsyncCallback callback, object asyncState)
{
if (context != null)
throw new InvalidOperationException ("another operation is in progress");
context = OperationContext.Current;
return _processDelegate.BeginInvoke (method, operationName, parameters, callback, asyncState);
}
public object EndProcess (MethodBase method, string operationName, object [] parameters, IAsyncResult result)
{
if (result == null)
throw new ArgumentNullException ("result");
if (parameters == null)
throw new ArgumentNullException ("parameters");
// FIXME: the method arguments should be verified to be
// identical to the arguments in the corresponding begin method.
object asyncResult = _processDelegate.EndInvoke (result);
context = null;
return asyncResult;
}
public object Process (MethodBase method, string operationName, object [] parameters)
{
var previousContext = OperationContext.Current;
try {
// Inherit the context from the calling thread
if (this.context != null)
OperationContext.Current = this.context;
return DoProcess (method, operationName, parameters);
} catch (Exception ex) {
#if MOONLIGHT // just for debugging
Console.Write ("Exception in async operation: ");
Console.WriteLine (ex);
#endif
throw;
} finally {
// Reset the context before the thread goes back into the pool
OperationContext.Current = previousContext;
}
}
object DoProcess (MethodBase method, string operationName, object [] parameters)
{
if (AllowInitializationUI)
DisplayInitializationUI ();
OperationDescription od = SelectOperation (method, operationName, parameters);
if (State != CommunicationState.Opened)
Open ();
if (!od.IsOneWay)
return Request (od, parameters);
else {
Output (od, parameters);
return null;
}
}
OperationDescription SelectOperation (MethodBase method, string operationName, object [] parameters)
{
string operation;
if (Runtime.OperationSelector != null)
operation = Runtime.OperationSelector.SelectOperation (method, parameters);
else
operation = operationName;
OperationDescription od = contract.Operations.Find (operation);
if (od == null)
throw new Exception (String.Format ("OperationDescription for operation '{0}' was not found in its internally-generated contract.", operation));
return od;
}
void Output (OperationDescription od, object [] parameters)
{
ClientOperation op = runtime.Operations [od.Name];
Send (CreateRequest (op, parameters), OperationTimeout);
}
object Request (OperationDescription od, object [] parameters)
{
ClientOperation op = runtime.Operations [od.Name];
object [] inspections = new object [runtime.MessageInspectors.Count];
Message req = CreateRequest (op, parameters);
for (int i = 0; i < inspections.Length; i++)
inspections [i] = runtime.MessageInspectors [i].BeforeSendRequest (ref req, this);
Message res = Request (req, OperationTimeout);
if (res.IsFault) {
var resb = res.CreateBufferedCopy (runtime.MaxFaultSize);
MessageFault fault = MessageFault.CreateFault (resb.CreateMessage (), runtime.MaxFaultSize);
var conv = OperationChannel.GetProperty<FaultConverter> () ?? FaultConverter.GetDefaultFaultConverter (res.Version);
Exception ex;
if (!conv.TryCreateException (resb.CreateMessage (), fault, out ex)) {
if (fault.HasDetail) {
Type detailType = typeof (ExceptionDetail);
var freader = fault.GetReaderAtDetailContents ();
DataContractSerializer ds = null;
#if !NET_2_1
foreach (var fci in op.FaultContractInfos)
if (res.Headers.Action == fci.Action || fci.Serializer.IsStartObject (freader)) {
detailType = fci.Detail;
ds = fci.Serializer;
break;
}
#endif
if (ds == null)
ds = new DataContractSerializer (detailType);
var detail = ds.ReadObject (freader);
ex = (Exception) Activator.CreateInstance (typeof (FaultException<>).MakeGenericType (detailType), new object [] {detail, fault.Reason, fault.Code, res.Headers.Action});
}
if (ex == null)
ex = new FaultException (fault);
}
throw ex;
}
for (int i = 0; i < inspections.Length; i++)
runtime.MessageInspectors [i].AfterReceiveReply (ref res, inspections [i]);
if (op.DeserializeReply)
return op.Formatter.DeserializeReply (res, parameters);
else
return res;
}
#region Message-based Request() and Send()
// They are internal for ClientBase<T>.ChannelBase use.
internal Message Request (Message msg, TimeSpan timeout)
{
if (RequestChannel != null)
return RequestChannel.Request (msg, timeout);
else
return RequestCorrelated (msg, timeout, OutputChannel);
}
internal virtual Message RequestCorrelated (Message msg, TimeSpan timeout, IOutputChannel channel)
{
// FIXME: implement ConcurrencyMode check:
// if it is .Single && this instance for a callback channel && the operation is invoked inside service operation, then error.
DateTime startTime = DateTime.Now;
OutputChannel.Send (msg, timeout);
return ((IDuplexChannel) channel).Receive (timeout - (DateTime.Now - startTime));
}
internal IAsyncResult BeginRequest (Message msg, TimeSpan timeout, AsyncCallback callback, object state)
{
return requestDelegate.BeginInvoke (msg, timeout, callback, state);
}
internal Message EndRequest (IAsyncResult result)
{
return requestDelegate.EndInvoke (result);
}
internal void Send (Message msg, TimeSpan timeout)
{
if (OutputChannel != null)
OutputChannel.Send (msg, timeout);
else
RequestChannel.Request (msg, timeout); // and ignore returned message.
}
internal IAsyncResult BeginSend (Message msg, TimeSpan timeout, AsyncCallback callback, object state)
{
return sendDelegate.BeginInvoke (msg, timeout, callback, state);
}
internal void EndSend (IAsyncResult result)
{
sendDelegate.EndInvoke (result);
}
#endregion
Message CreateRequest (ClientOperation op, object [] parameters)
{
MessageVersion version = message_version;
if (version == null)
version = MessageVersion.Default;
Message msg;
if (op.SerializeRequest)
msg = op.Formatter.SerializeRequest (
version, parameters);
else {
if (parameters.Length != 1)
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));
if (!(parameters [0] is Message))
throw new ArgumentException (String.Format ("Argument should be only a Message, but has {0}", parameters [0] != null ? parameters [0].GetType ().FullName : "null"));
msg = (Message) parameters [0];
}
context = context ?? OperationContext.Current;
if (context != null) {
// CopyHeadersFrom does not work here (brings duplicates -> error)
foreach (var mh in context.OutgoingMessageHeaders) {
int x = msg.Headers.FindHeader (mh.Name, mh.Namespace, mh.Actor);
if (x >= 0)
msg.Headers.RemoveAt (x);
msg.Headers.Add ((MessageHeader) mh);
}
msg.Properties.CopyProperties (context.OutgoingMessageProperties);
}
// FIXME: disabling MessageId as it's not seen for bug #567672 case. But might be required for PeerDuplexChannel. Check it later.
//if (OutputSession != null)
// msg.Headers.MessageId = new UniqueId (OutputSession.Id);
msg.Properties.AllowOutputBatching = AllowOutputBatching;
if (msg.Version.Addressing.Equals (AddressingVersion.WSAddressing10)) {
if (msg.Headers.MessageId == null)
msg.Headers.MessageId = new UniqueId ();
if (msg.Headers.ReplyTo == null)
msg.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
if (msg.Headers.To == null && RemoteAddress != null)
msg.Headers.To = RemoteAddress.Uri;
}
return msg;
}
#endregion
}
}
|