File: WorkflowServiceHost.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (831 lines) | stat: -rw-r--r-- 34,767 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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.ServiceModel.Activities
{
    using System.Activities;
    using System.Activities.Hosting;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.IO;
    using System.Runtime;
    using System.Runtime.DurableInstancing;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Activities.Configuration;
    using System.ServiceModel.Activities.Description;
    using System.ServiceModel.Activities.Dispatcher;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Activities.Diagnostics;
    using System.Xml;
    using System.Xml.Linq;

    [Fx.Tag.XamlVisible(false)]
    public class WorkflowServiceHost : ServiceHostBase
    {
        static readonly XName mexContractXName = XName.Get(ServiceMetadataBehavior.MexContractName, ServiceMetadataBehavior.MexContractNamespace);
        static readonly Type mexBehaviorType = typeof(ServiceMetadataBehavior);
        static readonly TimeSpan defaultPersistTimeout = TimeSpan.FromSeconds(30);
        static readonly TimeSpan defaultTrackTimeout = TimeSpan.FromSeconds(30);
        static readonly Type baseActivityType = typeof(Activity);
        static readonly Type correlationQueryBehaviorType = typeof(CorrelationQueryBehavior);
        static readonly Type bufferedReceiveServiceBehaviorType = typeof(BufferedReceiveServiceBehavior);

        WorkflowServiceHostExtensions workflowExtensions;
        DurableInstanceManager durableInstanceManager;

        WorkflowDefinitionProvider workflowDefinitionProvider;
    
        Activity activity;
        WorkflowService serviceDefinition;
        IDictionary<XName, ContractDescription> inferredContracts;
        IDictionary<XName, Collection<CorrelationQuery>> correlationQueries;

        WorkflowUnhandledExceptionAction unhandledExceptionAction;
        TimeSpan idleTimeToPersist;
        TimeSpan idleTimeToUnload;

        WorkflowServiceHostPerformanceCounters workflowServiceHostPerformanceCounters; 

        [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors, 
            Justification = "Based on prior are from WCF3: By design, don't want to complicate ServiceHost state model")]
        public WorkflowServiceHost(object serviceImplementation, params Uri[] baseAddresses)
            : base()
        {
            if (serviceImplementation == null)
            {
                throw FxTrace.Exception.ArgumentNull("serviceImplementation");
            }

            if (serviceImplementation is WorkflowService)
            {
                InitializeFromConstructor((WorkflowService)serviceImplementation, baseAddresses);
            }
            else
            {
                Activity activity = serviceImplementation as Activity;
                if (activity == null)
                {
                    throw FxTrace.Exception.Argument("serviceImplementation", SR.InvalidServiceImplementation);
                }
                InitializeFromConstructor(activity, baseAddresses);
            }
        }


        [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors, 
            Justification = "Based on prior are from WCF3: By design, don't want to complicate ServiceHost state model")]
        public WorkflowServiceHost(Activity activity, params Uri[] baseAddresses)
            : base()
        {
            if (activity == null)
            {
                throw FxTrace.Exception.ArgumentNull("activity");
            }

            InitializeFromConstructor(activity, baseAddresses);
        }

        [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
            Justification = "Based on prior art from WCF 3.0: By design, don't want to complicate ServiceHost state model")]
        public WorkflowServiceHost(WorkflowService serviceDefinition, params Uri[] baseAddresses)
            : base()
        {
            if (serviceDefinition == null)
            {
                throw FxTrace.Exception.ArgumentNull("serviceDefinition");
            }

            InitializeFromConstructor(serviceDefinition, baseAddresses);
      
        }

        [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
            Justification = "Based on prior art from WCF 3.0: By design, don't want to complicate ServiceHost state model")]
        protected WorkflowServiceHost()
        {
            InitializeFromConstructor((WorkflowService)null);
        }

        public Activity Activity
        {
            get
            {
                return this.activity;
            }
        }

        public WorkflowInstanceExtensionManager WorkflowExtensions
        {
            get
            {
                return this.workflowExtensions;
            }
        }

        public DurableInstancingOptions DurableInstancingOptions
        {
            get
            {
                return this.durableInstanceManager.DurableInstancingOptions;
            }
        }

        public ICollection<WorkflowService> SupportedVersions
        {
            get
            {
                return this.workflowDefinitionProvider.SupportedVersions;
            }
        }

        internal XName ServiceName
        {
            get;
            set;
        }

        internal TimeSpan PersistTimeout
        {
            get;
            set;
        }

        internal TimeSpan TrackTimeout
        {
            get;
            set;
        }

        // 
        internal TimeSpan FilterResumeTimeout
        {
            get;
            set;
        }

        internal DurableInstanceManager DurableInstanceManager
        {
            get
            {
                return this.durableInstanceManager;
            }
        }

        internal bool IsLoadTransactionRequired
        {
            get;
            private set;
        }

        // set by WorkflowUnhandledExceptionBehavior.ApplyDispatchBehavior, used by WorkflowServiceInstance.UnhandledExceptionPolicy
        internal WorkflowUnhandledExceptionAction UnhandledExceptionAction
        {
            get { return this.unhandledExceptionAction; }
            set 
            {
                Fx.Assert(WorkflowUnhandledExceptionActionHelper.IsDefined(value), "Undefined WorkflowUnhandledExceptionAction");
                this.unhandledExceptionAction = value; 
            }
        }

        // set by WorkflowIdleBehavior.ApplyDispatchBehavior, used by WorkflowServiceInstance.UnloadInstancePolicy
        internal TimeSpan IdleTimeToPersist
        {
            get { return this.idleTimeToPersist; }
            set 
            {
                Fx.Assert(value >= TimeSpan.Zero, "IdleTimeToPersist cannot be less than zero");
                this.idleTimeToPersist = value; 
            }
        }
        internal TimeSpan IdleTimeToUnload
        {
            get { return this.idleTimeToUnload; }
            set 
            {
                Fx.Assert(value >= TimeSpan.Zero, "IdleTimeToUnload cannot be less than zero");
                this.idleTimeToUnload = value; 
            }
        }

        internal bool IsConfigurable
        {
            get
            {
                lock (this.ThisLock)
                {
                    return this.State == CommunicationState.Created || this.State == CommunicationState.Opening;
                }
            }
        }

        internal WorkflowServiceHostPerformanceCounters WorkflowServiceHostPerformanceCounters
        {
            get
            {
                return this.workflowServiceHostPerformanceCounters;
            }
        }
        
        internal bool OverrideSiteName
        {
            get;
            set;
        }

        void InitializeFromConstructor(Activity activity, params Uri[] baseAddresses)
        {
            WorkflowService serviceDefinition = new WorkflowService 
            {
                Body = activity
            };

            InitializeFromConstructor(serviceDefinition, baseAddresses);
        }

        void InitializeFromConstructor(WorkflowService serviceDefinition, params Uri[] baseAddresses)
        {
            // first initialize some values to their defaults
            this.idleTimeToPersist = WorkflowIdleBehavior.defaultTimeToPersist;
            this.idleTimeToUnload = WorkflowIdleBehavior.defaultTimeToUnload;
            this.unhandledExceptionAction = WorkflowUnhandledExceptionBehavior.defaultAction;
            this.workflowExtensions = new WorkflowServiceHostExtensions();

            // If the AppSettings.DefaultAutomaticInstanceKeyDisassociation is specified and is true, create a DisassociateInstanceKeysExtension, set its
            // AutomaticDisassociationEnabled property to true, and add it to the extensions collection so that System.Activities.BookmarkScopeHandle will
            // unregister its BookmarkScope, which will cause key disassociation. KB2669774.
            if (AppSettings.DefaultAutomaticInstanceKeyDisassociation)
            {
                DisassociateInstanceKeysExtension extension = new DisassociateInstanceKeysExtension();
                extension.AutomaticDisassociationEnabled = true;
                this.workflowExtensions.Add(extension);
            }

            if (TD.CreateWorkflowServiceHostStartIsEnabled())
            {
                TD.CreateWorkflowServiceHostStart();
            }
            if (serviceDefinition != null)
            {
                this.workflowDefinitionProvider = new WorkflowDefinitionProvider(serviceDefinition, this);
                InitializeDescription(serviceDefinition, new UriSchemeKeyedCollection(baseAddresses));
            }
            this.durableInstanceManager = new DurableInstanceManager(this);            

            if (TD.CreateWorkflowServiceHostStopIsEnabled())
            {
                TD.CreateWorkflowServiceHostStop();
            }

            this.workflowServiceHostPerformanceCounters = new WorkflowServiceHostPerformanceCounters(this);
        }

        [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
        public ServiceEndpoint AddServiceEndpoint(XName serviceContractName, Binding binding, string address,
            Uri listenUri = null, string behaviorConfigurationName = null)
        {
            return AddServiceEndpoint(serviceContractName, binding, new Uri(address, UriKind.RelativeOrAbsolute), listenUri, behaviorConfigurationName);
        }

        [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
        public ServiceEndpoint AddServiceEndpoint(XName serviceContractName, Binding binding, Uri address,
            Uri listenUri = null, string behaviorConfigurationName = null)
        {
            if (binding == null)
            {
                throw FxTrace.Exception.ArgumentNull("binding");
            }
            if (address == null)
            {
                throw FxTrace.Exception.ArgumentNull("address");
            }

            Uri via = this.MakeAbsoluteUri(address, binding);
            return AddServiceEndpointCore(serviceContractName, binding, new EndpointAddress(via), listenUri, behaviorConfigurationName);
        }

        [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
        ServiceEndpoint AddServiceEndpointCore(XName serviceContractName, Binding binding, EndpointAddress address,
            Uri listenUri = null, string behaviorConfigurationName = null)
        {
            if (serviceContractName == null)
            {
                throw FxTrace.Exception.ArgumentNull("serviceContractName");
            }
            if (this.inferredContracts == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(
                    SR.ContractNotFoundInAddServiceEndpoint(serviceContractName.LocalName, serviceContractName.NamespaceName)));
            }

            ServiceEndpoint serviceEndpoint;
            ContractDescription description;
            
            ContractInferenceHelper.ProvideDefaultNamespace(ref serviceContractName);

            if (this.inferredContracts.TryGetValue(serviceContractName, out description))
            {
                serviceEndpoint = new ServiceEndpoint(description, binding, address);

                if (!string.IsNullOrEmpty(behaviorConfigurationName))
                {
                    ConfigLoader.LoadChannelBehaviors(behaviorConfigurationName, null, serviceEndpoint.Behaviors);
                }
            }
            else if (serviceContractName == mexContractXName)  // Special case for mex endpoint
            {
                if (!this.Description.Behaviors.Contains(mexBehaviorType))
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(
                        SR.ServiceMetadataBehaviorNotFoundForServiceMetadataEndpoint(this.Description.Name)));
                }

                serviceEndpoint = new ServiceMetadataEndpoint(binding, address);
            }
            else
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(
                    SR.ContractNotFoundInAddServiceEndpoint(serviceContractName.LocalName, serviceContractName.NamespaceName)));
            }

            if (listenUri != null)
            {
                listenUri = base.MakeAbsoluteUri(listenUri, binding);
                serviceEndpoint.ListenUri = listenUri;
            }

            base.Description.Endpoints.Add(serviceEndpoint);

            if (TD.ServiceEndpointAddedIsEnabled())
            {
                TD.ServiceEndpointAdded(address.Uri.ToString(), binding.GetType().ToString(), serviceEndpoint.Contract.Name);
            }

            return serviceEndpoint;
        }

        // Duplicate public AddServiceEndpoint methods from the base class
        // This is to ensure that base class methods with string are not hidden by derived class methods with XName
        public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address)
        {
            return base.AddServiceEndpoint(implementedContract, binding, address);
        }

        public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address)
        {
            return base.AddServiceEndpoint(implementedContract, binding, address);
        }

        public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri)
        {
            return base.AddServiceEndpoint(implementedContract, binding, address, listenUri);
        }

        public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri)
        {
            return base.AddServiceEndpoint(implementedContract, binding, address, listenUri);
        }

        public override void AddServiceEndpoint(ServiceEndpoint endpoint)
        {
            if (!endpoint.IsSystemEndpoint)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CannotUseAddServiceEndpointOverloadForWorkflowServices));
            }
            
            base.AddServiceEndpoint(endpoint);
        }        

        internal override void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints)
        {
            if (this.inferredContracts != null)
            {
                foreach (XName contractName in this.inferredContracts.Keys)
                {
                    ServiceEndpoint endpoint = AddServiceEndpoint(contractName, defaultBinding, String.Empty);
                    ConfigLoader.LoadDefaultEndpointBehaviors(endpoint);
                    AddCorrelationQueryBehaviorToServiceEndpoint(endpoint);
                    defaultEndpoints.Add(endpoint);
                }
            }
        }

        [SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, MessageId = "0#", Justification = "This is defined by the ServiceHost base class")]
        protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
        {
            Fx.AssertAndThrow(this.serviceDefinition != null, "serviceDefinition is null");

            this.activity = this.serviceDefinition.Body;

            Dictionary<string, ContractDescription> result = new Dictionary<string, ContractDescription>();

            // Note: We do not check whether this.inferredContracts == null || this.inferredContracts.Count == 0,
            // because we need to support hosting workflow with zero contract.
            this.inferredContracts = this.serviceDefinition.GetContractDescriptions();

            if (this.inferredContracts != null)
            {
                foreach (ContractDescription contract in this.inferredContracts.Values)
                {
                    if (!string.IsNullOrEmpty(contract.ConfigurationName))
                    {
                        if (result.ContainsKey(contract.ConfigurationName))
                        {
                            throw FxTrace.Exception.AsError(new InvalidOperationException(SR.DifferentContractsSameConfigName));
                        }
                        result.Add(contract.ConfigurationName, contract);
                    }
                }
            }

            implementedContracts = result;

            // Currently, only WorkflowService has CorrelationQueries property
            this.correlationQueries = this.serviceDefinition.CorrelationQueries;
            ServiceDescription serviceDescription = this.serviceDefinition.GetEmptyServiceDescription();
            serviceDescription.Behaviors.Add(new WorkflowServiceBehavior(this.workflowDefinitionProvider));
            return serviceDescription;
        }

        void InitializeDescription(WorkflowService serviceDefinition, UriSchemeKeyedCollection baseAddresses)
        {
            Fx.Assert(serviceDefinition != null, "caller must verify");

            this.serviceDefinition = serviceDefinition;
            base.InitializeDescription(baseAddresses);

            foreach (Endpoint endpoint in serviceDefinition.Endpoints)
            {
                if (endpoint.Binding == null)
                {
                    string endpointName = ContractValidationHelper.GetErrorMessageEndpointName(endpoint.Name);
                    string contractName = ContractValidationHelper.GetErrorMessageEndpointServiceContractName(endpoint.ServiceContractName);
                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.MissingBindingInEndpoint(endpointName, contractName)));
                }

                ServiceEndpoint serviceEndpoint = AddServiceEndpointCore(endpoint.ServiceContractName, endpoint.Binding,
                        endpoint.GetAddress(this), endpoint.ListenUri, endpoint.BehaviorConfigurationName);

                if (!string.IsNullOrEmpty(endpoint.Name))
                {
                    serviceEndpoint.Name = endpoint.Name;
                }
                serviceEndpoint.UnresolvedAddress = endpoint.AddressUri;
                serviceEndpoint.UnresolvedListenUri = endpoint.ListenUri;
            }

            this.PersistTimeout = defaultPersistTimeout;
            this.TrackTimeout = defaultTrackTimeout;
            this.FilterResumeTimeout = TimeSpan.FromSeconds(AppSettings.FilterResumeTimeoutInSeconds);
        }

        protected override void InitializeRuntime()
        {
            if (base.Description != null)
            {
                FixupEndpoints();
                this.SetScopeName();
                if (this.DurableInstancingOptions.ScopeName == null)
                {
                    this.DurableInstancingOptions.ScopeName = XNamespace.Get(this.Description.Namespace).GetName(this.Description.Name);
                }
            }

            base.InitializeRuntime();

            this.WorkflowServiceHostPerformanceCounters.InitializePerformanceCounters();
            
            this.ServiceName = XNamespace.Get(this.Description.Namespace).GetName(this.Description.Name);

            // add a host-wide SendChannelCache (with default settings) if one doesn't exist
            this.workflowExtensions.EnsureChannelCache();

            // add a host-wide (free-threaded) CorrelationExtension based on our ServiceName
            this.WorkflowExtensions.Add(new CorrelationExtension(this.DurableInstancingOptions.ScopeName));

            this.WorkflowExtensions.MakeReadOnly();

            // now calculate if IsLoadTransactionRequired
            this.IsLoadTransactionRequired = WorkflowServiceInstance.IsLoadTransactionRequired(this);

            if (this.serviceDefinition != null)
            {
                ValidateBufferedReceiveProperty();
                this.serviceDefinition.ResetServiceDescription();
            }
        }

        internal override void AfterInitializeRuntime(TimeSpan timeout)
        {
            this.durableInstanceManager.Open(timeout);
        }

        internal override IAsyncResult BeginAfterInitializeRuntime(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.durableInstanceManager.BeginOpen(timeout, callback, state);
        }

        internal override void EndAfterInitializeRuntime(IAsyncResult result)
        {
            this.durableInstanceManager.EndOpen(result);
        }

        protected override void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            base.OnClose(timeoutHelper.RemainingTime());

            this.durableInstanceManager.Close(timeoutHelper.RemainingTime());

            this.workflowServiceHostPerformanceCounters.Dispose();
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new CloseAsyncResult(this, timeout, callback, state);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            CloseAsyncResult.End(result);
        }

        protected override void OnAbort()
        {
            base.OnAbort();

            this.durableInstanceManager.Abort();

            this.workflowServiceHostPerformanceCounters.Dispose();
        }

        internal void FaultServiceHostIfNecessary(Exception exception)
        {
            if (exception is InstancePersistenceException && !(exception is InstancePersistenceCommandException))
            {
                this.Fault(exception);
            }
        }

        IAsyncResult BeginHostClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return base.OnBeginClose(timeout, callback, state);
        }
        void EndHostClose(IAsyncResult result)
        {
            base.OnEndClose(result);
        }

        void AddCorrelationQueryBehaviorToServiceEndpoint(ServiceEndpoint serviceEndpoint)
        {
            Fx.Assert(serviceEndpoint != null, "Argument cannot be null!");
            Fx.Assert(serviceEndpoint.Contract != null, "ServiceEndpoint must have a contract!");
            Fx.Assert(this.serviceDefinition != null, "Missing WorkflowService!");
            Fx.Assert(!serviceEndpoint.Behaviors.Contains(correlationQueryBehaviorType),
                "ServiceEndpoint should not have CorrelationQueryBehavior before this point!");

            XName endpointContractName = XName.Get(serviceEndpoint.Contract.Name, serviceEndpoint.Contract.Namespace);

            Collection<CorrelationQuery> queries;
            if (this.correlationQueries != null && this.correlationQueries.TryGetValue(endpointContractName, out queries))
            {
                // Filter out duplicate CorrelationQueries in the collection.
                // Currently, we only do reference comparison and Where message filter comparison.
                Collection<CorrelationQuery> uniqueQueries = new Collection<CorrelationQuery>();
                foreach (CorrelationQuery correlationQuery in queries)
                {
                    if (!uniqueQueries.Contains(correlationQuery))
                    {
                        uniqueQueries.Add(correlationQuery);
                    }
                    else
                    {
                        if (TD.DuplicateCorrelationQueryIsEnabled())
                        {
                            TD.DuplicateCorrelationQuery(correlationQuery.Where.ToString());
                        }
                    }
                }
                serviceEndpoint.Behaviors.Add(new CorrelationQueryBehavior(uniqueQueries) { ServiceContractName = endpointContractName });
            }
            else if (CorrelationQueryBehavior.BindingHasDefaultQueries(serviceEndpoint.Binding))
            {
                if (!serviceEndpoint.Behaviors.Contains(typeof(CorrelationQueryBehavior)))
                {
                    serviceEndpoint.Behaviors.Add(new CorrelationQueryBehavior(new Collection<CorrelationQuery>()) { ServiceContractName = endpointContractName });
                }
            }
        }

        void FixupEndpoints()
        {
            Fx.Assert(this.Description != null, "ServiceDescription cannot be null");

            Dictionary<Type, ContractDescription> contractDescriptionDictionary = new Dictionary<Type, ContractDescription>();
            foreach (ServiceEndpoint serviceEndpoint in this.Description.Endpoints)
            {
                if (this.serviceDefinition.AllowBufferedReceive)
                {
                    // All application-level endpoints need to support ReceiveContext
                    SetupReceiveContextEnabledAttribute(serviceEndpoint);
                }

                // Need to add CorrelationQueryBehavior here so that endpoints added from config are included.
                // It is possible that some endpoints already have CorrelationQueryBehavior from
                // the AddDefaultEndpoints code path. We should skip them.
                if (!serviceEndpoint.Behaviors.Contains(correlationQueryBehaviorType))
                {
                    AddCorrelationQueryBehaviorToServiceEndpoint(serviceEndpoint);
                }

                // Need to ensure that any WorkflowHostingEndpoints using the same contract type actually use the
                // same contractDescription instance since this is required by WCF.
                if (serviceEndpoint is WorkflowHostingEndpoint)
                {
                    ContractDescription contract;
                    if (contractDescriptionDictionary.TryGetValue(serviceEndpoint.Contract.ContractType, out contract))
                    {
                        serviceEndpoint.Contract = contract;
                    }
                    else
                    {
                        contractDescriptionDictionary[serviceEndpoint.Contract.ContractType] = serviceEndpoint.Contract;
                    }
                }
            }

            if (this.serviceDefinition.AllowBufferedReceive && !this.Description.Behaviors.Contains(bufferedReceiveServiceBehaviorType))
            {
                this.Description.Behaviors.Add(new BufferedReceiveServiceBehavior());
            }
        }

        void SetScopeName()
        {
            VirtualPathExtension virtualPathExtension = this.Extensions.Find<VirtualPathExtension>();
            if (virtualPathExtension != null)
            {
                // Web Hosted scenario            
                WorkflowHostingOptionsSection hostingOptions = (WorkflowHostingOptionsSection)ConfigurationManager.GetSection(ConfigurationStrings.WorkflowHostingOptionsSectionPath);
                if (hostingOptions != null && hostingOptions.OverrideSiteName)
                {
                    this.OverrideSiteName = hostingOptions.OverrideSiteName;

                    string fullVirtualPath = virtualPathExtension.VirtualPath.Substring(1);
                    fullVirtualPath = ("/" == virtualPathExtension.ApplicationVirtualPath) ? fullVirtualPath : virtualPathExtension.ApplicationVirtualPath + fullVirtualPath;

                    int index = fullVirtualPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase); 
                    string virtualDirectoryPath = fullVirtualPath.Substring(0, index + 1);

                    this.DurableInstancingOptions.ScopeName = XName.Get(XmlConvert.EncodeLocalName(Path.GetFileName(virtualPathExtension.VirtualPath)),
                        string.Format(CultureInfo.InvariantCulture, "/{0}{1}", this.Description.Name, virtualDirectoryPath));
                }
            }
        }
        
        void SetupReceiveContextEnabledAttribute(ServiceEndpoint serviceEndpoint)
        {
            if (BufferedReceiveServiceBehavior.IsWorkflowEndpoint(serviceEndpoint))
            {
                foreach (OperationDescription operation in serviceEndpoint.Contract.Operations)
                {
                    ReceiveContextEnabledAttribute behavior = operation.Behaviors.Find<ReceiveContextEnabledAttribute>();
                    if (behavior == null)
                    {
                        operation.Behaviors.Add(new ReceiveContextEnabledAttribute() { ManualControl = true });
                    }
                    else
                    {
                        behavior.ManualControl = true;
                    }
                }
            }
        }

        void ValidateBufferedReceiveProperty()
        {
            // Validate that the AttachedProperty is indeed being used when the behavior is also used
            bool hasBehavior = this.Description.Behaviors.Contains(bufferedReceiveServiceBehaviorType);
            if (hasBehavior && !this.serviceDefinition.AllowBufferedReceive)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BufferedReceiveBehaviorUsedWithoutProperty));
            }
        }

        // specialized WorkflowInstanceExtensionManager that can default in a SendMessageChannelCache
        class WorkflowServiceHostExtensions : WorkflowInstanceExtensionManager
        {
            static Type SendReceiveExtensionType = typeof(SendReceiveExtension);

            bool hasChannelCache;

            public WorkflowServiceHostExtensions()
                : base()
            {
            }

            public override void Add<T>(Func<T> extensionCreationFunction)
            {
                ThrowIfNotSupported(typeof(T));

                if (TypeHelper.AreTypesCompatible(typeof(T), typeof(SendMessageChannelCache)))
                {
                    this.hasChannelCache = true;
                }
                base.Add<T>(extensionCreationFunction);
            }

            public override void Add(object singletonExtension)
            {
                ThrowIfNotSupported(singletonExtension.GetType());

                if (singletonExtension is SendMessageChannelCache)
                {
                    this.hasChannelCache = true;
                }
                base.Add(singletonExtension);
            }

            public void EnsureChannelCache()
            {
                if (!this.hasChannelCache)
                {
                    Add(new SendMessageChannelCache());
                    this.hasChannelCache = true;
                }
            }

            void ThrowIfNotSupported(Type type)
            {
                if (TypeHelper.AreTypesCompatible(type, SendReceiveExtensionType))
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ExtensionTypeNotSupported(SendReceiveExtensionType.FullName)));
                }
            }
        }

        class CloseAsyncResult : AsyncResult
        {
            static AsyncCompletion handleDurableInstanceManagerEndClose = new AsyncCompletion(HandleDurableInstanceManagerEndClose);
            static AsyncCompletion handleEndHostClose = new AsyncCompletion(HandleEndHostClose);

            TimeoutHelper timeoutHelper;
            WorkflowServiceHost host;

            public CloseAsyncResult(WorkflowServiceHost host, TimeSpan timeout, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.timeoutHelper = new TimeoutHelper(timeout);
                this.host = host;

                if (CloseHost())
                {
                    Complete(true);
                }
            }

            bool CloseDurableInstanceManager()
            {
                IAsyncResult result = this.host.durableInstanceManager.BeginClose(
                    this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleDurableInstanceManagerEndClose), this);
                return SyncContinue(result);
            }

            bool CloseHost()
            {
                IAsyncResult result = this.host.BeginHostClose(
                    this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndHostClose), this);
                return SyncContinue(result);
            }

            static bool HandleDurableInstanceManagerEndClose(IAsyncResult result)
            {
                CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;

                thisPtr.host.durableInstanceManager.EndClose(result);
                
                thisPtr.host.WorkflowServiceHostPerformanceCounters.Dispose();
                return true;
            }

            static bool HandleEndHostClose(IAsyncResult result)
            {
                CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;

                thisPtr.host.EndHostClose(result);
                return thisPtr.CloseDurableInstanceManager();
            }

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