File: ServiceDurableInstance.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (956 lines) | stat: -rw-r--r-- 39,437 bytes parent folder | download | duplicates (7)
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
    using System;
    using System.Runtime;
    using System.Runtime.Diagnostics;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.Persistence;
    using System.Transactions;
    using System.Diagnostics;

    class ServiceDurableInstance : DurableInstance
    {
        bool abortInstance;
        DependentTransaction clonedTransaction;
        ServiceDurableInstanceContextProvider contextManager;
        bool existsInPersistence;
        object instance;
        LockingPersistenceProvider lockingProvider;
        bool markedForCompletion;
        Type newServiceType;
        TimeSpan operationTimeout;
        int outstandingOperations;
        PersistenceProvider provider;
        DurableRuntimeValidator runtimeValidator;
        bool saveStateInOperationTransaction;
        UnknownExceptionAction unknownExceptionAction;

        public ServiceDurableInstance(
            PersistenceProvider persistenceProvider,
            ServiceDurableInstanceContextProvider contextManager,
            bool saveStateInOperationTransaction,
            UnknownExceptionAction unknownExceptionAction,
            DurableRuntimeValidator runtimeValidator,
            TimeSpan operationTimeout)
            : this(persistenceProvider, contextManager, saveStateInOperationTransaction, unknownExceptionAction, runtimeValidator, operationTimeout, null)
        {
        }

        public ServiceDurableInstance(
            PersistenceProvider persistenceProvider,
            ServiceDurableInstanceContextProvider contextManager,
            bool saveStateInOperationTransaction,
            UnknownExceptionAction unknownExceptionAction,
            DurableRuntimeValidator runtimeValidator,
            TimeSpan operationTimeout,
            Type serviceType)
            : base(contextManager, persistenceProvider == null ? Guid.Empty : persistenceProvider.Id)
        {
            if (persistenceProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("persistenceProvider");
            }

            if (contextManager == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextManager");
            }

            if (runtimeValidator == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("runtimeValidator");
            }

            Fx.Assert(operationTimeout > TimeSpan.Zero,
                "Timeout needs to be greater than zero.");

            this.lockingProvider = persistenceProvider as LockingPersistenceProvider;
            this.provider = persistenceProvider;
            this.contextManager = contextManager;
            this.saveStateInOperationTransaction = saveStateInOperationTransaction;
            this.unknownExceptionAction = unknownExceptionAction;
            this.runtimeValidator = runtimeValidator;
            this.operationTimeout = operationTimeout;
            this.newServiceType = serviceType;
        }

        enum OperationType
        {
            None = 0,
            Delete = 1,
            Unlock = 2,
            Create = 3,
            Update = 4
        }

        public object Instance
        {
            get
            {
                return this.instance;
            }
        }

        public void AbortInstance()
        {
            ConcurrencyMode concurrencyMode = this.runtimeValidator.ConcurrencyMode;

            if (concurrencyMode != ConcurrencyMode.Single)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(
                    SR2.GetString(SR2.AbortInstanceRequiresSingle)));
            }

            if (this.saveStateInOperationTransaction)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(
                    SR2.GetString(SR2.CannotAbortWithSaveStateInTransaction)));
            }

            if (this.markedForCompletion)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(
                    SR2.GetString(
                    SR2.DurableOperationMethodInvalid,
                    "AbortInstance",
                    "CompleteInstance")));
            }

            this.abortInstance = true;
        }

        public IAsyncResult BeginFinishOperation(bool completeInstance, bool performPersistence, Exception operationException, AsyncCallback callback, object state)
        {
            return new FinishOperationAsyncResult(this, completeInstance, performPersistence, operationException, callback, state);
        }

        public IAsyncResult BeginStartOperation(bool canCreateInstance, AsyncCallback callback, object state)
        {
            return new StartOperationAsyncResult(this, canCreateInstance, callback, state);
        }

        public void EndFinishOperation(IAsyncResult result)
        {
            FinishOperationAsyncResult.End(result);
        }

        public object EndStartOperation(IAsyncResult result)
        {
            return StartOperationAsyncResult.End(result);
        }

        public void FinishOperation(bool completeInstance, bool performPersistence, Exception operationException)
        {
            try
            {
                bool disposeInstance;
                OperationType operation = FinishOperationCommon(completeInstance, operationException, out disposeInstance);

                Fx.Assert(
                    (performPersistence || (operation != OperationType.Delete && operation != OperationType.Unlock)),
                    "If we aren't performing persistence then we are a NotAllowed contract and therefore should never have loaded from persistence.");

                if (performPersistence)
                {
                    switch (operation)
                    {
                        case OperationType.Unlock:
                            // Do the null check out here to avoid creating the scope
                            if (this.lockingProvider != null)
                            {
                                using (PersistenceScope scope = new PersistenceScope(
                                    this.saveStateInOperationTransaction,
                                    this.clonedTransaction))
                                {
                                    this.lockingProvider.Unlock(this.operationTimeout);
                                }
                            }
                            break;
                        case OperationType.Delete:
                            using (PersistenceScope scope = new PersistenceScope(
                                this.saveStateInOperationTransaction,
                                this.clonedTransaction))
                            {
                                this.provider.Delete(this.instance, this.operationTimeout);

                                if (DiagnosticUtility.ShouldTraceInformation)
                                {
                                    string traceText = SR.GetString(SR.TraceCodeServiceDurableInstanceDeleted, this.InstanceId);
                                    TraceUtility.TraceEvent(TraceEventType.Information,
                                        TraceCode.ServiceDurableInstanceDeleted, traceText,
                                        new StringTraceRecord("DurableInstanceDetail", traceText),
                                        this, null);
                                }
                            }
                            break;
                        case OperationType.Create:
                            using (PersistenceScope scope = new PersistenceScope(
                                this.saveStateInOperationTransaction,
                                this.clonedTransaction))
                            {
                                if (this.lockingProvider != null)
                                {
                                    this.lockingProvider.Create(this.Instance, this.operationTimeout, disposeInstance);
                                }
                                else
                                {
                                    this.provider.Create(this.Instance, this.operationTimeout);
                                }

                                if (DiagnosticUtility.ShouldTraceInformation)
                                {
                                    string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
                                    TraceUtility.TraceEvent(TraceEventType.Information,
                                        TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved),
                                        new StringTraceRecord("DurableInstanceDetail", traceText),
                                        this, null);
                                }
                            }
                            break;
                        case OperationType.Update:
                            using (PersistenceScope scope = new PersistenceScope(
                                this.saveStateInOperationTransaction,
                                this.clonedTransaction))
                            {
                                if (this.lockingProvider != null)
                                {
                                    this.lockingProvider.Update(this.Instance, this.operationTimeout, disposeInstance);
                                }
                                else
                                {
                                    this.provider.Update(this.Instance, this.operationTimeout);
                                }

                                if (DiagnosticUtility.ShouldTraceInformation)
                                {
                                    string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
                                    TraceUtility.TraceEvent(TraceEventType.Information,
                                        TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved),
                                        new StringTraceRecord("DurableInstanceDetail", traceText),
                                        this, null);
                                }
                            }
                            break;
                        case OperationType.None:
                            break;
                        default:
                            Fx.Assert("We should never get an unknown OperationType.");
                            break;
                    }
                }

                if (disposeInstance)
                {
                    DisposeInstance();
                }
            }
            finally
            {
                CompleteClonedTransaction();
            }
        }

        public void MarkForCompletion()
        {
            if (this.abortInstance)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(
                    SR2.GetString(
                    SR2.DurableOperationMethodInvalid,
                    "CompleteInstance",
                    "AbortInstance")));
            }

            this.markedForCompletion = true;
        }

        public object StartOperation(bool canCreateInstance)
        {
            using (StartOperationScope scope = new StartOperationScope(this))
            {
                if (this.markedForCompletion)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InstanceNotFoundException(this.InstanceId));
                }

                if (this.instance == null)
                {
                    if (!TryActivateInstance(canCreateInstance))
                    {
                        using (PersistenceScope persistenceScope = new PersistenceScope(
                            this.saveStateInOperationTransaction,
                            this.clonedTransaction))
                        {
                            if (this.lockingProvider != null)
                            {
                                this.instance = this.lockingProvider.Load(this.operationTimeout, true);
                            }
                            else
                            {
                                this.instance = this.provider.Load(this.operationTimeout);
                            }

                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                string traceText = SR2.GetString(SR2.ServiceDurableInstanceLoadedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
                                TraceUtility.TraceEvent(TraceEventType.Information,
                                    TraceCode.ServiceDurableInstanceLoaded, SR.GetString(SR.TraceCodeServiceDurableInstanceLoaded),
                                    new StringTraceRecord("DurableInstanceDetail", traceText),
                                    this, null);
                            }
                        }

                        this.existsInPersistence = true;
                    }
                }

                scope.Complete();
            }

            Fx.Assert(
                this.instance != null,
                "Instance should definitely be non-null here or we should have thrown an exception.");

            return this.instance;
        }

        protected override void OnAbort()
        {
            this.provider.Abort();
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.provider.BeginClose(timeout, callback, state);
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.provider.BeginOpen(timeout, callback, state);
        }

        protected override void OnClose(TimeSpan timeout)
        {
            this.provider.Close(timeout);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            this.provider.EndClose(result);
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            this.provider.EndOpen(result);
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            this.provider.Open(timeout);
        }

        void CompleteClonedTransaction()
        {
            if (this.clonedTransaction != null)
            {
                this.clonedTransaction.Complete();
                this.clonedTransaction = null;
            }
        }

        void DisposeInstance()
        {
            Fx.Assert(
                this.instance != null,
                "Before making this call we should check instance for null.");

            IDisposable disposableInstance = this.instance as IDisposable;

            if (disposableInstance != null)
            {
                disposableInstance.Dispose();

                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    string traceText = SR.GetString(SR.TraceCodeServiceDurableInstanceDisposed, this.InstanceId);
                    TraceUtility.TraceEvent(TraceEventType.Information,
                        TraceCode.ServiceDurableInstanceDisposed, SR.GetString(SR.TraceCodeServiceDurableInstanceDisposed),
                        new StringTraceRecord("DurableInstanceDetail", traceText),
                        this, null);
                }
            }

            this.instance = null;
        }

        OperationType FinishOperationCommon(bool completeInstance, Exception operationException, out bool disposeInstance)
        {
            // No need for Interlocked because we don't support
            // ConcurrencyMode.Multiple
            this.outstandingOperations--;

            DurableOperationContext.EndOperation();

            Fx.Assert(this.outstandingOperations >= 0,
                "OutstandingOperations should never go below zero.");

            Fx.Assert(this.instance != null,
                "Instance should never been null here - we only get here if StartOperation completes successfully.");

            OperationType operation = OperationType.None;
            disposeInstance = false;

            // This is a "fuzzy" still referenced.  Immediately
            // after this line another message could come in and
            // reference this InstanceContext, but it doesn't matter
            // because regardless of scheme used the other message
            // would have had to reacquire the database lock.
            bool stillReferenced = this.contextManager.GetReferenceCount(this.InstanceId) > 1;

            this.markedForCompletion |= completeInstance;

            if (this.outstandingOperations == 0)
            {
                if (this.saveStateInOperationTransaction &&
                    this.clonedTransaction != null &&
                    this.clonedTransaction.TransactionInformation.Status == TransactionStatus.Aborted)
                {
                    this.abortInstance = false;
                    this.markedForCompletion = false;
                    disposeInstance = true;
                }
                else if (operationException != null && !(operationException is FaultException))
                {
                    if (this.unknownExceptionAction == UnknownExceptionAction.TerminateInstance)
                    {
                        if (this.existsInPersistence)
                        {
                            operation = OperationType.Delete;
                        }

                        this.existsInPersistence = true;
                        disposeInstance = true;
                    }
                    else
                    {
                        Fx.Assert(this.unknownExceptionAction == UnknownExceptionAction.AbortInstance, "If it is not TerminateInstance then it must be AbortInstance.");

                        if (this.existsInPersistence)
                        {
                            operation = OperationType.Unlock;
                        }

                        this.existsInPersistence = true;
                        disposeInstance = true;
                        this.markedForCompletion = false;
                    }
                }
                else if (this.abortInstance)
                {
                    this.abortInstance = false;

                    // AbortInstance can only be called in ConcurrencyMode.Single
                    // and therefore markedForCompletion could only have been
                    // set true by this same operation (either declaratively or
                    // programmatically).  We set it false again so that the
                    // next operation doesn't cause instance completion.
                    this.markedForCompletion = false;

                    if (this.existsInPersistence && !stillReferenced)
                    {
                        // No need for a transactional version of this as we do not allow
                        // AbortInstance to be called in scenarios with SaveStateInOperationTransaction
                        // set to true
                        Fx.Assert(!this.saveStateInOperationTransaction,
                            "SaveStateInOperationTransaction must be false if we allowed an abort.");

                        if (this.lockingProvider != null)
                        {
                            operation = OperationType.Unlock;
                        }
                    }

                    this.existsInPersistence = true;
                    disposeInstance = true;
                }
                else if (this.markedForCompletion)
                {
                    if (this.existsInPersistence)
                    {
                        // We don't set exists in persistence to 
                        // false here because we want the proper
                        // persistence exceptions to get back to the
                        // client if we end up here again.

                        operation = OperationType.Delete;
                    }

                    // Even if we didn't delete the instance because it
                    // never existed we should set this to true.  This will
                    // make sure that any future requests to this instance of
                    // ServiceDurableInstance will treat the object as deleted.
                    this.existsInPersistence = true;
                    disposeInstance = true;
                }
                else
                {
                    if (this.existsInPersistence)
                    {
                        operation = OperationType.Update;
                    }
                    else
                    {
                        operation = OperationType.Create;
                    }

                    this.existsInPersistence = true;
                    if (!stillReferenced)
                    {
                        disposeInstance = true;
                    }
                }
            }

            return operation;
        }

        bool TryActivateInstance(bool canCreateInstance)
        {
            if (this.newServiceType != null && !this.existsInPersistence)
            {
                if (canCreateInstance)
                {
                    this.instance = Activator.CreateInstance(this.newServiceType);
                    return true;
                }
                else
                {
                    DurableErrorHandler.CleanUpInstanceContextAtOperationCompletion();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FaultException(new DurableDispatcherAddressingFault()));
                }
            }

            return false;
        }

        class FinishOperationAsyncResult : AsyncResult
        {
            static AsyncCallback createCallback = Fx.ThunkCallback(new AsyncCallback(CreateComplete));
            static AsyncCallback deleteCallback = Fx.ThunkCallback(new AsyncCallback(DeleteComplete));
            static AsyncCallback unlockCallback = Fx.ThunkCallback(new AsyncCallback(UnlockComplete));
            static AsyncCallback updateCallback = Fx.ThunkCallback(new AsyncCallback(UpdateComplete));

            ServiceDurableInstance durableInstance;

            public FinishOperationAsyncResult(ServiceDurableInstance durableInstance, bool completeInstance, bool performPersistence, Exception operationException, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.durableInstance = durableInstance;

                IAsyncResult result = null;
                OperationType operation = OperationType.None;
                bool completeSelf = false;
                bool disposeInstace;
                operation = this.durableInstance.FinishOperationCommon(completeInstance, operationException, out disposeInstace);

                if (performPersistence)
                {
                    switch (operation)
                    {
                        case OperationType.Unlock:
                            if (this.durableInstance.lockingProvider != null)
                            {
                                using (PersistenceScope scope = new PersistenceScope(
                                    this.durableInstance.saveStateInOperationTransaction,
                                    this.durableInstance.clonedTransaction))
                                {
                                    result = this.durableInstance.lockingProvider.BeginUnlock(this.durableInstance.operationTimeout, unlockCallback, this);
                                }
                            }
                            break;
                        case OperationType.Delete:
                            using (PersistenceScope scope = new PersistenceScope(
                                this.durableInstance.saveStateInOperationTransaction,
                                this.durableInstance.clonedTransaction))
                            {
                                result = this.durableInstance.provider.BeginDelete(this.durableInstance.Instance, this.durableInstance.operationTimeout, deleteCallback, this);
                            }
                            break;
                        case OperationType.Create:
                            using (PersistenceScope scope = new PersistenceScope(
                                this.durableInstance.saveStateInOperationTransaction,
                                this.durableInstance.clonedTransaction))
                            {
                                if (this.durableInstance.lockingProvider != null)
                                {
                                    result = this.durableInstance.lockingProvider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, createCallback, this);
                                }
                                else
                                {
                                    result = this.durableInstance.provider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, createCallback, this);
                                }
                            }
                            break;
                        case OperationType.Update:
                            using (PersistenceScope scope = new PersistenceScope(
                                this.durableInstance.saveStateInOperationTransaction,
                                this.durableInstance.clonedTransaction))
                            {
                                if (this.durableInstance.lockingProvider != null)
                                {
                                    result = this.durableInstance.lockingProvider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, updateCallback, this);
                                }
                                else
                                {
                                    result = this.durableInstance.provider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, updateCallback, this);
                                }
                            }
                            break;
                        case OperationType.None:
                            break;
                        default:
                            Fx.Assert("Unknown OperationType was passed in.");
                            break;
                    }
                }

                if (disposeInstace)
                {
                    this.durableInstance.DisposeInstance();
                }

                if (operation == OperationType.None ||
                    (result != null && result.CompletedSynchronously))
                {
                    completeSelf = true;
                }

                if (!performPersistence)
                {
                    Fx.Assert(result == null, "Should not have had a result if we didn't perform persistence.");
                    Complete(true);
                    return;
                }

                if (completeSelf)
                {
                    CallEndOperation(operation, result);

                    Complete(true);
                }
            }

            public static void End(IAsyncResult result)
            {
                AsyncResult.End<FinishOperationAsyncResult>(result);
            }

            static void CreateComplete(IAsyncResult result)
            {
                HandleOperationCompletion(OperationType.Create, result);
            }

            static void DeleteComplete(IAsyncResult result)
            {
                HandleOperationCompletion(OperationType.Delete, result);
            }

            static void HandleOperationCompletion(OperationType operation, IAsyncResult result)
            {
                if (result.CompletedSynchronously)
                {
                    return;
                }

                Fx.Assert(result.AsyncState is FinishOperationAsyncResult,
                    "Async state should have been FinishOperationAsyncResult");

                FinishOperationAsyncResult finishResult = (FinishOperationAsyncResult) result.AsyncState;

                Exception completionException = null;
                try
                {
                    finishResult.CallEndOperation(operation, result);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    completionException = e;
                }

                finishResult.Complete(false, completionException);
            }

            static void UnlockComplete(IAsyncResult result)
            {
                HandleOperationCompletion(OperationType.Unlock, result);
            }

            static void UpdateComplete(IAsyncResult result)
            {
                HandleOperationCompletion(OperationType.Update, result);
            }

            void CallEndOperation(OperationType operation, IAsyncResult result)
            {
                try
                {
                    switch (operation)
                    {
                        case OperationType.Delete:
                            this.durableInstance.provider.EndDelete(result);
                            break;
                        case OperationType.Unlock:
                            this.durableInstance.lockingProvider.EndUnlock(result);
                            break;
                        case OperationType.Create:
                            this.durableInstance.provider.EndCreate(result);
                            break;
                        case OperationType.Update:
                            this.durableInstance.provider.EndUpdate(result);
                            break;
                        case OperationType.None:
                            break;
                        default:
                            Fx.Assert("Should never have an unknown value for this enum.");
                            break;
                    }
                }
                finally
                {
                    this.durableInstance.CompleteClonedTransaction();
                }
            }
        }

        class PersistenceScope : IDisposable
        {
            DependentTransaction clonedTransaction;
            TransactionScope scope;

            public PersistenceScope(bool saveStateInOperationTransaction, DependentTransaction clonedTransaction)
            {
                if (!saveStateInOperationTransaction)
                {
                    this.scope = new TransactionScope(TransactionScopeOption.Suppress);
                }
                else if (clonedTransaction != null)
                {
                    this.clonedTransaction = clonedTransaction;
                    this.scope = new TransactionScope(clonedTransaction);
                }
            }

            public void Dispose()
            {
                if (this.scope != null)
                {
                    this.scope.Complete();
                    this.scope.Dispose();
                    this.scope = null;
                }
            }
        }

        class StartOperationAsyncResult : AsyncResult
        {
            static AsyncCallback loadCallback = Fx.ThunkCallback(new AsyncCallback(LoadComplete));

            ServiceDurableInstance durableInstance;
            OperationContext operationContext;
            StartOperationScope scope;

            public StartOperationAsyncResult(ServiceDurableInstance durableInstance, bool canCreateInstance, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.durableInstance = durableInstance;

                bool completeSelf = false;
                IAsyncResult result = null;
                this.operationContext = OperationContext.Current;

                scope = new StartOperationScope(this.durableInstance);               
                bool success = false;
                try
                {                   
                    if (this.durableInstance.instance == null)
                    {
                        if (this.durableInstance.TryActivateInstance(canCreateInstance))
                        {
                            completeSelf = true;
                        }
                        else
                        {
                            using (PersistenceScope persistenceScope = new PersistenceScope(
                                this.durableInstance.saveStateInOperationTransaction,
                                this.durableInstance.clonedTransaction))
                            {
                                if (this.durableInstance.lockingProvider != null)
                                {
                                    result = this.durableInstance.lockingProvider.BeginLoad(this.durableInstance.operationTimeout, true, loadCallback, this);
                                }
                                else
                                {
                                    result = this.durableInstance.provider.BeginLoad(this.durableInstance.operationTimeout, loadCallback, this);
                                }
                            }

                            this.durableInstance.existsInPersistence = true;

                            if (result.CompletedSynchronously)
                            {
                                completeSelf = true;
                            }
                        }
                    }
                    else
                    {
                        completeSelf = true;
                    }


                    success = true;
                }
                finally
                {
                    if (!success)
                    {
                        scope.Dispose();                        
                    }
                }

                if (completeSelf)
                {
                    try
                    {
                        if (result != null)
                        {
                            this.durableInstance.instance = this.durableInstance.provider.EndLoad(result);
                        }

                        Fx.Assert(this.durableInstance.instance != null,
                            "The instance should always be set here.");

                        Complete(true);
                        scope.Complete();
                    }
                    finally
                    {
                        scope.Dispose();
                    }
                }              
            }

            public static object End(IAsyncResult result)
            {
                StartOperationAsyncResult startResult = AsyncResult.End<StartOperationAsyncResult>(result);

                return startResult.durableInstance.instance;
            }

            static void LoadComplete(IAsyncResult result)
            {
                if (result.CompletedSynchronously)
                {
                    return;
                }

                Fx.Assert(result.AsyncState is StartOperationAsyncResult,
                    "Should have been passed a StartOperationAsyncResult as the state");

                StartOperationAsyncResult startResult = (StartOperationAsyncResult) result.AsyncState;                                
                Exception completionException = null;
                OperationContext oldOperationContext = OperationContext.Current;
                OperationContext.Current = startResult.operationContext;

                try
                {
                    try
                    {
                        startResult.durableInstance.instance = startResult.durableInstance.provider.EndLoad(result);

                        Fx.Assert(startResult.durableInstance.instance != null,
                            "The instance should always be set here.");

                        startResult.scope.Complete();
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }

                        completionException = e;
                    }
                    finally
                    {
                        startResult.scope.Dispose();                        
                    }

                    startResult.Complete(false, completionException);
                }
                finally
                {
                    OperationContext.Current = oldOperationContext;
                }
            }
        }

        class StartOperationScope : IDisposable
        {
            ServiceDurableInstance durableInstance;
            bool success;

            public StartOperationScope(ServiceDurableInstance durableInstance)
            {
                this.durableInstance = durableInstance;

                this.durableInstance.runtimeValidator.ValidateRuntime();

                DurableOperationContext.BeginOperation();

                // No need for Interlocked because we don't support
                // ConcurrencyMode.Multiple
                this.durableInstance.outstandingOperations++;

                if (this.durableInstance.saveStateInOperationTransaction && Transaction.Current != null)
                {
                    this.durableInstance.clonedTransaction = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                }
            }

            public void Complete()
            {
                this.success = true;
            }

            public void Dispose()
            {
                if (!this.success)
                {
                    Fx.Assert(OperationContext.Current != null, "Operation context should not be null at this point.");

                    DurableOperationContext.EndOperation();

                    this.durableInstance.outstandingOperations--;
                    this.durableInstance.CompleteClonedTransaction();
                }
            }
        }
    }
}