File: HostedAspNetEnvironment.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 (784 lines) | stat: -rw-r--r-- 33,428 bytes parent folder | download
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
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------------------

namespace System.ServiceModel.Activation
{
    using System.Collections.Generic;
    using System.Configuration;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Net;
    using System.Runtime;
    using System.Runtime.CompilerServices;
    using System.Security;
    using System.Security.Authentication.ExtendedProtection;
    using System.Security.Permissions;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.Threading;
    using System.Transactions;
    using System.Web;
    using System.Web.Compilation;
    using System.Web.Configuration;

    class HostedAspNetEnvironment : AspNetEnvironment
    {
        // On IIS 8.0 (or later) the "WEBSOCKET_VERSION" server property indicates the WebSocket protocol version supported by the server.
        // The IIS WebSocket module sets this property when initialized.
        private const string WebSocketVersionServerProperty = "WEBSOCKET_VERSION";

        // Indicates if we determined the WebSocket version. If false, we'll need to check the "WEBSOCKET_VERSION" server property.
        private static bool isWebSocketVersionSet = false;

        // Provides the version of the WebSocket protocol supported by IIS.
        private static string webSocketVersion;

        // used to cache SiteName|ApplicationVirtualPath
        static string cachedServiceReference;

        // used to cache if windows auth is being used
        Nullable<bool> isWindowsAuthentication;

        HostedAspNetEnvironment()
            : base()
        {
        }

        public override bool AspNetCompatibilityEnabled
        {
            get
            {
                return ServiceHostingEnvironment.AspNetCompatibilityEnabled;
            }
        }

        public override string ConfigurationPath
        {
            get
            {
                if (ServiceHostingEnvironment.CurrentVirtualPath != null)
                {
                    return ServiceHostingEnvironment.CurrentVirtualPath + "web.config";
                }
                else
                {
                    return base.ConfigurationPath;
                }
            }
        }

        public override bool IsConfigurationBased
        {
            get
            {
                return ServiceHostingEnvironment.IsConfigurationBased;
            }
        }

        public override string CurrentVirtualPath
        {
            get
            {
                return ServiceHostingEnvironment.CurrentVirtualPath;
            }
        }

        public override string XamlFileBaseLocation
        {
            get
            {
                return ServiceHostingEnvironment.XamlFileBaseLocation;
            }
        }

        public override bool UsingIntegratedPipeline
        {
            get
            {
                return HttpRuntime.UsingIntegratedPipeline;
            }
        }

        // Provides the version of the WebSocket protocol supported by IIS. Throws an exception if called before we determined the value.
        // Returns null if WebSockets are not supported (because the IIS WebSocketModule is not installed or enabled).
        public override string WebSocketVersion
        {
            get
            {
                if (isWebSocketVersionSet)
                {
                    return webSocketVersion;
                }
                else
                {
                    throw Fx.AssertAndFailFast("The supported WebSocket protocol version is not determined at this time.");
                }
            }
        }

        public static void Enable()
        {
            AspNetEnvironment hostedEnvironment = new HostedAspNetEnvironment();
            AspNetEnvironment.Current = hostedEnvironment;
        }

        /// <summary>
        /// Tries to set the 'WebSocketVersion' property. The first call of this method sets the property (based on the "WEBSOCKET_VERSION" server property). 
        /// Subsequent calls do nothing.
        /// </summary>
        /// <param name="application">The HttpApplication used to determine the WebSocket version.</param>
        /// <remarks>
        /// Take caution when calling this method. The method initializes the 'WebSocketVersion' property based on the "WEBSOCKET_VERSION" server variable.
        /// This variable gets set by the WebSocketModule when it's loaded by IIS. If you call this method too early (before IIS got a chance to load the module list), 
        /// this method might incorrectly set 'WebSocketVersion' to 'null'.
        /// </remarks>
        public static void TrySetWebSocketVersion(HttpApplication application)
        {
            Fx.Assert(application != null, "Invalid argument.");

            if (!isWebSocketVersionSet)
            {
                webSocketVersion = application.Request.ServerVariables[WebSocketVersionServerProperty];
                isWebSocketVersionSet = true;
            }
        }

        public override void AddHostingBehavior(ServiceHostBase serviceHost, ServiceDescription description)
        {
            VirtualPathExtension virtualPathExtension = serviceHost.Extensions.Find<VirtualPathExtension>();
            if (virtualPathExtension != null)
            {
                description.Behaviors.Add(new HostedBindingBehavior(virtualPathExtension));
            }

            foreach (ServiceEndpoint endpoint in description.Endpoints)
            {
                if (ServiceMetadataBehavior.IsMetadataEndpoint(description, endpoint))
                {
                    endpoint.Behaviors.Add(new HostedMetadataExchangeEndpointBehavior());
                }
            }
        }

        public override bool IsWebConfigAboveApplication(object configHostingContext)
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            WebContext context = configHostingContext as WebContext;
            if (context != null)
            {
                return context.ApplicationLevel == WebApplicationLevel.AboveApplication;
            }

            return false; // if we don't recognize the context we can't enforce the special web.config logic
        }

        public override void EnsureCompatibilityRequirements(ServiceDescription description)
        {
            AspNetCompatibilityRequirementsAttribute aspNetCompatibilityRequirements = description.Behaviors.Find<AspNetCompatibilityRequirementsAttribute>();
            if (aspNetCompatibilityRequirements == null)
            {
                aspNetCompatibilityRequirements = new AspNetCompatibilityRequirementsAttribute();
                description.Behaviors.Add(aspNetCompatibilityRequirements);
            }
        }

        public override bool TryGetFullVirtualPath(out string virtualPath)
        {
            // subclass will use the virtual path from the compiled string
            virtualPath = ServiceHostingEnvironment.FullVirtualPath;
            return true;
        }

        public override string GetAnnotationFromHost(ServiceHostBase host)
        {
            //Format Website name\Application Virtual Path|\relative service virtual path|serviceName 
            if (host != null && host.Extensions != null)
            {
                string serviceName = (host.Description != null) ? host.Description.Name : string.Empty;
                string application = ServiceHostingEnvironment.ApplicationVirtualPath;
                string servicePath = string.Empty;
                VirtualPathExtension extension = host.Extensions.Find<VirtualPathExtension>();
                if (extension != null && extension.VirtualPath != null)
                {
                    servicePath = extension.VirtualPath.Replace("~", application + "|");
                    return string.Format(CultureInfo.InvariantCulture, "{0}{1}|{2}", ServiceHostingEnvironment.SiteName, servicePath, serviceName);
                }
            }
            if (string.IsNullOrEmpty(HostedAspNetEnvironment.cachedServiceReference))
            {
                HostedAspNetEnvironment.cachedServiceReference = string.Format(CultureInfo.InvariantCulture, "{0}{1}", ServiceHostingEnvironment.SiteName, ServiceHostingEnvironment.ApplicationVirtualPath);
            }
            return HostedAspNetEnvironment.cachedServiceReference;
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - can be called outside of user context.")]
        public override void EnsureAllReferencedAssemblyLoaded()
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();
            BuildManager.GetReferencedAssemblies();
        }

        public override BaseUriWithWildcard GetBaseUri(string transportScheme, Uri listenUri)
        {
            BaseUriWithWildcard baseAddress = null;
            HostedTransportConfigurationBase hostedConfiguration =
                HostedTransportConfigurationManager.GetConfiguration(transportScheme) as HostedTransportConfigurationBase;
            if (hostedConfiguration != null)
            {
                baseAddress = hostedConfiguration.FindBaseAddress(listenUri);
                if (baseAddress == null)
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Hosting_TransportBindingNotFound(listenUri.ToString())));
                }
            }
            return baseAddress;
        }

        public override void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes bindingElementAuthenticationSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
        {
            // Verify the authentication settings
            AuthenticationSchemes hostSupportedSchemes = HostedTransportConfigurationManager.MetabaseSettings.GetAuthenticationSchemes(virtualPath);

            if ((bindingElementAuthenticationSchemes & hostSupportedSchemes) == 0)
            {
                if (bindingElementAuthenticationSchemes == AuthenticationSchemes.Negotiate ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.Ntlm ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.IntegratedWindowsAuthentication)
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireWindowsAuth));
                }
                else
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireOtherAuth(bindingElementAuthenticationSchemes.ToString())));
                }
            }

            //only use AuthenticationSchemes, which are supported both in IIS and the WCF binding
            bindingElementAuthenticationSchemes &= hostSupportedSchemes;

            if (bindingElementAuthenticationSchemes != AuthenticationSchemes.Anonymous)
            {
                //Compare the ExtendedProtectionPolicy setttings to IIS
                ExtendedProtectionPolicy iisPolicy = HostedTransportConfigurationManager.MetabaseSettings.GetExtendedProtectionPolicy(virtualPath);

                if (iisPolicy == null) //OS doesn't support CBT
                {
                    if (extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always)
                    {
                        throw FxTrace.Exception.AsError(new NotSupportedException(SR.ExtendedProtectionNotSupported));
                    }
                }
                else
                {
                    if (isMetadataListener && ChannelBindingUtility.IsDefaultPolicy(extendedProtectionPolicy))
                    {
                        //push the IIS policy onto the metadataListener if and only if the default policy is 
                        //in force. policy for non metadata listeners will still have to match IIS policy.
                        extendedProtectionPolicy = iisPolicy;
                    }
                    else
                    {
                        if (!ChannelBindingUtility.AreEqual(iisPolicy, extendedProtectionPolicy))
                        {
                            string mismatchErrorMessage;
                            if (iisPolicy.PolicyEnforcement != extendedProtectionPolicy.PolicyEnforcement)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyEnforcementMismatch(iisPolicy.PolicyEnforcement, extendedProtectionPolicy.PolicyEnforcement);
                            }
                            else if (iisPolicy.ProtectionScenario != extendedProtectionPolicy.ProtectionScenario)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyScenarioMismatch(iisPolicy.ProtectionScenario, extendedProtectionPolicy.ProtectionScenario);
                            }
                            else 
                            {
                                Fx.Assert(iisPolicy.CustomChannelBinding != extendedProtectionPolicy.CustomChannelBinding, "new case in ChannelBindingUtility.AreEqual to account for");
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyCustomChannelBindingMismatch;
                            }

                            if (mismatchErrorMessage != null)
                            {
                                throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(mismatchErrorMessage)));
                            }
                        }

                        //when using the default SPN list we auto generate, we should make sure that the IIS policy is also the default...
                        ServiceNameCollection listenerSpnList = usingDefaultSpnList ? null : extendedProtectionPolicy.CustomServiceNames;
                        if (!ChannelBindingUtility.IsSubset(iisPolicy.CustomServiceNames, listenerSpnList))
                        {
                            throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(SR.Hosting_ExtendedProtectionSPNListNotSubset)));
                        }
                    }
                }
            }

            

            // Do not set realm for Cassini.
            if (!ServiceHostingEnvironment.IsSimpleApplicationHost)
            {
                // Set the realm
                realm = HostedTransportConfigurationManager.MetabaseSettings.GetRealm(virtualPath);
            }
        }

        public override bool ValidateHttpsSettings(string virtualPath, ref bool requireClientCertificate)
        {
            // Do not validate settings for Cassini. Actually current implementation of Cassini does not support HTTPS.
            if (ServiceHostingEnvironment.IsSimpleApplicationHost)
            {
                return false;
            }

            // Validate Ssl Settings
            HttpAccessSslFlags sslFlags = HostedTransportConfigurationManager.MetabaseSettings.GetAccessSslFlags(virtualPath);
            HttpAccessSslFlags channelListenerSslFlags = HttpAccessSslFlags.None;

            // Validating SSL flags. SslRequireCert means "require client certificate" in IIS terminology.
            if ((sslFlags & HttpAccessSslFlags.SslRequireCert) != 0)
            {
                // Require SSL.
                // We apply IIS settings to the ChannelListener to fix the endpoint
                requireClientCertificate = true;
            }
            else if (requireClientCertificate &&
                // Validating SSL flags. SslNegotiateCert means "accept client certificate" in IIS terminology.
                // We want to allow SslNegotiateCert in IIS to support hosting one endpoint requiring client
                // certificates and another endpoint not using client certificates in the same VirtualDirectory.
                // HttpsChannelListener.ValidateAuthentication ensures that authentication is denied for services
                // requiring client certificates when the client does not present one.
                (sslFlags & HttpAccessSslFlags.SslNegotiateCert) == 0)
            {
                // IIS ignores client cert but the binding requires it.
                channelListenerSslFlags |= HttpAccessSslFlags.SslRequireCert;

                throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_SslSettingsMisconfigured(
                    channelListenerSslFlags.ToString(), sslFlags.ToString())));
            }

            return (sslFlags & HttpAccessSslFlags.SslMapCert) != 0;
        }

        public override void ProcessNotMatchedEndpointAddress(Uri uri, string endpointName)
        {
            if (!object.ReferenceEquals(uri.Scheme, Uri.UriSchemeHttp) &&
                !object.ReferenceEquals(uri.Scheme, Uri.UriSchemeHttps))
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Hosting_NonHTTPInCompatibilityMode(endpointName)));
            }
        }

        public override void ValidateCompatibilityRequirements(AspNetCompatibilityRequirementsMode compatibilityMode)
        {
            if (compatibilityMode == AspNetCompatibilityRequirementsMode.Allowed)
            {
                return;
            }
            else if (ServiceHostingEnvironment.AspNetCompatibilityEnabled &&
                compatibilityMode == AspNetCompatibilityRequirementsMode.NotAllowed)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Hosting_ServiceCompatibilityNotAllowed));
            }
            else if (!ServiceHostingEnvironment.AspNetCompatibilityEnabled &&
                compatibilityMode == AspNetCompatibilityRequirementsMode.Required)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Hosting_ServiceCompatibilityRequire));
            }
        }

        public override IAspNetMessageProperty GetHostingProperty(Message message)
        {
            return GetHostingProperty(message, false);
        }

        public override IAspNetMessageProperty GetHostingProperty(Message message, bool removeFromMessage)
        {
            IAspNetMessageProperty result = null;
            object property;

            if (message.Properties.TryGetValue(HostingMessageProperty.Name, out property))
            {
                result = (HostingMessageProperty)property;
                if (removeFromMessage)
                {
                    message.Properties.Remove(HostingMessageProperty.Name);
                }
            }

            return result;
        }

        public override void PrepareMessageForDispatch(Message message)
        {
            ReceiveContext context = null;
            if (ReceiveContext.TryGet(message, out context) && !(context is ReceiveContextBusyCountWrapper))
            {
                ReceiveContextBusyCountWrapper wrapper = new ReceiveContextBusyCountWrapper(context);
                message.Properties.Remove(ReceiveContext.Name);
                message.Properties.Add(ReceiveContext.Name, wrapper);
            }
        }

        public override void ApplyHostedContext(TransportChannelListener listener, BindingContext context)
        {
            VirtualPathExtension virtualPathExtension = context.BindingParameters.Find<VirtualPathExtension>();

            if (virtualPathExtension != null)
            {
                HostedMetadataBindingParameter metadataBindingParameter = context.BindingParameters.Find<HostedMetadataBindingParameter>();
                listener.ApplyHostedContext(virtualPathExtension.VirtualPath, metadataBindingParameter != null);
            }
        }

        internal override void AddMetadataBindingParameters(Uri listenUri, KeyedByTypeCollection<IServiceBehavior> serviceBehaviors, BindingParameterCollection bindingParameters)
        {
            if (serviceBehaviors.Find<HostedBindingBehavior>() != null)
            {
                bindingParameters.Add(new HostedMetadataBindingParameter());
            }

            VirtualPathExtension virtualPathExtension = bindingParameters.Find<VirtualPathExtension>();

            if (virtualPathExtension != null)
            {
                AuthenticationSchemes hostSupportedAuthenticationSchemes = AspNetEnvironment.Current.GetAuthenticationSchemes(listenUri);

                if (hostSupportedAuthenticationSchemes != AuthenticationSchemes.None)
                {
                    if (bindingParameters.Find<AuthenticationSchemesBindingParameter>() == null)
                    {
                        bindingParameters.Add(new AuthenticationSchemesBindingParameter(hostSupportedAuthenticationSchemes));
                    }
                }
            }

            base.AddMetadataBindingParameters(listenUri, serviceBehaviors, bindingParameters);
        }

        internal override bool IsMetadataListener(BindingParameterCollection bindingParameters)
        {
            return base.IsMetadataListener(bindingParameters) || bindingParameters.Find<HostedMetadataBindingParameter>() != null;
        }

        public override void IncrementBusyCount()
        {
            HostingEnvironmentWrapper.IncrementBusyCount();
        }

        public override void DecrementBusyCount()
        {
            HostingEnvironmentWrapper.DecrementBusyCount();
        }
        
        public override bool TraceIncrementBusyCountIsEnabled()
        {
            return TD.IncrementBusyCountIsEnabled();
        }

        public override bool TraceDecrementBusyCountIsEnabled()
        {
            return TD.DecrementBusyCountIsEnabled();
        }
        public override void TraceIncrementBusyCount(string data)
        {
            if (data == null)
            {
                data = SR.DefaultBusyCountSource;
            }
            TD.IncrementBusyCount(data);
        }

        public override void TraceDecrementBusyCount(string data)
        {
            if (data == null)
            {
                data = SR.DefaultBusyCountSource;
            }
            TD.DecrementBusyCount(data);
        }

        public override object GetConfigurationSection(string sectionPath)
        {
            return GetSectionFromWebConfigurationManager(sectionPath, ServiceHostingEnvironment.FullVirtualPath);
        }

        [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetSectionFromWebConfigurationManager which elevates.")]
        [SecurityCritical]
        public override object UnsafeGetConfigurationSection(string sectionPath)
        {
            return UnsafeGetSectionFromWebConfigurationManager(sectionPath, ServiceHostingEnvironment.FullVirtualPath);
        }

        public override bool IsSimpleApplicationHost
        {
            get
            {
                return ServiceHostingEnvironment.IsSimpleApplicationHost;
            }
        }

        public override AuthenticationSchemes GetAuthenticationSchemes(Uri baseAddress)
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            string fileName = VirtualPathUtility.GetFileName(baseAddress.AbsolutePath);
            string virtualPath = ServiceHostingEnvironment.CurrentVirtualPath;
            string completePath;
            if (virtualPath != null && virtualPath.EndsWith("/", StringComparison.Ordinal))
            {
                completePath = virtualPath + fileName;
            }
            else
            {
                completePath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", virtualPath, fileName);
            }
            AuthenticationSchemes supportedSchemes = HostedTransportConfigurationManager.MetabaseSettings.GetAuthenticationSchemes(completePath);

            return supportedSchemes;
        }

        [Fx.Tag.SecurityNote(Critical = "Handles config objects, which should not be leaked.",
             Safe = "Doesn't leak config objects out of SecurityCritical code.")]
        [SecuritySafeCritical]
        [MethodImpl(MethodImplOptions.NoInlining)]
        public override bool IsWindowsAuthenticationConfigured()
        {
            if (!this.isWindowsAuthentication.HasValue)
            {
                AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

                AuthenticationSection authSection = (AuthenticationSection)UnsafeGetConfigurationSection("system.web/authentication");
                if (authSection != null)
                {
                    this.isWindowsAuthentication = (authSection.Mode == AuthenticationMode.Windows);
                }
                else
                {
                    this.isWindowsAuthentication = false;
                }
            }

            return this.isWindowsAuthentication.Value;
        }

        /// Be sure to update UnsafeGetSectionFromWebConfigurationManager if you modify this method
        [MethodImpl(MethodImplOptions.NoInlining)]
        static object GetSectionFromWebConfigurationManager(string sectionPath, string virtualPath)
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            if (virtualPath != null)
            {
                return WebConfigurationManager.GetSection(sectionPath, virtualPath);
            }
            else
            {
                return WebConfigurationManager.GetSection(sectionPath);
            }
        }

        // Be sure to update GetSectionFromWebConfigurationManager if you modify this method
        [SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts, Justification = "This is from an internal helper class and users have no way to pass arbitrary information to this code.")]
        [Fx.Tag.SecurityNote(Critical = "Asserts ConfigurationPermission in order to fetch config from WebConfigurationManager,"
            + "caller must guard return value.")]
        [SecurityCritical]
        [ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)]
        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static object UnsafeGetSectionFromWebConfigurationManager(string sectionPath, string virtualPath)
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            if (virtualPath != null)
            {
                return WebConfigurationManager.GetSection(sectionPath, virtualPath);
            }
            else
            {
                return WebConfigurationManager.GetSection(sectionPath);
            }
        }

        public override bool IsWithinApp(string absoluteVirtualPath)
        {
            return HostedTransportConfigurationManager.MetabaseSettings.IsWithinApp(absoluteVirtualPath);
        }

        // This class is intended to be empty.
        class HostedMetadataBindingParameter
        {
        }

        class HostedMetadataExchangeEndpointBehavior : IEndpointBehavior
        {
            void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
                bindingParameters.Add(new HostedMetadataBindingParameter());
            }

            void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, Dispatcher.ClientRuntime clientRuntime)
            {
            }

            void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, Dispatcher.EndpointDispatcher endpointDispatcher)
            {
            }

            void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
            {
            }
        }

        class ReceiveContextBusyCountWrapper : ReceiveContext
        {
            ReceiveContext wrappedContext;
            //possible values are 0 and 1.
            //using an integer to allow usage with Interlocked methods
            //synchronized access needed as there could be ---- between calls
            //to EndComplete and Tx notification.
            int busyCount;
            //possible values are 0 and 1
            //using an integer to allow usage with Interlocked methods
            //synchronized access needed as there could be ---- between calls
            //to EndComplete and Tx Status notification.
            int ambientTransactionCount;

            internal ReceiveContextBusyCountWrapper(ReceiveContext context)
            {
                this.wrappedContext = context;
                this.wrappedContext.Faulted += new EventHandler(OnWrappedContextFaulted);
                AspNetEnvironment.Current.IncrementBusyCount();
                if (AspNetEnvironment.Current.TraceIncrementBusyCountIsEnabled())
                {
                    AspNetEnvironment.Current.TraceIncrementBusyCount(this.GetType().FullName);
                }
                Interlocked.Increment(ref busyCount);
            }

            protected override void OnAbandon(TimeSpan timeout)
            {
                this.wrappedContext.Abandon(timeout);
                DecrementBusyCount();
            }

            protected override IAsyncResult OnBeginAbandon(TimeSpan timeout, AsyncCallback callback, object state)
            {
                return this.wrappedContext.BeginAbandon(timeout, callback, state);
            }

            protected override IAsyncResult OnBeginComplete(TimeSpan timeout, AsyncCallback callback, object state)
            {
                RegisterForTransactionNotification(Transaction.Current);
                return this.wrappedContext.BeginComplete(timeout, callback, state);
            }

            protected override void OnComplete(TimeSpan timeout)
            {
                RegisterForTransactionNotification(Transaction.Current);
                this.wrappedContext.Complete(timeout);
                DecrementOnNoAmbientTransaction();

            }

            protected override void OnEndAbandon(IAsyncResult result)
            {
                this.wrappedContext.EndAbandon(result);
                DecrementBusyCount();
            }

            protected override void OnEndComplete(IAsyncResult result)
            {
                this.wrappedContext.EndComplete(result);
                DecrementOnNoAmbientTransaction();
            }

            protected override void OnFaulted()
            {
                try
                {
                    this.wrappedContext.Fault();
                }
                finally
                {
                    base.OnFaulted();
                }
            }

            void OnWrappedContextFaulted(object sender, EventArgs e)
            {
                try
                {
                    Fault();
                }
                finally
                {
                    DecrementBusyCount();
                }
            }

            void RegisterForTransactionNotification(Transaction transaction)
            {
                if (Transaction.Current != null)
                {
                    ReceiveContextEnlistmentNotification notification = new ReceiveContextEnlistmentNotification(this);
                    transaction.EnlistVolatile(notification, EnlistmentOptions.None);
                    Interlocked.Increment(ref this.ambientTransactionCount);
                }
            }

            void DecrementOnNoAmbientTransaction()
            {
                if (Interlocked.Exchange(ref this.ambientTransactionCount, 0) != 1)
                {
                    DecrementBusyCount();
                }

            }

            void DecrementBusyCount()
            {
                if (Interlocked.Exchange(ref this.busyCount, 0) == 1)
                {
                    AspNetEnvironment.Current.DecrementBusyCount();
                    if (AspNetEnvironment.Current.TraceDecrementBusyCountIsEnabled())
                    {
                        AspNetEnvironment.Current.TraceDecrementBusyCount(this.GetType().FullName);
                    }
                }
            }

            class ReceiveContextEnlistmentNotification : IEnlistmentNotification
            {
                ReceiveContextBusyCountWrapper context;

                internal ReceiveContextEnlistmentNotification(ReceiveContextBusyCountWrapper context)
                {
                    this.context = context;
                }

                public void Commit(Enlistment enlistment)
                {
                    this.context.DecrementBusyCount();
                    enlistment.Done();
                }

                public void InDoubt(Enlistment enlistment)
                {
                    this.context.DecrementBusyCount();
                    enlistment.Done();
                }

                public void Prepare(PreparingEnlistment preparingEnlistment)
                {
                    preparingEnlistment.Prepared();
                }

                public void Rollback(Enlistment enlistment)
                {
                    enlistment.Done();
                }
            }
        }
    }
}