Inheritance: System.Attribute, IServiceBehavior
Ejemplo n.º 1
0
        protected override ServiceDescription CreateDescription(
            out IDictionary <string, ContractDescription> implementedContracts)
        {
            contracts            = new Dictionary <string, ContractDescription> ();
            implementedContracts = contracts;
            ServiceDescription sd;
            IEnumerable <ContractDescription> contractDescriptions = GetServiceContractDescriptions();

            foreach (ContractDescription cd in contractDescriptions)
            {
                contracts.Add(cd.ContractType.FullName, cd);
            }

            if (SingletonInstance != null)
            {
                sd = ServiceDescription.GetService(instance);
            }
            else
            {
                sd = ServiceDescription.GetService(service_type);
            }

            ServiceBehaviorAttribute sba = PopulateAttribute <ServiceBehaviorAttribute> ();

            if (SingletonInstance != null)
            {
                sba.SetWellKnownSingleton(SingletonInstance);
            }
            sd.Behaviors.Add(sba);

            return(sd);
        }
 private ServiceBehaviorAttribute EnsureBehaviorAttribute(System.ServiceModel.Description.ServiceDescription service)
 {
     if (service.Behaviors.Contains(typeof(ServiceBehaviorAttribute)))
     {
         return (ServiceBehaviorAttribute) service.Behaviors[typeof(ServiceBehaviorAttribute)];
     }
     ServiceBehaviorAttribute item = new ServiceBehaviorAttribute();
     service.Behaviors.Insert(0, item);
     return item;
 }
Ejemplo n.º 3
0
        protected override void OnOpening()
        {
            var serviceBehavior = Description.Behaviors.Find<ServiceBehaviorAttribute>();
            if (null == serviceBehavior)
            {
                serviceBehavior = new ServiceBehaviorAttribute();
                Description.Behaviors.Add(serviceBehavior);
            }
            serviceBehavior.InstanceContextMode = InstanceContextMode.PerCall;

            base.OnOpening();
        }
 ServiceBehaviorAttribute EnsureBehaviorAttribute(ServiceDescription service)
 {
     ServiceBehaviorAttribute serviceBehavior;
     if (service.Behaviors.Contains(typeof(ServiceBehaviorAttribute)))
     {
         serviceBehavior = (ServiceBehaviorAttribute)service.Behaviors[typeof(ServiceBehaviorAttribute)];
     }
     else
     {
         serviceBehavior = new ServiceBehaviorAttribute();
         service.Behaviors.Insert(0, serviceBehavior);
     }
     return serviceBehavior;
 }
Ejemplo n.º 5
0
        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;
        }
Ejemplo n.º 6
0
        /*
         * public static WebHttpBinding getWebHttpBinding(string bindingName)
         * {
         *  System.ServiceModel.WebHttpBinding binding = new System.ServiceModel.WebHttpBinding();
         *
         *  System.ServiceModel.ServiceBehaviorAttribute behavior = new System.ServiceModel.ServiceBehaviorAttribute();
         *
         *  behavior.MaxItemsInObjectGraph = 2147483647;
         *
         *  binding.Name = bindingName;
         *
         *  //binding.CloseTimeout = new TimeSpan(0, 1, 0);
         *  binding.CloseTimeout = new TimeSpan(0, 10, 0);
         *  //binding.OpenTimeout = new TimeSpan(0, 1, 0);
         *  binding.OpenTimeout = new TimeSpan(0, 10, 0);
         *  binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
         *  //binding.SendTimeout = new TimeSpan(0, 1, 0);
         *  binding.SendTimeout = new TimeSpan(0, 10, 0);
         *  binding.AllowCookies = false;
         *  binding.BypassProxyOnLocal = false;
         *  binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
         *  binding.MaxBufferSize = 2147483647;
         *  binding.MaxBufferPoolSize = 2147483647;
         *  binding.MaxReceivedMessageSize = 2147483647;
         *  //binding.MessageEncoding = System.ServiceModel.WSMessageEncoding.Text;
         *  //binding.TextEncoding = System.Text.Encoding.UTF8;
         *  binding.TransferMode = System.ServiceModel.TransferMode.Streamed;
         *  binding.UseDefaultWebProxy = true;
         *
         *  binding.ReaderQuotas.MaxDepth = 2147483647;
         *  binding.ReaderQuotas.MaxStringContentLength = 2147483647;
         *  binding.ReaderQuotas.MaxArrayLength = 2147483647;
         *  binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
         *  binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
         *
         *  //binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
         *  binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
         *  binding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.None;
         *  //binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
         *  //binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
         *
         *  return binding;
         * }
         */

        public static NetTcpBinding getNetTcpBinding(string bindingName)
        {
            System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();

            System.ServiceModel.ServiceBehaviorAttribute behavior = new System.ServiceModel.ServiceBehaviorAttribute();

            behavior.MaxItemsInObjectGraph = 2147483647;

            binding.Name = bindingName;

            /*
             * //binding.CloseTimeout = new TimeSpan(0, 1, 0);
             * binding.CloseTimeout = new TimeSpan(0, 10, 0);
             * //binding.OpenTimeout = new TimeSpan(0, 1, 0);
             * binding.OpenTimeout = new TimeSpan(0, 10, 0);
             * binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
             * //binding.SendTimeout = new TimeSpan(0, 1, 0);
             * binding.SendTimeout = new TimeSpan(0, 10, 0);
             * binding.AllowCookies = false;
             * binding.BypassProxyOnLocal = false;
             * binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
             * binding.MaxBufferSize = 2147483647;
             * binding.MaxBufferPoolSize = 2147483647;
             * binding.MaxReceivedMessageSize = 2147483647;
             * binding.MessageEncoding = System.ServiceModel.WSMessageEncoding.Text;
             * binding.TextEncoding = System.Text.Encoding.UTF8;
             * binding.TransferMode = System.ServiceModel.TransferMode.Streamed;
             * binding.UseDefaultWebProxy = true;
             *
             * binding.ReaderQuotas.MaxDepth = 2147483647;
             * binding.ReaderQuotas.MaxStringContentLength = 2147483647;
             * binding.ReaderQuotas.MaxArrayLength = 2147483647;
             * binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
             * binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
             *
             * binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
             * binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
             * binding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.None;
             * binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
             * binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
             */
            return(binding);
        }
        private static Lifetime GetLifetime(Type serviceType, out ServiceBehaviorAttribute attribute)
        {
            attribute =
                serviceType.GetCustomAttributes(typeof (ServiceBehaviorAttribute), true).Cast<ServiceBehaviorAttribute>()
                    .FirstOrDefault();

            var lifetime = Lifetime.Scoped;
            if (attribute != null)
            {
                switch (attribute.InstanceContextMode)
                {
                    case InstanceContextMode.Single:
                        lifetime = Lifetime.Singleton;
                        break;
                    case InstanceContextMode.PerCall:
                        lifetime = Lifetime.Transient;
                        break;
                }
            }
            return lifetime;
        }
 private void Host_Opening(object sender, EventArgs e)
 {
     ServiceHost host = sender as ServiceHost;
     if (host == null)
     {
         return;
     }
     RestServiceBehavior b = host.Description.Behaviors.Find<RestServiceBehavior>();
     if (b == null)
     {
         host.Description.Behaviors.Add(new RestServiceBehavior(m_BizExceptionTypeName, m_ExceptionHandlerTypeName));
     }
     ServiceBehaviorAttribute bb = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
     if (bb == null)
     {
         bb = new ServiceBehaviorAttribute();
         host.Description.Behaviors.Add(bb);
     }
     bb.ConcurrencyMode = ConcurrencyMode.Multiple;
     bb.AddressFilterMode = AddressFilterMode.Any;
     bb.InstanceContextMode = InstanceContextMode.Single;
     bb.MaxItemsInObjectGraph = Int32.MaxValue;
     if (ServiceHostingEnvironment.AspNetCompatibilityEnabled)
     {
         AspNetCompatibilityRequirementsAttribute a = host.Description.Behaviors.Find<AspNetCompatibilityRequirementsAttribute>();
         if (a == null)
         {
             host.Description.Behaviors.Add(new AspNetCompatibilityRequirementsAttribute() { RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed });
         }
         else
         {
             a.RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed;
         }
     }
     //------- 设置 dataContractSerializer的 maxItemsInObjectGraph属性为int.MaxValue
     Type t = host.GetType();
     object obj = t.Assembly.CreateInstance("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior", true, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { false, int.MaxValue }, null, null);
     IServiceBehavior myServiceBehavior = obj as IServiceBehavior;
     if (myServiceBehavior != null)
     {
         host.Description.Behaviors.Add(myServiceBehavior);
     }
     //-------
     foreach (var endpoint in host.Description.Endpoints)
     {
         WebHttpBinding binding = endpoint.Binding as WebHttpBinding;
         if (binding != null)
         {
             binding.MaxReceivedMessageSize = MAX_MSG_SIZE;
             binding.ReaderQuotas.MaxStringContentLength = MAX_MSG_SIZE;
             binding.ReaderQuotas.MaxArrayLength = MAX_MSG_SIZE;
             binding.ReaderQuotas.MaxBytesPerRead = MAX_MSG_SIZE;
             binding.ReaderQuotas.MaxDepth = MAX_MSG_SIZE;
             binding.ReaderQuotas.MaxNameTableCharCount = MAX_MSG_SIZE;
         }
         WebHttpEndpoint p = endpoint as WebHttpEndpoint;
         if (p != null)
         {
             p.HelpEnabled = true;
             p.AutomaticFormatSelectionEnabled = true;
         }
         WebHttpBehavior b0 = endpoint.Behaviors.Find<WebHttpBehavior>();
         if (b0 == null)
         {
             endpoint.Behaviors.Add(new WebHttpBehavior() { HelpEnabled = true, FaultExceptionEnabled = true, AutomaticFormatSelectionEnabled = true });
         }
         else
         {
             b0.HelpEnabled = true;
             b0.FaultExceptionEnabled = true;
             b0.AutomaticFormatSelectionEnabled = true;
         }
         RestEndpointBehavior b1 = endpoint.Behaviors.Find<RestEndpointBehavior>();
         if (b1 == null)
         {
             endpoint.Behaviors.Add(new RestEndpointBehavior());
         }
         foreach (var operation in endpoint.Contract.Operations)
         {
             NEOperationBehavior b2 = operation.Behaviors.Find<NEOperationBehavior>();
             if (b2 == null)
             {
                 operation.Behaviors.Add(new NEOperationBehavior(m_ConverterTypeName, m_ExceptionHandlerTypeName));
             }
         }
     }
 }
 /// <summary>
 /// Verifies that the throttling settings in ServiceBehaviorAttribute are maxed out.
 /// </summary>        
 private void VerifyServiceBehaviorAttributeSettings(ServiceBehaviorAttribute serviceBehavior)
 {
     Assert.IsTrue(serviceBehavior.MaxItemsInObjectGraph == int.MaxValue,
                   "Max items in object graph quota is not maxed out.");
 }
        static ServiceBehaviorAttribute EnsureBehaviorAttribute(ServiceDescription description)
        {
            ServiceBehaviorAttribute attr = description.Behaviors.Find<ServiceBehaviorAttribute>();

            if (attr == null)
            {
                attr = new ServiceBehaviorAttribute();
                description.Behaviors.Insert(0, attr);
            }

            return attr;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Start the interface
        /// </summary>
        /// <param name="myIGraphFSSession">An instance of IGraphFSSession</param>
        public void Start(IGraphFSSession myIGraphFSSession/*, String myEndpointPath*/)
        {
            if (myIGraphFSSession== null)
                throw new ArgumentNullException("IGraphFS has to be an instance.");

            _ServiceHost = new ServiceHost(myIGraphFSSession, _BaseAddress);

            try
            {
                ServiceBehaviorAttribute serviceBehaviorAttribute = new ServiceBehaviorAttribute();
                if (_ServiceHost.Description.Behaviors[typeof(ServiceBehaviorAttribute)] != null)
                    serviceBehaviorAttribute = (ServiceBehaviorAttribute)_ServiceHost.Description.Behaviors[typeof(ServiceBehaviorAttribute)];
                else
                    _ServiceHost.Description.Behaviors.Add(serviceBehaviorAttribute);

                serviceBehaviorAttribute.InstanceContextMode = InstanceContextMode.Single;
                serviceBehaviorAttribute.IncludeExceptionDetailInFaults = true;

                //_ServiceHost.Description.Behaviors[typeof(ServiceBehaviorAttribute)];
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
                binding.ReceiveTimeout = TimeSpan.MaxValue;
                binding.PortSharingEnabled = false;
                #if(!__MonoCS__)
                binding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;
                #endif

                #region Security
                /*
                binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
                _ServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByIssuerName, "SONES GmbH - Mail CA");
                _ServiceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                */
                #endregion

                _ServiceHost.AddServiceEndpoint(typeof(IGraphFSSession), binding, _BaseAddress);
                _ServiceHost.Open(new TimeSpan(0,1,0));

                _AdministrationServiceAnnouncer = new Announcer(myIGraphFSSession.GetFileSystemUUID().ToString(), _BaseAddress, DiscoverableServiceType.Filesystem);
            }
            catch (CommunicationException ce)
            {
                /*
                 * If you're getting an exception while starting up this the first time you probably want to do
                 * these things:
                 *
                 * 1. Start this as local Administrator OR Add your User to the SMSvcHost.exe.config file in the
                 *    \Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ directory
                 * 2. You want to run "sc.exe config NetTcpPortSharing start= demand" as local Administrator to
                 *    enable the net.tcp Port Sharing.
                 *
                 * */
                // TODO: Insert the above todo into the installer/wizard for final customer deployment.

                System.Diagnostics.Debug.WriteLine(ce);
                _ServiceHost.Abort();
                ((IDisposable)_ServiceHost).Dispose();

                throw ce;
            }
        }
        protected override System.ServiceModel.Description.ServiceDescription CreateDescription(out IDictionary <string, ContractDescription> implementedContracts)
        {
            System.ServiceModel.Description.ServiceDescription service;
            if (this.serviceType == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxServiceHostCannotCreateDescriptionWithoutServiceType")));
            }
            if (this.SingletonInstance != null)
            {
                service = System.ServiceModel.Description.ServiceDescription.GetService(this.SingletonInstance);
            }
            else
            {
                service = System.ServiceModel.Description.ServiceDescription.GetService(this.serviceType);
            }
            ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>();
            object wellKnownSingleton          = attribute.GetWellKnownSingleton();

            if (wellKnownSingleton == null)
            {
                wellKnownSingleton      = attribute.GetHiddenSingleton();
                this.disposableInstance = wellKnownSingleton as IDisposable;
            }
            if ((typeof(IServiceBehavior).IsAssignableFrom(this.serviceType) || typeof(IContractBehavior).IsAssignableFrom(this.serviceType)) && (wellKnownSingleton == null))
            {
                wellKnownSingleton      = System.ServiceModel.Description.ServiceDescription.CreateImplementation(this.serviceType);
                this.disposableInstance = wellKnownSingleton as IDisposable;
            }
            if ((this.SingletonInstance == null) && (wellKnownSingleton is IServiceBehavior))
            {
                service.Behaviors.Add((IServiceBehavior)wellKnownSingleton);
            }
            ReflectedContractCollection contracts  = new ReflectedContractCollection();
            List <System.Type>          interfaces = ServiceReflector.GetInterfaces(this.serviceType);

            for (int i = 0; i < interfaces.Count; i++)
            {
                System.Type key = interfaces[i];
                if (!contracts.Contains(key))
                {
                    ContractDescription item = null;
                    if (wellKnownSingleton != null)
                    {
                        item = ContractDescription.GetContract(key, wellKnownSingleton);
                    }
                    else
                    {
                        item = ContractDescription.GetContract(key, this.serviceType);
                    }
                    contracts.Add(item);
                    Collection <ContractDescription> inheritedContracts = item.GetInheritedContracts();
                    for (int j = 0; j < inheritedContracts.Count; j++)
                    {
                        ContractDescription description3 = inheritedContracts[j];
                        if (!contracts.Contains(description3.ContractType))
                        {
                            contracts.Add(description3);
                        }
                    }
                }
            }
            this.reflectedContracts = contracts;
            implementedContracts    = contracts.ToImplementedContracts();
            return(service);
        }
Ejemplo n.º 13
0
        private void LoadCustomConfig()
        {
            if (_setting != null)
            {
                _host.Description.Endpoints.Clear();
                for (int i = 0; i < _host.Description.Behaviors.Count; i++)
                {
                    if (_host.Description.Behaviors[i] is ServiceBehaviorAttribute)
                        ;
                    else if (_host.Description.Behaviors[i] is ServiceAuthenticationBehavior)
                        ;
                    else if (_host.Description.Behaviors[i] is ServiceAuthorizationBehavior)
                        ;
                    else
                    {
                        _host.Description.Behaviors.Remove(_host.Description.Behaviors[i]); i = 0;
                    }
                }
                foreach (ServiceElement service in _setting.ServiceConfig.Services)
                {
                    #region 添加服务
                    foreach (ServiceEndpointElement item in service.Endpoints)
                    {
                        ServiceEndpoint serviceTemp = _host.Description.Endpoints.Find(item.Address);
                        #region netTcpBinding
                        if (item.Binding.Equals("netTcpBinding", StringComparison.OrdinalIgnoreCase))
                        {
                            //System.ServiceModel.Channels.TcpTransportBindingElement tcptbe = new System.ServiceModel.Channels.TcpTransportBindingElement();
                            //tcptbe.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 100;//默认值为10
                            NetTcpBinding nettcp = new NetTcpBinding(SecurityMode.None);
                            if (_setting.BindingConfig.NetTcpBinding.ContainsKey(item.BindingConfiguration))
                            {
                                NetTcpBindingElement ele = _setting.BindingConfig.NetTcpBinding.Bindings[item.BindingConfiguration];
                                nettcp.OpenTimeout = ele.OpenTimeout;
                                nettcp.CloseTimeout = ele.CloseTimeout;
                                nettcp.SendTimeout = ele.SendTimeout;
                                nettcp.ReceiveTimeout = ele.ReceiveTimeout;
                                nettcp.MaxReceivedMessageSize = ele.MaxReceivedMessageSize;
                                nettcp.MaxBufferSize = ele.MaxBufferSize;
                                nettcp.MaxBufferPoolSize = ele.MaxBufferPoolSize;
                                nettcp.PortSharingEnabled = ele.PortSharingEnabled;
                                nettcp.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
                                nettcp.ReaderQuotas.MaxArrayLength = ele.ReaderQuotas.MaxArrayLength;
                                nettcp.ReaderQuotas.MaxStringContentLength = ele.ReaderQuotas.MaxStringContentLength;
                                nettcp.ReaderQuotas.MaxDepth = ele.ReaderQuotas.MaxDepth;
                                nettcp.ReaderQuotas.MaxBytesPerRead = ele.ReaderQuotas.MaxBytesPerRead;
                                nettcp.ReaderQuotas.MaxNameTableCharCount = ele.ReaderQuotas.MaxNameTableCharCount;
                                nettcp.Security.Mode = ele.Security.Mode;
                            }
                            if (serviceTemp == null)
                                _host.AddServiceEndpoint(item.Contract, nettcp, item.Address);
                            else
                                serviceTemp.Binding = nettcp;
                        }
                        #endregion

                        #region WSDualHttpBinding
                        else if (item.Binding.Equals("WSDualHttpBinding", StringComparison.OrdinalIgnoreCase))
                        {
                            WSDualHttpBinding wsdual = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
                            if (_setting.BindingConfig.WSDualHttpBinding.ContainsKey(item.BindingConfiguration))
                            {
                                WSDualHttpBindingElement ele = _setting.BindingConfig.WSDualHttpBinding.Bindings[item.BindingConfiguration];
                                wsdual.OpenTimeout = ele.OpenTimeout;
                                wsdual.CloseTimeout = ele.CloseTimeout;
                                wsdual.SendTimeout = ele.SendTimeout;
                                wsdual.ReceiveTimeout = ele.ReceiveTimeout;
                                wsdual.MaxReceivedMessageSize = ele.MaxReceivedMessageSize;
                                wsdual.ClientBaseAddress = ele.ClientBaseAddress;
                                wsdual.MaxBufferPoolSize = ele.MaxBufferPoolSize;
                                wsdual.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
                                wsdual.ReaderQuotas.MaxArrayLength = ele.ReaderQuotas.MaxArrayLength;
                                wsdual.ReaderQuotas.MaxStringContentLength = ele.ReaderQuotas.MaxStringContentLength;
                                wsdual.ReaderQuotas.MaxDepth = ele.ReaderQuotas.MaxDepth;
                                wsdual.ReaderQuotas.MaxBytesPerRead = ele.ReaderQuotas.MaxBytesPerRead;
                                wsdual.ReaderQuotas.MaxNameTableCharCount = ele.ReaderQuotas.MaxNameTableCharCount;
                                wsdual.UseDefaultWebProxy = ele.UseDefaultWebProxy;
                                wsdual.Security.Mode = ele.Security.Mode;
                            }
                            if (serviceTemp == null)
                                _host.AddServiceEndpoint(item.Contract, wsdual, item.Address);
                            else
                                serviceTemp.Binding = wsdual;
                        }
                        #endregion

                        #region BasicHttpBinding
                        else if (item.Binding.Equals("BasicHttpBinding", StringComparison.OrdinalIgnoreCase))
                        {
                            BasicHttpBinding wsdual = new BasicHttpBinding();
                            if (_setting.BindingConfig.BasicHttpBinding.ContainsKey(item.BindingConfiguration))
                            {
                                BasicHttpBindingElement ele = _setting.BindingConfig.BasicHttpBinding.Bindings[item.BindingConfiguration];
                                wsdual.OpenTimeout = ele.OpenTimeout;
                                wsdual.CloseTimeout = ele.CloseTimeout;
                                wsdual.SendTimeout = ele.SendTimeout;
                                wsdual.ReceiveTimeout = ele.ReceiveTimeout;
                                wsdual.MaxReceivedMessageSize = ele.MaxReceivedMessageSize;
                                wsdual.MaxBufferSize = ele.MaxBufferSize;
                                wsdual.MaxBufferPoolSize = ele.MaxBufferPoolSize;
                                wsdual.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
                                wsdual.ReaderQuotas.MaxArrayLength = ele.ReaderQuotas.MaxArrayLength;
                                wsdual.ReaderQuotas.MaxStringContentLength = ele.ReaderQuotas.MaxStringContentLength;
                                wsdual.ReaderQuotas.MaxDepth = ele.ReaderQuotas.MaxDepth;
                                wsdual.ReaderQuotas.MaxBytesPerRead = ele.ReaderQuotas.MaxBytesPerRead;
                                wsdual.ReaderQuotas.MaxNameTableCharCount = ele.ReaderQuotas.MaxNameTableCharCount;
                                wsdual.UseDefaultWebProxy = ele.UseDefaultWebProxy;
                                wsdual.Security.Mode = ele.Security.Mode;
                            }
                            if (serviceTemp == null)
                                _host.AddServiceEndpoint(item.Contract, wsdual, item.Address);
                            else
                                serviceTemp.Binding = wsdual;
                        }
                        #endregion

                        #region WSHttpBinding
                        else if (item.Binding.Equals("WSHttpBinding", StringComparison.OrdinalIgnoreCase))
                        {
                            WSHttpBinding wsdual = new WSHttpBinding();
                            if (_setting.BindingConfig.WSHttpBinding.ContainsKey(item.BindingConfiguration))
                            {
                                WSHttpBindingElement ele = _setting.BindingConfig.WSHttpBinding.Bindings[item.BindingConfiguration];
                                wsdual.OpenTimeout = ele.OpenTimeout;
                                wsdual.CloseTimeout = ele.CloseTimeout;
                                wsdual.SendTimeout = ele.SendTimeout;
                                wsdual.ReceiveTimeout = ele.ReceiveTimeout;
                                wsdual.MaxReceivedMessageSize = ele.MaxReceivedMessageSize;
                                //wsdual.MaxBufferSize = ele.MaxBufferSize;
                                wsdual.MaxBufferPoolSize = ele.MaxBufferPoolSize;
                                wsdual.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
                                wsdual.ReaderQuotas.MaxArrayLength = ele.ReaderQuotas.MaxArrayLength;
                                wsdual.ReaderQuotas.MaxStringContentLength = ele.ReaderQuotas.MaxStringContentLength;
                                wsdual.ReaderQuotas.MaxDepth = ele.ReaderQuotas.MaxDepth;
                                wsdual.ReaderQuotas.MaxBytesPerRead = ele.ReaderQuotas.MaxBytesPerRead;
                                wsdual.ReaderQuotas.MaxNameTableCharCount = ele.ReaderQuotas.MaxNameTableCharCount;
                                wsdual.UseDefaultWebProxy = ele.UseDefaultWebProxy;
                                wsdual.Security.Mode = ele.Security.Mode;
                            }
                            if (serviceTemp == null)
                                _host.AddServiceEndpoint(item.Contract, wsdual, item.Address);
                            else
                                serviceTemp.Binding = wsdual;
                        }
                        #endregion
                    }
                    #endregion

                    #region 行为设置
                    if (_setting.BehaviorConfig.ServiceBehaviors.ContainsKey(service.BehaviorConfiguration))
                    {
                        ServiceBehaviorElement haviorelement = _setting.BehaviorConfig.ServiceBehaviors[service.BehaviorConfiguration];

                        #region 并发设置
                        List<ServiceThrottlingElement> throttlingConfig = haviorelement.OfType<ServiceThrottlingElement>().ToList();
                        ServiceThrottlingBehavior throttlingBehavior = _host.Description.Behaviors.Find<ServiceThrottlingBehavior>();
                        if (null == throttlingBehavior)
                        {
                            throttlingBehavior = new ServiceThrottlingBehavior();
                            _host.Description.Behaviors.Add(throttlingBehavior);
                        }
                        if (throttlingConfig.Count > 0)
                        {
                            //当前ServiceHost能够处理的最大并发消息数量,默认值为16
                            throttlingBehavior.MaxConcurrentCalls = throttlingConfig[0].MaxConcurrentCalls;
                            //当前ServiceHost允许存在的InstanceContext的最大数量,默认值为26
                            throttlingBehavior.MaxConcurrentInstances = throttlingConfig[0].MaxConcurrentInstances;
                            //当前ServiceHost允许的最大并发会话数量,默认值为10
                            throttlingBehavior.MaxConcurrentSessions = throttlingConfig[0].MaxConcurrentSessions;
                        }
                        #endregion

                        #region 序列化最大项
                        ServiceBehaviorAttribute att = new ServiceBehaviorAttribute();
                        att.Name = service.BehaviorConfiguration;
                        if (_host.Description.Behaviors.Find<ServiceBehaviorAttribute>() == null)
                        {
                            _host.Description.Behaviors.Add(att);
                        }
                        else
                        {
                            att = _host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
                        }
                        List<DataContractSerializerElement> serializerConfig = haviorelement.OfType<DataContractSerializerElement>().ToList();
                        if (serializerConfig.Count > 0)
                        {
                            att.MaxItemsInObjectGraph = serializerConfig[0].MaxItemsInObjectGraph;
                        }
                        #endregion

                        #region 是否充许客户端看到详细错误信息
                        List<ServiceDebugElement> debugConfig = haviorelement.OfType<ServiceDebugElement>().ToList();
                        if (debugConfig.Count > 0)
                        {
                            ServiceDebugBehavior debug = new ServiceDebugBehavior();
                            if (_host.Description.Behaviors.Find<ServiceDebugBehavior>() == null)
                            {
                                _host.Description.Behaviors.Add(debug);
                            }
                            else
                            {
                                debug = _host.Description.Behaviors.Find<ServiceDebugBehavior>();
                            }
                            debug.IncludeExceptionDetailInFaults = debugConfig[0].IncludeExceptionDetailInFaults;
                            if (_setting.MetaDataPort>0 && service.Endpoints.Count > 0)
                            {
                                try
                                {
                                    ServiceMetadataBehavior metadata = new ServiceMetadataBehavior();
                                    if (_host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                                    {
                                        _host.Description.Behaviors.Add(metadata);
                                    }
                                    else
                                    {
                                        metadata = _host.Description.Behaviors.Find<ServiceMetadataBehavior>();
                                    }
                                    metadata.HttpGetEnabled = true;
                                    string tempurl = service.Endpoints[0].Address.ToString();
                                    tempurl = tempurl.Substring(tempurl.LastIndexOf(':'));
                                    tempurl = tempurl.Substring(tempurl.IndexOf('/'));
                                    metadata.HttpGetUrl = new Uri(string.Format("http://localhost:{0}{1}/{2}", _setting.MetaDataPort, tempurl, "metadata"));
                                }
                                catch
                                {
                                    _host.Description.Behaviors.Remove<ServiceMetadataBehavior>();
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion
                }
            }
        }
 private static ServiceBehaviorAttribute EnsureBehaviorAttribute(System.ServiceModel.Description.ServiceDescription description)
 {
     ServiceBehaviorAttribute item = description.Behaviors.Find<ServiceBehaviorAttribute>();
     if (item == null)
     {
         item = new ServiceBehaviorAttribute();
         description.Behaviors.Insert(0, item);
     }
     return item;
 }
Ejemplo n.º 15
0
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            ServiceHost host = new ServiceHost(serviceType, baseAddresses);  //base.CreateServiceHost(serviceType, baseAddresses);
            Type contractType = FindServiceContractInterface(serviceType);
            host.AddServiceEndpoint(contractType, FindBinding(m_BindingType), "");
            ServiceMetadataBehavior b1 = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (b1 == null)
            {
                b1 = new ServiceMetadataBehavior() { HttpGetEnabled = true };
                host.Description.Behaviors.Add(b1);
            }
            else
            {
                b1.HttpGetEnabled = true;
            }
            StandardExceptionBehavior b = host.Description.Behaviors.Find<StandardExceptionBehavior>();
            if (b == null)
            {
                host.Description.Behaviors.Add(new StandardExceptionBehavior(m_BizExceptionTypeName, m_ExceptionHandlerTypeName));
            }
            //if (url.IndexOf("http://") < 0)
            //{
            //    b1.HttpGetUrl = new Uri(string.Format("http://{0}{1}{2}", hostIP, (service.Port > 0 ? (":" + service.Port) : string.Empty), url));
            //}
            ServiceDebugBehavior b2 = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (b2 == null)
            {
                host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
            }
            else
            {
                b2.IncludeExceptionDetailInFaults = true;
            }
            ServiceBehaviorAttribute bb = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
            if (bb == null)
            {
                bb = new ServiceBehaviorAttribute();
                host.Description.Behaviors.Add(bb);
            }
            bb.ConcurrencyMode = ConcurrencyMode.Multiple;
            bb.AddressFilterMode = AddressFilterMode.Any;
            bb.InstanceContextMode = InstanceContextMode.Single;
            bb.MaxItemsInObjectGraph = Int32.MaxValue;
            if (ServiceHostingEnvironment.AspNetCompatibilityEnabled)
            {
                AspNetCompatibilityRequirementsAttribute a = host.Description.Behaviors.Find<AspNetCompatibilityRequirementsAttribute>();
                if (a == null)
                {
                    host.Description.Behaviors.Add(new AspNetCompatibilityRequirementsAttribute() { RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed });
                }
                else
                {
                    a.RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed;
                }
            }
            //------- 设置 dataContractSerializer的 maxItemsInObjectGraph属性为int.MaxValue
            Type t = host.GetType();
            object obj = t.Assembly.CreateInstance("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior", true, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { false, int.MaxValue }, null, null);
            IServiceBehavior myServiceBehavior = obj as IServiceBehavior;
            if (myServiceBehavior != null)
            {
                host.Description.Behaviors.Add(myServiceBehavior);
            }
            //-------

            return host;
        }
 protected override void Configure(ServiceBehaviorAttribute serviceBehavior)
 {
     serviceBehavior.InstanceContextMode = InstanceContextMode.PerCall;
 }
Ejemplo n.º 17
0
        private static void ConfigureInstanceContextMode(ServiceHost host, InstanceContextMode mode)
        {
            ServiceBehaviorAttribute serviceBehaviorAttribute = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
            if (serviceBehaviorAttribute == null)
            {
                serviceBehaviorAttribute = new ServiceBehaviorAttribute();
                host.Description.Behaviors.Add(serviceBehaviorAttribute);
            }

            serviceBehaviorAttribute.InstanceContextMode = mode;
        }