/// <summary> /// Incluir um serviço (Wcf) /// </summary> /// <param name="servico">Serviço a ser incluído</param> public static void IncluirCanalWcfHost(ServiceType servico) { try { // Endereço string enderecoTmp = string.Format("net.tcp://{0}:{1}/PointBlankCore/{2}", WcfNetwork.ConexaoEndereco, WcfNetwork.ConexaoPorta, servico.GetServiceType(false).Name); // Instânciar um host para o serviço ServiceHost host = new ServiceHost(servico.GetServiceType(false), new Uri[] { new Uri(enderecoTmp) }); ServiceBehaviorAttribute serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); serviceBehavior.IncludeExceptionDetailInFaults = true; // Controle endpoint host.AddServiceEndpoint(servico.GetServiceType(true), WcfNetwork.ObterNovoNetTcpBinding(), enderecoTmp); host.Description.Behaviors.Add(new ServiceThrottlingBehavior() { MaxConcurrentCalls = int.MaxValue, MaxConcurrentInstances = int.MaxValue, MaxConcurrentSessions = int.MaxValue }); // Abrir o serviço host.Open(); // Atualizar lista de controle WcfNetwork.ListaServiceHost.Add(host); } catch (AddressAlreadyInUseException) { throw new PointBlankException(string.Format("A porta {0} já está em uso. Verifique senão foi iniciado um outro serviço na mesma", WcfNetwork.ConexaoPorta)); } }
static void Main(string[] args) { // .\SvcUtil.exe /d:D\ /a /o:D:\Clients.cs /config: D:\App.config net.tcp://localhost:8888 using (ServiceHost host = new ServiceHost(typeof(TestSvc), new Uri("net.tcp://localhost:8888"))) { ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITestSvc), new NetTcpBinding(), "TestService"); endpoint.Contract.SessionMode = SessionMode.Allowed;//会话 ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(metadataBehavior); ServiceBehaviorAttribute serviceBehaviorAttribute = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); if (serviceBehaviorAttribute == null) { serviceBehaviorAttribute = new ServiceBehaviorAttribute(); } serviceBehaviorAttribute.ConcurrencyMode = ConcurrencyMode.Single;//并发 serviceBehaviorAttribute.InstanceContextMode = InstanceContextMode.PerCall; host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); host.Open(); Console.WriteLine("服务开始。。。"); Console.ReadLine(); } }
/// <summary> /// Запустить WCF-службу для взаимодействия с агентом /// </summary> private bool StartWcfService() { try { agentSvcHost = new ServiceHost(typeof(AgentSvc)); ServiceBehaviorAttribute behavior = agentSvcHost.Description.Behaviors.Find <ServiceBehaviorAttribute>(); behavior.ConcurrencyMode = ConcurrencyMode.Multiple; behavior.InstanceContextMode = InstanceContextMode.Single; behavior.UseSynchronizationContext = false; agentSvcHost.Open(); string serviceUrl = agentSvcHost.BaseAddresses.Count > 0 ? agentSvcHost.BaseAddresses[0].AbsoluteUri : ""; log.WriteAction(string.Format(Localization.UseRussian ? "WCF-служба запущена по адресу {0}" : "WCF service is started at {0}", serviceUrl)); return(true); } catch (Exception ex) { log.WriteException(ex, Localization.UseRussian ? "Ошибка при запуске WCF-службы" : "Error starting WCF service"); return(false); } }
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase host) { ServiceBehaviorAttribute behavior = description.Behaviors.Find <ServiceBehaviorAttribute>(); behavior.ReleaseServiceInstanceOnTransactionComplete = false; DurableServiceAttribute durable = new DurableServiceAttribute(); durable.SaveStateInOperationTransaction = true; description.Behaviors.Add(durable); PersistenceProviderFactory factory = new TransactionalMemoryProviderFactory(); PersistenceProviderBehavior persistenceBehavior = new PersistenceProviderBehavior(factory); description.Behaviors.Add(persistenceBehavior); if (m_TransactionRequiredAllOperations) { foreach (ServiceEndpoint endpoint in description.Endpoints) { foreach (OperationDescription operation in endpoint.Contract.Operations) { operation.Behaviors.Find <OperationBehaviorAttribute>().TransactionScopeRequired = true; } } } }
void ValidateAutoCompleteFalseRequirements(ServiceDescription service, ServiceEndpoint endpoint) { OperationDescription autoCompleteFalseOperation = GetAutoCompleteFalseOperation(endpoint); if (autoCompleteFalseOperation != null) { // Does the service have InstanceContextMode.PerSession or Shareable? ServiceBehaviorAttribute serviceBehavior = service.Behaviors.Find <ServiceBehaviorAttribute>(); if (serviceBehavior != null) { InstanceContextMode instanceMode = serviceBehavior.InstanceContextMode; if (instanceMode != InstanceContextMode.PerSession) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxTransactionAutoCompleteFalseAndInstanceContextMode, endpoint.Contract.Name, autoCompleteFalseOperation.Name))); } } // Does the binding support sessions? if (!autoCompleteFalseOperation.IsInsideTransactedReceiveScope) { if (!RequiresSessions(endpoint)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxTransactionAutoCompleteFalseAndSupportsSession, endpoint.Contract.Name, autoCompleteFalseOperation.Name))); } } } }
public static ServiceHost GetServiceHost(RichTextBox newsTextBox, Statistics statistics) { if (TerminalService.newsTextBox != null) { throw new InvalidOperationException("Cannot create multiple TerminalService hosts."); } TerminalService.newsTextBox = newsTextBox; TerminalService.statistics = statistics; var host = new ServiceHost(typeof(TerminalService), Uri); #if DEBUG var bhv = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); if (bhv == null) { host.Description.Behaviors.Add(bhv = new ServiceBehaviorAttribute()); } bhv.IncludeExceptionDetailInFaults = true; var mta = host.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (mta == null) { host.Description.Behaviors.Add(mta = new ServiceMetadataBehavior()); } mta.HttpGetEnabled = true; #endif host.Open(); return(host); }
void ValidateServiceBehaviorAttributeWithNoScopeRequired(ServiceDescription service) { // If the service has no operations with TransactionScopeRequired=true, disallow any // transaction-related properties on the ServiceBehaviorAttribute if (!HasTransactedOperations(service)) { ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>(); if (attribute != null) { if (attribute.TransactionTimeoutSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxTransactionTransactionTimeoutNeedsScope, service.Name))); } if (attribute.IsolationLevelSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxTransactionIsolationLevelNeedsScope, service.Name))); } if (attribute.ReleaseServiceInstanceOnTransactionCompleteSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxTransactionReleaseServiceInstanceOnTransactionCompleteNeedsScope, service.Name))); } if (attribute.TransactionAutoCompleteOnSessionCloseSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxTransactionTransactionAutoCompleteOnSessionCloseNeedsScope, service.Name))); } } } }
private void ValidateServiceBehaviorAttributeWithNoScopeRequired(System.ServiceModel.Description.ServiceDescription service) { if (!this.HasTransactedOperations(service)) { ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>(); if (attribute != null) { if (attribute.TransactionTimeoutSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxTransactionTransactionTimeoutNeedsScope", new object[] { service.Name }))); } if (attribute.IsolationLevelSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxTransactionIsolationLevelNeedsScope", new object[] { service.Name }))); } if (attribute.ReleaseServiceInstanceOnTransactionCompleteSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxTransactionReleaseServiceInstanceOnTransactionCompleteNeedsScope", new object[] { service.Name }))); } if (attribute.TransactionAutoCompleteOnSessionCloseSet) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxTransactionTransactionAutoCompleteOnSessionCloseNeedsScope", new object[] { service.Name }))); } } } }
static void AddBehaviors(ServiceDescription serviceDescription) { Type type = serviceDescription.ServiceType; System.ServiceModel.Description.TypeLoader.ApplyServiceInheritance <IServiceBehavior, KeyedByTypeCollection <IServiceBehavior> >( type, serviceDescription.Behaviors, ServiceDescription.GetIServiceBehaviorAttributes); ServiceBehaviorAttribute serviceBehavior = EnsureBehaviorAttribute(serviceDescription); if (serviceBehavior.Name != null) { serviceDescription.Name = new XmlName(serviceBehavior.Name).EncodedName; } if (serviceBehavior.Namespace != null) { serviceDescription.Namespace = serviceBehavior.Namespace; } if (String.IsNullOrEmpty(serviceBehavior.ConfigurationName)) { serviceDescription.ConfigurationName = type.FullName; } else { serviceDescription.ConfigurationName = serviceBehavior.ConfigurationName; } AspNetEnvironment.Current.EnsureCompatibilityRequirements(serviceDescription); }
/// <summary> /// Constructor: Starts the Web service /// </summary> public WebService() { //Define SSL endpoint String address = "localhost"; UriBuilder uriBuilder = new UriBuilder(Uri.UriSchemeHttps, address, 443, "/FileService"); _serviceHost = new ServiceHost(typeof(FileService), uriBuilder.Uri); //Create a Basic binding with Windows authentication BasicHttpBinding binding = new BasicHttpBinding(); binding.Security.Mode = BasicHttpSecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; _serviceHost.AddServiceEndpoint(typeof(IFileService), binding, uriBuilder.Uri); ServiceBehaviorAttribute sba = _serviceHost.Description.Behaviors.Find <ServiceBehaviorAttribute>(); if (sba == null) { sba = new ServiceBehaviorAttribute(); } sba.InstanceContextMode = InstanceContextMode.Single; ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior(); serviceMetadataBehavior.HttpsGetEnabled = true; _serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); }
/// <summary> /// 启动服务 /// </summary> private void OpenWCFServer() { WSHttpBinding wsHttp = new WSHttpBinding(); wsHttp.MaxBufferPoolSize = 524288; wsHttp.MaxReceivedMessageSize = 2147483647; wsHttp.ReaderQuotas.MaxArrayLength = 6553600; wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647; wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600; wsHttp.ReaderQuotas.MaxDepth = 6553600; wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600; wsHttp.CloseTimeout = new TimeSpan(0, 1, 0); wsHttp.OpenTimeout = new TimeSpan(0, 1, 0); wsHttp.ReceiveTimeout = new TimeSpan(0, 10, 0); wsHttp.SendTimeout = new TimeSpan(0, 10, 0); wsHttp.Security.Mode = SecurityMode.None; Uri baseAddress = new Uri("http://127.0.0.1:9999/wcfserver"); ServiceHost host = new ServiceHost(typeof(WCFServer), baseAddress); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); ServiceBehaviorAttribute sba = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); sba.MaxItemsInObjectGraph = 2147483647; host.AddServiceEndpoint(typeof(IWCFServer), wsHttp, ""); host.Open(); }
private void ValidateConfigInstanceSettings(System.ServiceModel.Description.ServiceDescription service) { ServiceBehaviorAttribute attribute = this.EnsureBehaviorAttribute(service); foreach (ServiceEndpoint endpoint in service.Endpoints) { if ((endpoint != null) && !endpoint.InternalIsSystemEndpoint(service)) { if (endpoint.Contract.SessionMode == SessionMode.Required) { if (attribute.InstanceContextMode == InstanceContextMode.PerCall) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.InconsistentSessionRequirements()); } attribute.InstanceContextMode = InstanceContextMode.PerSession; } else { if (attribute.InstanceContextMode == InstanceContextMode.PerSession) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.InconsistentSessionRequirements()); } attribute.InstanceContextMode = InstanceContextMode.PerCall; } } } if (attribute.InstanceContextMode == InstanceContextMode.Single) { attribute.InstanceContextMode = InstanceContextMode.PerSession; } }
public string GetInstanceContextMode() { // Return the InstanceContextMode of the service ServiceHost host = (ServiceHost)OperationContext.Current.Host; ServiceBehaviorAttribute behavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); return(behavior.InstanceContextMode.ToString()); }
private static ServiceHost agentSvcHost; // хост WCF-службы для взаимодействия с агентом /// <summary> /// Запустить WCF-службу для взаимодействия с агентом /// </summary> private static bool StartWcfService(out string serviceUrl) { try { agentSvcHost = new ServiceHost(typeof(AgentSvc)); ServiceBehaviorAttribute behavior = agentSvcHost.Description.Behaviors.Find <ServiceBehaviorAttribute>(); behavior.InstanceContextMode = InstanceContextMode.Single; behavior.UseSynchronizationContext = false; agentSvcHost.Open(); serviceUrl = agentSvcHost.BaseAddresses.Count > 0 ? agentSvcHost.BaseAddresses[0].AbsoluteUri : ""; //Log.WriteAction(Localization.UseRussian ? // "WCF-служба запущена" : // "WCF service is started"); Console.WriteLine("WCF service is started"); return(true); } catch (Exception ex) { //Log.WriteException(ex, Localization.UseRussian ? // "Ошибка при запуске WCF-службы" : // "Error starting WCF service"); Console.WriteLine(ex.ToString()); serviceUrl = ""; return(false); } }
void AddBehaviors(ServiceDescription service) { // The philosophy here is to respect settings from configuration // At the moment, none of the settings we care about can be modified // through configuration. That may change in the future. // However, we never want to silently overwrite a user's configuration. // So we should either accept overrides or reject them, but never // silently update them. // ServiceBehaviorAttribute serviceBehavior = EnsureBehaviorAttribute(service); serviceBehavior.InstanceProvider = new ComPlusInstanceProvider(this.info); serviceBehavior.InstanceContextMode = InstanceContextMode.Single; // SHOULD: There is no reason to not allow concurrency at this level serviceBehavior.ConcurrencyMode = ConcurrencyMode.Multiple; serviceBehavior.UseSynchronizationContext = false; service.Behaviors.Add(new SecurityCookieModeValidator()); if (AspNetEnvironment.Enabled) { AspNetCompatibilityRequirementsAttribute aspNetCompatibilityRequirements = service.Behaviors.Find <AspNetCompatibilityRequirementsAttribute>(); if (aspNetCompatibilityRequirements == null) { aspNetCompatibilityRequirements = new AspNetCompatibilityRequirementsAttribute(); service.Behaviors.Add(aspNetCompatibilityRequirements); } } }
/// <summary> /// Запустить WCF-службы /// </summary> private bool StartWCF() { try { ScadaSchemeSvc schemeSvc = new ScadaSchemeSvc(); schemeSvcHost = new ServiceHost(schemeSvc); ServiceBehaviorAttribute behavior = schemeSvcHost.Description.Behaviors.Find <ServiceBehaviorAttribute>(); behavior.InstanceContextMode = InstanceContextMode.Single; behavior.UseSynchronizationContext = false; schemeSvcHost.Open(); domainSvcHost = new ServiceHost(typeof(CrossDomainSvc)); domainSvcHost.Open(); return(true); } catch (Exception ex) { log.WriteAction("Ошибка при запуске WCF-служб: " + ex.Message, Log.ActTypes.Exception); ScadaUtils.ShowError( "Ошибка при запуске служб обмена данными.\nНормальная работа программы невозможна."); return(false); } }
internal static void AddBehaviors <TService>(ServiceDescription serviceDescription) where TService : class { TypeLoader <TService> .ApplyServiceInheritance <IServiceBehavior, KeyedByTypeCollection <IServiceBehavior> >( serviceDescription.Behaviors, GetIServiceBehaviorAttributes); ServiceBehaviorAttribute serviceBehavior = EnsureBehaviorAttribute(serviceDescription); if (serviceBehavior.Name != null) { serviceDescription.Name = new XmlName(serviceBehavior.Name).EncodedName; } if (serviceBehavior.Namespace != null) { serviceDescription.Namespace = serviceBehavior.Namespace; } if (string.IsNullOrEmpty(serviceBehavior.ConfigurationName)) { serviceDescription.ConfigurationName = typeof(TService).FullName; } else { serviceDescription.ConfigurationName = serviceBehavior.ConfigurationName; } }
public static void EnableIncludeExceptionInFaultBehavior(this ServiceHost host) { ServiceBehaviorAttribute debuggingBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); debuggingBehavior.IncludeExceptionDetailInFaults = true; }
/// <summary> /// Запустить WCF-службу для взаимодействия с веб-интерфейсом /// </summary> private bool StartWcfService(out string serviceUrl) { try { schemeEditorSvcHost = new ServiceHost(typeof(SchemeEditorSvc)); ServiceBehaviorAttribute behavior = schemeEditorSvcHost.Description.Behaviors.Find <ServiceBehaviorAttribute>(); behavior.InstanceContextMode = InstanceContextMode.Single; behavior.UseSynchronizationContext = false; schemeEditorSvcHost.Open(); serviceUrl = schemeEditorSvcHost.BaseAddresses.Count > 0 ? schemeEditorSvcHost.BaseAddresses[0].AbsoluteUri : ""; Log.WriteAction(Localization.UseRussian ? "WCF-служба запущена" : "WCF service is started"); return(true); } catch (Exception ex) { Log.WriteException(ex, Localization.UseRussian ? "Ошибка при запуске WCF-службы" : "Error starting WCF service"); serviceUrl = ""; return(false); } }
private void ValidateNotConcurrentWhenReleaseServiceInstanceOnTxComplete(System.ServiceModel.Description.ServiceDescription service) { ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>(); if (((attribute != null) && this.HasTransactedOperations(service)) && (attribute.ReleaseServiceInstanceOnTransactionComplete && !this.IsSingleThreaded(service))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxTransactionNonConcurrentOrReleaseServiceInstanceOnTxComplete", new object[] { service.Name }))); } }
private bool IsSingleThreaded(System.ServiceModel.Description.ServiceDescription service) { ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>(); if (attribute != null) { return(attribute.ConcurrencyMode == ConcurrencyMode.Single); } return(true); }
public ServiceHost CreateServiceHost() { List <Uri> objUriBaseAddresses = new List <Uri>(); foreach (string strBaseAddress in BaseAddresses) { objUriBaseAddresses.Add(new Uri(strBaseAddress)); } ServiceHost objServiceHost = new ServiceHost(Type, objUriBaseAddresses.ToArray()); foreach (WcfServiceEndpoint objServiceEndpoint in ServiceEndpoints) { objServiceHost.AddServiceEndpoint(objServiceEndpoint.Type, objServiceEndpoint.Binding.Binding, objServiceEndpoint.Address); } ServiceBehaviorAttribute objServiceBehavior = objServiceHost.Description.Behaviors.Find <ServiceBehaviorAttribute>(); if (objServiceBehavior == null) { objServiceBehavior = new ServiceBehaviorAttribute(); objServiceHost.Description.Behaviors.Add(objServiceBehavior); } objServiceBehavior.ConcurrencyMode = Behavior.ConcurrencyMode; objServiceBehavior.InstanceContextMode = Behavior.InstanceContextMode; if (MetadataEndpoint.Enabled == true) { objServiceHost.Description.Behaviors.Add(MetadataEndpoint.CreateBehavior()); } ServiceDebugBehavior objServiceDebugBehavior = objServiceHost.Description.Behaviors.Find <ServiceDebugBehavior>(); if (objServiceDebugBehavior == null) { objServiceDebugBehavior = new ServiceDebugBehavior(); objServiceHost.Description.Behaviors.Add(objServiceDebugBehavior); } objServiceDebugBehavior.IncludeExceptionDetailInFaults = true; ServiceThrottlingBehavior objThrottlingBehavior = objServiceHost.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (objThrottlingBehavior == null) { objThrottlingBehavior = new ServiceThrottlingBehavior(); objServiceHost.Description.Behaviors.Add(objThrottlingBehavior); } objThrottlingBehavior.MaxConcurrentCalls = Throttling.MaxConcurrentCalls; objThrottlingBehavior.MaxConcurrentInstances = Throttling.MaxConcurrentCalls; objThrottlingBehavior.MaxConcurrentSessions = Throttling.MaxConcurrentSessions; return(objServiceHost); }
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); }
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); }
private static ServiceHost CreateServiceHost( object wcfServiceObject, ServiceEndpoint endpoint) { var host = new ServiceHost(wcfServiceObject); // set singleton var serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); if (serviceBehavior == null) { serviceBehavior = new ServiceBehaviorAttribute(); host.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.InstanceContextMode = InstanceContextMode.Single; serviceBehavior.ConcurrencyMode = ConcurrencyMode.Multiple; // set global error handler behavior var globalErrorHandlerBehavior = new WcfGlobalErrorHandlerBehaviorAttribute(); host.Description.Behaviors.Add(globalErrorHandlerBehavior); // set debug behavior var serviceDebug = host.Description.Behaviors.Find <ServiceDebugBehavior>(); if (serviceDebug == null) { serviceDebug = new ServiceDebugBehavior(); host.Description.Behaviors.Add(serviceDebug); } serviceDebug.IncludeExceptionDetailInFaults = true; // set throttling behavior var serviceThrottle = host.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (serviceThrottle == null) { serviceThrottle = new ServiceThrottlingBehavior(); host.Description.Behaviors.Add(serviceThrottle); } serviceThrottle.MaxConcurrentCalls = int.MaxValue; serviceThrottle.MaxConcurrentInstances = int.MaxValue; serviceThrottle.MaxConcurrentSessions = int.MaxValue; if (endpoint.ListenUri.Port == 0) { endpoint.ListenUriMode = ListenUriMode.Unique; serviceBehavior.AddressFilterMode = AddressFilterMode.Any; } host.AddServiceEndpoint(endpoint); //Exception Handler for Background Threads ExceptionHandler.AsynchronousThreadExceptionHandler = new WcfAsyncThreadExceptionHandler(); return(host); }
/// <summary> /// Ensures the <see cref="ServiceDescription"/> has a service behaviour attribute specified. /// </summary> /// <param name="description">The service description.</param> /// <returns>An instance of <see cref="ServiceBehaviorAttribute"/>.</returns> private static ServiceBehaviorAttribute EnsureServiceBehavior(ServiceDescription description) { var attr = description.Behaviors.Find <ServiceBehaviorAttribute>(); if (attr == null) { attr = new ServiceBehaviorAttribute(); description.Behaviors.Insert(0, attr); } return(attr); }
bool IsSingleThreaded(ServiceDescription service) { ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>(); if (attribute != null) { return(attribute.ConcurrencyMode == ConcurrencyMode.Single); } // The default is ConcurrencyMode.Single return(true); }
public static void SetAddressFilterMode(this ServiceHostBase host, AddressFilterMode mode) { ServiceBehaviorAttribute existingBehavior = host.Description.Behaviors.FirstOrDefault(b => b.GetType() == typeof(ServiceBehaviorAttribute)) as ServiceBehaviorAttribute; if (existingBehavior == null) { existingBehavior = new ServiceBehaviorAttribute(); host.Description.Behaviors.Add(existingBehavior); } existingBehavior.AddressFilterMode = mode; }
public void Initialize() { try { var host = new ServiceHost(typeof(SMSService)); var binding = new NetTcpBinding { MaxReceivedMessageSize = 2147483647, MaxBufferPoolSize = 2147483647, MaxBufferSize = 2147483647, MaxConnections = 30000, ReaderQuotas = { MaxBytesPerRead = 2147483647, MaxDepth = 2147483647, MaxArrayLength = 2147483647, MaxNameTableCharCount = 2147483647, MaxStringContentLength = 2147483647 } }; binding.SendTimeout = binding.ReceiveTimeout = new TimeSpan(0, 15, 0); host.AddServiceEndpoint(typeof(ISMSService), binding, string.Format("net.tcp://{0}:{1}", _host, _port)); ServiceBehaviorAttribute serviceBehaviorAttribute = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); if (serviceBehaviorAttribute != null) { serviceBehaviorAttribute.MaxItemsInObjectGraph = int.MaxValue; } if (host.Description != null) { var throttle = host.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior { MaxConcurrentCalls = 80, MaxConcurrentSessions = 1200, MaxConcurrentInstances = 1200 }; host.Description.Behaviors.Add(throttle); } } host.Open(); } catch (Exception exception) { //Console.WriteLine(ex.Message); EventLog.WriteEntry("SMS Service Host", exception.Message, EventLogEntryType.Error); } }
//internal static object CreateImplementation(Type serviceType) //{ // var constructors = serviceType.GetConstructors(TypeLoader.DefaultBindingFlags); // ConstructorInfo constructor = null; // foreach (var constr in constructors) // { // if (constr.GetParameters().Length == 0) // { // constructor = constr; // break; // } // } // if (constructor == null) // { // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( // SR.SFxNoDefaultConstructor)); // } // return constructor.Invoke(null, null); //} private static ServiceBehaviorAttribute EnsureBehaviorAttribute(ServiceDescription description) { ServiceBehaviorAttribute attr = ((KeyedByTypeCollection <IServiceBehavior>)description.Behaviors).Find <ServiceBehaviorAttribute>(); if (attr == null) { attr = new ServiceBehaviorAttribute(); description.Behaviors.Insert(0, attr); } return(attr); }