コード例 #1
0
        /// <summary>
        /// Creates a new instance of the <see cref="WorldGeocoder"/> class for the specified
        /// service configuration.
        /// </summary>
        /// <param name="serviceInfo">The instance of the geocoding service configuration
        /// specifying World geocoder service to create geocoder for.</param>
        /// <param name="exceptionHandler">Exception handler.</param>
        /// <returns>A new instance of the <see cref="WorldGeocoder"/> class.</returns>
        /// <exception cref="System.ArgumentNullException"><paramref name="serviceInfo"/> is a null
        /// reference.</exception>
        public static GeocoderBase CreateWorldGeocoder(GeocodingServiceInfo serviceInfo,
                                                       IServiceExceptionHandler exceptionHandler)
        {
            CodeContract.RequiresNotNull("serviceInfo", serviceInfo);

            // Create binding for the geocoder REST service.
            var webBinding             = ServiceHelper.CreateWebHttpBinding("WorldGeocoder");
            var binding                = new CustomBinding(webBinding);
            var messageEncodingElement = binding.Elements.Find <WebMessageEncodingBindingElement>();

            messageEncodingElement.ContentTypeMapper = new ArcGisWebContentTypeMapper();

            // Create endpoint for the geocoder REST service.
            var contract       = ContractDescription.GetContract(typeof(IGeocodingService));
            var serviceAddress = new EndpointAddress(serviceInfo.RestUrl);
            var endpoint       = new WebHttpEndpoint(contract, serviceAddress);

            endpoint.Binding = binding;

            // Replace default endpoint behavior with a customized one.
            endpoint.Behaviors.Remove <WebHttpBehavior>();
            endpoint.Behaviors.Add(new GeocodingServiceWebHttpBehavior());

            // Create the geocoder instance.
            var channelFactory = new WebChannelFactory <IGeocodingService>(endpoint);
            var client         = new GeocodingServiceClient(channelFactory, serviceInfo, exceptionHandler);

            return(new WorldGeocoder(serviceInfo, client));
        }
コード例 #2
0
        public void ReplaceBinding2()
        {
            var se = new WebHttpEndpoint(ContractDescription.GetContract(typeof(IMetadataExchange)), null);

            se.Binding       = new NetTcpBinding();
            se.WriteEncoding = Encoding.UTF8;
        }
コード例 #3
0
        void InternalOnApplyConfiguration(ServiceEndpoint endpoint)
        {
            WebHttpEndpoint webHttpEndpoint = endpoint as WebHttpEndpoint;

            Fx.Assert(webHttpEndpoint != null, "The endpoint should be of type WebHttpServiceEndpoint since this is what was returned with CreateServiceEndpoint().");


            if (IsSet(ConfigurationStrings.HostNameComparisonMode))
            {
                webHttpEndpoint.HostNameComparisonMode = this.HostNameComparisonMode;
            }
            if (IsSet(ConfigurationStrings.MaxBufferPoolSize))
            {
                webHttpEndpoint.MaxBufferPoolSize = this.MaxBufferPoolSize;
            }
            if (IsSet(ConfigurationStrings.MaxReceivedMessageSize))
            {
                webHttpEndpoint.MaxReceivedMessageSize = this.MaxReceivedMessageSize;
            }
            if (IsSet(ConfigurationStrings.WriteEncoding))
            {
                webHttpEndpoint.WriteEncoding = this.WriteEncoding;
            }
            if (IsSet(ConfigurationStrings.TransferMode))
            {
                webHttpEndpoint.TransferMode = this.TransferMode;
            }
            if (IsSet(WebConfigurationStrings.HelpEnabled))
            {
                webHttpEndpoint.HelpEnabled = this.HelpEnabled;
            }
            if (IsSet(WebConfigurationStrings.DefaultOutgoingResponseFormat))
            {
                webHttpEndpoint.DefaultOutgoingResponseFormat = this.DefaultOutgoingResponseFormat;
            }
            if (IsSet(WebConfigurationStrings.AutomaticFormatSelectionEnabled))
            {
                webHttpEndpoint.AutomaticFormatSelectionEnabled = this.AutomaticFormatSelectionEnabled;
            }
            if (IsSet(WebConfigurationStrings.CrossDomainScriptAccessEnabled))
            {
                webHttpEndpoint.CrossDomainScriptAccessEnabled = this.CrossDomainScriptAccessEnabled;
            }
            if (IsSet(WebConfigurationStrings.FaultExceptionEnabled))
            {
                webHttpEndpoint.FaultExceptionEnabled = this.FaultExceptionEnabled;
            }
            PropertyInformationCollection propertyInfo = this.ElementInformation.Properties;

            if (propertyInfo[ConfigurationStrings.MaxBufferSize].ValueOrigin != PropertyValueOrigin.Default)
            {
                webHttpEndpoint.MaxBufferSize = this.MaxBufferSize;
            }
            if (IsSet(WebConfigurationStrings.ContentTypeMapper))
            {
                webHttpEndpoint.ContentTypeMapper = WebHttpBindingElement.GetContentTypeMapper(this.ContentTypeMapper);
            }
            this.Security.ApplyConfiguration(webHttpEndpoint.Security);
            WebHttpBindingElement.ApplyReaderQuotasConfiguration(webHttpEndpoint.ReaderQuotas, this.ReaderQuotas);
        }
コード例 #4
0
        private static ServiceEndpoint CreateEndpoint(Binding binding, EndpointAddress address, ContractDescription cd, Endpoint serviceInterface)
        {
            if (!serviceInterface.EndpointName.EqualsCaseInsensitive("rest") && !serviceInterface.EndpointName.EqualsCaseInsensitive("securerest"))
            {
                return(new ServiceEndpoint(cd, binding, address));
            }
            var restEndpoint = new WebHttpEndpoint(cd, address)
            {
                HelpEnabled = true,
                DefaultOutgoingResponseFormat = WebMessageFormat.Json,
                Binding = binding,
                FaultExceptionEnabled           = true,
                AutomaticFormatSelectionEnabled = true
            };

            restEndpoint.AutomaticFormatSelectionEnabled = true;
            restEndpoint.FaultExceptionEnabled           = true;
            return(restEndpoint);
        }
コード例 #5
0
        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));
                    }
                }
            }
        }
コード例 #6
0
        public bool RunHostBothHttpAndTcpProtocol(out string StrResult)
        {
            try
            {
                StrResult = "";
                serviceHosts.Clear();
                string TypeFullName = this.GetType().FullName;
                Type[] allclass     = Assembly.Load(service_dll).GetTypes().Where(n => n.IsPublic == true && n.FullName != TypeFullName && n.FullName.Contains(service_dll) && !n.Name.Contains("DuplexService")).ToArray <Type>();
                foreach (var acitem in allclass)
                {
                    Type[] allinterface = acitem.GetInterfaces().Where(n => n.IsPublic == true && n.GetCustomAttributes(false).OfType <ServiceContractAttribute>().Any()).ToArray <Type>();
                    if (allinterface.Length == 0)
                    {
                        continue;
                    }
                    Uri         httpuri   = new Uri(httpStr + acitem.Name);
                    Uri         tcpuri    = new Uri(TcpStr + acitem.Name);
                    Uri         wshttpuri = new Uri(wshttpStr + acitem.Name);
                    ServiceHost sssh      = new ServiceHost(acitem, new Uri[] { wshttpuri, tcpuri });

                    WebHttpBinding webhttpBInding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
                    webhttpBInding.CrossDomainScriptAccessEnabled = true;

                    NetTcpBinding tcpBingding = GetNetTcpBinding();

                    WSHttpBinding           wshttpbinding = GetWSHttpBinding();
                    EndpointAddress         httpepa       = new EndpointAddress(httpuri);
                    EndpointAddress         tcpepa        = new EndpointAddress(tcpuri);
                    EndpointAddress         wshttpepa     = new EndpointAddress(wshttpuri);
                    ServiceMetadataBehavior smbhhtp       = new ServiceMetadataBehavior();
                    smbhhtp.HttpGetEnabled = true;
                    smbhhtp.HttpGetUrl     = wshttpuri;
                    sssh.Description.Behaviors.Add(smbhhtp);
                    ServiceDebugBehavior sdb = sssh.Description.Behaviors.Find <ServiceDebugBehavior>();
                    sdb.IncludeExceptionDetailInFaults = true;
                    if (sdb == null)
                    {
                        sdb = new ServiceDebugBehavior();
                        sssh.Description.Behaviors.Add(sdb);
                    }
                    sssh.Description.Name = acitem.Name;
                    serviceHosts.Add(sssh);

                    foreach (var aiItem in allinterface)
                    {
                        ContractDescription contract = ContractDescription.GetContract(aiItem.UnderlyingSystemType);
                        contract.Name = acitem.Name + "Proxy";
                        WebHttpEndpoint httpesp = new WebHttpEndpoint(contract, httpepa);
                        httpesp.CrossDomainScriptAccessEnabled = true;
                        webhttpBInding.CloseTimeout            = new TimeSpan(0, 1, 0);
                        webhttpBInding.OpenTimeout             = new TimeSpan(0, 1, 0);
                        webhttpBInding.ReceiveTimeout          = new TimeSpan(0, 10, 0);
                        webhttpBInding.SendTimeout             = new TimeSpan(0, 1, 0);
                        webhttpBInding.BypassProxyOnLocal      = false;

                        webhttpBInding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                        webhttpBInding.MaxBufferPoolSize      = 524288;
                        webhttpBInding.MaxReceivedMessageSize = 2147483647;
                        webhttpBInding.UseDefaultWebProxy     = false;
                        webhttpBInding.AllowCookies           = false;
                        webhttpBInding.ReaderQuotas.MaxDepth  = 32;
                        webhttpBInding.ReaderQuotas.MaxStringContentLength = 8192;
                        webhttpBInding.ReaderQuotas.MaxNameTableCharCount  = 16384;
                        webhttpBInding.ReaderQuotas.MaxBytesPerRead        = 4096;
                        webhttpBInding.ReaderQuotas.MaxArrayLength         = 16384;
                        WebHttpBehavior whb = new WebHttpBehavior();
                        whb.AutomaticFormatSelectionEnabled = true;
                        whb.FaultExceptionEnabled           = true;
                        whb.HelpEnabled = true;
                        whb.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
                        httpesp.EndpointBehaviors.Clear();
                        httpesp.EndpointBehaviors.Add(whb);
                        httpesp.EndpointBehaviors.Add(new WebScriptEnablingBehavior());
                        httpesp.Binding = webhttpBInding;


                        ServiceEndpoint tcpsep    = new ServiceEndpoint(contract, tcpBingding, tcpepa);
                        ServiceEndpoint wshttpsep = new ServiceEndpoint(contract, wshttpbinding, wshttpepa);

                        sssh.AddServiceEndpoint(httpesp);
                        sssh.AddServiceEndpoint(tcpsep);
                        sssh.AddServiceEndpoint(wshttpsep);
                        sssh.Open();
                    }
                }
                RunDulplex();
                return(true);
            }
            catch (Exception ex)
            {
                string str = "";
                CloseAllHosts(ref str);
                StrResult = ex.Message.ToString();
                serviceHosts.Clear();
                return(false);
            }
        }
コード例 #7
0
        public void ReplaceBinding1()
        {
            var se = new WebHttpEndpoint(ContractDescription.GetContract(typeof(IMetadataExchange)), null);

            se.Binding = new NetTcpBinding();              // this does not throw exception yet.
        }
コード例 #8
0
ファイル: WCFManager.cs プロジェクト: zebingzhou/WMS
        /// <summary>
        /// 启动指定地址服务
        /// </summary>
        /// <param name="servAddr">服务地址</param>
        /// <param name="restr">执行描述</param>
        /// <returns>执行标志</returns>
        public bool Start(Uri servAddr, EnumWCFProtocol protocol, ref string restr)
        {
            //承载和运行服务(MSDN第三步)
            //为服务配置基址
            //1.为服务的基址创建 Uri 实例。此 URI 指定 HTTP 方案、本地计算机、端口号 8000,以及服务协定中为服务命名空间指定的服务路径 ServiceModelSample/Service。
            //Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

            //承载服务
            //1.导入 System.ServiceModel.Description 命名空间。这行代码应该与 using 或 imports 语句的其余部分一起放置在 Program.cs/Program.vb 文件的顶部。
            //2.创建一个新的 ServiceHost 实例以承载服务。必须指定实现服务协定和基址的类型。对于此示例,基址为 http://localhost:8000/ServiceModelSamples/Service,CalculatorService 为实现服务协定的类型。

            //3.添加一个捕获 CommunicationException 的 try-catch 语句,并在接下来的三个步骤中将该代码添加到 try 块中。catch 子句应该显示错误信息,然后调用 selfHost.Abort()。
            try

            {
                if (this.ServiceContractObj == null)
                {
                    restr = "服务宿主对象未设置!";
                    return(false);
                }
                if (servAddr == null)
                {
                    restr = "服务器地址为空!";
                    return(false);
                }
                this.Stop(ref restr);

                //4.添加公开服务的终结点。为此,必须指定终结点公开的协议、绑定和终结点的地址。对于此示例,将 ICalculator 指定为协定,将 WSHttpBinding 指定为绑定,并将 CalculatorService 指定为地址。在这里请注意,终结点地址是相对地址。终结点的完整地址是基址和终结点地址的组合。在此例中,完整地址是 http://localhost:8000/ServiceModelSamples/Service/CalculatorService。
                EndpointAddress  _address     = new EndpointAddress(servAddr);
                BasicHttpBinding basicBinding = null;
                WebHttpBinding   webBinding   = null;
                if (protocol == EnumWCFProtocol.BasicHttp)
                {
                    basicBinding = new BasicHttpBinding();
                    basicBinding.MaxBufferPoolSize = 2147483647;
                    basicBinding.MaxBufferSize     = 2147483647;

                    basicBinding.MaxReceivedMessageSize = 2147483647;
                    basicBinding.ReceiveTimeout         = TimeSpan.MaxValue;        //20s
                    basicBinding.SendTimeout            = TimeSpan.FromSeconds(50); //20s
                }
                else if (protocol == EnumWCFProtocol.WebHttp)
                {
                    webBinding = new WebHttpBinding();
                    webBinding.MaxBufferPoolSize = 2147483647;
                    webBinding.MaxBufferSize     = 2147483647;

                    webBinding.MaxReceivedMessageSize = 2147483647;
                    webBinding.ReceiveTimeout         = TimeSpan.MaxValue;        //20s
                    webBinding.SendTimeout            = TimeSpan.FromSeconds(50); //20s
                }



                ContractDescription _contract = ContractDescription.GetContract(typeof(IContractObj));



                this.SelfHost = new ServiceHost(this.ServiceContractObj, servAddr);
                //添加终结点ABC
                if (protocol == EnumWCFProtocol.BasicHttp)
                {
                    ServiceEndpoint basicendpoint = new ServiceEndpoint(_contract, basicBinding, _address);

                    this.SelfHost.Description.Endpoints.Add(basicendpoint);
                }
                else if (protocol == EnumWCFProtocol.WebHttp)
                {
                    WebHttpEndpoint webEndpoint = new WebHttpEndpoint(_contract, _address);
                    webEndpoint.HelpEnabled = true;
                    webEndpoint.Binding     = webBinding;
                    this.SelfHost.Description.Endpoints.Add(webEndpoint);
                }


                //启用元数据交换
                ServiceMetadataBehavior meta = new ServiceMetadataBehavior();
                meta.HttpsGetEnabled = true;
                meta.HttpGetEnabled  = true;
                this.SelfHost.Description.Behaviors.Add(meta);
                this.SelfHost.Open();


                return(true);
            }
            catch (CommunicationException ce)
            {
                restr = ce.StackTrace;
                this.SelfHost.Abort();
                return(false);
            }
        }