コード例 #1
0
        private static void ValidateDescription(ServiceHostBase serviceHost)
        {
            var description = serviceHost.Description;

            description.EnsureInvariants();
            // TODO: Reenable SecurityValidationBehavior validation
            //(SecurityValidationBehavior.Instance as IServiceBehavior).Validate(description, serviceHost);
            (new UniqueContractNameValidationBehavior() as IServiceBehavior).Validate(description, serviceHost);
            for (int i = 0; i < description.Behaviors.Count; i++)
            {
                IServiceBehavior iServiceBehavior = description.Behaviors[i];
                iServiceBehavior.Validate(description, serviceHost);
            }
            for (int i = 0; i < description.Endpoints.Count; i++)
            {
                ServiceEndpoint     endpoint      = description.Endpoints[i];
                ContractDescription contract      = endpoint.Contract;
                bool alreadyProcessedThisContract = false;
                for (int j = 0; j < i; j++)
                {
                    if (description.Endpoints[j].Contract == contract)
                    {
                        alreadyProcessedThisContract = true;
                        break;
                    }
                }
                endpoint.ValidateForService(!alreadyProcessedThisContract);
            }
        }
コード例 #2
0
        void AddServiceBehaviors(string configurationName, bool throwIfNotFound)
        {
            if (configurationName == null)
            {
                return;
            }
            ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors [configurationName];

            if (behavior == null)
            {
                if (throwIfNotFound)
                {
                    throw new ArgumentException(String.Format("Service behavior configuration '{0}' was not found", configurationName));
                }
                return;
            }

            KeyedByTypeCollection <IServiceBehavior> behaviors = Description.Behaviors;

            foreach (var bxe in behavior)
            {
                IServiceBehavior b = (IServiceBehavior)bxe.CreateBehavior();
                if (behaviors.Contains(b.GetType()))
                {
                    continue;
                }
                behaviors.Add(b);
            }
        }
コード例 #3
0
        public DiscoverableAttribute(Type resolverType, string[] ignoredContractTypeNames, string[] ignoredEndpoints, params Type[] pluginTypes)
        {
            _ignoredContractTypeNames = ignoredContractTypeNames ?? new string[] { };
            _ignoredEndpoints = ignoredEndpoints ?? new string[] { };

            var resolver = Activator.CreateInstance(resolverType) as IDiscoveryServiceResolver;
            var binding = resolver.AnnouncementBinding;
            var endpointUrl = resolver.AnnouncementEndpoint;
            _announcementEndpoint = new AnnouncementEndpoint(binding, new EndpointAddress(endpointUrl));

            var serviceDiscoveryBehavior = new ServiceDiscoveryBehavior();
            serviceDiscoveryBehavior.AnnouncementEndpoints.Add(_announcementEndpoint);
            _serviceDiscoveryBehavior = serviceDiscoveryBehavior;

            // initialize the plugin instances (ensure the parameter is not null)
            var plugins = new List<PluginBase>();
            foreach (var plugInType in pluginTypes ?? new Type[] { })
            {
                var plugin = Activator.CreateInstance(plugInType) as PluginBase;
                if (plugin != null)
                {
                    plugins.Add(plugin);
                }
            }
            _plugins = plugins;
        }
コード例 #4
0
ファイル: WCFConfigProvider.cs プロジェクト: ITanyx/GitTest
        public static List <IServiceBehavior> GetDefaultSeviceBehaviors(string scheme)
        {
            List <IServiceBehavior> list = new List <IServiceBehavior>();

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

            if (WCFConfigProvider._serviceModel.Behaviors.ServiceBehaviors.ContainsKey(defaultServiceBehaviorName))
            {
                ServiceBehaviorElement serviceBehaviorElement = WCFConfigProvider._serviceModel.Behaviors.ServiceBehaviors[defaultServiceBehaviorName];
                foreach (BehaviorExtensionElement current in serviceBehaviorElement)
                {
                    IServiceBehavior serviceBehavior = WCFConfigProvider.CreateBehavior <IServiceBehavior>(current);
                    if (serviceBehavior != null)
                    {
                        list.Add(serviceBehavior);
                    }
                }
            }
            return(list);
        }
コード例 #5
0
 public override void ProcessBehaviorForMetadataExtension(IServiceBehavior serviceBehavior, BindingParameterCollection bindingParameters)
 {
     if (serviceBehavior is HostedBindingBehavior)
     {
         bindingParameters.Add(((HostedBindingBehavior)serviceBehavior).VirtualPathExtension);
         bindingParameters.Add(new HostedMetadataBindingParameter());
     }
 }
コード例 #6
0
ファイル: RestService.cs プロジェクト: santedb/restsrvr
 /// <summary>
 /// Adds a service behavior to this instance
 /// </summary>
 public void AddServiceBehavior(IServiceBehavior behavior)
 {
     if (this.IsRunning)
     {
         throw new InvalidOperationException("Cannot add policy when service is running");
     }
     this.m_serviceBehaviors.Add(behavior);
 }
コード例 #7
0
        public void Validate()
        {
            var b = new ServiceAuthorizationBehavior();
            IServiceBehavior sb = b;

            sb.Validate(new ServiceDescription(),
                        new ServiceHost(typeof(object)));
        }
コード例 #8
0
ファイル: InProcFactory.cs プロジェクト: eraj2587/NSB7
        static EndpointAddress GetAddress <S, I>(IServiceBehavior serviceBehavior, NetNamedPipeContextBinding binding) where I : class
            where S : class, I
        {
            if (m_Hosts.ContainsKey(typeof(S)))
            {
                Debug.Assert(m_Hosts[typeof(S)].ContainsKey(typeof(I)));

                return(m_Hosts[typeof(S)][typeof(I)].Item2);
            }
            else
            {
                ServiceHost <S> host;
                if (m_Singletons.ContainsKey(typeof(S)))
                {
                    S singleton = m_Singletons[typeof(S)] as S;
                    Debug.Assert(singleton != null);
                    host = new ServiceHost <S>(singleton);
                }
                else
                {
                    host = new ServiceHost <S>();
                }

                if (serviceBehavior != null)
                {
                    host.Description.Behaviors.Insert(0, serviceBehavior);
                }
                Type[] contracts = GetContracts <S>();
                Debug.Assert(contracts.Any());

                m_Hosts[typeof(S)] = new Dictionary <Type, Tuple <ServiceHost, EndpointAddress> >();

                foreach (Type contract in contracts)
                {
                    string address = BaseAddress + Guid.NewGuid() + "_" + contract;

                    m_Hosts[typeof(S)][contract] = new Tuple <ServiceHost, EndpointAddress>(host, new EndpointAddress(address));
                    host.AddServiceEndpoint(contract, binding, address);
                }

                if (m_Throttles.ContainsKey(typeof(S)))
                {
                    host.SetThrottle(m_Throttles[typeof(S)]);
                }

                if (Scope == null)
                {
                    throw new InvalidOperationException(string.Format("Scope is not set yet when trying to instantiate {0}", typeof(I).FullName));
                }
                host.AddDependencyInjectionBehavior <S>(Scope);
                host.IncludeExceptionDetailInFaults = true;
                host.AddGenericResolver(defaultGenericResolverTypes);
                defaultServiceBehaviors.ForEach(b => host.Description.Behaviors.Add(b));
                host.Open();
            }
            return(GetAddress <S, I>());
        }
コード例 #9
0
        public ExceptionShieldingAttribute(string exceptionPolicyName)
        {
            this.exceptionPolicyName = exceptionPolicyName;
            ExceptionShieldingBehavior behavior = new ExceptionShieldingBehavior(exceptionPolicyName);

            this.contractBehavior = (IContractBehavior)behavior;
            this.serviceBehavior  = (IServiceBehavior)behavior;
            this.errorHandler     = new ExceptionShieldingErrorHandler(exceptionPolicyName);
        }
コード例 #10
0
        /// <summary>
        /// Removes/unregisters a global behavior instance.
        /// </summary>
        /// <param name="behavior">The behavior instance.</param>
        /// <returns>true if the behavior was removed; false if the behavior instance had not been registered</returns>
        public bool RemoveGlobalBehavior(IServiceBehavior behavior)
        {
            if (behavior == null)
            {
                throw new ArgumentNullException("behavior");
            }

            return ServiceBehaviorRegistry.RemoveGlobalBehavior(behavior);
        }
コード例 #11
0
        static I Create <I>(string applicationName, string serviceName) where I : class, IService
        {
            Debug.Assert(FabricRuntime.Services != null, "Use ServiceProxy only within Service Fabric");
            Debug.Assert(FabricRuntime.Services.ContainsKey(applicationName));

            Type serviceType = FabricRuntime.Services[applicationName].SingleOrDefault(type => type.GetInterfaces().Where(interfaceType => interfaceType == typeof(I)).Any());

            Debug.Assert(serviceType != null);
            Debug.Assert(serviceType.BaseType != null);

            bool serviceExists = serviceType.GetCustomAttributes <ApplicationManifestAttribute>().Where(attribute => attribute.ApplicationName.Equals(applicationName)).Any(attribute => attribute.ServiceName.Equals(serviceName));

            Debug.Assert(serviceExists);
            if (!serviceExists)
            {
                throw new InvalidOperationException("Service does not exist.");
            }

            IServiceBehavior serviceBehavior = null;

            if (serviceType.BaseType.Equals(typeof(StatelessService)))
            {
                serviceBehavior = new StatelessServiceBehavior();
            }
            else
            {
                throw new InvalidOperationException("Validation failed.");
            }

            if ((ServiceTestBase.ServiceMocks != null) && (ServiceTestBase.ServiceMocks.ContainsKey(serviceType)) && (ServiceTestBase.ServiceMocks[serviceType] != null))
            {
                if (ServiceTestBase.ServiceMocks[serviceType] is Moq.Mock)
                {
                    return(((Moq.Mock)ServiceTestBase.ServiceMocks[serviceType]).Object as I);
                }
                else
                {
                    return(ServiceTestBase.ServiceMocks[serviceType] as I);
                }
            }

            try
            {
                ServiceContext context = new ServiceContext {
                    ServiceName = new Uri("fabric:/" + applicationName + "/" + serviceName)
                };
                MethodInfo         initializeInstance = m_InitializeInstanceDefinition.MakeGenericMethod(serviceType, typeof(I));
                ChannelFactory <I> factory            = initializeInstance.Invoke(null, new object[] { serviceBehavior, new ProxyMessageInterceptor(context), m_ProxyBinding, m_ServiceBinding }) as ChannelFactory <I>;
                I channel = new ServiceChannelInvoker <I>().Install(factory);
                return(channel);
            }
            catch (TargetInvocationException exception)
            {
                throw exception.InnerException;
            }
        }
コード例 #12
0
ファイル: InProcFactory.cs プロジェクト: eraj2587/NSB7
        internal static I CreateInstance <S, I>(IServiceBehavior serviceBehavior) 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(defaultGenericResolverTypes);

            return(factory.CreateChannel());
        }
コード例 #13
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());
        }
コード例 #14
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();
            }
        }
コード例 #15
0
        protected override void ApplyServiceBehaviorInternal()
        {
            base.ApplyServiceBehaviorInternal();
            this.AddDefaultServiceBehaviors();

            IServiceBehavior behavior = this.Description.Behaviors.Find <WcfCustomBehavior>();

            if (behavior == null)
            {
                this.Description.Behaviors.Add(this.CreateCustomBehavior());
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NinjectAbstractWebServiceHost{T}"/> class.
        /// </summary>
        /// <param name="serviceBehavior">The service behavior.</param>
        /// <param name="instance">The instance.</param>
        /// <param name="baseBaseAddresses">The base addresses.</param>
        protected NinjectAbstractWebServiceHost(IServiceBehavior serviceBehavior, T instance, Uri[] baseBaseAddresses)
            : base(serviceBehavior)
        {
            var addresses = new UriSchemeKeyedCollection(baseBaseAddresses);

            if (ServiceTypeHelper.IsSingletonService(instance))
            {
                this.InitializeDescription(instance, addresses);
            }
            else
            {
                this.InitializeDescription(typeof(T), addresses);
            }
        }
コード例 #17
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public TcpChatServiceMode()
        {
            var binding = new NetTcpBinding();

            binding.Security.Mode  = SecurityMode.None;
            ServiceEndpointBinding = binding;
            ServiceMetadataBinding = MetadataExchangeBindings.CreateMexTcpBinding();
            ServiceBehavior        = new ServiceMetadataBehavior {
                MetadataExporter =
                {
                    PolicyVersion = PolicyVersion.Policy15
                }
            };
        }
コード例 #18
0
        internal static I CreateInstance <S, I>(IServiceBehavior serviceBehavior,
                                                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();

            return(factory.CreateChannel());
        }
        public void UseHttpBinding()
        {
            var    ahost     = new ServiceHost(typeof(AnnouncementService));
            var    aendpoint = new AnnouncementEndpoint(new CustomBinding(new HttpTransportBindingElement()), new EndpointAddress("http://localhost:4989"));
            var    ib        = new InspectionBehavior();
            object state     = new object();

            ib.RequestReceived += delegate
            {
                InspectionBehavior.State = state;
                return(null);
            };
            aendpoint.Behaviors.Add(ib);
            ahost.AddServiceEndpoint(aendpoint);
            ahost.Open();
            try
            {
                Assert.IsTrue(ib.DispatchBehaviorApplied, "#1");
                var b = new ServiceDiscoveryBehavior();
                b.AnnouncementEndpoints.Add(new AnnouncementEndpoint(new CustomBinding(new HttpTransportBindingElement()), new EndpointAddress("http://localhost:4989")));
                IServiceBehavior sb = b;
                var host            = new ServiceHost(typeof(TestService));
                var se = host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), new Uri("http://localhost:37564"));

                var bc = new BindingParameterCollection();
                sb.AddBindingParameters(host.Description, host, host.Description.Endpoints, bc);
                sb.Validate(host.Description, host);
                // ... should "validate" not "apply dispatch behavior" do "add host extension" job? I doubt that.
                var dse = host.Extensions.Find <DiscoveryServiceExtension> ();
                Assert.IsNotNull(dse, "#2");
                sb.ApplyDispatchBehavior(host.Description, host);

                // The IEndpointBehavior from ServiceDiscoveryBehavior, when ApplyDispatchBehavior() is invoked, publishes an endpoint.
                se.Behaviors [0].ApplyDispatchBehavior(se, new EndpointDispatcher(new EndpointAddress("http://localhost:37564"), "ITestService", "http://tempuri.org/"));

                host.Open();
                try
                {
                    Assert.AreEqual(state, InspectionBehavior.State, "#3");
                }
                finally
                {
                    host.Close();
                }
            }
            finally
            {
                ahost.Close();
            }
        }
コード例 #20
0
        /// <summary>
        /// Method ApplyMultiBehaviors
        /// </summary>
        /// <param name="serviceModelSectionGroup">ServiceModel section group.</param>
        /// <returns>true if succeeded; otherwise, false.</returns>
        private bool ApplyMultiBehaviors(ServiceModelSectionGroup serviceModelSectionGroup)
        {
            if (serviceModelSectionGroup == null)
            {
                return(false);
            }

            foreach (ServiceBehaviorElement element in serviceModelSectionGroup.Behaviors.ServiceBehaviors)
            {
                foreach (BehaviorExtensionElement behavior in element)
                {
                    BehaviorExtensionElement behaviorExtensionElement = behavior;

                    object extention = behaviorExtensionElement.GetType().InvokeMember(
                        "CreateBehavior",
                        BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
                        null,
                        behaviorExtensionElement,
                        null);

                    if (extention == null)
                    {
                        continue;
                    }

                    IServiceBehavior serviceBehavior = (IServiceBehavior)extention;

                    bool isBehaviorExist = false;

                    foreach (IServiceBehavior item in this.Description.Behaviors)
                    {
                        if (item.GetType().Name == serviceBehavior.GetType().Name)
                        {
                            isBehaviorExist = true;

                            break;
                        }
                    }

                    if (isBehaviorExist)
                    {
                        break;
                    }

                    this.Description.Behaviors.Add((IServiceBehavior)extention);
                }
            }

            return(true);
        }
コード例 #21
0
        static EndpointAddress GetAddress <S, I>(IServiceBehavior serviceBehavior, NetNamedPipeContextBinding binding) where I : class
            where S : class, I
        {
            if (m_Hosts.ContainsKey(typeof(S)))
            {
                Debug.Assert(m_Hosts[typeof(S)].ContainsKey(typeof(I)));

                return(m_Hosts[typeof(S)][typeof(I)].Item2);
            }
            else
            {
                ServiceHost <S> host;
                if (m_Singletons.ContainsKey(typeof(S)))
                {
                    S singleton = m_Singletons[typeof(S)] as S;
                    Debug.Assert(singleton != null);
                    host = new ServiceHost <S>(singleton);
                }
                else
                {
                    host = new ServiceHost <S>();
                }

                if (serviceBehavior != null)
                {
                    host.Description.Behaviors.Insert(0, serviceBehavior);
                }

                Type[] contracts = GetContracts <S>();
                Debug.Assert(contracts.Any());

                m_Hosts[typeof(S)] = new Dictionary <Type, Tuple <ServiceHost, EndpointAddress> >();

                foreach (Type contract in contracts)
                {
                    string address = BaseAddress + Guid.NewGuid() + "_" + contract;

                    m_Hosts[typeof(S)][contract] = new Tuple <ServiceHost, EndpointAddress>(host, new EndpointAddress(address));
                    host.AddServiceEndpoint(contract, binding, address);
                }

                if (m_Throttles.ContainsKey(typeof(S)))
                {
                    host.SetThrottle(m_Throttles[typeof(S)]);
                }
                host.Open();
            }
            return(GetAddress <S, I>());
        }
コード例 #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ExceptionShieldingAttribute"/> class.
        /// </summary>
        /// <param name="exceptionPolicyName">Name of the exception policy.</param>
        public ExceptionShieldingAttribute(string exceptionPolicyName)
        {
            this.exceptionPolicyName = exceptionPolicyName;
            
            //The ServiceHost applies behaviors in the following order:
            // Contract
            // Operation
            // Endpoint
            // Service

            ExceptionShieldingBehavior behavior = new ExceptionShieldingBehavior(exceptionPolicyName);
            this.contractBehavior = (IContractBehavior)behavior;
            this.serviceBehavior = (IServiceBehavior)behavior;
            this.errorHandler = new ExceptionShieldingErrorHandler(exceptionPolicyName);
        }
コード例 #23
0
        IChannelListener <IReplyChannel> CreateListener(ReplyHandler handler, RequestReceiver receiver)
        {
            CustomBinding rb = CreateBinding(handler, receiver);
            BindingParameterCollection bpl =
                new BindingParameterCollection();
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2("Test/Resources/test.pfx", "mono");
            IServiceBehavior sb = cred;

            sb.AddBindingParameters(null, null, null, bpl);
            IChannelListener <IReplyChannel> listener = rb.BuildChannelListener <IReplyChannel> (bpl);

            return(listener);
        }
コード例 #24
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public HttpChatServiceMode()
        {
            var binding = new WSDualHttpBinding();

            binding.Security.Mode  = WSDualHttpSecurityMode.None;
            ServiceEndpointBinding = binding;

            ServiceMetadataBinding = MetadataExchangeBindings.CreateMexHttpBinding();
            ServiceBehavior        = new ServiceMetadataBehavior {
                MetadataExporter =
                {
                    PolicyVersion = PolicyVersion.Policy15
                },
                HttpGetEnabled = true
            };
        }
コード例 #25
0
        public void OpenListenerNoPrivateKeyInServiceCertificate()
        {
            CustomBinding rb = CreateBinding();
            BindingParameterCollection bpl =
                new BindingParameterCollection();
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2("Test/Resources/test.cer");
            IServiceBehavior sb = cred;

            sb.AddBindingParameters(null, null, null, bpl);
            IChannelListener <IReplyChannel> listener = rb.BuildChannelListener <IReplyChannel> (bpl);

            listener.Open();
        }
コード例 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ExceptionShieldingAttribute"/> class.
        /// </summary>
        /// <param name="exceptionPolicyName">Name of the exception policy.</param>
        public ExceptionShieldingAttribute(string exceptionPolicyName)
        {
            this.exceptionPolicyName = exceptionPolicyName;

            //The ServiceHost applies behaviors in the following order:
            // Contract
            // Operation
            // Endpoint
            // Service

            ExceptionShieldingBehavior behavior = new ExceptionShieldingBehavior(exceptionPolicyName);

            this.contractBehavior = (IContractBehavior)behavior;
            this.serviceBehavior  = (IServiceBehavior)behavior;
            this.errorHandler     = new ExceptionShieldingErrorHandler(exceptionPolicyName);
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: huoxudong125/WCF-Demo
        static ServiceDescription CreateDescription(Type serviceType)
        {
            ServiceDescription description = new ServiceDescription();

            //添加以特性方式应用的服务行为
            description.ServiceType = serviceType;
            var behaviors = (from attribute in serviceType.GetCustomAttributes(false)
                             where attribute is IServiceBehavior
                             select(IServiceBehavior) attribute).ToArray();

            Array.ForEach <IServiceBehavior>(behaviors, behavior => description.Behaviors.Add(behavior));

            //确保服务具有一个ServiceBehaviorAttribute行为
            ServiceBehaviorAttribute serviceBehaviorAttribute = description.Behaviors.Find <ServiceBehaviorAttribute>();

            if (null == serviceBehaviorAttribute)
            {
                serviceBehaviorAttribute = new ServiceBehaviorAttribute();
                description.Behaviors.Add(serviceBehaviorAttribute);
            }

            //初始化Name、Namespace和ConfigurationName
            description.Name              = serviceBehaviorAttribute.Name ?? serviceType.Name;
            description.Namespace         = serviceBehaviorAttribute.Namespace ?? "http://tempuri.org/";
            description.ConfigurationName = serviceBehaviorAttribute.ConfigurationName ?? serviceType.Namespace + "." + serviceType.Name;

            //添加以配置方式应用的服务行为
            ServiceElement serviceElement = ConfigLoader.GetServiceElement(description.ConfigurationName);

            if (!string.IsNullOrEmpty(serviceElement.BehaviorConfiguration))
            {
                ServiceBehaviorElement behaviorElement = ConfigLoader.GetServiceBehaviorElement(serviceElement.BehaviorConfiguration);
                foreach (BehaviorExtensionElement extensionElement in behaviorElement)
                {
                    IServiceBehavior serviceBehavior = (IServiceBehavior)extensionElement.CreateBehavior();
                    description.Behaviors.Add(serviceBehavior);
                }
            }

            //添加配置的终结点
            foreach (ServiceEndpointElement endpointElement in serviceElement.Endpoints)
            {
                description.Endpoints.Add(CreateServiceEndpoint(serviceType, endpointElement));
            }
            return(description);
        }
コード例 #28
0
        public NinjectServiceHelper(IServiceBehavior serviceBehavior, string address, Binding binding)
        {
            // Create Ninject service host
            if (binding.GetType() == typeof(WebHttpBinding))
            {
                _serviceHost = new NinjectWebServiceHost(serviceBehavior, typeof(TServiceType));
            }
            else
            {
                _serviceHost = new NinjectServiceHost(serviceBehavior, typeof(TServiceType));
            }

            // Add endpoint
            _serviceHost.AddServiceEndpoint(typeof(TServiceContract), binding, address);

            // Add web behavior
            if (binding.GetType() == typeof(WebHttpBinding))
            {
                var webBehavior = new WebHttpBehavior
                {
                    AutomaticFormatSelectionEnabled = true,
                    HelpEnabled           = true,
                    FaultExceptionEnabled = true
                };
                _serviceHost.Description.Endpoints[0].Behaviors.Add(webBehavior);
            }

            // Add service metadata
            var metadataBehavior = new ServiceMetadataBehavior();

            if (binding.GetType() == typeof(BasicHttpBinding))
            {
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl     = new Uri(address);
            }
            _serviceHost.Description.Behaviors.Add(metadataBehavior);

            // Open service host
            _serviceHost.Open();

            // Init client
            var factory = new ChannelFactory <TServiceContract>(binding);

            _client = factory.CreateChannel(new EndpointAddress(address));
        }
コード例 #29
0
ファイル: InProcFactory.cs プロジェクト: eraj2587/NSB7
        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);
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: liuhonglei/WCFStudy
        private static ServiceDescription   CreateDescription(Type serviceType)
        {
            ServiceDescription description = new ServiceDescription();

            description.ServiceType = serviceType;
            var behaivors = (from attribute in serviceType.GetCustomAttributes(false)
                             where attribute is IServiceBehavior
                             select(IServiceBehavior) attribute).ToArray();

            Array.ForEach <IServiceBehavior>(behaivors, behaivor => description.Behaviors.Add(behaivor));

            ServiceBehaviorAttribute serviceBehaviorAttribute =
                description.Behaviors.Find <ServiceBehaviorAttribute>();

            if (null == serviceBehaviorAttribute)
            {
                serviceBehaviorAttribute = new ServiceBehaviorAttribute();
                description.Behaviors.Add(serviceBehaviorAttribute);
            }
            description.Name              = serviceBehaviorAttribute.Name ?? serviceType.Name;
            description.Namespace         = serviceBehaviorAttribute.Namespace ?? "http://www.tempri.org";
            description.ConfigurationName = serviceBehaviorAttribute.ConfigurationName ?? description.Namespace + "." + description.Name;

            //添加服务行为
            ServiceElement serviceElement = ConfigLoader.GetServiceElement(description.ConfigurationName);

            if (!string.IsNullOrEmpty(serviceElement.BehaviorConfiguration))
            {
                ServiceBehaviorElement behaviorElement =
                    ConfigLoader.GetServiceBehaviorElement(serviceElement.BehaviorConfiguration);
                foreach (BehaviorExtensionElement item in behaviorElement)
                {
                    IServiceBehavior serviceBehavior = item.CreateBehavior() as IServiceBehavior;
                    description.Behaviors.Add(serviceBehavior);
                }
            }

            foreach (ServiceEndpointElement item in serviceElement.Endpoints)
            {
                description.Endpoints.Add(CreateServiceEndpoint(serviceType, item));
            }

            return(description);
        }
コード例 #31
0
        static void Main(string[] args)
        {
            Dataflow dataflow      = new Dataflow();
            var      notifyService = new StockQuoteService(dataflow);
            //=======================================================================================================
            // Call this before you initialize a new BackgroundJobServer()
            var container = new Unity.UnityContainer();

            GlobalConfiguration.Configuration.UseActivator(new UnityJobActivator(container));
            container.RegisterInstance <IDataflow>(dataflow);
            container.RegisterInstance <INotifyService>(notifyService);
            //=======================================================================================================
            JobStorage storage = new MemoryStorage(new MemoryStorageOptions());

            LogProvider.SetCurrentLogProvider(new ColouredConsoleLogProvider());
            var serverOptions = new BackgroundJobServerOptions()
            {
                ShutdownTimeout = TimeSpan.FromSeconds(5)
            };
            var server = new BackgroundJobServer(serverOptions, storage);

            JobStorage.Current = storage;

            Log("Hangfire Server started. Press any key to exit...", LogLevel.Fatal);
            //=======================================================================================================
            //ServiceHost host = new ServiceHost(typeof(StockQuoteService), new Uri("http://localhost:12345/StockQuoteService.svc"));
            //host.Open();
            var host = new ServiceHost(typeof(StockQuoteService), new Uri("http://localhost:12345/StockQuoteService.svc"));
            //object instanceService = Activator.CreateInstance(typeof(StockQuoteService), dataflow);
            //IServiceBehavior instanceBehavior = Activator.CreateInstance(typeof(StockQuoteServiceBehavior), instanceService) as IServiceBehavior;
            object           instanceService  = Activator.CreateInstance(typeof(StockQuoteService), dataflow);
            IServiceBehavior instanceBehavior = Activator.CreateInstance(typeof(StockQuoteServiceBehavior), notifyService) as IServiceBehavior;

            host.Description.Behaviors.Add(instanceBehavior);
            host.Open();
            SesionSocketRunConsole.Start();
            //=======================================================================================================

            BackgroundJob.Enqueue <JobTest>(x => x.Execute("Hello, world!"));
            //=======================================================================================================
            Console.WriteLine("Enter to exit ...");
            Console.ReadLine();
        }
コード例 #32
0
ファイル: ServiceHost.cs プロジェクト: eraj2587/NSB7
        /// <summary>
        /// Can only call before openning the host
        /// </summary>
        public void AddErrorHandler(IErrorHandler errorHandler)
        {
            if (State == CommunicationState.Opened)
            {
                throw new InvalidOperationException("Host is already opened");
            }
            Debug.Assert(errorHandler != null);
            IServiceBehavior errorHandlerBehavior = null;

            if (errorHandler is IServiceBehavior)
            {
                errorHandlerBehavior = errorHandler as IServiceBehavior;
            }
            else
            {
                errorHandlerBehavior = new ErrorHandlerBehavior(errorHandler);
            }
            m_ErrorHandlers.Add(errorHandlerBehavior);
        }
コード例 #33
0
        static void cacheStart()
        {
            int port = (int)getOptions("port");

            string[] rounters = typeof(_API_CONST).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                                .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType.Name == "String")
                                .Select(x => x.GetRawConstantValue() as string)
                                .ToArray();
            for (int i = 0; i < rounters.Length; i++)
            {
                string serviceName = getServiceName(rounters[i]);

                Type typeService = Type.GetType("MessageBroker." + serviceName + "Service, MessageBroker");
                if (typeService == null)
                {
                    continue;
                }

                Type typeBehavior = Type.GetType("MessageBroker." + serviceName + "Behavior, MessageBroker");
                if (typeBehavior == null)
                {
                    continue;
                }

                object           instanceService  = Activator.CreateInstance(typeService, Dataflow, new oCacheModel());
                IServiceBehavior instanceBehavior = Activator.CreateInstance(typeBehavior, instanceService) as IServiceBehavior;

                ServiceHost host = new ServiceHost(typeService, new Uri("http://localhost:" + port + "/" + rounters[i] + "/"));
                host.AddServiceEndpoint(typeof(ICacheService), new BasicHttpBinding(), "");
                host.Description.Behaviors.Add(instanceBehavior);
                host.Open();
            }

            //ServiceHost userService = new ServiceHost(typeof(UserLoginService), new Uri("http://localhost:" + port + "/" + _API_CONST.USER_LOGIN + "/"));
            //userService.AddServiceEndpoint(typeof(ICacheService), new BasicHttpBinding(), "");
            //userService.Description.Behaviors.Add(new UserLoginBehavior(new UserLoginService(Dataflow, new oCacheModel())));
            //userService.Open();

            //ServiceHost taohopdongService = new ServiceHost(typeof(PawnInfoService), new Uri("http://localhost:" + port + "/" + _API_CONST.PAWN_INFO + "/"));
            //taohopdongService.AddServiceEndpoint(typeof(ICacheService), new BasicHttpBinding(), "");
            //taohopdongService.Description.Behaviors.Add(new PawnInfoBehavior(new PawnInfoService(Dataflow, new oCacheModel())));
            //taohopdongService.Open();
        }
コード例 #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NinjectServiceHost"/> class.
 /// </summary>
 /// <param name="serviceBehavior">The behavior factory.</param>
 /// <param name="singletonInstance">The singleton instance.</param>
 public NinjectServiceHost(IServiceBehavior serviceBehavior, object singletonInstance)
     : base(singletonInstance)
 {
     this.serviceBehavior = serviceBehavior;
 }
コード例 #35
0
        void FillBehaviorInfo(IServiceBehavior behavior, IWmiInstance existingInstance, out IWmiInstance instance)
        {
            Fx.Assert(null != existingInstance, "");
            Fx.Assert(null != behavior, "");
            instance = null;
            if (behavior is AspNetCompatibilityRequirementsAttribute)
            {
                instance = existingInstance.NewInstance("AspNetCompatibilityRequirementsAttribute");
                AspNetCompatibilityRequirementsAttribute specificBehavior = (AspNetCompatibilityRequirementsAttribute)behavior;
                instance.SetProperty(AdministrationStrings.RequirementsMode, specificBehavior.RequirementsMode.ToString());
            }
            else if (behavior is ServiceCredentials)
            {
                instance = existingInstance.NewInstance("ServiceCredentials");
                ServiceCredentials specificBehavior = (ServiceCredentials)behavior;
                if (specificBehavior.ClientCertificate != null && specificBehavior.ClientCertificate.Certificate != null)
                {
                    string result = string.Empty;
                    result += String.Format(CultureInfo.InvariantCulture, "Certificate: {0}\n", specificBehavior.ClientCertificate.Certificate);
                    instance.SetProperty(AdministrationStrings.ClientCertificate, result);
                }
                if (specificBehavior.IssuedTokenAuthentication != null && specificBehavior.IssuedTokenAuthentication.KnownCertificates != null)
                {
                    string result = string.Empty;
                    result += String.Format(CultureInfo.InvariantCulture, "AllowUntrustedRsaIssuers: {0}\n", specificBehavior.IssuedTokenAuthentication.AllowUntrustedRsaIssuers);
                    result += String.Format(CultureInfo.InvariantCulture, "CertificateValidationMode: {0}\n", specificBehavior.IssuedTokenAuthentication.CertificateValidationMode);
                    result += String.Format(CultureInfo.InvariantCulture, "RevocationMode: {0}\n", specificBehavior.IssuedTokenAuthentication.RevocationMode);
                    result += String.Format(CultureInfo.InvariantCulture, "TrustedStoreLocation: {0}\n", specificBehavior.IssuedTokenAuthentication.TrustedStoreLocation);
                    foreach (X509Certificate2 certificate in specificBehavior.IssuedTokenAuthentication.KnownCertificates)
                    {
                        if (certificate != null)
                        {
                            result += String.Format(CultureInfo.InvariantCulture, "Known certificate: {0}\n", certificate.FriendlyName);
                        }
                    }
                    result += String.Format(CultureInfo.InvariantCulture, "AudienceUriMode: {0}\n", specificBehavior.IssuedTokenAuthentication.AudienceUriMode);
                    if (specificBehavior.IssuedTokenAuthentication.AllowedAudienceUris != null)
                    {
                        foreach (string str in specificBehavior.IssuedTokenAuthentication.AllowedAudienceUris)
                        {
                            if (str != null)
                            {
                                result += String.Format(CultureInfo.InvariantCulture, "Allowed Uri: {0}\n", str);
                            }
                        }
                    }

                    instance.SetProperty(AdministrationStrings.IssuedTokenAuthentication, result);
                }
                if (specificBehavior.Peer != null && specificBehavior.Peer.Certificate != null)
                {
                    string result = string.Empty;
                    result += String.Format(CultureInfo.InvariantCulture, "Certificate: {0}\n", specificBehavior.Peer.Certificate.ToString(true));
                    instance.SetProperty(AdministrationStrings.Peer, result);
                }
                if (specificBehavior.SecureConversationAuthentication != null && specificBehavior.SecureConversationAuthentication.SecurityContextClaimTypes != null)
                {
                    string result = string.Empty;
                    foreach (Type claimType in specificBehavior.SecureConversationAuthentication.SecurityContextClaimTypes)
                    {
                        if (claimType != null)
                        {
                            result += String.Format(CultureInfo.InvariantCulture, "ClaimType: {0}\n", claimType);
                        }
                    }
                    instance.SetProperty(AdministrationStrings.SecureConversationAuthentication, result);
                }
                if (specificBehavior.ServiceCertificate != null && specificBehavior.ServiceCertificate.Certificate != null)
                {
                    instance.SetProperty(AdministrationStrings.ServiceCertificate, specificBehavior.ServiceCertificate.Certificate.ToString());
                }
                if (specificBehavior.UserNameAuthentication != null)
                {
                    instance.SetProperty(AdministrationStrings.UserNameAuthentication, String.Format(CultureInfo.InvariantCulture, "{0}: {1}", AdministrationStrings.ValidationMode, specificBehavior.UserNameAuthentication.UserNamePasswordValidationMode.ToString()));
                }
                if (specificBehavior.WindowsAuthentication != null)
                {
                    instance.SetProperty(AdministrationStrings.WindowsAuthentication, String.Format(CultureInfo.InvariantCulture, "{0}: {1}", AdministrationStrings.AllowAnonymous, specificBehavior.WindowsAuthentication.AllowAnonymousLogons.ToString()));
                }
            }
            else if (behavior is ServiceAuthorizationBehavior)
            {
                instance = existingInstance.NewInstance("ServiceAuthorizationBehavior");
                ServiceAuthorizationBehavior specificBehavior = (ServiceAuthorizationBehavior)behavior;
                instance.SetProperty(AdministrationStrings.ImpersonateCallerForAllOperations, specificBehavior.ImpersonateCallerForAllOperations);
                instance.SetProperty(AdministrationStrings.ImpersonateOnSerializingReply, specificBehavior.ImpersonateOnSerializingReply);
                if (specificBehavior.RoleProvider != null)
                {
                    instance.SetProperty(AdministrationStrings.RoleProvider, specificBehavior.RoleProvider.ToString());
                }
                if (specificBehavior.ServiceAuthorizationManager != null)
                {
                    instance.SetProperty(AdministrationStrings.ServiceAuthorizationManager, specificBehavior.ServiceAuthorizationManager.ToString());
                }
                instance.SetProperty(AdministrationStrings.PrincipalPermissionMode, specificBehavior.PrincipalPermissionMode.ToString());
            }
            else if (behavior is ServiceSecurityAuditBehavior)
            {
                instance = existingInstance.NewInstance("ServiceSecurityAuditBehavior");
                ServiceSecurityAuditBehavior specificBehavior = (ServiceSecurityAuditBehavior)behavior;
                instance.SetProperty(AdministrationStrings.AuditLogLocation, specificBehavior.AuditLogLocation.ToString());
                instance.SetProperty(AdministrationStrings.SuppressAuditFailure, specificBehavior.SuppressAuditFailure);
                instance.SetProperty(AdministrationStrings.ServiceAuthorizationAuditLevel, specificBehavior.ServiceAuthorizationAuditLevel.ToString());
                instance.SetProperty(AdministrationStrings.MessageAuthenticationAuditLevel, specificBehavior.MessageAuthenticationAuditLevel.ToString());
            }
            else if (behavior is ServiceBehaviorAttribute)
            {
                instance = existingInstance.NewInstance("ServiceBehaviorAttribute");
                ServiceBehaviorAttribute serviceBehavior = (ServiceBehaviorAttribute)behavior;
                instance.SetProperty(AdministrationStrings.AddressFilterMode, serviceBehavior.AddressFilterMode.ToString());
                instance.SetProperty(AdministrationStrings.AutomaticSessionShutdown, serviceBehavior.AutomaticSessionShutdown);
                instance.SetProperty(AdministrationStrings.ConcurrencyMode, serviceBehavior.ConcurrencyMode.ToString());
                instance.SetProperty(AdministrationStrings.ConfigurationName, serviceBehavior.ConfigurationName);
                instance.SetProperty(AdministrationStrings.EnsureOrderedDispatch, serviceBehavior.EnsureOrderedDispatch);
                instance.SetProperty(AdministrationStrings.IgnoreExtensionDataObject, serviceBehavior.IgnoreExtensionDataObject);
                instance.SetProperty(AdministrationStrings.IncludeExceptionDetailInFaults, serviceBehavior.IncludeExceptionDetailInFaults);
                instance.SetProperty(AdministrationStrings.InstanceContextMode, serviceBehavior.InstanceContextMode.ToString());
                instance.SetProperty(AdministrationStrings.MaxItemsInObjectGraph, serviceBehavior.MaxItemsInObjectGraph);
                instance.SetProperty(AdministrationStrings.Name, serviceBehavior.Name);
                instance.SetProperty(AdministrationStrings.Namespace, serviceBehavior.Namespace);
                instance.SetProperty(AdministrationStrings.ReleaseServiceInstanceOnTransactionComplete, serviceBehavior.ReleaseServiceInstanceOnTransactionComplete);
                instance.SetProperty(AdministrationStrings.TransactionAutoCompleteOnSessionClose, serviceBehavior.TransactionAutoCompleteOnSessionClose);
                instance.SetProperty(AdministrationStrings.TransactionIsolationLevel, serviceBehavior.TransactionIsolationLevel.ToString());
                if (serviceBehavior.TransactionTimeoutSet)
                {
                    instance.SetProperty(AdministrationStrings.TransactionTimeout, serviceBehavior.TransactionTimeoutTimespan);
                }
                instance.SetProperty(AdministrationStrings.UseSynchronizationContext, serviceBehavior.UseSynchronizationContext);
                instance.SetProperty(AdministrationStrings.ValidateMustUnderstand, serviceBehavior.ValidateMustUnderstand);
            }
            else if (behavior is ServiceDebugBehavior)
            {
                instance = existingInstance.NewInstance("ServiceDebugBehavior");
                ServiceDebugBehavior specificBehavior = (ServiceDebugBehavior)behavior;
                if (null != specificBehavior.HttpHelpPageUrl)
                {
                    instance.SetProperty(AdministrationStrings.HttpHelpPageUrl, specificBehavior.HttpHelpPageUrl.ToString());
                }
                instance.SetProperty(AdministrationStrings.HttpHelpPageEnabled, specificBehavior.HttpHelpPageEnabled);
                if (null != specificBehavior.HttpsHelpPageUrl)
                {
                    instance.SetProperty(AdministrationStrings.HttpsHelpPageUrl, specificBehavior.HttpsHelpPageUrl.ToString());
                }
                instance.SetProperty(AdministrationStrings.HttpsHelpPageEnabled, specificBehavior.HttpsHelpPageEnabled);
                instance.SetProperty(AdministrationStrings.IncludeExceptionDetailInFaults, specificBehavior.IncludeExceptionDetailInFaults);
            }
            else if (behavior is ServiceMetadataBehavior)
            {
                instance = existingInstance.NewInstance("ServiceMetadataBehavior");
                ServiceMetadataBehavior metadataBehavior = (ServiceMetadataBehavior)behavior;
                if (null != metadataBehavior.ExternalMetadataLocation)
                {
                    instance.SetProperty(AdministrationStrings.ExternalMetadataLocation, metadataBehavior.ExternalMetadataLocation.ToString());
                }
                instance.SetProperty(AdministrationStrings.HttpGetEnabled, metadataBehavior.HttpGetEnabled);
                if (null != metadataBehavior.HttpGetUrl)
                {
                    instance.SetProperty(AdministrationStrings.HttpGetUrl, metadataBehavior.HttpGetUrl.ToString());
                }
                instance.SetProperty(AdministrationStrings.HttpsGetEnabled, metadataBehavior.HttpsGetEnabled);
                if (null != metadataBehavior.HttpsGetUrl)
                {
                    instance.SetProperty(AdministrationStrings.HttpsGetUrl, metadataBehavior.HttpsGetUrl.ToString());
                }
                FillMetadataExporterInfo(instance, metadataBehavior.MetadataExporter);
            }
            else if (behavior is ServiceThrottlingBehavior)
            {
                instance = existingInstance.NewInstance("ServiceThrottlingBehavior");
                ServiceThrottlingBehavior throttlingBehavior = (ServiceThrottlingBehavior)behavior;
                instance.SetProperty(AdministrationStrings.MaxConcurrentCalls, throttlingBehavior.MaxConcurrentCalls);
                instance.SetProperty(AdministrationStrings.MaxConcurrentSessions, throttlingBehavior.MaxConcurrentSessions);
                instance.SetProperty(AdministrationStrings.MaxConcurrentInstances, throttlingBehavior.MaxConcurrentInstances);
            }
            else if (behavior is ServiceTimeoutsBehavior)
            {
                instance = existingInstance.NewInstance("ServiceTimeoutsBehavior");
                ServiceTimeoutsBehavior specificBehavior = (ServiceTimeoutsBehavior)behavior;
                instance.SetProperty(AdministrationStrings.TransactionTimeout, specificBehavior.TransactionTimeout);
            }
            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);
            }
        }
コード例 #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NinjectServiceHost"/> class.
 /// </summary>
 /// <param name="serviceBehavior">The behavior factory.</param>
 public NinjectServiceHost(IServiceBehavior serviceBehavior)
 {
     this.serviceBehavior = serviceBehavior;
 }
コード例 #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NinjectServiceHost"/> class.
 /// </summary>
 /// <param name="serviceBehavior">The behavior factory.</param>
 /// <param name="serviceType">Type of the service.</param>
 public NinjectServiceHost(IServiceBehavior serviceBehavior, TypeCode serviceType)
     : base(serviceType)
 {
     this.serviceBehavior = serviceBehavior;
 }
コード例 #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NinjectDataServiceHost"/> class.
 /// </summary>
 /// <param name="serviceBehavior">The behavior factory.</param>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="baseAddresses">The base addresses.</param>
 public NinjectDataServiceHost(IServiceBehavior serviceBehavior, Type serviceType, params Uri[] baseAddresses)
     : base(serviceType, baseAddresses)
 {
     this.serviceBehavior = serviceBehavior;
 }
コード例 #39
0
 public CustomConfigurationSectionBehavior(IServiceBehavior instance)
 {
     this._instance = instance;
 }
コード例 #40
0
		public ServiceHostConfigurator(Type implementedContract, IServiceBehavior[] behaviors, Binding[] bindings)
		{
			ImplementedContract = implementedContract;
			this.behaviors = behaviors;
			this.bindings = bindings;
		}
 private void FillBehaviorInfo(IServiceBehavior behavior, IWmiInstance existingInstance, out IWmiInstance instance)
 {
     instance = null;
     if (behavior is AspNetCompatibilityRequirementsAttribute)
     {
         instance = existingInstance.NewInstance("AspNetCompatibilityRequirementsAttribute");
         AspNetCompatibilityRequirementsAttribute attribute = (AspNetCompatibilityRequirementsAttribute) behavior;
         instance.SetProperty("RequirementsMode", attribute.RequirementsMode.ToString());
     }
     else if (behavior is ServiceCredentials)
     {
         instance = existingInstance.NewInstance("ServiceCredentials");
         ServiceCredentials credentials = (ServiceCredentials) behavior;
         if ((credentials.ClientCertificate != null) && (credentials.ClientCertificate.Certificate != null))
         {
             string str = string.Empty + string.Format(CultureInfo.InvariantCulture, "Certificate: {0}\n", new object[] { credentials.ClientCertificate.Certificate });
             instance.SetProperty("ClientCertificate", str);
         }
         if ((credentials.IssuedTokenAuthentication != null) && (credentials.IssuedTokenAuthentication.KnownCertificates != null))
         {
             string str2 = (string.Empty + string.Format(CultureInfo.InvariantCulture, "AllowUntrustedRsaIssuers: {0}\n", new object[] { credentials.IssuedTokenAuthentication.AllowUntrustedRsaIssuers }) + string.Format(CultureInfo.InvariantCulture, "CertificateValidationMode: {0}\n", new object[] { credentials.IssuedTokenAuthentication.CertificateValidationMode })) + string.Format(CultureInfo.InvariantCulture, "RevocationMode: {0}\n", new object[] { credentials.IssuedTokenAuthentication.RevocationMode }) + string.Format(CultureInfo.InvariantCulture, "TrustedStoreLocation: {0}\n", new object[] { credentials.IssuedTokenAuthentication.TrustedStoreLocation });
             foreach (X509Certificate2 certificate in credentials.IssuedTokenAuthentication.KnownCertificates)
             {
                 if (certificate != null)
                 {
                     str2 = str2 + string.Format(CultureInfo.InvariantCulture, "Known certificate: {0}\n", new object[] { certificate.FriendlyName });
                 }
             }
             str2 = str2 + string.Format(CultureInfo.InvariantCulture, "AudienceUriMode: {0}\n", new object[] { credentials.IssuedTokenAuthentication.AudienceUriMode });
             if (credentials.IssuedTokenAuthentication.AllowedAudienceUris != null)
             {
                 foreach (string str3 in credentials.IssuedTokenAuthentication.AllowedAudienceUris)
                 {
                     if (str3 != null)
                     {
                         str2 = str2 + string.Format(CultureInfo.InvariantCulture, "Allowed Uri: {0}\n", new object[] { str3 });
                     }
                 }
             }
             instance.SetProperty("IssuedTokenAuthentication", str2);
         }
         if ((credentials.Peer != null) && (credentials.Peer.Certificate != null))
         {
             string str4 = string.Empty + string.Format(CultureInfo.InvariantCulture, "Certificate: {0}\n", new object[] { credentials.Peer.Certificate.ToString(true) });
             instance.SetProperty("Peer", str4);
         }
         if ((credentials.SecureConversationAuthentication != null) && (credentials.SecureConversationAuthentication.SecurityContextClaimTypes != null))
         {
             string str5 = string.Empty;
             foreach (System.Type type in credentials.SecureConversationAuthentication.SecurityContextClaimTypes)
             {
                 if (type != null)
                 {
                     str5 = str5 + string.Format(CultureInfo.InvariantCulture, "ClaimType: {0}\n", new object[] { type });
                 }
             }
             instance.SetProperty("SecureConversationAuthentication", str5);
         }
         if ((credentials.ServiceCertificate != null) && (credentials.ServiceCertificate.Certificate != null))
         {
             instance.SetProperty("ServiceCertificate", credentials.ServiceCertificate.Certificate.ToString());
         }
         if (credentials.UserNameAuthentication != null)
         {
             instance.SetProperty("UserNameAuthentication", string.Format(CultureInfo.InvariantCulture, "{0}: {1}", new object[] { "ValidationMode", credentials.UserNameAuthentication.UserNamePasswordValidationMode.ToString() }));
         }
         if (credentials.WindowsAuthentication != null)
         {
             instance.SetProperty("WindowsAuthentication", string.Format(CultureInfo.InvariantCulture, "{0}: {1}", new object[] { "AllowAnonymous", credentials.WindowsAuthentication.AllowAnonymousLogons.ToString() }));
         }
     }
     else if (behavior is ServiceAuthorizationBehavior)
     {
         instance = existingInstance.NewInstance("ServiceAuthorizationBehavior");
         ServiceAuthorizationBehavior behavior2 = (ServiceAuthorizationBehavior) behavior;
         instance.SetProperty("ImpersonateCallerForAllOperations", behavior2.ImpersonateCallerForAllOperations);
         if (behavior2.RoleProvider != null)
         {
             instance.SetProperty("RoleProvider", behavior2.RoleProvider.ToString());
         }
         if (behavior2.ServiceAuthorizationManager != null)
         {
             instance.SetProperty("ServiceAuthorizationManager", behavior2.ServiceAuthorizationManager.ToString());
         }
         instance.SetProperty("PrincipalPermissionMode", behavior2.PrincipalPermissionMode.ToString());
     }
     else if (behavior is ServiceSecurityAuditBehavior)
     {
         instance = existingInstance.NewInstance("ServiceSecurityAuditBehavior");
         ServiceSecurityAuditBehavior behavior3 = (ServiceSecurityAuditBehavior) behavior;
         instance.SetProperty("AuditLogLocation", behavior3.AuditLogLocation.ToString());
         instance.SetProperty("SuppressAuditFailure", behavior3.SuppressAuditFailure);
         instance.SetProperty("ServiceAuthorizationAuditLevel", behavior3.ServiceAuthorizationAuditLevel.ToString());
         instance.SetProperty("MessageAuthenticationAuditLevel", behavior3.MessageAuthenticationAuditLevel.ToString());
     }
     else if (behavior is ServiceBehaviorAttribute)
     {
         instance = existingInstance.NewInstance("ServiceBehaviorAttribute");
         ServiceBehaviorAttribute attribute2 = (ServiceBehaviorAttribute) behavior;
         instance.SetProperty("AddressFilterMode", attribute2.AddressFilterMode.ToString());
         instance.SetProperty("AutomaticSessionShutdown", attribute2.AutomaticSessionShutdown);
         instance.SetProperty("ConcurrencyMode", attribute2.ConcurrencyMode.ToString());
         instance.SetProperty("ConfigurationName", attribute2.ConfigurationName);
         instance.SetProperty("IgnoreExtensionDataObject", attribute2.IgnoreExtensionDataObject);
         instance.SetProperty("IncludeExceptionDetailInFaults", attribute2.IncludeExceptionDetailInFaults);
         instance.SetProperty("InstanceContextMode", attribute2.InstanceContextMode.ToString());
         instance.SetProperty("MaxItemsInObjectGraph", attribute2.MaxItemsInObjectGraph);
         instance.SetProperty("Name", attribute2.Name);
         instance.SetProperty("Namespace", attribute2.Namespace);
         instance.SetProperty("ReleaseServiceInstanceOnTransactionComplete", attribute2.ReleaseServiceInstanceOnTransactionComplete);
         instance.SetProperty("TransactionAutoCompleteOnSessionClose", attribute2.TransactionAutoCompleteOnSessionClose);
         instance.SetProperty("TransactionIsolationLevel", attribute2.TransactionIsolationLevel.ToString());
         if (attribute2.TransactionTimeoutSet)
         {
             instance.SetProperty("TransactionTimeout", attribute2.TransactionTimeoutTimespan);
         }
         instance.SetProperty("UseSynchronizationContext", attribute2.UseSynchronizationContext);
         instance.SetProperty("ValidateMustUnderstand", attribute2.ValidateMustUnderstand);
     }
     else if (behavior is ServiceDebugBehavior)
     {
         instance = existingInstance.NewInstance("ServiceDebugBehavior");
         ServiceDebugBehavior behavior4 = (ServiceDebugBehavior) behavior;
         if (null != behavior4.HttpHelpPageUrl)
         {
             instance.SetProperty("HttpHelpPageUrl", behavior4.HttpHelpPageUrl.ToString());
         }
         instance.SetProperty("HttpHelpPageEnabled", behavior4.HttpHelpPageEnabled);
         if (null != behavior4.HttpsHelpPageUrl)
         {
             instance.SetProperty("HttpsHelpPageUrl", behavior4.HttpsHelpPageUrl.ToString());
         }
         instance.SetProperty("HttpsHelpPageEnabled", behavior4.HttpsHelpPageEnabled);
         instance.SetProperty("IncludeExceptionDetailInFaults", behavior4.IncludeExceptionDetailInFaults);
     }
     else if (behavior is ServiceMetadataBehavior)
     {
         instance = existingInstance.NewInstance("ServiceMetadataBehavior");
         ServiceMetadataBehavior behavior5 = (ServiceMetadataBehavior) behavior;
         if (null != behavior5.ExternalMetadataLocation)
         {
             instance.SetProperty("ExternalMetadataLocation", behavior5.ExternalMetadataLocation.ToString());
         }
         instance.SetProperty("HttpGetEnabled", behavior5.HttpGetEnabled);
         if (null != behavior5.HttpGetUrl)
         {
             instance.SetProperty("HttpGetUrl", behavior5.HttpGetUrl.ToString());
         }
         instance.SetProperty("HttpsGetEnabled", behavior5.HttpsGetEnabled);
         if (null != behavior5.HttpsGetUrl)
         {
             instance.SetProperty("HttpsGetUrl", behavior5.HttpsGetUrl.ToString());
         }
         this.FillMetadataExporterInfo(instance, behavior5.MetadataExporter);
     }
     else if (behavior is ServiceThrottlingBehavior)
     {
         instance = existingInstance.NewInstance("ServiceThrottlingBehavior");
         ServiceThrottlingBehavior behavior6 = (ServiceThrottlingBehavior) behavior;
         instance.SetProperty("MaxConcurrentCalls", behavior6.MaxConcurrentCalls);
         instance.SetProperty("MaxConcurrentSessions", behavior6.MaxConcurrentSessions);
         instance.SetProperty("MaxConcurrentInstances", behavior6.MaxConcurrentInstances);
     }
     else if (behavior is ServiceTimeoutsBehavior)
     {
         instance = existingInstance.NewInstance("ServiceTimeoutsBehavior");
         ServiceTimeoutsBehavior behavior7 = (ServiceTimeoutsBehavior) behavior;
         instance.SetProperty("TransactionTimeout", behavior7.TransactionTimeout);
     }
     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);
     }
 }
 public virtual void ProcessBehaviorForMetadataExtension(IServiceBehavior serviceBehavior, BindingParameterCollection bindingParameters)
 {
 }
 public override void ProcessBehaviorForMetadataExtension(IServiceBehavior serviceBehavior, BindingParameterCollection bindingParameters)
 {
     if (serviceBehavior is HostedBindingBehavior)
     {
         bindingParameters.Add(((HostedBindingBehavior) serviceBehavior).VirtualPathExtension);
         bindingParameters.Add(new HostedMetadataBindingParameter());
     }
 }
コード例 #44
0
 public ServiceConfigurerBase(IServiceBehavior[] serviceBehaviors)
 {
     _serviceBehaviors = new List<IServiceBehavior>(serviceBehaviors ?? new IServiceBehavior[0]);
 }
コード例 #45
0
		public static void AddBehavior(this ServiceHost serviceHost, IServiceBehavior behavior)
		{
			serviceHost.Description.Behaviors.Remove(behavior.GetType());
			serviceHost.Description.Behaviors.Add(behavior);
		}
コード例 #46
0
ファイル: UnityServiceHost.cs プロジェクト: LTornos/Protozoo
 // private IServiceBehavior Behavior { get; set; }
 public UnityServiceHost(IServiceBehavior behavior, Type serviceType, params Uri[] baseAddresses)
     : base(serviceType, baseAddresses)
 {
     //  Behavior = behavior;
     this.Description.Behaviors.Add(behavior);
 }