public static IContainer ConfigureContainer()
        {
            var cb = new ContainerBuilder();

            cb.RegisterType <HealthMonitorService>().As <IHealthMonitorService>();

            AutofacHostFactory.HostConfigurationAction = host =>
            {
                foreach (var endpoint in host.Description.Endpoints)
                {
                    var configuredBehaviors = new IEndpointBehavior[endpoint.Behaviors.Count];
                    endpoint.Behaviors.CopyTo(configuredBehaviors, 0);

                    endpoint.Behaviors.Clear();
                    endpoint.Behaviors.Add(new PingEndpointBehavior());

                    foreach (var configuredBehavior in configuredBehaviors)
                    {
                        if (!endpoint.Behaviors.Contains(configuredBehavior.GetType()))
                        {
                            endpoint.Behaviors.Add(configuredBehavior);
                        }
                    }
                }
            };

            var reader = new ConfigurationSettingsReader();

            cb.RegisterModule(reader);

            Container = cb.Build();

            return(Container);
        }
Пример #2
0
        // This method runs validators (both builtin and ones in description).
        // Precondition: EnsureInvariants() should already have been called.
        void Validate(bool runOperationValidators, bool isForService)
        {
            // contract behaviors
            ContractDescription contract = Contract;

            for (int j = 0; j < contract.ContractBehaviors.Count; j++)
            {
                IContractBehavior iContractBehavior = contract.ContractBehaviors[j];
                iContractBehavior.Validate(contract, this);
            }
            // endpoint behaviors
            for (int j = 0; j < EndpointBehaviors.Count; j++)
            {
                IEndpointBehavior ieb = EndpointBehaviors[j];
                ieb.Validate(this);
            }
            // operation behaviors
            if (runOperationValidators)
            {
                for (int j = 0; j < contract.Operations.Count; j++)
                {
                    OperationDescription op = contract.Operations[j];
                    TaskOperationDescriptionValidator.Validate(op, isForService);
                    for (int k = 0; k < op.OperationBehaviors.Count; k++)
                    {
                        IOperationBehavior iob = op.OperationBehaviors[k];
                        iob.Validate(op);
                    }
                }
            }
        }
Пример #3
0
        void ApplyServiceElement(ServiceElement service)
        {
            //base addresses
            HostElement host = service.Host;

            foreach (BaseAddressElement baseAddress in host.BaseAddresses)
            {
                AddBaseAddress(new Uri(baseAddress.BaseAddress));
            }

            // behaviors
            AddServiceBehaviors(service.BehaviorConfiguration, true);

            // endpoints
            foreach (ServiceEndpointElement endpoint in service.Endpoints)
            {
                ServiceEndpoint se;

                var binding = String.IsNullOrEmpty(endpoint.Binding) ? null : ConfigUtil.CreateBinding(endpoint.Binding, endpoint.BindingConfiguration);

                if (!String.IsNullOrEmpty(endpoint.Kind))
                {
                    var contract = String.IsNullOrEmpty(endpoint.Contract) ? null : GetContract(endpoint.Contract, false);
                    se = ConfigUtil.ConfigureStandardEndpoint(contract, endpoint);
                    if (se.Binding == null)
                    {
                        se.Binding = binding;
                    }
                    if (se.Address == null && se.Binding != null)                     // standard endpoint might have empty address
                    {
                        se.Address = new EndpointAddress(CreateUri(se.Binding.Scheme, endpoint.Address));
                    }
                    if (se.Binding == null && se.Address != null)                     // look for protocol mapping
                    {
                        se.Binding = ConfigUtil.GetBindingByProtocolMapping(se.Address.Uri);
                    }

                    AddServiceEndpoint(se);
                }
                else
                {
                    if (binding == null && endpoint.Address != null)                     // look for protocol mapping
                    {
                        binding = ConfigUtil.GetBindingByProtocolMapping(endpoint.Address);
                    }
                    se = AddServiceEndpoint(endpoint.Contract, binding, endpoint.Address);
                }

                // endpoint behaviors
                EndpointBehaviorElement epbehavior = ConfigUtil.BehaviorsSection.EndpointBehaviors [endpoint.BehaviorConfiguration];
                if (epbehavior != null)
                {
                    foreach (var bxe in epbehavior)
                    {
                        IEndpointBehavior b = (IEndpointBehavior)bxe.CreateBehavior();
                        se.Behaviors.Add(b);
                    }
                }
            }
        }
Пример #4
0
        public object CreateClient(string configurationName, IEndpointBehavior behaviour)
        {
            var client = (ClientBase <TChannel>)CreateClient(configurationName);

            client.Endpoint.Behaviors.Add(behaviour);
            return(client);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SoapPatientService"/> class.
        /// Constructor that requires an IEndpointBehavior for dependency injection.
        /// </summary>
        /// <param name="logger">The service Logger.</param>
        /// <param name="configuration">The service configuration.</param>
        /// <param name="loggingEndpointBehaviour">Endpoint behaviour for logging purposes.</param>
        public SoapPatientService(ILogger <SoapPatientService> logger, IConfiguration configuration, IEndpointBehavior loggingEndpointBehaviour)
        {
            if (configuration is null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            this.loggingEndpointBehaviour = loggingEndpointBehaviour;
            this.logger = logger;

            IConfigurationSection clientConfiguration = configuration.GetSection("ClientRegistries");

            // Load Certificate
            string           clientCertificatePath = clientConfiguration.GetSection("ClientCertificate").GetValue <string>("Path");
            string           certificatePassword   = clientConfiguration.GetSection("ClientCertificate").GetValue <string>("Password");
            X509Certificate2 clientCertificate     = new X509Certificate2(System.IO.File.ReadAllBytes(clientCertificatePath), certificatePassword);

            string          serviceUrl = clientConfiguration.GetValue <string>("ServiceUrl");
            EndpointAddress endpoint   = new EndpointAddress(new Uri(serviceUrl));

            // Create client
            this.getDemographicsClient = new QUPA_AR101102_PortTypeClient(QUPA_AR101102_PortTypeClient.EndpointConfiguration.QUPA_AR101102_Port, endpoint);
            this.getDemographicsClient.Endpoint.EndpointBehaviors.Add(this.loggingEndpointBehaviour);
            this.getDemographicsClient.ClientCredentials.ClientCertificate.Certificate = clientCertificate;

            // TODO: - HACK - Remove this once we can get the server certificate to be trusted.
            this.getDemographicsClient.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
                new X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = X509CertificateValidationMode.None,
                RevocationMode            = X509RevocationMode.NoCheck,
            };
        }
Пример #6
0
        /// <summary>
        /// Creates the WCF endpoint and configures port sharing depending on the
        /// Core.WCFEnablePortSharing setting.
        /// </summary>
        /// <returns>The Castle endpoint facility contract</returns>

        private IWcfEndpoint CreateEndpoint(
            BindingEndpointModel baseEndpoint,
            IEndpointBehavior endpointBehaviour,
            List <string> baseAddresses,
            string serviceUri)
        {
            IWcfEndpoint endpoint = baseEndpoint;

            if (Settings.WCFEnablePortSharing)
            {
                baseAddresses.Add(serviceUri);
                baseEndpoint.AddExtensions(endpointBehaviour);
            }
            else
            {
                // add ACL's to allow http service registrations without account elevation (for mex endpoints)
                // run these commands in an elevated console (only need to run this once)
                // NOTE: this is only required when not running as an administrator
                // netsh http add urlacl url = http://+:8002/ user=\Everyone
                // netsh http add urlacl url = http://+:8003/ user=\Everyone
                // netsh http add urlacl url = http://+:8502/ user=\Everyone

                endpoint = baseEndpoint
                           // The .At(uri) enables a fully qualified endpoint Uri which avoids using a base address configuration
                           // By limiting base addresses to only HTTP (mex) endpoints we eliminate the requirement of port sharing
                           .At(serviceUri)
                           .AddExtensions(endpointBehaviour);
            }

            return(endpoint);
        }
Пример #7
0
        private void SetBehaviors( )
        {
            ValidationBehavior validation = new ValidationBehavior(true, false, ruleSet);

            endpointBehavior = (IEndpointBehavior)validation;
            contractBehavior = (IContractBehavior)validation;
        }
Пример #8
0
        public static List <IEndpointBehavior> GetDefaultEndPointBehaviors(string scheme)
        {
            List <IEndpointBehavior> list = new List <IEndpointBehavior>();

            WCFConfigProvider.InitServiceModel();
            if (WCFConfigProvider._serviceModel == null)
            {
                return(list);
            }
            string defaultEndPointBehaviorName = WCFConfigProvider.GetDefaultEndPointBehaviorName(scheme);

            if (WCFConfigProvider._serviceModel.Behaviors.EndpointBehaviors.ContainsKey(defaultEndPointBehaviorName))
            {
                EndpointBehaviorElement endpointBehaviorElement = WCFConfigProvider._serviceModel.Behaviors.EndpointBehaviors[defaultEndPointBehaviorName];
                foreach (BehaviorExtensionElement current in endpointBehaviorElement)
                {
                    IEndpointBehavior endpointBehavior = WCFConfigProvider.CreateBehavior <IEndpointBehavior>(current);
                    if (endpointBehavior != null)
                    {
                        list.Add(endpointBehavior);
                    }
                }
            }
            return(list);
        }
Пример #9
0
        /// <summary>
        /// 获取终结点行为列表
        /// </summary>
        /// <returns>终结点行为列表</returns>
        private ICollection <IEndpointBehavior> GetEndpointBehaviors <T>()
        {
            string endpointName = typeof(T).FullName;

            #region # 验证

            if (!ServiceModelSetting.Endpoints.ContainsKey(endpointName))
            {
                throw new NullReferenceException($"名称为\"{endpointName}\"的终结点未配置!");
            }

            #endregion

            ICollection <IEndpointBehavior> endpointBehaviors = new HashSet <IEndpointBehavior>();
            ChannelEndpointElement          endpoint          = ServiceModelSetting.Endpoints[endpointName];
            if (!string.IsNullOrWhiteSpace(endpoint.BehaviorConfiguration))
            {
                if (!ServiceModelSetting.BehaviorConfigurations.TryGetValue(endpoint.BehaviorConfiguration, out BehaviorConfigurationElement behaviorConfiguration))
                {
                    throw new KeyNotFoundException($"未找到名称为\"{endpoint.BehaviorConfiguration}\"的行为配置!");
                }
                foreach (EndpointBehaviorElement endpointBehaviorElement in behaviorConfiguration.EndpointBehaviors)
                {
                    IEndpointBehavior endpointBehavior = endpointBehaviorElement.CreateEndpointBehavior();
                    endpointBehaviors.Add(endpointBehavior);
                }
            }

            return(endpointBehaviors);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceClient{TLocalType}"/> class.
 /// </summary>
 /// <param name="customEndPointBehaviour">The custom end point behaviour.</param>
 public ServiceClient(IEndpointBehavior customEndPointBehaviour)
 {
     _channel = new ChannelFactory <TLocalType>(typeof(TLocalType).FullName);
     _channel.Endpoint.Behaviors.Add(customEndPointBehaviour);
     _serviceInstance  = _channel.CreateChannel();
     _channel.Faulted += ServiceInstance_Faulted;
 }
Пример #11
0
 public ProxyMapper(Binding binding, IEndpointBehavior endpointBehavior, INameMapper nameMapper)
 {
     _generator        = new ProxyGenerator();
     _nameMapper       = nameMapper;
     _binding          = binding;
     _endpointBehavior = endpointBehavior;
 }
 private void SetBehaviors()
 {
     ValidationBehavior validation = new ValidationBehavior(true, false, ruleSet);
     endpointBehavior = (IEndpointBehavior)validation;
     contractBehavior = (IContractBehavior)validation;
     operationBehavior = (IOperationBehavior)validation;
 }
Пример #13
0
 public VerintConnection(IOptions <VerintConnectionConfiguration> verintConfiguration, IEndpointBehavior requestBehavior)
 {
     _verintConfiguration = verintConfiguration.Value;
     _requestBehavior     = requestBehavior;
     _verintHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
     _verintHttpBinding.Security.Mode = BasicHttpSecurityMode.None;
 }
 private void ReflectOnCallbackInstance(ServiceEndpoint endpoint)
 {
     if (this.callbackType != null)
     {
         if (endpoint.Contract.CallbackContractType == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SfxCallbackTypeCannotBeNull", new object[] { endpoint.Contract.ContractType.FullName })));
         }
         this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, this.callbackType);
     }
     else if ((this.CallbackInstance != null) && (this.CallbackInstance.UserObject != null))
     {
         if (endpoint.Contract.CallbackContractType == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SfxCallbackTypeCannotBeNull", new object[] { endpoint.Contract.ContractType.FullName })));
         }
         object      userObject         = this.CallbackInstance.UserObject;
         System.Type implementationType = userObject.GetType();
         this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, implementationType);
         IEndpointBehavior item = userObject as IEndpointBehavior;
         if (item != null)
         {
             endpoint.Behaviors.Add(item);
         }
         IContractBehavior behavior2 = userObject as IContractBehavior;
         if (behavior2 != null)
         {
             endpoint.Contract.Behaviors.Add(behavior2);
         }
     }
 }
Пример #15
0
        public void addService(Type contract, String address, Binding binding, IEndpointBehavior behavior)
        {
            ServiceEndpoint endPt = sh.AddServiceEndpoint(contract, binding, address);

            endPt.Behaviors.Add(behavior);

            endPt.Behaviors.Add(new MessageInterceptor());
        }
Пример #16
0
        private void SetBehaviors()
        {
            ValidatingBehavior validation = new ValidatingBehavior(true, false, Ruleset);

            _endpointBehavior  = (IEndpointBehavior)validation;
            _contractBehavior  = (IContractBehavior)validation;
            _operationBehavior = (IOperationBehavior)validation;
        }
 public static void AddBehaviorOnAllEndpoints(
     this ServiceHostBase serviceHost,
     IEndpointBehavior behavior)
 {
     ReplaceBehaviorOnAllEndpoints(
         serviceHost,
         null,
         behavior);
 }
        void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase host)
        {
            IEndpointBehavior endpointBehavior = this;

            foreach (ServiceEndpoint endpoint in description.Endpoints)
            {
                endpointBehavior.Validate(endpoint);
            }
        }
Пример #19
0
        private IEndpointBehavior GetEndpointBehavior()
        {
            if (_endpointBehavior == null)
            {
                _endpointBehavior = new CancellationEndpointBehavior(new ServiceServiceProvider());
            }

            return(_endpointBehavior);
        }
Пример #20
0
        public CurrencyConverterModel(
            CurrencyConverterServiceClient currencyConverterServiceProxy,
            IEndpointBehavior endpointBehavior
            )
        {
            _currencyConverterServiceProxy = currencyConverterServiceProxy ?? throw new ArgumentNullException(nameof(currencyConverterServiceProxy));
            endpointBehavior = endpointBehavior ?? throw new ArgumentNullException(nameof(endpointBehavior));

            _currencyConverterServiceProxy.ChannelFactory.Endpoint.Behaviors.Add(endpointBehavior);
        }
Пример #21
0
        public static IEndpointBehavior CreateBehavior(BehaviorExtensionElement behaviorExtension)
        {
            IEndpointBehavior endPointBehavior = (IEndpointBehavior)behaviorExtension.GetType().InvokeMember(
                "CreateBehavior",
                BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                behaviorExtension,
                null);

            return(endPointBehavior);
        }
Пример #22
0
        public IOnvifRequestBuilder <DeviceInformation, IDeviceInformation> SetAuthentication(IEndpointBehavior authenticator)
        {
            if (authenticator == null)
            {
                throw new ArgumentNullException(nameof(authenticator));
            }

            _authenticator = authenticator;

            return(this);
        }
Пример #23
0
        public static I CreateInstance <S, I>(IServiceBehavior serviceBehavior, IEndpointBehavior clientBehavior) where I : class
            where S : class, I
        {
            EndpointAddress    address = GetAddress <S, I>(serviceBehavior, Binding as NetNamedPipeContextBinding);
            ChannelFactory <I> factory = new ChannelFactory <I>(Binding, address);

            factory.AddGenericResolver();
            factory.Endpoint.EndpointBehaviors.Add(clientBehavior);

            return(factory.CreateChannel());
        }
        public ServiceModelBuilder AddGlobalBehavior(IEndpointBehavior behavior)
        {
            Services.ConfigureAll <ServiceModelOptions>(option =>
            {
                foreach (var service in option.Services)
                {
                    service.Behaviors.Add(behavior);
                }
            });

            return(this);
        }
Пример #25
0
        public void Use2()
        {
            // This time with ServiceDiscoveryBehavior.
            var b = new EndpointDiscoveryBehavior();
            IEndpointBehavior eb = b;
            var host             = new ServiceHost(typeof(TestService));
            var se  = host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), new Uri("http://localhost:37564"));
            var sdb = new ServiceDiscoveryBehavior();

            sdb.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint());
            IServiceBehavior sb = sdb;

            se.Behaviors.Add(b);

            var bc = new BindingParameterCollection();

            sb.AddBindingParameters(host.Description, host, host.Description.Endpoints, bc);
            eb.AddBindingParameters(se, bc);
            Assert.AreEqual(0, bc.Count, "#1");
            Assert.AreEqual(0, host.Extensions.Count, "#1-2");

            sb.Validate(host.Description, host);
            eb.Validate(se);
            // ... should "validate" not "apply dispatch behavior" do "add host extension" job? I doubt that.
            Assert.AreEqual(1, host.Extensions.Count, "#2-2");
            var dse = host.Extensions.Find <DiscoveryServiceExtension> ();

            Assert.IsNotNull(dse, "#2-3");
            Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#2-4");
            Assert.AreEqual(2, se.Behaviors.Count, "#2-5"); // EndpointDiscoveryBehavior + discovery initializer.

            Assert.AreEqual(0, host.ChannelDispatchers.Count, "#3-1");
            Assert.AreEqual(1, host.Description.Endpoints.Count, "#3-2");
            Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-4");

            // The IEndpointBehavior from EndpointDiscoveryBehavior, when ApplyDispatchBehavior() is invoked, publishes an endpoint.
            sb.ApplyDispatchBehavior(host.Description, host);
            Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-5");    // not yet published
            eb.ApplyDispatchBehavior(se, new EndpointDispatcher(new EndpointAddress("http://localhost:37564"), "ITestService", "http://tempuri.org/"));
            Assert.AreEqual(2, host.ChannelDispatchers.Count, "#3-6-1"); // for online and offline announcements
            Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-6-2");  // still not published.

            host.Open();
            try
            {
                Assert.AreEqual(3, host.ChannelDispatchers.Count, "#4-1"); // for online and offline announcements
                Assert.AreEqual(1, dse.PublishedEndpoints.Count, "#4-2");  // The endpoint is published again. (Not sure if it's worthy of testing.)
            }
            finally
            {
                host.Close();
            }
        }
Пример #26
0
        private void ApplyBehavior(string behaviorConfig)
        {
            BehaviorsSection        behaviorsSection = ConfigUtil.BehaviorsSection;
            EndpointBehaviorElement behaviorElement  = behaviorsSection.EndpointBehaviors [behaviorConfig];
            int i = 0;

            foreach (BehaviorExtensionElement el in behaviorElement)
            {
                IEndpointBehavior behavior = (IEndpointBehavior)el.CreateBehavior();
                Endpoint.Behaviors.Remove(behavior.GetType());
                Endpoint.Behaviors.Add(behavior);
            }
        }
Пример #27
0
        private ChannelFactory GetChannelFactory <T>(string URI, Binding binding, IEndpointBehavior endpointBehavior)
        {
            string key = typeof(T).FullName + URI;

            return(_channels.GetOrAdd(key, k =>
            {
                var channel = new ChannelFactory <T>(binding);
                if (endpointBehavior != null)
                {
                    channel.Endpoint.Behaviors.Add(endpointBehavior);
                }
                channel.Endpoint.Address = new EndpointAddress(URI);
                return channel;
            }));
        }
Пример #28
0
        internal static ChannelFactory <I> InitializeInstance <S, I>(IServiceBehavior serviceBehavior,
                                                                     IEndpointBehavior clientBehavior,
                                                                     NetNamedPipeContextBinding proxyBinding,
                                                                     NetNamedPipeContextBinding serviceBinding) where I : class
            where S : class, I
        {
            Debug.Assert(proxyBinding != null);
            Debug.Assert(serviceBinding != null);
            EndpointAddress    address = GetAddress <S, I>(serviceBehavior, serviceBinding);
            ChannelFactory <I> factory = new ChannelFactory <I>(proxyBinding, address);

            factory.AddGenericResolver();
            factory.Endpoint.EndpointBehaviors.Add(clientBehavior);

            return(factory);
        }
Пример #29
0
        public static IEndpoint AddBehavior(this IEndpoint endpoint, IEndpointBehavior behavior)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (behavior == null)
            {
                throw new ArgumentNullException(nameof(behavior));
            }

            endpoint.Behaviors.Add(behavior);

            return(endpoint);
        }
        /// <summary>
        /// 创建终结点行为
        /// </summary>
        /// <returns>终结点行为</returns>
        public IEndpointBehavior CreateEndpointBehavior()
        {
            Assembly assembly = System.Reflection.Assembly.Load(this.Assembly);
            Type     type     = assembly.GetType(this.Type);

            #region # 验证

            if (!typeof(IEndpointBehavior).IsAssignableFrom(type))
            {
                throw new InvalidOperationException($"类型\"{type.FullName}\"未实现接口\"{nameof(IEndpointBehavior)}\"!");
            }

            #endregion

            IEndpointBehavior endpointBehavior = (IEndpointBehavior)Activator.CreateInstance(type);

            return(endpointBehavior);
        }
Пример #31
0
        internal static ChannelFactory <I> InitializeInstance <S, I>(IServiceBehavior serviceBehavior,
                                                                     IEndpointBehavior clientBehavior,
                                                                     NetNamedPipeContextBinding proxyBinding,
                                                                     NetNamedPipeContextBinding serviceBinding) where I : class
            where S : class, I
        {
            if (serviceBinding == null)
            {
                serviceBinding = Binding as NetNamedPipeContextBinding;
            }
            EndpointAddress    address = GetAddress <S, I>(serviceBehavior, serviceBinding);
            ChannelFactory <I> factory = new ChannelFactory <I>(proxyBinding, address);

            factory.AddGenericResolver(defaultGenericResolverTypes);
            factory.Endpoint.EndpointBehaviors.Add(clientBehavior);

            return(factory);
        }
 private static void FillBehaviorInfo(IEndpointBehavior behavior, IWmiInstance existingInstance, out IWmiInstance instance)
 {
     instance = null;
     if (behavior is ClientCredentials)
     {
         instance = existingInstance.NewInstance("ClientCredentials");
         ClientCredentials credentials = (ClientCredentials) behavior;
         instance.SetProperty("SupportInteractive", credentials.SupportInteractive);
         if ((credentials.ClientCertificate != null) && (credentials.ClientCertificate.Certificate != null))
         {
             instance.SetProperty("ClientCertificate", credentials.ClientCertificate.Certificate.ToString());
         }
         if (credentials.IssuedToken != null)
         {
             string str = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", new object[] { "CacheIssuedTokens", credentials.IssuedToken.CacheIssuedTokens });
             instance.SetProperty("IssuedToken", str);
         }
         if (credentials.HttpDigest != null)
         {
             string str2 = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", new object[] { "AllowedImpersonationLevel", credentials.HttpDigest.AllowedImpersonationLevel.ToString() });
             instance.SetProperty("HttpDigest", str2);
         }
         if ((credentials.Peer != null) && (credentials.Peer.Certificate != null))
         {
             instance.SetProperty("Peer", credentials.Peer.Certificate.ToString(true));
         }
         if (credentials.UserName != null)
         {
             instance.SetProperty("UserName", "********");
         }
         if (credentials.Windows != null)
         {
             string str3 = string.Format(CultureInfo.InvariantCulture, "{0}: {1}, {2}: {3}", new object[] { "AllowedImpersonationLevel", credentials.Windows.AllowedImpersonationLevel.ToString(), "AllowNtlm", credentials.Windows.AllowNtlm });
             instance.SetProperty("Windows", str3);
         }
     }
     else if (behavior is MustUnderstandBehavior)
     {
         instance = existingInstance.NewInstance("MustUnderstandBehavior");
     }
     else if (behavior is SynchronousReceiveBehavior)
     {
         instance = existingInstance.NewInstance("SynchronousReceiveBehavior");
     }
     else if (behavior is DispatcherSynchronizationBehavior)
     {
         instance = existingInstance.NewInstance("DispatcherSynchronizationBehavior");
     }
     else if (behavior is TransactedBatchingBehavior)
     {
         instance = existingInstance.NewInstance("TransactedBatchingBehavior");
         instance.SetProperty("MaxBatchSize", ((TransactedBatchingBehavior) behavior).MaxBatchSize);
     }
     else if (behavior is ClientViaBehavior)
     {
         instance = existingInstance.NewInstance("ClientViaBehavior");
         instance.SetProperty("Uri", ((ClientViaBehavior) behavior).Uri.ToString());
     }
     else if (behavior is IWmiInstanceProvider)
     {
         IWmiInstanceProvider provider = (IWmiInstanceProvider) behavior;
         instance = existingInstance.NewInstance(provider.GetInstanceType());
         provider.FillInstance(instance);
     }
     else
     {
         instance = existingInstance.NewInstance("Behavior");
     }
     if (instance != null)
     {
         instance.SetProperty("Type", behavior.GetType().FullName);
     }
 }
        static void FillBehaviorInfo(IEndpointBehavior behavior, IWmiInstance existingInstance, out IWmiInstance instance)
        {
            Fx.Assert(null != existingInstance, "");
            Fx.Assert(null != behavior, "");
            instance = null;
            if (behavior is ClientCredentials)
            {
                instance = existingInstance.NewInstance("ClientCredentials");
                ClientCredentials specificBehavior = (ClientCredentials)behavior;
                instance.SetProperty(AdministrationStrings.SupportInteractive, specificBehavior.SupportInteractive);
                if (specificBehavior.ClientCertificate != null && specificBehavior.ClientCertificate.Certificate != null)
                {
                    instance.SetProperty(AdministrationStrings.ClientCertificate, specificBehavior.ClientCertificate.Certificate.ToString());
                }
                if (specificBehavior.IssuedToken != null)
                {
                    string result = String.Format(CultureInfo.InvariantCulture,
                                        "{0}: {1}",
                                        AdministrationStrings.CacheIssuedTokens, specificBehavior.IssuedToken.CacheIssuedTokens);
                    instance.SetProperty(AdministrationStrings.IssuedToken, result);
                }
                if (specificBehavior.HttpDigest != null)
                {
                    string result = String.Format(CultureInfo.InvariantCulture,
                                "{0}: {1}",
                                AdministrationStrings.AllowedImpersonationLevel, specificBehavior.HttpDigest.AllowedImpersonationLevel.ToString());
                    instance.SetProperty(AdministrationStrings.HttpDigest, result);
                }
                if (specificBehavior.Peer != null && specificBehavior.Peer.Certificate != null)
                {
                    instance.SetProperty(AdministrationStrings.Peer, specificBehavior.Peer.Certificate.ToString(true));
                }
                if (specificBehavior.UserName != null)
                {
                    instance.SetProperty(AdministrationStrings.UserName, "********");
                }
                if (specificBehavior.Windows != null)
                {

#pragma warning disable 618 // To suppress AllowNtlm warning.
                    string result = String.Format(CultureInfo.InvariantCulture,
                                                    "{0}: {1}, {2}: {3}",
                                                    AdministrationStrings.AllowedImpersonationLevel,
                                                    specificBehavior.Windows.AllowedImpersonationLevel.ToString(),
                                                    AdministrationStrings.AllowNtlm,
                                                    specificBehavior.Windows.AllowNtlm);
#pragma warning restore 618

                    instance.SetProperty(AdministrationStrings.Windows, result);


                }
            }
            else if (behavior is MustUnderstandBehavior)
            {
                instance = existingInstance.NewInstance("MustUnderstandBehavior");
            }
            else if (behavior is SynchronousReceiveBehavior)
            {
                instance = existingInstance.NewInstance("SynchronousReceiveBehavior");
            }
            else if (behavior is DispatcherSynchronizationBehavior)
            {
                instance = existingInstance.NewInstance("DispatcherSynchronizationBehavior");
            }
            else if (behavior is TransactedBatchingBehavior)
            {
                instance = existingInstance.NewInstance("TransactedBatchingBehavior");
                instance.SetProperty(AdministrationStrings.MaxBatchSize, ((TransactedBatchingBehavior)behavior).MaxBatchSize);
            }
            else if (behavior is ClientViaBehavior)
            {
                instance = existingInstance.NewInstance("ClientViaBehavior");
                instance.SetProperty(AdministrationStrings.Uri, ((ClientViaBehavior)behavior).Uri.ToString());
            }
            else if (behavior is IWmiInstanceProvider)
            {
                IWmiInstanceProvider instanceProvider = (IWmiInstanceProvider)behavior;
                instance = existingInstance.NewInstance(instanceProvider.GetInstanceType());
                instanceProvider.FillInstance(instance);
            }
            else
            {
                instance = existingInstance.NewInstance("Behavior");
            }
            if (null != instance)
            {
                instance.SetProperty(AdministrationStrings.Type, behavior.GetType().FullName);
            }
        }
Пример #34
0
        private static ServiceHost GetServiceHost(Type serviceType, IEndpointBehavior endpointBehavior, Binding binding, out string baseAddress)
        {
            ServiceHost host = null;
            baseAddress = null;
            while (host == null)
            {
                try
                {
                    baseAddress = string.Format("http://localhost:{0}/SomeBasePath", GetNextPortNumber());
                    host = new ServiceHost(serviceType, new Uri(baseAddress));
                    ServiceEndpoint endpoint = host.AddServiceEndpoint(serviceType, binding, string.Empty);
                    endpoint.Behaviors.Add(endpointBehavior);
                    host.Open();
                }
                catch (AddressAlreadyInUseException)
                {
                    host = null;
                }
                catch (UriFormatException)
                {
                    host = null;
                }
            }

            return host;
        }