static void Main(string[] args) { Console.WriteLine("Инициализация..."); var properties = ConnectionSettings.Default; var baseUrl = new Uri(properties.host); var contractType = typeof (IRestBridgeContract); var binding = new WebHttpBinding(WebHttpSecurityMode.None); binding.ContentTypeMapper = new JsonContentTypeMapper(); var server = new ServiceHost(typeof (CastDriverBridgeEmulatorImpl)); var endPoint = server.AddServiceEndpoint(contractType, binding, baseUrl); var behavior = new WebHttpBehavior(); behavior.FaultExceptionEnabled = false; behavior.HelpEnabled = true; behavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json; behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json; endPoint.Behaviors.Add(behavior); Console.WriteLine("Инициализация завершена."); Console.WriteLine("Запуск сервера..."); server.Open(); Console.WriteLine("Сервер запущен. Адрес сервера: {0}\nДля остановки нажмите Enter.", properties.host); Console.ReadLine(); Console.WriteLine("Остановка сервера..."); server.Close(); Console.WriteLine("Сервер остановлен."); Console.ReadLine(); }
/// <summary> /// Configures service endpoint and adds special behaviors to it (WebHttp and CorsSupport) /// </summary> protected override void OnOpening() { var securityMode = BaseAddresses.FirstOrDefault().Scheme == "https" ? WebHttpSecurityMode.Transport : WebHttpSecurityMode.None; var receiveTimeout = new TimeSpan(1, 0, 0); var defaultWebHttpBehavior = new WebHttpBehavior() { AutomaticFormatSelectionEnabled = true, DefaultBodyStyle = WebMessageBodyStyle.Wrapped, DefaultOutgoingRequestFormat = WebMessageFormat.Json, HelpEnabled = false }; var endPoint = new ServiceEndpoint( ContractDescription.GetContract(Description.ServiceType), new WebHttpBinding(securityMode) { UseDefaultWebProxy = false, ReceiveTimeout = receiveTimeout, MaxBufferSize = Config.MaxBufferSize, MaxReceivedMessageSize = Config.MaxReceivedMessageSize }, new EndpointAddress(BaseAddresses.FirstOrDefault()) ); endPoint.EndpointBehaviors.Add(defaultWebHttpBehavior); endPoint.EndpointBehaviors.Add(new CorsSupportBehavior()); endPoint.EndpointBehaviors.Add(new BrowserCompatibilityBehavior()); AddServiceEndpoint(endPoint); base.OnOpening(); }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8000/"); ServiceHost selfHost = new WebServiceHost(typeof(MonitorService), baseAddress); try { // Step 3 Add a service endpoint. var t = new WebHttpBinding(); selfHost.AddServiceEndpoint(typeof(IMonitorService), t, "test"); WebHttpBehavior whb = new WebHttpBehavior(); // Step 4 Enable metadata exchange. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); // Step 5 Start the service. selfHost.Open(); Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); selfHost.Abort(); } }
public QueryServiceHost(Uri address, object service) { host = new WebServiceHost(service); host.AddServiceEndpoint(typeof(IQueryService), new WebHttpBinding(), address); WebHttpBehavior behavior = new WebHttpBehavior(); host.Description.Endpoints[0].Behaviors.Add(behavior); }
public static ServiceHost GetServiceHost(Uri baseAddress) { ServiceHost host = new ServiceHost(typeof(KORTService), baseAddress); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService), GetBinding(), baseAddress); WebHttpBehavior httpBehavior = new WebHttpBehavior {DefaultBodyStyle = WebMessageBodyStyle.Bare }; endpoint.Behaviors.Add(httpBehavior); return host; }
public void AddBiningParameters () { var se = CreateEndpoint (); var b = new WebHttpBehavior (); var pl = new BindingParameterCollection (); b.AddBindingParameters (se, pl); Assert.AreEqual (0, pl.Count, "#1"); }
public void DefaultValues () { var b = new WebHttpBehavior (); Assert.AreEqual (WebMessageBodyStyle.Bare, b.DefaultBodyStyle, "#1"); Assert.AreEqual (WebMessageFormat.Xml, b.DefaultOutgoingRequestFormat, "#2"); Assert.AreEqual (WebMessageFormat.Xml, b.DefaultOutgoingResponseFormat, "#3"); Assert.IsFalse (b.AutomaticFormatSelectionEnabled, "#11"); Assert.IsFalse (b.FaultExceptionEnabled, "#12"); Assert.IsFalse (b.HelpEnabled, "#13"); }
public HelpPage(WebHttpBehavior behavior, ContractDescription description) { this.operationInfoDictionary = new Dictionary<string, OperationHelpInformation>(); this.operationPageCache = new NameValueCache<string>(); this.helpPageCache = new NameValueCache<string>(); foreach (OperationDescription od in description.Operations) { operationInfoDictionary.Add(od.Name, new OperationHelpInformation(behavior, od)); } }
static void Main(string[] args) { const String soapServiceEndpointAddress = "SOAP"; const String restServiceEndpointAddress = "REST"; Uri soapBaseAddress = new Uri("http://*****:*****@"C:\Temp\")) { Dictionary<string, OraclePermissionGeneratorDataInterfaceLayer> userDataRespository = new Dictionary<string, OraclePermissionGeneratorDataInterfaceLayer>(); SoapWebServiceApi soapApiInstance = new SoapWebServiceApi(userDataRespository, trackingDataLogger); RestWebServiceApi restApiInstance = new RestWebServiceApi(userDataRespository, trackingDataLogger); soapApiInstance.AddUser("*****@*****.**"); soapApiInstance.LoadDataModelFromFile("*****@*****.**", @"..\..\..\Resources\Tutorial 2.xml", @"..\..\..\Resources\ORACLE_PERMISSION_GENERATOR_CONFIG.xsd"); using (ServiceHost soapServiceHost = new ServiceHost(soapApiInstance, soapBaseAddress)) using (ServiceHost restServiceHost = new ServiceHost(restApiInstance, restBaseAddress)) { // Set SOAP service host settings ServiceMetadataBehavior soapServiceMetadataBehavior = new ServiceMetadataBehavior(); soapServiceMetadataBehavior.HttpGetEnabled = true; soapServiceMetadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; soapServiceHost.Description.Behaviors.Add(soapServiceMetadataBehavior); BasicHttpBinding soapBinding = new BasicHttpBinding(); ServiceEndpoint soapEndpoint = soapServiceHost.AddServiceEndpoint(typeof(ISoapWebServiceApi), soapBinding, soapServiceEndpointAddress); // Set single instance soapServiceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>().InstanceContextMode = InstanceContextMode.Single; // Turn on option to include exception in any web service interface errors soapServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; // Set REST service host settings ServiceMetadataBehavior restServiceMetadataBehavior = new ServiceMetadataBehavior(); restServiceMetadataBehavior.HttpGetEnabled = true; restServiceMetadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; restServiceHost.Description.Behaviors.Add(restServiceMetadataBehavior); WebHttpBinding restBinding = new WebHttpBinding(); ServiceEndpoint restEndpoint = restServiceHost.AddServiceEndpoint(typeof(IRestWebServiceApi), restBinding, restServiceEndpointAddress); WebHttpBehavior restBehavior = new WebHttpBehavior(); restEndpoint.Behaviors.Add(restBehavior); restServiceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>().InstanceContextMode = InstanceContextMode.Single; restServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; // Start the services soapServiceHost.Open(); restServiceHost.Open(); Console.WriteLine("Press [Enter] to stop the service."); Console.ReadLine(); restServiceHost.Close(); soapServiceHost.Close(); } } }
public WebMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior) { this.operation = operation; this.endpoint = endpoint; this.converter = converter; this.behavior = behavior; ApplyWebAttribute (); // This is a hack for WebScriptEnablingBehavior var jqc = converter as JsonQueryStringConverter; if (jqc != null) BodyName = jqc.CustomWrapperName; }
public static void OpenRESTfulTestHost() { ServiceHost host = new ServiceHost(typeof(RESTfulTest), new Uri("http://localhost:8088/")); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IRESTfulTest), new WebHttpBinding(), "restful"); WebHttpBehavior httpBehavior = new WebHttpBehavior(); endpoint.Behaviors.Add(httpBehavior); //ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); //behavior.HttpGetEnabled = true; //host.Description.Behaviors.Add(behavior); host.Open(); }
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { // Check security requirement. bool integratedSecurity = (Service.GetAuthenticationSchemes(baseAddresses[0]) & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.Anonymous; // Initialize host and binding. ServiceHost host = new ServiceHost(serviceType, baseAddresses); // Enable metadata publishing. ServiceMetadataBehavior serviceBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (serviceBehavior == null) { serviceBehavior = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.HttpGetEnabled = true; // Add REST endpoint. WebHttpBinding restBinding = new WebHttpBinding(); WebHttpBehavior restBehavior = new WebHttpBehavior(); ServiceEndpoint restEndpoint = host.AddServiceEndpoint(typeof(ISecurityService), restBinding, "rest"); if (integratedSecurity) { // Enable security on the binding. restBinding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly; restBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; } #if !MONO restBehavior.HelpEnabled = true; #endif restEndpoint.Behaviors.Add(restBehavior); // Add SOAP endpoint. BasicHttpBinding soapBinding = new BasicHttpBinding(); if (integratedSecurity) { // Enable security on the binding. soapBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; soapBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; } host.AddServiceEndpoint(typeof(ISecurityService), soapBinding, "soap"); host.AddServiceEndpoint(typeof(IMetadataExchange), soapBinding, "soap/mex"); return host; }
public static WebHost StartHost() { Trace.TraceInformation("Starting host.."); WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.None); ServiceEndpoint endPoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(BlocksOptimizationServices)), binding, new EndpointAddress(WebHostAdress)); WebHttpBehavior webBehavior = new WebHttpBehavior(); endPoint.Behaviors.Add(webBehavior); ServiceHost serviceHost = new ServiceHost(typeof(BlocksOptimizationServices)); serviceHost.AddServiceEndpoint(endPoint); serviceHost.Open(); Trace.TraceInformation("Service Host Started."); return new WebHost(serviceHost); }
public void ApplyDispatchBehavior () { var se = CreateEndpoint (); var od = se.Contract.Operations [0]; // in .NET 3.5 it adds "OperationSelectorBehavior" int initCB = ContractDescription.GetContract (typeof (IMyService)).Behaviors.Count; // in .NET 3.5 it adds // - OperationInvokeBehavior, // - OperationBehaviorAttribute, // - DataContractSerializerOperationBehavior and // - DataContractSerializerOperationGenerator int initOB = od.Behaviors.Count; // Assert.AreEqual (1, initCB, "#0-1"); // Assert.AreEqual (4, initOB, "#0-2"); var b = new WebHttpBehavior (); se.Behaviors.Add (b); var ed = new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace); IChannelListener l = new WebHttpBinding ().BuildChannelListener<IReplyChannel> (new BindingParameterCollection ()); var cd = new ChannelDispatcher (l); cd.Endpoints.Add (ed); // without it this test results in NRE (it blindly adds IErrorHandler). Assert.AreEqual (0, cd.ErrorHandlers.Count, "#1-1"); Assert.IsNull (ed.DispatchRuntime.OperationSelector, "#1-2"); Assert.AreEqual (1, se.Behaviors.Count, "#1-3-1"); Assert.AreEqual (initCB, se.Contract.Behaviors.Count, "#1-3-2"); Assert.AreEqual (initOB, od.Behaviors.Count, "#1-3-3"); Assert.IsTrue (ed.AddressFilter is EndpointAddressMessageFilter, "#1-4"); b.ApplyDispatchBehavior (se, ed); // FIXME: implement and enable it later //Assert.AreEqual (1, cd.ErrorHandlers.Count, "#2-1"); Assert.AreEqual (typeof (WebHttpDispatchOperationSelector), ed.DispatchRuntime.OperationSelector.GetType (), "#2-2"); Assert.AreEqual (1, se.Behaviors.Count, "#3-1"); Assert.AreEqual (initCB, se.Contract.Behaviors.Count, "#3-2"); Assert.AreEqual (initOB, od.Behaviors.Count, "#3-3"); // ... i.e. nothing is added. Assert.IsTrue (ed.AddressFilter is PrefixEndpointAddressMessageFilter, "#3-4"); Assert.AreEqual (0, ed.DispatchRuntime.Operations.Count, "#4-0"); // hmm... really? }
public UProveThreadWorkerProver() { WebHttpBinding binding = new WebHttpBinding(); UProveRestServiceProver instance = UProveRestServiceProver.Instance; _host = new WebServiceHost(instance, new Uri(ParseConfigManager.GetAddress(), ParseConfigManager.GetProverApiPath())); _serviceEndPoint = _host.AddServiceEndpoint(typeof(IUProveRestServiceProver), binding, ""); WebHttpBehavior enableHelp = new WebHttpBehavior(); enableHelp.HelpEnabled = true; enableHelp.DefaultOutgoingResponseFormat = WebMessageFormat.Json; enableHelp.DefaultOutgoingRequestFormat = WebMessageFormat.Json; _serviceEndPoint.EndpointBehaviors.Add(enableHelp); if (ParseConfigManager.SetupTimeProfiles()) { _serviceEndPoint.Behaviors.Add(new WcfTimeProfileEndPointLogger()); } }
public FormatSelectingMessageInspector(WebHttpBehavior webHttpBehavior, List<MultiplexingFormatMapping> mappings) { if (webHttpBehavior == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("webHttpBehavior"); } if (mappings == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("mappings"); } this.automaticFormatSelectionEnabled = webHttpBehavior.AutomaticFormatSelectionEnabled; this.formatters = new Dictionary<string, MultiplexingDispatchMessageFormatter>(); this.caches = new Dictionary<string, NameValueCache<FormatContentTypePair>>(); this.mappings = mappings; }
/// <summary> /// The create service host. /// </summary> /// <param name="serviceType"> /// The service type. /// </param> /// <param name="baseAddresses"> /// The base addresses. /// </param> /// <returns> /// The <see cref="ServiceHost"/>. /// </returns> protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { try { _log.DebugFormat("Creating REST service host for {0} for uri : {1}", serviceType, baseAddresses[0]); ServiceHost serviceHost = base.CreateServiceHost(serviceType, baseAddresses); var webBehavior = new WebHttpBehavior { AutomaticFormatSelectionEnabled = false, HelpEnabled = true, FaultExceptionEnabled = false, DefaultBodyStyle = WebMessageBodyStyle.Bare }; var binding = new WebHttpBinding { TransferMode = TransferMode.Streamed, ContentTypeMapper = new SdmxContentMapper()}; var endpoint = serviceHost.AddServiceEndpoint(this._type, binding, baseAddresses[0]); endpoint.Behaviors.Add(webBehavior); return serviceHost; } catch (Exception e) { _log.Error("While creating service host", e); throw; } }
static ServiceHost CreateService(Uri[] serviceAddresses, Type serviceType, Type serviceContract) { // Create ServiceHost var host = new ServiceHost(serviceType, serviceAddresses); // var host = new WebServiceHost(serviceType, serviceAddresses); // Add service endpoint(s) // http://wcftutorial.net/WCF-Types-of-Binding.aspx // host.AddServiceEndpoint(serviceContract, new WSHttpBinding(), "/ws"); // host.AddServiceEndpoint(serviceContract, new BasicHttpBinding(), "/basic"); // host.AddServiceEndpoint(serviceContract, new NetTcpBinding(), "/tcp"); // host.AddServiceEndpoint(serviceContract, new NetNamedPipeBinding(), "/pipe"); // host.AddServiceEndpoint(serviceContract, new NetPeerTcpBinding(), "/peer"); // host.AddServiceEndpoint(serviceContract, new WebHttpBinding(), "/web"); var endpoint = host.AddServiceEndpoint(serviceContract, new WebHttpBinding(), "/rest"); var webBehavior = new WebHttpBehavior { AutomaticFormatSelectionEnabled = true, DefaultBodyStyle = WebMessageBodyStyle.Bare, DefaultOutgoingRequestFormat = WebMessageFormat.Json, DefaultOutgoingResponseFormat = WebMessageFormat.Json, FaultExceptionEnabled = true, HelpEnabled = true }; endpoint.Behaviors.Add(webBehavior); /* */ // Enable metadata exchange var metadataBehavior = new ServiceMetadataBehavior { HttpGetEnabled = true }; // metadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(metadataBehavior); // Adding metadata exchange endpoint var mexBinding = MetadataExchangeBindings.CreateMexHttpBinding(); host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex"); return host; }
public static ServiceHost CreateServiceHost(ISimplexConfigUpdaterContract instance, Uri baseAddress) { ServiceHost service = new ServiceHost(instance, baseAddress); var contract = ContractDescription.GetContract(typeof(ISimplexConfigUpdaterContract)); var webBinding = new WebHttpBinding(); var webEndPoint = new ServiceEndpoint(contract, webBinding, new EndpointAddress(baseAddress)); WebHttpBehavior webBehaviour = new WebHttpBehavior(); webBehaviour.HelpEnabled = true; webEndPoint.EndpointBehaviors.Add(webBehaviour); service.AddServiceEndpoint(webEndPoint); // service.Description.Behaviors.Add(new ServiceMetadataBehavior()); //var metaBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); //metaBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.InheritedFromHost; //service.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); return service; }
public void Start() { if (_serviceHost != null) throw new InvalidOperationException("_serviceHost already started"); if (_automationController != null) throw new InvalidOperationException("_automationController already created"); InvokeTrace("building host..."); // build the service var phoneAutomationService = new PhoneAutomationService(); phoneAutomationService.Trace += (sender, args) => InvokeTrace(args); var serviceHost = new ServiceHost(phoneAutomationService, BindingAddress); // Enable metadata publishing var smb = new ServiceMetadataBehavior { HttpGetEnabled = true, MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 } }; serviceHost.Description.Behaviors.Add(smb); // build SOAP ServiceEndpoint serviceHost.AddServiceEndpoint( typeof(IPhoneAutomationService), GetHttpBinding(), BindingAddress + "/automate"); // build JSON ServiceEndpoint var jsonServiceEndpoint = serviceHost.AddServiceEndpoint( typeof(IPhoneAutomationService), GetWebHttpBinding(), BindingAddress + "/jsonAutomate"); var webHttpBehavior = new WebHttpBehavior() { DefaultOutgoingRequestFormat = WebMessageFormat.Json, DefaultOutgoingResponseFormat = WebMessageFormat.Json, DefaultBodyStyle = WebMessageBodyStyle.Wrapped }; jsonServiceEndpoint.Behaviors.Add(webHttpBehavior); // open the host InvokeTrace("opening host..."); serviceHost.Open(); InvokeTrace("host open"); _automationController = new PhoneAutomationController(phoneAutomationService, AutomationIdentification); _serviceHost = serviceHost; }
/// <summary> /// Initializes the <see cref="ServiceHost"/>. /// </summary> protected virtual void InitializeServiceHost() { if (m_serviceEnabled && !string.IsNullOrEmpty(m_endpoints)) { // Initialize service host. string serviceUri = GetServiceAddress(); if (m_singleton) m_serviceHost = new ServiceHost(this, new Uri(serviceUri)); else m_serviceHost = new ServiceHost(this.GetType(), new Uri(serviceUri)); // Enable metadata publishing. if (m_publishMetadata) { ServiceMetadataBehavior serviceBehavior = m_serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>(); if ((object)serviceBehavior == null) { serviceBehavior = new ServiceMetadataBehavior(); m_serviceHost.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.HttpGetEnabled = true; } // Enable security on the service. if (!string.IsNullOrEmpty(m_securityPolicy)) { ServiceAuthorizationBehavior serviceBehavior = m_serviceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); if ((object)serviceBehavior == null) { serviceBehavior = new ServiceAuthorizationBehavior(); m_serviceHost.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom; List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(); Type securityPolicyType = Type.GetType(m_securityPolicy); if ((object)securityPolicyType == null) throw new NullReferenceException(string.Format("Failed get security policy type '{0}' for self-hosting service - check config file settings.", m_securityPolicy.ToNonNullNorWhiteSpace("[undefined]"))); policies.Add((IAuthorizationPolicy)Activator.CreateInstance(securityPolicyType)); serviceBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly(); } // Add specified service endpoints. string serviceAddress; string[] serviceAddresses; Binding serviceBinding; ServiceEndpoint serviceEndpoint; serviceAddresses = m_endpoints.Split(';'); // Enable Windows Authentication if authorization policy is configured. if (!string.IsNullOrEmpty(m_securityPolicy)) m_windowsAuthentication = true; for (int i = 0; i < serviceAddresses.Length; i++) { serviceAddress = serviceAddresses[i].Trim(); serviceBinding = Service.CreateServiceBinding(ref serviceAddress, m_windowsAuthentication); if ((object)serviceBinding == null) continue; Type contractInterfaceType = Type.GetType(m_contractInterface); if ((object)contractInterfaceType == null) throw new NullReferenceException(string.Format("Failed to get contract interface type '{0}' for self-hosting service - check config file settings.", m_contractInterface.ToNonNullNorWhiteSpace("[undefined]"))); serviceEndpoint = m_serviceHost.AddServiceEndpoint(contractInterfaceType, serviceBinding, serviceAddress); if (serviceBinding is WebHttpBinding) { // Special handling for REST endpoint. WebHttpBehavior restBehavior = new WebHttpBehavior(); #if !MONO if (m_publishMetadata) restBehavior.HelpEnabled = true; #endif serviceEndpoint.Behaviors.Add(restBehavior); } else if (m_publishMetadata) { // Add endpoint for service metadata. if (serviceAddress.StartsWith("http://")) m_serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), serviceAddress + "/mex"); else if (serviceAddress.StartsWith("net.tcp://")) m_serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), serviceAddress + "/mex"); else if (serviceAddress.StartsWith("net.pipe://")) m_serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexNamedPipeBinding(), serviceAddress + "/mex"); } } // Enable cross domain access. if (m_allowCrossDomainAccess) m_serviceHost.AddServiceEndpoint(typeof(IPolicyRetriever), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); // Allow for customization. OnServiceHostCreated(); // Start the service. m_serviceHost.Open(); OnServiceHostStarted(); } }
public WebErrorHandler(WebHttpBehavior webHttpBehavior, ContractDescription contractDescription, bool includeExceptionDetailInFaults) { this.webHttpBehavior = webHttpBehavior; this.contractDescription = contractDescription; this.includeExceptionDetailInFaults = includeExceptionDetailInFaults; }
protected override WISE_RESULT OnCreateDatabase(string strDatabaseName, DatabaseHandle hDatabase, DatabaseHandle hTemplateDatabase, DatabaseDistType eDatabaseDistType, DatabaseType eDatabaseType, OwnershipMode eModeOwnership, AttributeQualityMode eModeAttributeQuality, AttributeTimeMode eModeAttributeTime) { WISE_RESULT result = WISEError.WISE_OK; // Call base class implementation result = base.OnCreateDatabase(strDatabaseName, hDatabase, hTemplateDatabase, eDatabaseDistType, eDatabaseType, eModeOwnership, eModeAttributeQuality, eModeAttributeTime); WISEError.CheckCallFailedEx(result); if (eDatabaseType == DatabaseType.Application) { // // TODO: Open driver communication for the specified database. // Uri baseAddress = new Uri(string.Format("{0}:{1}", _baseAddress, _port)); IService service = new Service(this.WISE, hDatabase); _serviceHost = new WebServiceHost(service, baseAddress); ServiceEndpoint serviceEndpoint = _serviceHost.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), ""); WebHttpBehavior webHttpBehavior = _serviceHost.Description.Behaviors.Find<WebHttpBehavior>(); if (webHttpBehavior != null) { webHttpBehavior.AutomaticFormatSelectionEnabled = true; } else { WebHttpBehavior webBehavior = new WebHttpBehavior(); webBehavior.AutomaticFormatSelectionEnabled = true; serviceEndpoint.Behaviors.Add(webBehavior); } // // Enable metadata // //ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior(); //metadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; //metadataBehavior.HttpGetEnabled = true; //_serviceHost.Description.Behaviors.Add(metadataBehavior); //_serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), //MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); //WebHttpBinding webHttpBinding = new WebHttpBinding(); //webHttpBinding. //_serviceHost.AddServiceEndpoint(typeof(IService), webHttpBinding, ""); // Initialize generated code. // TODO: handle error code Model.InitializeModel(this.WISE); _serviceHost.Open(); } return WISEError.WISE_OK; }
private static void RegisterWcfServices() { WebHttpBinding basicHttpBinding = new WebHttpBinding(); basicHttpBinding.MaxReceivedMessageSize = 100000000; basicHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1); basicHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1); basicHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10); basicHttpBinding.SendTimeout = TimeSpan.FromMinutes(10); basicHttpBinding.ReaderQuotas.MaxArrayLength = 100000000; basicHttpBinding.ReaderQuotas.MaxBytesPerRead = 100000000; basicHttpBinding.ReaderQuotas.MaxStringContentLength = 100000000; basicHttpBinding.TransferMode = TransferMode.Streamed; List<Type> types = new List<Type>(); //types.Add(typeof(PhoneManager)); types.Add(typeof(HelloService)); //types.Add(typeof(ASC.BusinessLogic.ManagerClasses.IPhoneMemberShipManager)); //types.Add(typeof(ASC.BusinessLogic.ManagerClasses.IPhoneStockListEqueryManager)); foreach (Type type in types) { string serviceName = string.Empty; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { object[] attributes = interfaceType.GetCustomAttributes(typeof(ServiceContractAttribute), true); if (attributes.Length > 0) { ServiceHost host = null; host = new ServiceHost(type, new Uri[] { new Uri(string.Format("http://localhost:{0}/{1}", 5295, type.Name)) }); ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (smb == null) { smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(smb); } else { smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; } //host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); //host.AddServiceEndpoint(interfaceType, basicHttpBinding, ""); WebHttpBehavior webHttpBehavior = new WebHttpBehavior(); ServiceEndpoint endpoint = host.AddServiceEndpoint(interfaceType, basicHttpBinding, ""); endpoint.Behaviors.Add(webHttpBehavior); //AssignServiceBehaviorParameter<ServiceDebugBehavior>(host, "IncludeExceptionDetailInFaults", true); //AssignServiceBehaviorParameter<ServiceThrottlingBehavior>(host, "MaxConcurrentCalls", Int32.MaxValue); //AssignServiceBehaviorParameter<ServiceThrottlingBehavior>(host, "MaxConcurrentInstances", Int32.MaxValue); //AssignServiceBehaviorParameter<ServiceThrottlingBehavior>(host, "MaxConcurrentSessions", Int32.MaxValue); host.Open(); } } } }
void ThreadMain() { CloseHosts(); for (int i = 0; ; i++) { string strInstanceName = ""; string strDataDir = ""; string strCertSN = ""; string[] existing_urls = null; string strSerialNumber = ""; bool bRet = GetInstanceInfo("dp2Library", i, out strInstanceName, out strDataDir, out existing_urls, out strCertSN, out strSerialNumber); if (bRet == false) break; int nMaxClients = 0; string strLicenseType = ""; #if SN //string strLocalString = OneInstanceDialog.GetEnvironmentString(strSerialNumber, strInstanceName); //string strSha1 = Cryptography.GetSHA1(StringUtil.SortParams(strLocalString) + "_reply"); if (String.IsNullOrEmpty(strSerialNumber) == true) { nMaxClients = SessionInfo.DEFAULT_MAX_CLIENTS; } else { string strDebugInfo = ""; if (MatchLocalString(strSerialNumber, strInstanceName, out strDebugInfo) == false) //if (strSha1 != SerialCodeForm.GetCheckCode(strSerialNumber)) { this.Log.WriteEntry("dp2Library 实例 '"+strInstanceName+"' 序列号不合法,无法启动。\r\n调试信息如下:\r\n" + strDebugInfo, EventLogEntryType.Error); continue; } string strMaxClients = GetMaxClients(strSerialNumber); // 2015/1/7 if (string.IsNullOrEmpty(strMaxClients) == true) nMaxClients = SessionInfo.DEFAULT_MAX_CLIENTS; else { if (Int32.TryParse(strMaxClients, out nMaxClients) == false) { this.Log.WriteEntry("dp2Library 实例 '" + strInstanceName + "' 序列号 '" + strSerialNumber + "' 中 clients 参数值 '" + strMaxClients + "' 不合法,无法启动", EventLogEntryType.Error); continue; } } strLicenseType = GetLicenseType(strSerialNumber); } #else nMaxClients = 100; strLicenseType = "server"; #endif ServiceHost host = new ServiceHost(typeof(LibraryService)); this.m_hosts.Add(host); HostInfo info = new HostInfo(); info.DataDir = strDataDir; info.MaxClients = nMaxClients; info.LicenseType = strLicenseType; host.Extensions.Add(info); /// bool bHasWsHttp = false; // 绑定协议 foreach (string url in existing_urls) { if (string.IsNullOrEmpty(url) == true) continue; Uri uri = null; try { uri = new Uri(url); } catch (Exception ex) { this.Log.WriteEntry("dp2Library OnStart() 警告:发现不正确的协议URL '" + url + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。", EventLogEntryType.Error); continue; } if (uri.Scheme.ToLower() == "http") { ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryService), CreateWsHttpBinding1(), url); bHasWsHttp = true; } else if (uri.Scheme.ToLower() == "rest.http") { ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryServiceREST), CreateWebHttpBinding1(), url.Substring(5)); if (endpoint.Behaviors.Find<WebHttpBehavior>() == null) { WebHttpBehavior behavior = new WebHttpBehavior(); behavior.DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped; behavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json; behavior.AutomaticFormatSelectionEnabled = true; behavior.HelpEnabled = true; endpoint.Behaviors.Add(behavior); } } else if (uri.Scheme.ToLower() == "basic.http") { ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryServiceREST), CreateBasicHttpBinding1(), url.Substring(6)); #if NO if (endpoint.Behaviors.Find<WebHttpBehavior>() == null) { WebHttpBehavior behavior = new WebHttpBehavior(); behavior.DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped; behavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json; behavior.AutomaticFormatSelectionEnabled = true; behavior.HelpEnabled = true; endpoint.Behaviors.Add(behavior); } #endif } else if (uri.Scheme.ToLower() == "net.pipe") { host.AddServiceEndpoint(typeof(ILibraryService), CreateNamedpipeBinding0(), url); } else if (uri.Scheme.ToLower() == "net.tcp") { host.AddServiceEndpoint(typeof(ILibraryService), CreateNetTcpBinding0(), url); } else { // 警告不能支持的协议 this.Log.WriteEntry("dp2Library OnStart() 警告:发现不能支持的协议类型 '" + url + "'", EventLogEntryType.Information); } info.Protocol = uri.Scheme.ToLower(); } // 如果具有ws1/ws2 binding,才启用证书 if (bHasWsHttp == true) { try { string strError = ""; X509Certificate2 cert = GetCertificate(strCertSN, out strError); if (cert == null) this.Log.WriteEntry("dp2Library OnStart() 准备证书 时发生错误: " + strError, EventLogEntryType.Error); else host.Credentials.ServiceCertificate.Certificate = cert; } catch (Exception ex) { this.Log.WriteEntry("dp2Library OnStart() 获取证书时发生错误: " + ExceptionUtil.GetExceptionMessage(ex), EventLogEntryType.Error); return; } } // 只有第一个host才有metadata能力 if (i == 0 && host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null) { string strWsHostUrl = FindUrl("http", existing_urls); string strMetadataUrl = strWsHostUrl; if (String.IsNullOrEmpty(strMetadataUrl) == true) strMetadataUrl = "http://localhost:8001/dp2library/"; if (strMetadataUrl[strMetadataUrl.Length - 1] != '/') strMetadataUrl += "/"; strMetadataUrl += "metadata"; ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri(strMetadataUrl); host.Description.Behaviors.Add(behavior); } if (host.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null) { ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior(); behavior.MaxConcurrentCalls = 50; behavior.MaxConcurrentInstances = 1000; behavior.MaxConcurrentSessions = 1000; host.Description.Behaviors.Add(behavior); } // IncludeExceptionDetailInFaults ServiceDebugBehavior debug_behavior = host.Description.Behaviors.Find<ServiceDebugBehavior>(); if (debug_behavior == null) { host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true }); } else { if (debug_behavior.IncludeExceptionDetailInFaults == false) debug_behavior.IncludeExceptionDetailInFaults = true; } #if NO host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom; host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new MyValidator(); #endif host.Opening += new EventHandler(host_Opening); host.Closing += new EventHandler(m_host_Closing); try { host.Open(); } catch (Exception ex) { // 让调试器能感觉到 if (this.m_bConsoleRun == true) throw ex; this.Log.WriteEntry("dp2Library OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ExceptionUtil.GetExceptionMessage(ex), EventLogEntryType.Error); return; } } this.Log.WriteEntry("dp2Library OnStart() end", EventLogEntryType.Information); this.m_thread = null; }
private void AddDefaultBehaviors() { ModuleProc PROC = new ModuleProc("WcfWebServiceHostBase", "AddDefaultBehaviors"); try { foreach (ServiceEndpoint sep in this.Description.Endpoints) { try { if (sep.Binding.GetType() == typeof(WebHttpBinding)) { WebHttpBehavior httpBehavior = sep.Behaviors.Find<WebHttpBehavior>(); if (httpBehavior == null) { httpBehavior = new WebHttpBehavior(); sep.Behaviors.Add(httpBehavior); } httpBehavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json; } } catch (Exception ex) { Log.Exception(PROC, ex); } } } catch (Exception ex) { Log.Exception(PROC, ex); } }
private static void StartHttpService(string serviceAddress) { var baseAddress = new Uri(serviceAddress); _serviceHost?.Close(); _tsAnalyserApi = new TsAnalyserApi { NetworkMetric = _networkMetric, TsMetrics = _pidMetrics, RtpMetric = _rtpMetric }; _tsAnalyserApi.StreamCommand += _tsAnalyserApi_StreamCommand; _serviceHost = new ServiceHost(_tsAnalyserApi, baseAddress); var webBinding = new WebHttpBinding(); var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(ITsAnalyserApi))) { Binding = webBinding, Address = new EndpointAddress(baseAddress) }; _serviceHost.AddServiceEndpoint(serviceEndpoint); var webBehavior = new WebHttpBehavior { AutomaticFormatSelectionEnabled = true, DefaultOutgoingRequestFormat = WebMessageFormat.Json, HelpEnabled = true }; serviceEndpoint.Behaviors.Add(webBehavior); //TODO: Trying to disable MEX, to allow serving of index when visiting root... //Metadata Exchange //var serviceBehavior = new ServiceMetadataBehavior {HttpGetEnabled = true}; //_serviceHost.Description.Behaviors.AddData(serviceBehavior); try { _serviceHost.Open(); } catch (Exception ex) { var msg = "Failed to start local web API for player - either something is already using the requested URL, the tool is not running as local administrator, or netsh url reservations have not been made " + "to allow non-admin users to host services.\n\n" + "To make a URL reservation, permitting non-admin execution, run:\n" + "netsh http add urlacl http://+:8124/ user=BUILTIN\\Users\n\n" + "This is the details of the exception thrown:" + ex.Message + "\n\nHit enter to continue without services.\n\n"; Console.WriteLine(msg); Console.ReadLine(); LogMessage(msg); } }
public ReplyDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior) : base (operation, endpoint, converter, behavior) { }
protected WebDispatchMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior) : base (operation, endpoint, converter, behavior) { }
protected void StartService() { Dictionary<string, string> configs = ConfigHelper.GetPluginSpecificConfig (PluginName); // wenn ein zweiter Port vorhanden ist, kann eine zweite Instanz gestartet werden int instances = configs.ContainsKey ("2ndPort") ? 2 : 1; string[] prefixes = new string[] { "", "2nd" }; // TODO: Dynamisch Anzahl und Art der Prefixes herausfinden; momentan sind die Werte fix (max 2 Prefixes/Instanzen, einmal "" und einmal "2nd") try { for (int instance = 1; instance <= instances; instance++) { String authMethod = ConfigHelper.GetInstanceParam (configs, "AuthenticationMethod", prefixes, instance); ServiceSecurity serviceSecurity = new ServiceSecurity (authMethod); Uri uri = new Uri (serviceSecurity.HTTP_S + "://" + _address + ":" + _port + "/" + _uriPattern + "/REST"); if (!uri.IsWellFormedOriginalString ()) { throw new Exception ("The URI Pattern is not well formed!"); } _uris.Add (uri); ServiceHost host = new ServiceHost (_service, uri) { CloseTimeout = new TimeSpan (0, 0, 0, 0, 50) }; _hosts.Add (host); var binding = new WebHttpBinding { MaxReceivedMessageSize = 268435456, SendTimeout = new TimeSpan (1, 0, 0), ReceiveTimeout = new TimeSpan (1, 0, 0), // für Security: Anhand des Binding-Namens wird eruiert, welche ConfigSection & Prefix für diese ServiceBinding-Instanz genutzt werden soll Name = PluginName + "." + prefixes [instance - 1] }; binding.Security.Mode = serviceSecurity.BindingSecurityMode; binding.Security.Transport.ClientCredentialType = serviceSecurity.BindingClientCredentialType; var readerQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 2147483647, MaxStringContentLength = 2147483647, MaxBytesPerRead = 2147483647, MaxNameTableCharCount = 2147483647, MaxArrayLength = 2147483647 }; binding.ReaderQuotas = readerQuotas; var se = host.AddServiceEndpoint (RESTServiceInterfaceType, binding, uri); var webBehav = new WebHttpBehavior { FaultExceptionEnabled = true, HelpEnabled = true }; se.Behaviors.Add (webBehav); // this adds a additional instanceId header to every response se.Behaviors.Add (new FaultTolerantServiceBehavior ()); ((ServiceBehaviorAttribute)host.Description.Behaviors [typeof(ServiceBehaviorAttribute)]).InstanceContextMode = InstanceContextMode.Single; } } catch (Exception) { _hosts.ForEach (h => h.Abort ()); throw; } }