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
|
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Routing
{
using System;
using System.Collections.Generic;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Transactions;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
static class ClientFactory
{
public static IRoutingClient Create(RoutingEndpointTrait endpointTrait, RoutingService service, bool impersonating)
{
Type contractType = endpointTrait.RouterContract;
IRoutingClient client;
if (contractType == typeof(ISimplexDatagramRouter))
{
client = new SimplexDatagramClient(endpointTrait, service.RoutingConfig, impersonating);
}
else if (contractType == typeof(IRequestReplyRouter))
{
client = new RequestReplyClient(endpointTrait, service.RoutingConfig, impersonating);
}
else if (contractType == typeof(ISimplexSessionRouter))
{
client = new SimplexSessionClient(endpointTrait, service.RoutingConfig, impersonating);
}
else //if (contractType == typeof(IDuplexSessionRouter))
{
Fx.Assert(contractType == typeof(IDuplexSessionRouter), "Only one contract type remaining.");
client = new DuplexSessionClient(service, endpointTrait, impersonating);
}
return client;
}
abstract class RoutingClientBase<TChannel> : ClientBase<TChannel>, IRoutingClient
where TChannel : class
{
bool openCompleted;
object thisLock;
Queue<OperationAsyncResult> waiters;
protected RoutingClientBase(RoutingEndpointTrait endpointTrait, RoutingConfiguration routingConfig, bool impersonating)
: base(endpointTrait.Endpoint.Binding, endpointTrait.Endpoint.Address)
{
Initialize(endpointTrait, routingConfig, impersonating);
}
protected RoutingClientBase(RoutingEndpointTrait endpointTrait, RoutingConfiguration routingConfig, object callbackInstance, bool impersonating)
: base(new InstanceContext(callbackInstance), endpointTrait.Endpoint.Binding, endpointTrait.Endpoint.Address)
{
Initialize(endpointTrait, routingConfig, impersonating);
}
public RoutingEndpointTrait Key
{
get;
private set;
}
public event EventHandler Faulted;
static void ConfigureImpersonation(ServiceEndpoint endpoint, bool impersonating)
{
// Used for both impersonation and ASP.NET Compatibilty Mode. Both currently require
// everything to be synchronous.
if (impersonating)
{
CustomBinding binding = endpoint.Binding as CustomBinding;
if (binding == null)
{
binding = new CustomBinding(endpoint.Binding);
}
SynchronousSendBindingElement syncSend = binding.Elements.Find<SynchronousSendBindingElement>();
if (syncSend == null)
{
binding.Elements.Insert(0, new SynchronousSendBindingElement());
endpoint.Binding = binding;
}
}
}
static void ConfigureTransactionFlow(ServiceEndpoint endpoint)
{
CustomBinding binding = endpoint.Binding as CustomBinding;
if (binding == null)
{
binding = new CustomBinding(endpoint.Binding);
}
TransactionFlowBindingElement transactionFlow = binding.Elements.Find<TransactionFlowBindingElement>();
if (transactionFlow != null)
{
transactionFlow.AllowWildcardAction = true;
endpoint.Binding = binding;
}
}
void Initialize(RoutingEndpointTrait endpointTrait, RoutingConfiguration routingConfig, bool impersonating)
{
this.thisLock = new object();
this.Key = endpointTrait;
if (TD.RoutingServiceCreatingClientForEndpointIsEnabled())
{
TD.RoutingServiceCreatingClientForEndpoint(this.Key.ToString());
}
ServiceEndpoint clientEndpoint = endpointTrait.Endpoint;
ServiceEndpoint endpoint = this.Endpoint;
KeyedByTypeCollection<IEndpointBehavior> behaviors = endpoint.Behaviors;
endpoint.ListenUri = clientEndpoint.ListenUri;
endpoint.ListenUriMode = clientEndpoint.ListenUriMode;
endpoint.Name = clientEndpoint.Name;
foreach (IEndpointBehavior behavior in clientEndpoint.Behaviors)
{
// Remove if present, ok to call if not there (will simply return false)
behaviors.Remove(behavior.GetType());
behaviors.Add(behavior);
}
// If the configuration doesn't explicitly add MustUnderstandBehavior (to override us)
// add it here, with mustunderstand = false.
if (behaviors.Find<MustUnderstandBehavior>() == null)
{
behaviors.Add(new MustUnderstandBehavior(false));
}
// If the configuration doesn't explicitly turn off marshaling we add it here.
if (routingConfig.SoapProcessingEnabled && behaviors.Find<SoapProcessingBehavior>() == null)
{
behaviors.Add(new SoapProcessingBehavior());
}
ConfigureTransactionFlow(endpoint);
ConfigureImpersonation(endpoint, impersonating);
}
protected override TChannel CreateChannel()
{
TChannel channel = base.CreateChannel();
((ICommunicationObject)channel).Faulted += this.InnerChannelFaulted;
return channel;
}
public IAsyncResult BeginOperation(Message message, Transaction transaction, AsyncCallback callback, object state)
{
return new OperationAsyncResult(this, message, transaction, callback, state);
}
public Message EndOperation(IAsyncResult result)
{
return OperationAsyncResult.End(result);
}
protected abstract IAsyncResult OnBeginOperation(Message message, AsyncCallback callback, object state);
protected abstract Message OnEndOperation(IAsyncResult asyncResult);
void InnerChannelFaulted(object sender, EventArgs args)
{
EventHandler handlers = this.Faulted;
if (handlers != null)
{
handlers(this, args);
}
}
class OperationAsyncResult : TransactedAsyncResult
{
static AsyncCompletion openComplete = OpenComplete;
static AsyncCompletion operationComplete = OperationComplete;
static Action<object> signalWaiter;
RoutingClientBase<TChannel> parent;
Message replyMessage;
Message requestMessage;
Transaction transaction;
public OperationAsyncResult(RoutingClientBase<TChannel> parent, Message requestMessage, Transaction transaction, AsyncCallback callback, object state)
: base(callback, state)
{
this.parent = parent;
this.requestMessage = requestMessage;
this.transaction = transaction;
bool shouldOpen = false;
if (!this.parent.openCompleted)
{
lock (this.parent.thisLock)
{
if (!this.parent.openCompleted)
{
//The first to open initializes the waiters queue others add themselves to it.
if (this.parent.waiters == null)
{
//it's our job to open the proxy
this.parent.waiters = new Queue<OperationAsyncResult>();
shouldOpen = true;
}
else
{
//Someone beat us to it, just join the list of waiters.
this.parent.waiters.Enqueue(this);
return;
}
}
}
}
if (shouldOpen)
{
//we are the first so we need to open this channel
IAsyncResult asyncResult;
using (this.PrepareTransactionalCall(this.transaction))
{
//This will use the binding's OpenTimeout.
asyncResult = ((ICommunicationObject)this.parent).BeginOpen(this.PrepareAsyncCompletion(openComplete), this);
}
if (this.SyncContinue(asyncResult))
{
this.Complete(true);
}
}
else
{
if (this.CallOperation())
{
this.Complete(true);
}
}
}
public static Message End(IAsyncResult result)
{
OperationAsyncResult thisPtr = AsyncResult.End<OperationAsyncResult>(result);
return thisPtr.replyMessage;
}
static bool OpenComplete(IAsyncResult openResult)
{
OperationAsyncResult thisPtr = (OperationAsyncResult)openResult.AsyncState;
try
{
((ICommunicationObject)thisPtr.parent).EndOpen(openResult);
}
finally
{
Queue<OperationAsyncResult> localWaiters = null;
lock (thisPtr.parent.thisLock)
{
localWaiters = thisPtr.parent.waiters;
thisPtr.parent.waiters = null;
thisPtr.parent.openCompleted = true;
}
if (localWaiters != null && localWaiters.Count > 0)
{
if (signalWaiter == null)
{
signalWaiter = new Action<object>(SignalWaiter);
}
//foreach over Queue<T> goes FIFO
foreach (OperationAsyncResult waiter in localWaiters)
{
ActionItem.Schedule(signalWaiter, waiter);
}
}
}
return thisPtr.CallOperation();
}
bool CallOperation()
{
IAsyncResult asyncResult;
using (this.PrepareTransactionalCall(this.transaction))
{
asyncResult = this.parent.OnBeginOperation(this.requestMessage, this.PrepareAsyncCompletion(operationComplete), this);
}
return this.SyncContinue(asyncResult);
}
static bool OperationComplete(IAsyncResult result)
{
OperationAsyncResult thisPtr = (OperationAsyncResult)result.AsyncState;
thisPtr.replyMessage = thisPtr.parent.OnEndOperation(result);
return true;
}
static void SignalWaiter(object state)
{
OperationAsyncResult waiter = (OperationAsyncResult)state;
try
{
if (waiter.CallOperation())
{
waiter.Complete(false);
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
waiter.Complete(false, exception);
}
}
}
}
class SimplexDatagramClient : RoutingClientBase<ISimplexDatagramRouter>
{
public SimplexDatagramClient(RoutingEndpointTrait endpointTrait, RoutingConfiguration routingConfig, bool impersonating)
: base(endpointTrait, routingConfig, impersonating)
{
}
protected override IAsyncResult OnBeginOperation(Message message, AsyncCallback callback, object state)
{
return this.Channel.BeginProcessMessage(message, callback, state);
}
protected override Message OnEndOperation(IAsyncResult result)
{
this.Channel.EndProcessMessage(result);
return null;
}
}
class SimplexSessionClient : RoutingClientBase<ISimplexSessionRouter>
{
public SimplexSessionClient(RoutingEndpointTrait endointTrait, RoutingConfiguration routingConfig, bool impersonating)
: base(endointTrait, routingConfig, impersonating)
{
}
protected override IAsyncResult OnBeginOperation(Message message, AsyncCallback callback, object state)
{
return this.Channel.BeginProcessMessage(message, callback, state);
}
protected override Message OnEndOperation(IAsyncResult result)
{
this.Channel.EndProcessMessage(result);
return null;
}
}
class DuplexSessionClient : RoutingClientBase<IDuplexSessionRouter>
{
public DuplexSessionClient(RoutingService service, RoutingEndpointTrait endpointTrait, bool impersonating)
: base(endpointTrait, service.RoutingConfig, new DuplexCallbackProxy(service.ChannelExtension.ActivityID, endpointTrait.CallbackInstance), impersonating)
{
}
protected override IAsyncResult OnBeginOperation(Message message, AsyncCallback callback, object state)
{
return this.Channel.BeginProcessMessage(message, callback, state);
}
protected override Message OnEndOperation(IAsyncResult result)
{
this.Channel.EndProcessMessage(result);
return null;
}
class DuplexCallbackProxy : IDuplexRouterCallback
{
Guid activityID;
IDuplexRouterCallback callbackInstance;
EventTraceActivity eventTraceActivity;
public DuplexCallbackProxy(Guid activityID, IDuplexRouterCallback callbackInstance)
{
this.activityID = activityID;
this.callbackInstance = callbackInstance;
if (Fx.Trace.IsEtwProviderEnabled)
{
this.eventTraceActivity = new EventTraceActivity(activityID);
}
}
IAsyncResult IDuplexRouterCallback.BeginProcessMessage(Message message, AsyncCallback callback, object state)
{
FxTrace.Trace.SetAndTraceTransfer(this.activityID, true);
try
{
return new CallbackAsyncResult(this.callbackInstance, message, callback, state);
}
catch (Exception e)
{
if (TD.RoutingServiceDuplexCallbackExceptionIsEnabled())
{
TD.RoutingServiceDuplexCallbackException(this.eventTraceActivity, "DuplexCallbackProxy.BeginProcessMessage", e);
}
throw;
}
}
void IDuplexRouterCallback.EndProcessMessage(IAsyncResult result)
{
FxTrace.Trace.SetAndTraceTransfer(this.activityID, true);
try
{
CallbackAsyncResult.End(result);
}
catch (Exception e)
{
if (TD.RoutingServiceDuplexCallbackExceptionIsEnabled())
{
TD.RoutingServiceDuplexCallbackException(this.eventTraceActivity, "DuplexCallbackProxy.EndProcessMessage", e);
}
throw;
}
}
// We have to have an AsyncResult implementation here in order to handle the
// TransactionScope appropriately (use PrepareTransactionalCall, SyncContinue, etc...)
class CallbackAsyncResult : TransactedAsyncResult
{
static AsyncCompletion processCallback = ProcessCallback;
IDuplexRouterCallback callbackInstance;
public CallbackAsyncResult(IDuplexRouterCallback callbackInstance, Message message, AsyncCallback callback, object state)
: base(callback, state)
{
this.callbackInstance = callbackInstance;
IAsyncResult result;
using (this.PrepareTransactionalCall(TransactionMessageProperty.TryGetTransaction(message)))
{
result = this.callbackInstance.BeginProcessMessage(message,
this.PrepareAsyncCompletion(processCallback), this);
}
if (this.SyncContinue(result))
{
this.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CallbackAsyncResult>(result);
}
static bool ProcessCallback(IAsyncResult result)
{
CallbackAsyncResult thisPtr = (CallbackAsyncResult)result.AsyncState;
thisPtr.callbackInstance.EndProcessMessage(result);
return true;
}
}
}
}
class RequestReplyClient : RoutingClientBase<IRequestReplyRouter>
{
public RequestReplyClient(RoutingEndpointTrait endpointTrait, RoutingConfiguration routingConfig, bool impersonating)
: base(endpointTrait, routingConfig, impersonating)
{
}
protected override IAsyncResult OnBeginOperation(Message message, AsyncCallback callback, object state)
{
return this.Channel.BeginProcessRequest(message, callback, state);
}
protected override Message OnEndOperation(IAsyncResult result)
{
return this.Channel.EndProcessRequest(result);
}
}
}
}
|