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 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activities
{
using System.Activities;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.ServiceModel.Activation;
using System.ServiceModel.Activities.Description;
using System.ServiceModel.Activities.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Transactions;
using TD2 = System.ServiceModel.Diagnostics.Application.TD;
// This AsyncResult completion is very tricky. It can complete in two path.
// FastPath: When workflow executes synchronously(SendFault/SendReply called before ResumeBookmark completes) we complete the AsyncResult at HandleEndResumeBookmark;
// Async Path: If workflow goes async (SendFault/SendReply called after ResumeBookmark completes) we complete the AsyncResult at SendFault/SendReply.
class WorkflowOperationContext : AsyncResult
{
static readonly ReadOnlyDictionaryInternal<string, string> emptyDictionary = new ReadOnlyDictionaryInternal<string, string>(new Dictionary<string, string>());
static readonly object[] emptyObjectArray = new object[0];
static AsyncCompletion handleEndResumeBookmark = new AsyncCompletion(HandleEndResumeBookmark);
static AsyncCompletion handleEndWaitForPendingOperations = new AsyncCompletion(HandleEndWaitForPendingOperations);
static AsyncCompletion handleEndProcessReceiveContext;
static Action<AsyncResult, Exception> onCompleting = new Action<AsyncResult, Exception>(Finally);
object[] inputs;
string operationName;
object[] outputs;
object operationReturnValue;
object thisLock;
WorkflowServiceInstance workflowInstance;
Bookmark bookmark;
object bookmarkValue;
BookmarkScope bookmarkScope;
IInvokeReceivedNotification notification;
IAsyncResult pendingAsyncResult;
TimeoutHelper timeoutHelper;
Exception pendingException;
ReceiveContext receiveContext;
// perf counter data
bool performanceCountersEnabled;
long beginTime;
// tracing data
bool propagateActivity;
Guid ambientActivityId;
Guid e2eActivityId;
EventTraceActivity eventTraceActivity;
long beginOperation;
//Tracking for decrement of ASP.NET busy count
bool hasDecrementedBusyCount;
WorkflowOperationContext(object[] inputs, OperationContext operationContext, string operationName,
bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction,
WorkflowServiceInstance workflowInstance, IInvokeReceivedNotification notification, WorkflowOperationBehavior behavior, ServiceEndpoint endpoint,
TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.inputs = inputs;
this.operationName = operationName;
this.OperationContext = operationContext;
this.ServiceEndpoint = endpoint;
this.CurrentTransaction = currentTransaction;
this.performanceCountersEnabled = performanceCountersEnabled;
this.propagateActivity = propagateActivity;
this.timeoutHelper = new TimeoutHelper(timeout);
this.workflowInstance = workflowInstance;
this.thisLock = new object();
this.notification = notification;
this.OnCompleting = onCompleting;
// Resolve bookmark
Fx.Assert(behavior != null, "behavior must not be null!");
this.bookmark = behavior.OnResolveBookmark(this, out this.bookmarkScope, out this.bookmarkValue);
Fx.Assert(this.bookmark != null, "bookmark must not be null!");
bool completeSelf = false;
try
{
// set activity ID on the executing thread (Bug 113386)
if (TraceUtility.MessageFlowTracingOnly)
{
this.e2eActivityId = TraceUtility.GetReceivedActivityId(this.OperationContext);
DiagnosticTraceBase.ActivityId = this.e2eActivityId;
}
if (Fx.Trace.IsEtwProviderEnabled)
{
this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(this.OperationContext.IncomingMessage);
}
// Take ownership of the ReceiveContext when buffering is enabled by removing the property
if (this.workflowInstance.BufferedReceiveManager != null)
{
if (!ReceiveContext.TryGet(this.OperationContext.IncomingMessageProperties, out this.receiveContext))
{
Fx.Assert("ReceiveContext expected when BufferedReceives are enabled");
}
this.OperationContext.IncomingMessageProperties.Remove(ReceiveContext.Name);
}
completeSelf = ProcessRequest();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// Failing synchronously is one case where AsyncResult won't handle calling OnCompleting
OnCompleting(this, e);
throw;
}
if (completeSelf)
{
base.Complete(true);
}
}
public object[] Inputs
{
get
{
return this.inputs;
}
}
public OperationContext OperationContext
{
get;
private set;
}
public ServiceEndpoint ServiceEndpoint
{
get;
private set;
}
public Transaction CurrentTransaction
{
get;
private set;
}
public object BookmarkValue
{
get
{
return this.bookmarkValue;
}
}
public bool HasResponse
{
get
{
lock (this.thisLock)
{
return this.CurrentState == State.Completed || this.CurrentState == State.ResultReceived;
}
}
}
//Completion state of this AsyncResult guarded by propertyLock
State CurrentState
{
get;
set;
}
public Guid E2EActivityId
{
get
{
return this.e2eActivityId;
}
}
public static IAsyncResult BeginProcessRequest(WorkflowServiceInstance workflowInstance, OperationContext operationContext, string operationName,
object[] inputs, bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction, IInvokeReceivedNotification notification,
WorkflowOperationBehavior behavior, ServiceEndpoint endpoint, TimeSpan timeout, AsyncCallback callback, object state)
{
Fx.Assert(inputs != null, "Null inputs");
return new WorkflowOperationContext(inputs, operationContext, operationName, performanceCountersEnabled,
propagateActivity, currentTransaction, workflowInstance, notification, behavior, endpoint, timeout, callback, state);
}
public static object EndProcessRequest(IAsyncResult result, out object[] outputs)
{
WorkflowOperationContext thisPtr = AsyncResult.End<WorkflowOperationContext>(result);
outputs = thisPtr.outputs;
return thisPtr.operationReturnValue;
}
public void SendFault(Exception exception)
{
Fx.Assert(exception != null, "Null Exception");
this.pendingException = exception;
bool completeNow;
lock (this.thisLock)
{
Fx.Assert(this.CurrentState != State.Completed && this.CurrentState != State.ResultReceived, "Cannot receive this call after completion/result");
completeNow = ProcessReply();
}
if (completeNow)
{
this.Complete(false, exception);
}
}
public void SendReply(Message returnValue)
{
bool completeNow;
lock (this.thisLock)
{
Fx.Assert(this.CurrentState != State.Completed && this.CurrentState != State.ResultReceived, "Cannot receive this call after completion/result");
this.outputs = WorkflowOperationContext.emptyObjectArray; // everything is in the Message return value for workflow
this.operationReturnValue = returnValue;
completeNow = ProcessReply();
}
if (completeNow)
{
base.Complete(false);
}
}
public void SendReply(object returnValue, object[] outputs)
{
bool completeNow;
lock (this.thisLock)
{
Fx.Assert(this.CurrentState != State.Completed && this.CurrentState != State.ResultReceived, "Cannot receive this call after completion/result");
this.outputs = outputs ?? WorkflowOperationContext.emptyObjectArray;
this.operationReturnValue = returnValue;
completeNow = ProcessReply();
}
if (completeNow)
{
base.Complete(false);
}
}
//No-op for two-ways.
public void SetOperationCompleted()
{
bool completeNow;
lock (this.thisLock)
{
completeNow = ProcessReply();
}
if (completeNow)
{
base.Complete(false);
}
}
bool ProcessReply()
{
bool completed = false;
this.workflowInstance.ReleaseContext(this);
this.RemovePendingOperation();
if (this.CurrentState == State.BookmarkResumption) //We are still in Bookmark Resume
{
this.CurrentState = State.ResultReceived; //HandleEndResumeBookmark will take care of Completing AsyncResult.
}
else if (this.CurrentState == State.WaitForResult) //We already finished the bookmarkOperation; Now have to signal the AsynResult.
{
this.CurrentState = State.Completed;
completed = true;
}
// we are not really completed until the ReceiveContext finishes its work
if (completed)
{
if (this.pendingException == null)
{
completed = ProcessReceiveContext();
}
else
{
// if there's a pendingException, we let the RC abandon async so there's no need
// to affect the completed status
BufferedReceiveManager.AbandonReceiveContext(this.receiveContext);
}
}
return completed;
}
void ProcessInitializationTraces()
{
//Let asp.net know that it needs to wait
IncrementBusyCount();
try
{
if (TraceUtility.MessageFlowTracingOnly)
{
//ensure that Activity ID is set
DiagnosticTraceBase.ActivityId = this.E2EActivityId;
this.propagateActivity = false;
}
if (TraceUtility.ActivityTracing || (!TraceUtility.MessageFlowTracing && this.propagateActivity))
{
this.e2eActivityId = TraceUtility.GetReceivedActivityId(this.OperationContext);
if ((this.E2EActivityId != Guid.Empty) && (this.E2EActivityId != InternalReceiveMessage.TraceCorrelationActivityId))
{
this.propagateActivity = true;
this.OperationContext.IncomingMessageProperties[MessagingActivityHelper.E2EActivityId] = this.E2EActivityId;
this.ambientActivityId = InternalReceiveMessage.TraceCorrelationActivityId;
FxTrace.Trace.SetAndTraceTransfer(this.E2EActivityId, true);
if (TD.StartSignpostEventIsEnabled())
{
TD.StartSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(2) {
{ MessagingActivityHelper.ActivityName, MessagingActivityHelper.ActivityNameWorkflowOperationInvoke },
{ MessagingActivityHelper.ActivityType, MessagingActivityHelper.ActivityTypeExecuteUserCode }
}));
}
}
else
{
this.propagateActivity = false;
}
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
FxTrace.Exception.AsInformation(ex);
}
}
void DecrementBusyCount()
{
lock (this.thisLock)
{
if (!this.hasDecrementedBusyCount)
{
AspNetEnvironment.Current.DecrementBusyCount();
if (AspNetEnvironment.Current.TraceDecrementBusyCountIsEnabled())
{
AspNetEnvironment.Current.TraceDecrementBusyCount(SR.BusyCountTraceFormatString(this.workflowInstance.Id));
}
this.hasDecrementedBusyCount = true;
}
}
}
void IncrementBusyCount()
{
AspNetEnvironment.Current.IncrementBusyCount();
if (AspNetEnvironment.Current.TraceIncrementBusyCountIsEnabled())
{
AspNetEnvironment.Current.TraceIncrementBusyCount(SR.BusyCountTraceFormatString(this.workflowInstance.Id));
}
}
void EmitTransferFromInstanceId()
{
if (TraceUtility.MessageFlowTracing)
{
//set the WF instance ID as the Activity ID
if (DiagnosticTraceBase.ActivityId != this.workflowInstance.Id)
{
DiagnosticTraceBase.ActivityId = this.workflowInstance.Id;
}
FxTrace.Trace.SetAndTraceTransfer(this.E2EActivityId, true);
}
}
void ProcessFinalizationTraces()
{
try
{
if (this.propagateActivity)
{
Guid oldId = InternalReceiveMessage.TraceCorrelationActivityId;
if (TD.StopSignpostEventIsEnabled())
{
TD.StopSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(2) {
{ MessagingActivityHelper.ActivityName, MessagingActivityHelper.ActivityNameWorkflowOperationInvoke },
{ MessagingActivityHelper.ActivityType, MessagingActivityHelper.ActivityTypeExecuteUserCode }
}));
}
FxTrace.Trace.SetAndTraceTransfer(this.ambientActivityId, true);
this.ambientActivityId = Guid.Empty;
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
FxTrace.Exception.AsInformation(ex);
}
DecrementBusyCount();
}
//Perf counter helpers.
[Fx.Tag.SecurityNote(Critical = "Critical because it accesses UnsafeNativeMethods.QueryPerformanceCounter.",
Safe = "Safe because we only make the call if the PartialTrustHelper.AppDomainFullyTrusted is true.")]
[SecuritySafeCritical]
void TrackMethodCalled()
{
if (PartialTrustHelpers.AppDomainFullyTrusted && this.performanceCountersEnabled)
{
using (new OperationContextScopeHelper(this.OperationContext))
{
PerformanceCounters.MethodCalled(this.operationName);
}
if (System.Runtime.Interop.UnsafeNativeMethods.QueryPerformanceCounter(out this.beginTime) == 0)
{
this.beginTime = -1;
}
}
if (TD2.OperationCompletedIsEnabled() ||
TD2.OperationFaultedIsEnabled() ||
TD2.OperationFailedIsEnabled())
{
this.beginOperation = DateTime.UtcNow.Ticks;
}
if (TD2.OperationInvokedIsEnabled())
{
using (new OperationContextScopeHelper(this.OperationContext))
{
TD2.OperationInvoked(this.eventTraceActivity, this.operationName, TraceUtility.GetCallerInfo(this.OperationContext));
}
}
}
void TrackMethodFaulted()
{
if (this.performanceCountersEnabled)
{
long duration = this.GetDuration();
using (new OperationContextScopeHelper(this.OperationContext))
{
PerformanceCounters.MethodReturnedFault(this.operationName, duration);
}
}
if (TD2.OperationFaultedIsEnabled())
{
using (new OperationContextScopeHelper(this.OperationContext))
{
TD2.OperationFaulted(this.eventTraceActivity, this.operationName,
TraceUtility.GetUtcBasedDurationForTrace(this.beginOperation));
}
}
}
void TrackMethodFailed()
{
if (this.performanceCountersEnabled)
{
long duration = this.GetDuration();
using (new OperationContextScopeHelper(this.OperationContext))
{
PerformanceCounters.MethodReturnedError(this.operationName, duration);
}
}
if (TD2.OperationFailedIsEnabled())
{
using (new OperationContextScopeHelper(this.OperationContext))
{
TD2.OperationFailed(this.eventTraceActivity, this.operationName,
TraceUtility.GetUtcBasedDurationForTrace(this.beginOperation));
}
}
}
[Fx.Tag.SecurityNote(Critical = "Critical because it accesses UnsafeNativeMethods.QueryPerformanceCounter.",
Safe = "Safe because we only make the call if the PartialTrustHelper.AppDomainFullyTrusted is true.")]
[SecuritySafeCritical]
long GetDuration()
{
long currentTime = 0;
long duration = 0;
if (PartialTrustHelpers.AppDomainFullyTrusted && this.performanceCountersEnabled && (this.beginTime >= 0) &&
(System.Runtime.Interop.UnsafeNativeMethods.QueryPerformanceCounter(out currentTime) != 0))
{
duration = currentTime - this.beginTime;
}
return duration;
}
void TrackMethodSucceeded()
{
if (this.performanceCountersEnabled)
{
long duration = this.GetDuration();
using (new OperationContextScopeHelper(this.OperationContext))
{
PerformanceCounters.MethodReturnedSuccess(this.operationName, duration);
}
}
if (TD2.OperationCompletedIsEnabled())
{
using (new OperationContextScopeHelper(this.OperationContext))
{
TD2.OperationCompleted(this.eventTraceActivity, this.operationName,
TraceUtility.GetUtcBasedDurationForTrace(this.beginOperation));
}
}
}
void TrackMethodCompleted(object returnValue)
{
// WorkflowOperationInvoker always deals at the Message/Message level
Message faultMessage = returnValue as Message;
if (faultMessage != null && faultMessage.IsFault)
{
TrackMethodFaulted();
}
else
{
TrackMethodSucceeded();
}
}
bool ProcessRequest()
{
this.TrackMethodCalled();
this.ProcessInitializationTraces();
if (this.notification == null)
{
return OnResumeBookmark();
}
string sessionId = this.OperationContext.SessionId;
if (sessionId == null)
{
return OnResumeBookmark();
}
// if there is a session, queue up this request in the per session pending request queue before notifying
// the dispatcher to start the next invoke
IAsyncResult pendingAsyncResult = this.workflowInstance.BeginWaitForPendingOperations(sessionId, this.timeoutHelper.RemainingTime(), this.PrepareAsyncCompletion(handleEndWaitForPendingOperations), this);
bool completed;
this.notification.NotifyInvokeReceived();
if (pendingAsyncResult.CompletedSynchronously)
{
completed = HandleEndWaitForPendingOperations(pendingAsyncResult);
}
else
{
completed = false;
}
return completed;
}
void RemovePendingOperation()
{
if (this.pendingAsyncResult != null)
{
this.workflowInstance.RemovePendingOperation(this.OperationContext.SessionId, this.pendingAsyncResult);
this.pendingAsyncResult = null;
}
}
static bool HandleEndWaitForPendingOperations(IAsyncResult result)
{
WorkflowOperationContext thisPtr = (WorkflowOperationContext)result.AsyncState;
thisPtr.pendingAsyncResult = result;
bool success = false;
try
{
thisPtr.workflowInstance.EndWaitForPendingOperations(result);
bool retval = thisPtr.OnResumeBookmark();
success = true;
return retval;
}
finally
{
if (!success)
{
thisPtr.RemovePendingOperation();
}
}
}
bool OnResumeBookmark()
{
bool success = false;
try
{
IAsyncResult nextResult = this.workflowInstance.BeginResumeProtocolBookmark(
this.bookmark, this.bookmarkScope, this,
this.timeoutHelper.RemainingTime(), this.PrepareAsyncCompletion(handleEndResumeBookmark), this);
bool completed;
if (nextResult.CompletedSynchronously)
{
completed = HandleEndResumeBookmark(nextResult);
}
else
{
completed = false;
}
success = true;
return completed;
}
finally
{
if (!success)
{
this.RemovePendingOperation();
}
}
}
static bool HandleEndResumeBookmark(IAsyncResult result)
{
WorkflowOperationContext thisPtr = (WorkflowOperationContext)result.AsyncState;
bool completed = false;
bool shouldAbandon = true;
try
{
BookmarkResumptionResult resumptionResult = thisPtr.workflowInstance.EndResumeProtocolBookmark(result);
if (resumptionResult != BookmarkResumptionResult.Success)
{
// Raise UnkownMessageReceivedEvent when we fail to resume bookmark
thisPtr.OperationContext.Host.RaiseUnknownMessageReceived(thisPtr.OperationContext.IncomingMessage);
// Only delay-retry this operation once (and only if retries are supported). Future calls will ensure the bookmark is set.
if (thisPtr.workflowInstance.BufferedReceiveManager != null)
{
bool bufferSuccess = thisPtr.workflowInstance.BufferedReceiveManager.BufferReceive(
thisPtr.OperationContext, thisPtr.receiveContext, thisPtr.bookmark.Name, BufferedReceiveState.WaitingOnBookmark, false);
if (bufferSuccess)
{
if (TD.BufferOutOfOrderMessageNoBookmarkIsEnabled())
{
TD.BufferOutOfOrderMessageNoBookmark(thisPtr.eventTraceActivity, thisPtr.workflowInstance.Id.ToString(), thisPtr.bookmark.Name);
}
shouldAbandon = false;
}
}
// The throw exception is intentional whether or not BufferedReceiveManager is set.
// This is to allow exception to bubble up the stack to WCF to cleanup various state (like Transaction).
// This is queue scenario and as far as the client is concerned, the client will not see any exception.
throw FxTrace.Exception.AsError(new FaultException(OperationExecutionFault.CreateOperationNotAvailableFault(thisPtr.workflowInstance.Id, thisPtr.bookmark.Name)));
}
lock (thisPtr.thisLock)
{
if (thisPtr.CurrentState == State.ResultReceived)
{
thisPtr.CurrentState = State.Completed;
if (thisPtr.pendingException != null)
{
throw FxTrace.Exception.AsError(thisPtr.pendingException);
}
completed = true;
}
else
{
thisPtr.CurrentState = State.WaitForResult;
completed = false;
}
// we are not really completed until the ReceiveContext finishes its work
if (completed)
{
completed = thisPtr.ProcessReceiveContext();
}
shouldAbandon = false;
}
}
finally
{
if (shouldAbandon)
{
BufferedReceiveManager.AbandonReceiveContext(thisPtr.receiveContext);
}
thisPtr.RemovePendingOperation();
}
return completed;
}
bool ProcessReceiveContext()
{
if (this.receiveContext != null)
{
if (handleEndProcessReceiveContext == null)
{
handleEndProcessReceiveContext = new AsyncCompletion(HandleEndProcessReceiveContext);
}
IAsyncResult nextResult = ReceiveContextAsyncResult.BeginProcessReceiveContext(this, this.receiveContext, PrepareAsyncCompletion(handleEndProcessReceiveContext), this);
return SyncContinue(nextResult);
}
return true;
}
static bool HandleEndProcessReceiveContext(IAsyncResult result)
{
ReceiveContextAsyncResult.EndProcessReceiveContext(result);
return true;
}
static void Finally(AsyncResult result, Exception completionException)
{
WorkflowOperationContext thisPtr = (WorkflowOperationContext)result;
thisPtr.EmitTransferFromInstanceId();
if (completionException != null)
{
if (completionException is FaultException)
{
thisPtr.TrackMethodFaulted();
}
else
{
thisPtr.TrackMethodFailed();
}
}
else
{
thisPtr.TrackMethodCompleted(thisPtr.operationReturnValue);
}
thisPtr.ProcessFinalizationTraces();
// will be a no-op if we were never added to the instance
thisPtr.workflowInstance.ReleaseContext(thisPtr);
thisPtr.RemovePendingOperation();
}
enum State
{
BookmarkResumption,
WaitForResult,
ResultReceived,
Completed
}
class OperationContextScopeHelper : IDisposable
{
OperationContext currentOperationContext;
public OperationContextScopeHelper(OperationContext operationContext)
{
this.currentOperationContext = OperationContext.Current;
OperationContext.Current = operationContext;
}
void IDisposable.Dispose()
{
OperationContext.Current = this.currentOperationContext;
}
}
class ReceiveContextAsyncResult : TransactedAsyncResult
{
static AsyncCompletion handleEndComplete = new AsyncCompletion(HandleEndComplete);
WorkflowOperationContext context;
ReceiveContext receiveContext;
ReceiveContextAsyncResult(WorkflowOperationContext context, ReceiveContext receiveContext, AsyncCallback callback, object state)
: base(callback, state)
{
this.context = context;
this.receiveContext = receiveContext;
if (ProcessReceiveContext())
{
base.Complete(true);
}
}
public static IAsyncResult BeginProcessReceiveContext(WorkflowOperationContext context, ReceiveContext receiveContext, AsyncCallback callback, object state)
{
return new ReceiveContextAsyncResult(context, receiveContext, callback, state);
}
public static void EndProcessReceiveContext(IAsyncResult result)
{
ReceiveContextAsyncResult.End(result);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<ReceiveContextAsyncResult>(result);
}
bool ProcessReceiveContext()
{
IAsyncResult result;
using (PrepareTransactionalCall(this.context.CurrentTransaction))
{
if (this.context.CurrentTransaction != null)
{
// make sure we Abandon if the transaction ends up with an outcome of Aborted
this.context.CurrentTransaction.TransactionCompleted += new TransactionCompletedEventHandler(OnTransactionComplete);
}
result = this.receiveContext.BeginComplete(
this.context.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleEndComplete), this);
}
return SyncContinue(result);
}
// This happens out-of-band of ReceiveAsyncResult.
// When transaction was aborted, we best-effort abandon the context.
void OnTransactionComplete(object sender, TransactionEventArgs e)
{
if (e.Transaction.TransactionInformation.Status != TransactionStatus.Committed)
{
BufferedReceiveManager.AbandonReceiveContext(this.context.receiveContext);
}
}
static bool HandleEndComplete(IAsyncResult result)
{
ReceiveContextAsyncResult thisPtr = (ReceiveContextAsyncResult)result.AsyncState;
thisPtr.receiveContext.EndComplete(result);
return true;
}
}
}
}
|