public static IAdvertManageService CreateChannelAdvertManageService(string readerOperateEndpointAddress) { NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; binding.ReaderQuotas.MaxArrayLength = int.MaxValue; binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue; binding.ReaderQuotas.MaxStringContentLength = int.MaxValue; binding.MaxReceivedMessageSize = int.MaxValue; string endPointAddress = readerOperateEndpointAddress + "AdvertManageService/"; ChannelFactory <IAdvertManageService> proxy = new ChannelFactory <IAdvertManageService>(binding, new EndpointAddress(endPointAddress)); foreach (OperationDescription op in proxy.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue; } } IAdvertManageService obj = proxy.CreateChannel(); return(obj); }
/// <summary> /// 构造文件传输的服务地址 /// </summary> /// <returns></returns> public static IFileTransportService CreateChannelFileTransportService() { if (ConfigurationManager.ConnectionStrings["AdvertServiceEndpointAddress"] != null) { readerOperateEndpointAddress = SeatManage.SeatManageComm.AESAlgorithm.AESDecrypt(ConfigurationManager.ConnectionStrings["AdvertServiceEndpointAddress"].ConnectionString); } else { // throw new Exception("未设置远程服务连接字符串"); } NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; binding.ReaderQuotas.MaxArrayLength = int.MaxValue; binding.ReaderQuotas.MaxArrayLength = int.MaxValue; binding.ReaderQuotas.MaxStringContentLength = int.MaxValue; binding.MaxReceivedMessageSize = int.MaxValue; string endPointAddress = readerOperateEndpointAddress + "TransportService/"; ChannelFactory <IFileTransportService> proxy = new ChannelFactory <IFileTransportService>(binding, new EndpointAddress(endPointAddress)); IFileTransportService obj = proxy.CreateChannel(); return(obj); }
public static IAdvertManageService CreateChannelAdvertManageService() { if (advertManageServiceProxy == null) { if (ConfigurationManager.ConnectionStrings["AdvertServiceEndpointAddress"] != null) { readerOperateEndpointAddress = SeatManage.SeatManageComm.AESAlgorithm.AESDecrypt(ConfigurationManager.ConnectionStrings["AdvertServiceEndpointAddress"].ConnectionString); } else { // throw new Exception("未设置远程服务连接字符串"); } NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; binding.ReaderQuotas.MaxArrayLength = int.MaxValue; binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue; binding.ReaderQuotas.MaxStringContentLength = int.MaxValue; binding.MaxReceivedMessageSize = int.MaxValue; binding.ReceiveTimeout = new TimeSpan(0, 10, 0); string endPointAddress = readerOperateEndpointAddress + "AdvertManageService/"; advertManageServiceProxy = new ChannelFactory <IAdvertManageService>(binding, new EndpointAddress(endPointAddress)); #region 设置ListItem最大值 foreach (OperationDescription op in advertManageServiceProxy.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue; } } #endregion } IAdvertManageService obj = advertManageServiceProxy.CreateChannel(); return(obj); }
private static ChannelFactory <T1> GetChannelFactory <T1>(string pHandlerAddress) { Binding lBinding; if (pHandlerAddress.Contains("net.tcp")) { lBinding = new NetTcpBinding(); } else if (pHandlerAddress.Contains("net.msmq")) { lBinding = new NetMsmqBinding(NetMsmqSecurityMode.None) { Durable = true }; } else { throw new Exception("Unrecognized address type"); } EndpointAddress myEndpoint = new EndpointAddress(pHandlerAddress); ChannelFactory <T1> myChannelFactory = new ChannelFactory <T1>(lBinding, myEndpoint); return(myChannelFactory); }
static void Main(string[] args) { // There are lost of forms to host a WCF service. Console, WPF, Web, IIS // what is needed is to instantiate aserviceHost form the System.ServiceModel // with the desired service ServiceHost geoManagerHost = new ServiceHost(typeof(GeoManager)); // -- // With this we don't need any configuration reference in App.config string address = "net.tcp://localhost:8086/GeoService"; Binding binding = new NetTcpBinding(); Type contract = typeof(IGeoService); geoManagerHost.AddServiceEndpoint(contract, binding, address); //-- geoManagerHost.Open(); // if it gets here, the service is ready to be consumed. Console.WriteLine("Service started. Press [Enter] to close it."); Console.ReadLine(); geoManagerHost.Close(); }
public static void InitTransportHost() { if (XTransportConfiguration.UseDirectAccess) { return; } var host = new ServiceHost(typeof(XTransportService), new UriBuilder("net.tcp", "localhost", 9010, XTransportConfiguration.ServiceName).Uri); var binding = new NetTcpBinding { Security = new NetTcpSecurity { Mode = SecurityMode.None } }; host.AddServiceEndpoint(typeof(IXTransportContract), binding, "Transport"); var thServer = new Thread(host.Open) { IsBackground = true }; thServer.Start(); Thread.Sleep(1000); }
static void Main(string[] args) { if (!IsPlaformCompatable()) { return; } Uri uri = new Uri("net.tcp://localhost:8082/ImageService"); NetTcpBinding binding = new NetTcpBinding(); ServiceHost host = new ServiceHost(typeof(ImageService)); ServiceBehaviorAttribute serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>(); serviceBehavior.IncludeExceptionDetailInFaults = true; // Create endpoint host.AddServiceEndpoint(typeof(IImageService), binding, uri); host.Open(); Console.WriteLine("Service is ready, press any key to terminate."); Console.ReadKey(); host.Close(); }
public static void Main() { ServiceHost host = new ServiceHost(typeof(Foo)); var binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Message; binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; binding.ReceiveTimeout = TimeSpan.FromSeconds(5); host.AddServiceEndpoint("IFoo", binding, new Uri("net.tcp://localhost:8080")); ServiceCredentials cred = new ServiceCredentials(); cred.ServiceCertificate.Certificate = new X509Certificate2("test.pfx", "mono"); cred.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; host.Description.Behaviors.Add(cred); host.Description.Behaviors.Find <ServiceDebugBehavior> () .IncludeExceptionDetailInFaults = true; host.Open(); Console.WriteLine("Hit [CR] key to close ..."); Console.ReadLine(); host.Close(); }
static void Main(string[] args) { NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; string address = "net.tcp://localhost:9999/WCFService"; ServiceHost host = new ServiceHost(typeof(SmartMeterService)); host.AddServiceEndpoint(typeof(ISmartMeterService), binding, address); host.Description.Behaviors.Remove(typeof(ServiceDebugBehavior)); host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true }); host.Authorization.ServiceAuthorizationManager = new CustomAuthorizationManager(); // Add a custom authorization policy to the service authorization behavior. List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(); policies.Add(new CustomAuthorizationPolicy()); host.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly(); host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom; host.Open(); Console.WriteLine("WCFService is opened. Press <enter> to finish..."); Console.ReadLine(); host.Close(); }
private void StartupEndpoint() { var config = new SetupConfig(); try { LoggerCQ.LogInfo("Attempting to upgrade database."); var connectionStringSettings = ConfigurationManager.ConnectionStrings["DatastoreEntities"]; var connectionStringBuilder = new SqlConnectionStringBuilder(connectionStringSettings.ConnectionString) { InitialCatalog = "Master" }; //Make sure there are no other nHydrate installations on this database if (DbMaintenanceHelper.ContainsOtherInstalls(connectionStringSettings.ConnectionString)) { LoggerCQ.LogError($"The database contains another installation. This is an error condition. Database={connectionStringBuilder.InitialCatalog}"); throw new Exception($"The database contains another installation. This is an error condition. Database={connectionStringBuilder.InitialCatalog}"); } //Even a blank database gets updated below so save if DB is blank when started var isBlank = DbMaintenanceHelper.IsBlank(connectionStringSettings.ConnectionString); var installer = new DatabaseInstaller(); if (installer.NeedsUpdate(connectionStringSettings.ConnectionString)) { var setup = new InstallSetup { AcceptVersionWarningsChangedScripts = true, AcceptVersionWarningsNewScripts = true, ConnectionString = connectionStringSettings.ConnectionString, InstallStatus = InstallStatusConstants.Upgrade, MasterConnectionString = connectionStringBuilder.ToString(), SuppressUI = true, }; installer.Install(setup); } //If new database then add file split data files to reduce file locking if (isBlank) { try { DbMaintenanceHelper.SplitDbFiles(connectionStringSettings.ConnectionString); LoggerCQ.LogInfo("New database has split data files."); } catch { LoggerCQ.LogWarning("New database could not split data files."); } try { var configFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "setup.config"); if (File.Exists(configFile)) { var barr = File.ReadAllBytes(configFile); config = ServerUtilities.DeserializeObject <SetupConfig>(barr); } } catch (Exception ex) { throw new Exception($"Setup configuration file is not valid."); } if (config != null) { if (!string.IsNullOrEmpty(config.ListDataPath) && !Directory.Exists(config.ListDataPath)) { throw new Exception("The setup configuration file value 'ListDataPath' is not valid"); } if (!string.IsNullOrEmpty(config.IndexPath) && !Directory.Exists(config.IndexPath)) { throw new Exception("The setup configuration file value 'IndexPath' is not valid"); } //Create a file group for List tables config.ListDataPath = DbMaintenanceHelper.CreateFileGroup(connectionStringSettings.ConnectionString, config.ListDataPath, SetupConfig.YFileGroup); //Create a file group for Indexes config.IndexPath = DbMaintenanceHelper.CreateFileGroup(connectionStringSettings.ConnectionString, config.IndexPath, SetupConfig.IndexFileGroup); } } } catch (Exception ex) { LoggerCQ.LogError(ex, "Failed on database upgrade."); throw new Exception("Failed on database upgrade."); } LoggerCQ.LogInfo("Service started begin"); try { #region Primary Endpoint var service = new Gravitybox.Datastore.Server.Core.SystemCore(ConfigurationManager.ConnectionStrings["DatastoreEntities"].ConnectionString, _enableHouseKeeping); if (config != null) { ConfigHelper.SetupConfig = config; } #region Determine if configured port is free var isPortFree = false; do { try { //Determine if can connect to port using (var p1 = new System.Net.Sockets.TcpClient("localhost", ConfigHelper.Port)) { } //If did connect successfully then there is already something on this port isPortFree = false; LoggerCQ.LogInfo($"Port {ConfigHelper.Port} is in use..."); System.Threading.Thread.Sleep(3000); //wait... } catch (Exception ex) { //If there is an error connecting then nothing is listening on that port so FREE isPortFree = true; } } while (!isPortFree); #endregion var primaryAddress = new Uri($"net.tcp://localhost:{ConfigHelper.Port}/__datastore_core"); var primaryHost = new ServiceHost(service, primaryAddress); //Initialize the service var netTcpBinding = new NetTcpBinding(); netTcpBinding.MaxConnections = ThrottleMax; netTcpBinding.Security.Mode = SecurityMode.None; primaryHost.AddServiceEndpoint(typeof(Gravitybox.Datastore.Common.ISystemCore), netTcpBinding, string.Empty); //Add more threads var stb = new ServiceThrottlingBehavior { MaxConcurrentSessions = ThrottleMax, MaxConcurrentCalls = ThrottleMax, MaxConcurrentInstances = ThrottleMax, }; primaryHost.Description.Behaviors.Add(stb); primaryHost.Open(); //Create Core Listener var primaryEndpoint = new EndpointAddress(primaryHost.BaseAddresses.First().AbsoluteUri); var primaryClient = new ChannelFactory <Gravitybox.Datastore.Common.ISystemCore>(netTcpBinding, primaryEndpoint); _core = primaryClient.CreateChannel(); (_core as IContextChannel).OperationTimeout = new TimeSpan(0, 0, 120); //Timeout=2m #endregion LoadEngine(service); service.Manager.ResetMaster(); LoggerCQ.LogInfo("Service started complete"); ConfigHelper.StartUp(); } catch (Exception ex) { LoggerCQ.LogError(ex); throw; } }
public WCFClient(NetTcpBinding binding, EndpointAddress address) : base(binding, address) { factory = this.CreateChannel(); }
public static void Run(string[] args) { try { // Initialize Ninject (the DI framework) var kernel = new StandardKernel(new CommonModule(), new WinFormsModule()); // Start a pending worker process WorkerManager.Init(); // Set up basic application configuration Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += UnhandledException; TaskScheduler.UnobservedTaskException += UnhandledTaskException; // Set up a form for the server process var form = new BackgroundForm(); Invoker.Current = form; int port = DEFAULT_PORT; foreach (var portArg in args.Where(a => a.StartsWith("/Port:", StringComparison.OrdinalIgnoreCase))) { if (int.TryParse(portArg.Substring(6), out int parsedPort)) { port = parsedPort; } } new Thread(() => ServerDiscovery.ListenForBroadcast(port)) { IsBackground = true }.Start(); // Listen for requests using (var host = new ServiceHost(typeof(ScanService))) { var serverIcon = new ServerNotifyIcon(port, () => form.Close()); host.Opened += (sender, eventArgs) => serverIcon.Show(); host.Description.Behaviors.Add(new ServiceFactoryBehavior(() => kernel.Get <ScanService>())); var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.FromHours(1), SendTimeout = TimeSpan.FromHours(1), Security = { Mode = SecurityMode.None } }; host.AddServiceEndpoint(typeof(IScanService), binding, $"net.tcp://0.0.0.0:{port}/NAPS2.Server"); host.Open(); try { Application.Run(form); } finally { serverIcon.Hide(); } } } catch (Exception ex) { Log.FatalException("An error occurred that caused the server application to close.", ex); Environment.Exit(1); } }
public WCFClient(NetTcpBinding binding, EndpointAddress address) : base(binding, address) { this.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; factory = this.CreateChannel(); }
public bool Start(string listenUri, ISchedulerHelper schedulerHelper) { DryadLogger.LogMethodEntry(listenUri); Uri baseAddress = new Uri(listenUri); try { NetTcpBinding binding = schedulerHelper.GetVertexServiceBinding(); selfHost = null; // Retry opening the service port if address is already in use int maxRetryCount = 20; // Results in retrying for ~1 min for (int retryCount = 0; retryCount < maxRetryCount; retryCount++) { try { //Step 1 of the hosting procedure: Create ServiceHost selfHost = new ServiceHost(callbackService, baseAddress); //Step 2 of the hosting procedure: Add service endpoints. ServiceEndpoint vertexEndpoint = selfHost.AddServiceEndpoint(typeof(IDryadVertexCallback), binding, Constants.vertexCallbackServiceName); ServiceThrottlingBehavior stb = new ServiceThrottlingBehavior(); stb.MaxConcurrentCalls = Constants.MaxConnections; stb.MaxConcurrentSessions = Constants.MaxConnections; selfHost.Description.Behaviors.Add(stb); //Step 3 of hosting procedure : Add a security manager selfHost.Authorization.ServiceAuthorizationManager = new DryadVertexServiceAuthorizationManager(); // Step 4 of the hosting procedure: Start the service. selfHost.Open(); break; } catch (AddressAlreadyInUseException) { if (selfHost != null) { selfHost.Abort(); selfHost = null; } // If this is the last try, dont sleep. Just rethrow exception to exit. if (retryCount < maxRetryCount - 1) { DryadLogger.LogInformation("Start Vertex Callback Service", "Address already in use. Retrying..."); System.Threading.Thread.Sleep(3000); } else { throw; } } } DryadLogger.LogInformation("Start Vertex Callback Service", "Service Host started successfully"); return(true); } catch (CommunicationException ce) { DryadLogger.LogCritical(0, ce, "Failed to start vertex callback service"); try { if (selfHost != null) { selfHost.Abort(); } } catch { } return(false); } }
void ConfigureReliability(Binding binding) { if (binding is NetTcpBinding) { NetTcpBinding tcpBinding = binding as NetTcpBinding; if (tcpBinding.ReliableSession.Enabled) { m_ReliabilityEnabledLabel.Text = "Enabled"; if (tcpBinding.ReliableSession.Ordered) { m_OrderedLabel.Text = "Ordered"; } else { m_OrderedLabel.Text = "Unordered"; } } else { m_ReliabilityEnabledLabel.Text = "Disabled"; m_OrderedLabel.Text = "Unordered"; } } if (binding is NetNamedPipeBinding) { m_ReliabilityEnabledLabel.Text = "Enabled"; m_OrderedLabel.Text = "Ordered"; } if (binding is NetMsmqBinding) { m_OrderedLabel.Text = "Reliability: N/A"; m_OrderedLabel.Text = "Ordered: N/A"; } if (binding is BasicHttpBinding || binding is NetPeerTcpBinding) { m_ReliabilityEnabledLabel.Text = "Disabled"; m_OrderedLabel.Text = "Unordered"; } if (binding is WSHttpBinding) { WSHttpBinding wsBinding = binding as WSHttpBinding; if (wsBinding.ReliableSession.Enabled) { m_ReliabilityEnabledLabel.Text = "Enabled"; if (wsBinding.ReliableSession.Ordered) { m_OrderedLabel.Text = "Ordered"; } else { m_OrderedLabel.Text = "Unordered"; } } else { m_ReliabilityEnabledLabel.Text = "Disabled"; m_OrderedLabel.Text = "Unordered"; } } if (binding is WSDualHttpBinding) { m_ReliabilityEnabledLabel.Text = "Enabled"; WSDualHttpBinding wsDualBinding = binding as WSDualHttpBinding; if (wsDualBinding.ReliableSession.Ordered) { m_OrderedLabel.Text = "Ordered"; } else { m_OrderedLabel.Text = "Unordered"; } } if (binding is WSFederationHttpBinding) { WSFederationHttpBinding federatedBinding = binding as WSFederationHttpBinding; if (federatedBinding.ReliableSession.Enabled) { m_ReliabilityEnabledLabel.Text = "Enabled"; if (federatedBinding.ReliableSession.Ordered) { m_OrderedLabel.Text = "Ordered"; } else { m_OrderedLabel.Text = "Unordered"; } } else { m_ReliabilityEnabledLabel.Text = "Disabled"; m_OrderedLabel.Text = "Unordered"; } } }
void ConfigureCredentialsType(Binding binding) { CredentialTypeEx credentialType = CredentialTypeEx.None; if (binding is NetTcpBinding) { NetTcpBinding tcpBinding = binding as NetTcpBinding; switch (tcpBinding.Security.Mode) { case SecurityMode.Message: { credentialType = ConvertCredentials(tcpBinding.Security.Message.ClientCredentialType); break; } case SecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case SecurityMode.Transport: { credentialType = ConvertCredentials(tcpBinding.Security.Transport.ClientCredentialType); break; } } } if (binding is NetNamedPipeBinding) { NetNamedPipeBinding pipeBinding = binding as NetNamedPipeBinding; switch (pipeBinding.Security.Mode) { case NetNamedPipeSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case NetNamedPipeSecurityMode.Transport: { credentialType = CredentialTypeEx.Windows; break; } } } if (binding is NetMsmqBinding) { NetMsmqBinding msmqBinding = binding as NetMsmqBinding; switch (msmqBinding.Security.Mode) { case NetMsmqSecurityMode.Both: case NetMsmqSecurityMode.Message: { credentialType = ConvertCredentials(msmqBinding.Security.Message.ClientCredentialType); break; } case NetMsmqSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case NetMsmqSecurityMode.Transport: { credentialType = ConvertCredentials(msmqBinding.Security.Transport.MsmqAuthenticationMode); break; } } } if (binding is BasicHttpBinding) { BasicHttpBinding basicBinding = binding as BasicHttpBinding; switch (basicBinding.Security.Mode) { case BasicHttpSecurityMode.Message: case BasicHttpSecurityMode.TransportWithMessageCredential: { credentialType = ConvertCredentials(basicBinding.Security.Message.ClientCredentialType); break; } case BasicHttpSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case BasicHttpSecurityMode.Transport: case BasicHttpSecurityMode.TransportCredentialOnly: { credentialType = ConvertCredentials(basicBinding.Security.Transport.ClientCredentialType); break; } } } if (binding is WSHttpBinding) { WSHttpBinding wsBinding = binding as WSHttpBinding; switch (wsBinding.Security.Mode) { case SecurityMode.TransportWithMessageCredential: case SecurityMode.Message: { credentialType = ConvertCredentials(wsBinding.Security.Message.ClientCredentialType); break; } case SecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case SecurityMode.Transport: { credentialType = ConvertCredentials(wsBinding.Security.Transport.ClientCredentialType); break; } } } if (binding is WSDualHttpBinding) { WSDualHttpBinding wsDualBinding = binding as WSDualHttpBinding; switch (wsDualBinding.Security.Mode) { case WSDualHttpSecurityMode.Message: { credentialType = ConvertCredentials(wsDualBinding.Security.Message.ClientCredentialType); break; } case WSDualHttpSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } } } if (binding is NetPeerTcpBinding) { NetPeerTcpBinding peerBinding = binding as NetPeerTcpBinding; switch (peerBinding.Security.Mode) { case SecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case SecurityMode.Transport: { credentialType = ConvertCredentials(peerBinding.Security.Transport.CredentialType); break; } } } if (binding is WSFederationHttpBinding) { credentialType = CredentialTypeEx.Token; } m_NoCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.None; m_WindowsCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.Windows; m_UsernameCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.Username; m_CertificateCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.Certificate; m_TokenRadioButton.Checked = credentialType == CredentialTypeEx.Token; }
static void Main(string[] args) { //change the headnode name here const string headnode = "[headnode]"; const string serviceName = "EchoService"; const int numRequests = 8; SessionStartInfo info = new SessionStartInfo(headnode, serviceName); //the sample code needs at least 2 cores in the cluster info.SessionResourceUnitType = SessionUnitType.Core; info.MaximumUnits = 2; info.MinimumUnits = 2; Console.Write("Creating a session for EchoService..."); using (DurableSession session = DurableSession.CreateSession(info)) { Console.WriteLine("done session id = {0}", session.Id); NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding)) { Console.Write("Sending {0} requests...", numRequests); for (int i = 0; i < numRequests; i++) { EchoOnExitRequest request = new EchoOnExitRequest(new TimeSpan(0, 0, 5)); client.SendRequest <EchoOnExitRequest>(request, i); } client.EndRequests(); Console.WriteLine("done"); // cancel half of the service tasks when processing the requests ThreadPool.QueueUserWorkItem(delegate { //wait 5 seconds to try cancel service tasks. Thread.Sleep(3 * 1000); try { Scheduler scheduler = new Scheduler(); try { scheduler.Connect(headnode); } catch (Exception e) { Console.WriteLine("Error connecting store.{0}", e.ToString()); return; } int jobId = session.GetProperty <int>("HPC_ServiceJobId"); ISchedulerJob job = scheduler.OpenJob(jobId); job.Refresh(); ISchedulerCollection taskList = job.GetTaskList(null, null, true); int onFlag = 0; foreach (ISchedulerTask task in taskList) { // cancel half of the service tasks if (onFlag++ % 2 == 0) { try { if (task.State == TaskState.Running) { Console.WriteLine("Try to cancel task {0}", task.TaskId); job.CancelTask(task.TaskId); job.Commit(); } } catch (Exception ex) { Console.WriteLine("Got exception when trying to cancel task {0}:{1}", task.TaskId, ex.Message); } } } } catch (Exception ex) { Console.WriteLine("Exception when trying to cancel the service tasks. {0}", ex.Message); } }); Console.WriteLine("Retrieving responses..."); try { int count = 0; foreach (var response in client.GetResponses <EchoOnExitResponse>()) { try { string reply = response.Result.EchoOnExitResult; Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply); count++; } catch (Exception ex) { Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message); } } Console.WriteLine("Done retrieving responses.{0}/{1} responses retrieved ", count, numRequests); } catch (SessionException ex) { Console.WriteLine("SessionException while getting responses: {0}", ex.Message); } catch (Exception ex) { Console.WriteLine("Exception while getting responses: {0}", ex.Message); } } // Close connections and delete messages stored in the system session.Close(); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
public void Open() { logger.Debug("ScreenCastService::Open(...)"); try { var session = mediaStreamer.Session; var videoSettings = session.VideoSettings; var videoDeviceName = videoSettings.CaptureDevice?.Name ?? ""; var hostName = session.StreamName; if (!string.IsNullOrEmpty(videoDeviceName)) { hostName += " (" + videoDeviceName + ")"; } var audioSettings = session.AudioSettings; var audioDeviceName = audioSettings.CaptureDevice?.Name ?? ""; var communicationPort = session.CommunicationPort; if (communicationPort < 0) { communicationPort = 0; } if (communicationPort == 0) {// FIXME: переделать // если порт не задан - ищем свободный начиная с 808 //communicationPort = GetRandomTcpPort(); var freeTcpPorts = MediaToolkit.Utils.NetTools.GetFreePortRange(System.Net.Sockets.ProtocolType.Tcp, 1, 808); if (freeTcpPorts != null && freeTcpPorts.Count() > 0) { communicationPort = freeTcpPorts.FirstOrDefault(); } } session.CommunicationPort = communicationPort; var communicationIp = session.NetworkIpAddress; var address = session.CommunicationAddress; this.ListenUri = new Uri(address); this.HostName = hostName; this.ServerId = MediaToolkit.Utils.RngProvider.GetRandomNumber().ToString(); Dictionary <string, string> endpointExtensions = new Dictionary <string, string> {// инфа которая будет доступна как расширение в WSDiscovery { "HostName", HostName }, { "StreamId", ServerId }, { "StreamName", session.StreamName }, { "AudioInfo", audioDeviceName }, { "VideoInfo", videoDeviceName }, }; //NetHttpBinding binding = new NetHttpBinding //{ // ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), // SendTimeout = TimeSpan.FromSeconds(10), //}; //NetTcpSecurity security = new NetTcpSecurity //{ // Mode = SecurityMode.Transport, // Transport = new TcpTransportSecurity // { // ClientCredentialType = TcpClientCredentialType.Windows, // ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign, // }, //}; NetTcpSecurity security = new NetTcpSecurity { Mode = SecurityMode.None, }; var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), SendTimeout = TimeSpan.FromSeconds(10), Security = security, // PortSharingEnabled = true, }; host = new ServiceHost(this, ListenUri); //host = new ServiceHost(this); //var endpoint = host.AddServiceEndpoint(typeof(IScreenCastService), binding, ""); var endpoint = host.AddServiceEndpoint(typeof(IScreenCastService), binding, ListenUri); if (communicationPort == 0) {// сейчас не работает на клиенте !! // нужно доделать клиент endpoint.ListenUriMode = System.ServiceModel.Description.ListenUriMode.Unique; } var endpointDiscoveryBehavior = new EndpointDiscoveryBehavior(); foreach (var key in endpointExtensions.Keys) { var element = new System.Xml.Linq.XElement(key, endpointExtensions[key]); endpointDiscoveryBehavior.Extensions.Add(element); } //var addrInfos = MediaToolkit.Utils.NetworkHelper.GetActiveUnicastIpAddressInfos(); //foreach (var addr in addrInfos) //{ // endpointDiscoveryBehavior.Scopes.Add(new Uri(uri, @"ListenAddr/" + addr.Address)); //} endpoint.EndpointBehaviors.Add(endpointDiscoveryBehavior); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(serviceDiscoveryBehavior); //host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); host.Description.Endpoints.Add(new UdpDiscoveryEndpoint()); host.Opened += Host_Opened; host.Faulted += Host_Faulted; host.Closed += Host_Closed; host.Open(); foreach (var dispatcher in host.ChannelDispatchers) { var listener = dispatcher.Listener; if (listener != null) { var uri = listener.Uri; if (uri != null) { var _host = uri.Host; if (_host == session.NetworkIpAddress) { //получаем порт на котором работает служба // если порт задан динамически session.CommunicationPort = uri.Port; } logger.Info(uri); } } } logger.Debug("Service opened: " + ListenUri.ToString()); } catch (Exception ex) { logger.Error(ex); Close(); var caption = "Network Error"; var message = "Network host opening error. Check network port and other settings."; throw new StreamerException(message, caption); } }
public void TpcIp() { var address = @"net.tcp://127.0.0.1:18080"; var serv = new Service(null); var host = new ServiceHost(serv, new Uri(address)); var b = new NetTcpBinding(); host.AddServiceEndpoint(typeof(IService), b, address); host.Open(); var f = new ChannelFactory<IService>(b); var c = f.CreateChannel(new EndpointAddress(address)); var result = c.DoWithParamsAndResult(":)", Guid.NewGuid()); Assert.AreEqual(2, result.d1); host.Dispose(); }
void ConfigureSecurityMode(Binding binding) { SecurityModeEx securityMode = SecurityModeEx.None; if (binding is NetTcpBinding) { NetTcpBinding tcpBinding = binding as NetTcpBinding; switch (tcpBinding.Security.Mode) { case SecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case SecurityMode.None: { securityMode = SecurityModeEx.None; break; } case SecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case SecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } } if (binding is NetNamedPipeBinding) { NetNamedPipeBinding pipeBinding = binding as NetNamedPipeBinding; switch (pipeBinding.Security.Mode) { case NetNamedPipeSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case NetNamedPipeSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } } } if (binding is NetMsmqBinding) { NetMsmqBinding msmqBinding = binding as NetMsmqBinding; switch (msmqBinding.Security.Mode) { case NetMsmqSecurityMode.Both: { securityMode = SecurityModeEx.Both; break; } case NetMsmqSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case NetMsmqSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case NetMsmqSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } } } if (binding is BasicHttpBinding) { BasicHttpBinding basicBinding = binding as BasicHttpBinding; switch (basicBinding.Security.Mode) { case BasicHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case BasicHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case BasicHttpSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case BasicHttpSecurityMode.TransportCredentialOnly: { securityMode = SecurityModeEx.Transport; break; } case BasicHttpSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } } if (binding is WSHttpBinding) { WSHttpBinding wsBinding = binding as WSHttpBinding; switch (wsBinding.Security.Mode) { case SecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case SecurityMode.None: { securityMode = SecurityModeEx.None; break; } case SecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case SecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } } if (binding is WSDualHttpBinding) { WSDualHttpBinding wsDualBinding = binding as WSDualHttpBinding; switch (wsDualBinding.Security.Mode) { case WSDualHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case WSDualHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } } } if (binding is NetPeerTcpBinding) { NetPeerTcpBinding peerBinding = binding as NetPeerTcpBinding; switch (peerBinding.Security.Mode) { case SecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case SecurityMode.None: { securityMode = SecurityModeEx.None; break; } case SecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case SecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Transport; break; } } } if (binding is WSFederationHttpBinding) { WSFederationHttpBinding federatedBinding = binding as WSFederationHttpBinding; switch (federatedBinding.Security.Mode) { case WSFederationHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case WSFederationHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case WSFederationHttpSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } } m_NoneRadioButton.Checked = securityMode == SecurityModeEx.None; m_TransportRadioButton.Checked = securityMode == SecurityModeEx.Transport; m_MessageRadioButton.Checked = securityMode == SecurityModeEx.Message; m_MixedRadioButton.Checked = securityMode == SecurityModeEx.Mixed; m_BothRadioButton.Checked = securityMode == SecurityModeEx.Both; }
// Start the Windows service. protected override void OnStart(string[] args) { try { EchoService.StartLogger(); _log = EchoService.Logger; List <Type> serviceTypes = new List <Type>(); string path = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); var files = Directory.GetFiles(path, "Skywolf.*Service.dll"); List <string> serviceBinaries = new List <string>(); files.ToList().ForEach(serviceBinaries.Add); TypeFilter myFilter = new TypeFilter((typeObj, criteriaObj) => typeObj.ToString() == criteriaObj.ToString()); foreach (string filePath in serviceBinaries) { _log.InfoFormat("Module: {0}", filePath); Assembly asm = Assembly.LoadFile(filePath); Type[] exportedTypes = asm.GetExportedTypes(); foreach (Type t in exportedTypes) { if (t.IsAbstract) { continue; } Type[] myInterfaces = t.FindInterfaces(myFilter, ECHO_INTERFACE); if (myInterfaces.Length > 0 && CustomServiceHost.Contains(t)) { serviceTypes.Add(t); } } } string hostMode = ConfigurationManager.AppSettings["HostMode"]; if (string.IsNullOrEmpty(hostMode)) { hostMode = "Multiple"; } if (string.Equals(hostMode, "Single", StringComparison.OrdinalIgnoreCase) && serviceTypes.Count > 1) { throw new ArgumentException("current design of service hose supports only one model."); } if (serviceTypes.Count() == 0) { throw new ArgumentException("no service is found."); } svcHosts = new CustomServiceHost[serviceTypes.Count]; int i = 0; var config = new XPathDocument(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); var servicesElement = config.CreateNavigator().SelectSingleNode("//system.serviceModel/services"); var logOperationBehavior = new LogOperationBehavior(); foreach (Type serviceType in serviceTypes) { var host = new CustomServiceHost(serviceType); var firstEp = host.Description.Endpoints[0]; var binding = firstEp.Binding; foreach (var op in firstEp.Contract.Operations) { if (op.Name != "UpdateStatus") //filter out UpdateStatus. { op.Behaviors.Add(logOperationBehavior); } } host.AddServiceEndpoint(ECHO_INTERFACE, binding, "Echo"); Binding newBinding; var bindingConfig = servicesElement.SelectSingleNode( string.Format("service[@name='{0}']/endpoint[1]/@bindingConfiguration", host.Description.ConfigurationName)); if (binding is NetTcpBinding) { var newTcpBinding = new NetTcpBinding(bindingConfig.Value); newTcpBinding.Security.Mode = SecurityMode.Transport; newTcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign; newBinding = newTcpBinding; } else if (binding is WebHttpBinding) { var newHttpBinding = new WebHttpBinding(bindingConfig.Value); newHttpBinding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly; newHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; newBinding = newHttpBinding; } else { var newHttpBinding = new BasicHttpBinding(bindingConfig.Value); newHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; newHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; newBinding = newHttpBinding; } host.AddServiceEndpoint(host.Description.Endpoints[0].Contract.ContractType, newBinding, "wid"); host.Open(); _log.Info(String.Format("{0} service is ready.", serviceType.Name)); foreach (var endpoint in host.Description.Endpoints) { _log.Info(String.Format("service endpoint: {0}", endpoint.Address)); } svcHosts[i] = host; i++; } } catch (Exception ex) { _log.Error(string.Format("Exception thrown from {0}", "unknown"), ex); throw; } }
void ConfigureTransactions(Binding binding) { if (binding is NetTcpBinding) { NetTcpBinding tcpBinding = binding as NetTcpBinding; if (tcpBinding.TransactionFlow) { m_TransactionFlowLabel.Text = "Flow: Enabled"; if (tcpBinding.TransactionProtocol == TransactionProtocol.OleTransactions) { m_TransactionProtocol.Text = "Protocol: OleTx"; } else { m_TransactionProtocol.Text = "Protocol: WSAT"; } } else { m_TransactionFlowLabel.Text = "Flow: Disabled"; m_TransactionProtocol.Text = "Protocol: -"; } } if (binding is NetNamedPipeBinding) { NetNamedPipeBinding pipeBinding = binding as NetNamedPipeBinding; if (pipeBinding.TransactionFlow) { m_TransactionFlowLabel.Text = "Flow: Enabled"; if (pipeBinding.TransactionProtocol == TransactionProtocol.OleTransactions) { m_TransactionProtocol.Text = "Protocol: OleTx"; } else { m_TransactionProtocol.Text = "Protocol: WSAT"; } } else { m_TransactionFlowLabel.Text = "Flow: Disabled"; m_TransactionProtocol.Text = "Protocol: -"; } } if (binding is NetMsmqBinding) { m_TransactionFlowLabel.Text = "Flow: N/A"; m_TransactionProtocol.Text = "Protocol: -"; } if (binding is BasicHttpBinding || binding is NetPeerTcpBinding) { m_TransactionFlowLabel.Text = "Flow: Disabled"; m_TransactionProtocol.Text = "Protocol: -"; } if (binding is WSHttpBinding) { WSHttpBinding wsBinding = binding as WSHttpBinding; if (wsBinding.TransactionFlow) { m_TransactionFlowLabel.Text = "Flow: Enabled"; m_TransactionProtocol.Text = "Protocol: WSAT"; } else { m_TransactionFlowLabel.Text = "Flow: Disabled"; m_TransactionProtocol.Text = "Protocol: -"; } } if (binding is WSDualHttpBinding) { WSDualHttpBinding wsDualBinding = binding as WSDualHttpBinding; if (wsDualBinding.TransactionFlow) { m_TransactionFlowLabel.Text = "Flow: Enabled"; m_TransactionProtocol.Text = "Protocol: WSAT"; } else { m_TransactionFlowLabel.Text = "Flow: Disabled"; m_TransactionProtocol.Text = "Protocol: -"; } } if (binding is WSFederationHttpBinding) { WSFederationHttpBinding federatedBinding = binding as WSFederationHttpBinding; if (federatedBinding.TransactionFlow) { m_TransactionFlowLabel.Text = "Flow: Enabled"; m_TransactionProtocol.Text = "Protocol: WSAT"; } else { m_TransactionFlowLabel.Text = "Flow: Disabled"; m_TransactionProtocol.Text = "Protocol: -"; } } }
internal static Binding CreateBinding(string scheme, int limitMultiplier, TimeSpan msgLifetime) { // returns a wcf binding with send/recv limits to n times default size const int poolMultiplier = 8; switch (scheme) { //case WcfConst.NetMsmq: //{ //var msmqBinding = new NetMsmqBinding(NetMsmqSecurityMode.None) //{ // ExactlyOnce = false, // Durable = false, // TimeToLive = msgLifetime, // MaxReceivedMessageSize = limitMultiplier * 64 * 1024, // ReaderQuotas = // { // MaxStringContentLength = limitMultiplier * 8 * 1024, // MaxArrayLength = limitMultiplier * 16384, // MaxBytesPerRead = limitMultiplier * 4096 // }, // MaxBufferPoolSize = poolMultiplier * limitMultiplier * 512 * 1024 //}; //return msmqBinding; //} //case WcfConst.NetPipe: //{ //var pipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) //{ // MaxReceivedMessageSize = limitMultiplier * 64 * 1024, // ReaderQuotas = // { // MaxStringContentLength = limitMultiplier * 8 * 1024, // MaxArrayLength = limitMultiplier * 16384, // MaxBytesPerRead = limitMultiplier * 4096 // }, // MaxBufferPoolSize = poolMultiplier * limitMultiplier * 512 * 1024 //}; //return pipeBinding; //} case WcfConst.NetTcp: { var tcpBinding = new NetTcpBinding(SecurityMode.None) { MaxReceivedMessageSize = limitMultiplier * 64 * 1024, ReaderQuotas = { MaxStringContentLength = limitMultiplier * 8 * 1024, MaxArrayLength = limitMultiplier * 16384, MaxBytesPerRead = limitMultiplier * 4096 }, MaxBufferPoolSize = poolMultiplier * limitMultiplier * 512 * 1024 }; return(tcpBinding); } case WcfConst.Http: { var httpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None) { MaxReceivedMessageSize = limitMultiplier * 64 * 1024, ReaderQuotas = { MaxStringContentLength = limitMultiplier * 8 * 1024, MaxArrayLength = limitMultiplier * 16384, MaxBytesPerRead = limitMultiplier * 4096 }, MaxBufferPoolSize = poolMultiplier * limitMultiplier * 512 * 1024 }; return(httpBinding); } default: throw new NotSupportedException($"scheme: '{scheme}'"); } }
private void TcpTransportCert() { // This string uses a function to prepend the computer name at run time. string addressTCP = String.Format( "net.tcp://{0}:8036/NetTcpSecurity/Transport/Certificate", System.Net.Dns.GetHostEntry("").HostName); // <Snippet1> NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; // </Snippet1> // <Snippet3> NetTcpBinding bSecurity = new NetTcpBinding(SecurityMode.Transport); // </Snippet3> // <Snippet4> NetTcpBinding bConfigurationName = new NetTcpBinding("MyConfiguration"); // </Snippet4> // <Snippet5> NetTcpBinding bSecurityReliable = new NetTcpBinding(SecurityMode.Transport, true); // </Snippet5> // <Snippet6> EnvelopeVersion envelopeVersion = binding.EnvelopeVersion; // </Snippet6> // <Snippet7> HostNameComparisonMode hostNameComparisonMode = binding.HostNameComparisonMode; // </Snippet7> // <Snippet8> int listenBacklog = binding.ListenBacklog; // </Snippet8> // <Snippet9> long maxBufferPoolsize = binding.MaxBufferPoolSize; // </Snippet9> // <Snippet10> int maxBufferSize = binding.MaxBufferSize; // </Snippet10> // <Snippet11> int maxConnections = binding.MaxConnections; // </Snippet11> // <Snippet12> long MaxReceivedMessageSize = binding.MaxReceivedMessageSize; // </Snippet12> // <Snippet13> bool portSharingEnabled = binding.PortSharingEnabled; // </Snippet13> // <Snippet14> XmlDictionaryReaderQuotas xmlDictionaryReaderQuotas = binding.ReaderQuotas; // </Snippet14> // <Snippet15> OptionalReliableSession reliableSession = binding.ReliableSession; // </Snippet15> // <Snippet16> string scheme = binding.Scheme; // </Snippet16> // <Snippet17> NetTcpSecurity security = binding.Security; // </Snippet17> // <Snippet18> bool transactionFlow = binding.TransactionFlow; // </Snippet18> // <Snippet19> TransactionProtocol transactionProtocol = binding.TransactionProtocol; // </Snippet19> // <Snippet20> BindingElementCollection elementCollection = binding.CreateBindingElements(); // </Snippet20> // <Snippet21> // P:System.ServiceModel.NetTcpBinding.System.ServiceModel.Channels. // IBindingRuntimePreferences.ReceiveSynchronously // Private, no example needed // </Snippet21> // <Snippet22> TransferMode transferMode = binding.TransferMode; // </Snippet22> // You must create an array of URI objects to have a base address. Uri a = new Uri(addressTCP); Uri[] baseAddresses = new Uri[] { a }; // Create the ServiceHost. The service type (Calculator) is not // shown here. ServiceHost sh = new ServiceHost(typeof(Calculator), baseAddresses); // Add an endpoint to the service. Insert the thumbprint of an X.509 // certificate found on your computer. Type c = typeof(ICalculator); //sh.AddServiceEndpoint(c, b, "Aloha"); sh.Credentials.ServiceCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "af1f51b25cd413ed9cd00c315bbb6dc1c08da5e6"); // This next line is optional. It specifies that the client's certificate // does not have to be issued by a trusted authority, but can be issued // by a peer if it is in the Trusted People store. Do not use this setting // for production code. // sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode = //X509CertificateValidationMode.PeerOrChainTrust; sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; Console.WriteLine("Listening @ {0}", address); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); }
private void AddBindingForNetTcp(ServiceHost serviceHost, Uri url) { string address = "net.tcp://" + url.Host + url.AbsolutePath + "/nettcp"; NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); ServiceEndpoint serviceEndpoint = serviceHost.AddServiceEndpoint(typeof(IChatService), binding, address); }
public void ReaderQuotasDefault_Bug15153() { NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); binding.ReaderQuotas.MaxStringContentLength = 8192; }
public void ResetPassword(string username, string oldPassword, string newPassword) { List <string> loggedIn = new List <string>(); string srvCertCN = "wcfservice"; NetTcpBinding binding = new NetTcpBinding(); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; X509Certificate2 srvCert = CertManager.GetCertificateFromStorage(StoreName.TrustedPeople, StoreLocation.LocalMachine, srvCertCN); EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:9000/AuthenticationService"), new X509CertificateEndpointIdentity(srvCert)); using (AuthenticationServiceAuditProxy proxy = new AuthenticationServiceAuditProxy(binding, address)) { loggedIn = proxy.GetAllLoggedUsers(); //provera da li je user ulogovan pre reset-a } if (loggedIn.Contains(username)) { User user = UserService.Instance.GetUser(username); if (user != null) { if (user.Password.Equals(oldPassword)) { if (PasswordPolicy.ValidatePasswordComplex(newPassword)) { string newPass4 = SecureConverter.Hash(newPassword); if (PasswordPolicy.ValidatePasswordHistory(username, newPass4)) { UserService.Instance.DeleteUser(user); user.Password = newPass4; user.CreatePass = DateTime.Now; UserService.Instance.AddToBase(user); PasswordHistoryService.Instance.AddToBase(user.Username, newPass4); } else { Console.WriteLine("This password has been used too many times"); } } else { Console.WriteLine("This password must contain numbers and length must be 5 characters"); } } else { Console.WriteLine("Wrong old password"); } } else { Console.WriteLine("User does not exist"); } } else { Console.WriteLine("User is not logged in"); } }
static void Main(string[] args) { NetTcpBinding binding = new NetTcpBinding(); EndpointAddress address = new EndpointAddress("net.tcp://localhost:9003/XML_Service"); //TODO: nece biti localhost int input; using (Client client = new Client(binding, address)) { do { Console.WriteLine("1. Allow Process"); Console.WriteLine("2. Ban Group"); Console.WriteLine("3. Ban User"); Console.WriteLine("4. Ban User In Group"); Console.WriteLine("5. Forbid Process"); Console.WriteLine("6. Lift Group Ban"); Console.WriteLine("7. Lift User Ban"); Console.WriteLine("8. Lift User In Group Ban"); Console.WriteLine("0. Exit"); if (!Int32.TryParse(Console.ReadLine(), out input)) { input = 9; } switch (input) { case 1: Console.WriteLine("Enter process name: "); client.AllowProcess(Console.ReadLine()); break; case 2: Console.WriteLine("Enter process name: "); string process = Console.ReadLine(); Console.WriteLine("Enter group name: "); string group = Console.ReadLine(); client.BanGroup(group, process); break; case 3: Console.WriteLine("Enter process name: "); process = Console.ReadLine(); Console.WriteLine("Enter user name: "); string user = Console.ReadLine(); client.BanUser(user, process); break; case 4: Console.WriteLine("Enter process name: "); process = Console.ReadLine(); Console.WriteLine("Enter user name: "); user = Console.ReadLine(); Console.WriteLine("Enter group name: "); group = Console.ReadLine(); client.BanUserInGroup(user, group, process); break; case 5: Console.WriteLine("Enter process name: "); process = Console.ReadLine(); client.ForbidProcess(process); break; case 6: Console.WriteLine("Enter process name: "); process = Console.ReadLine(); Console.WriteLine("Enter group name: "); group = Console.ReadLine(); client.LiftGroupBan(group, process); break; case 7: Console.WriteLine("Enter process name: "); process = Console.ReadLine(); Console.WriteLine("Enter user name: "); user = Console.ReadLine(); client.LiftUserBan(user, process); break; case 8: Console.WriteLine("Enter process name: "); process = Console.ReadLine(); Console.WriteLine("Enter user name: "); user = Console.ReadLine(); Console.WriteLine("Enter group name: "); group = Console.ReadLine(); client.LiftUserInGroupBan(user, group, process); break; case 0: break; default: Console.WriteLine("Wrong input!"); break; } }while (input != 0); } }
public Message ProcessMessage(Message requestMessage) { try { begintime(); IRouterBaseHandler proxy = null; HeaderParameter para = HeaderOperater.GetHeaderValue(requestMessage); if (RouterManage.routerDic.ContainsKey(para.routerid)) { proxy = RouterManage.routerDic[para.routerid]; para.replyidentify = RouterManage.headParaDic[para.routerid].replyidentify; } else { //Binding binding = null; EndpointAddress endpointAddress = null; Uri touri = null; para = RouterManage.AddClient(requestMessage, para, out endpointAddress, out touri); requestMessage.Headers.To = touri; IRouterBaseReply callback = OperationContext.Current.GetCallbackChannel <IRouterBaseReply>(); NetTcpBinding tbinding = new NetTcpBinding("NetTcpBinding_BaseService"); DuplexChannelFactory <IRouterBaseHandler> factory = new DuplexChannelFactory <IRouterBaseHandler>(new InstanceContext(new ReplyRouterBaseCallback(callback)), tbinding, endpointAddress); proxy = factory.CreateChannel(); //缓存会话 RouterManage.routerDic.Add(para.routerid, proxy); RouterManage.headParaDic.Add(para.routerid, para); } Message responseMessage = null; try { HeaderOperater.AddMessageHeader(requestMessage, para);//增加自定义消息头 responseMessage = proxy.ProcessMessage(requestMessage); } catch (CommunicationException e) { RouterManage.RemoveClient(para); throw e; } if (para.cmd == "Quit") { //关闭连接释放缓存会话 RouterManage.RemoveClient(para); } double outtime = endtime(); // 请求消息记录 if (WcfGlobal.IsDebug) { MiddlewareLogHelper.WriterLog(LogType.MidLog, true, Color.Black, String.Format("路由请求消息发送(耗时[" + outtime + "]): {0}", requestMessage.Headers.Action)); } return(responseMessage); } catch (Exception e) { return(Message.CreateMessage(requestMessage.Version, FaultCode.CreateReceiverFaultCode("error", RouterManage.ns), e.Message, requestMessage.Headers.Action)); } }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); if (!System.IO.Directory.Exists(LogDirectory)) { System.IO.Directory.CreateDirectory(LogDirectory); } Console.WriteLine("log ok."); ///////////////////////////////////////////////////////////////////////// #if (MONO) if (Environment.GetEnvironmentVariable("MONO_STRICT_MS_COMPLIANT") != "yes") { Environment.SetEnvironmentVariable("MONO_STRICT_MS_COMPLIANT", "yes"); Console.WriteLine("设置环境变量“MONO_STRICT_MS_COMPLIANT”为Yes!"); } else { Console.WriteLine("当前环境变量“MONO_STRICT_MS_COMPLIANT”值为Yes!"); } #endif /////////////////////////////////////////////////////////////////////////// //参数获取设置的服务地址,如果没有,则保留默认的 127.0.0.1:8888 string ip = System.Configuration.ConfigurationManager.AppSettings["ServerIP"];// "127.0.0.1"; //string ip = "127.0.0.1"; IPAddress ipAddr; if (args.Length > 0 && IPAddress.TryParse(args[0], out ipAddr)) { ip = ipAddr.ToString(); } Console.WriteLine("ip config ok."); int port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ServerPort"]); // 8888; int tempPort; if (args.Length > 1 && int.TryParse(args[1], out tempPort)) { port = tempPort; } if (args.Length > 2 && args[2].ToLower() == "outlog") { EnableConsoleOut = true; } Console.WriteLine("address config ok."); //// string uri1 = string.Format("net.tcp://{0}:{1}", ip, port - 1); NetTcpBinding binding1 = new NetTcpBinding(SecurityMode.None); ServiceHost calculatorHost = new ServiceHost(typeof(CalculatorService)); calculatorHost.AddServiceEndpoint(typeof(ICalculator), binding1, uri1); calculatorHost.Opened += delegate { Console.WriteLine("The Test Service(calculator) has begun to listen"); }; calculatorHost.Open(); //// string uri = string.Format("net.tcp://{0}:{1}", ip, port); NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); //Console.WriteLine("binding init 1,ok."); binding.MaxBufferSize = int.MaxValue; //Console.WriteLine("binding init 2,ok."); binding.MaxReceivedMessageSize = int.MaxValue; //Console.WriteLine("binding init 3,ok."); #if (MONO) XmlDictionaryReaderQuotas quo = new XmlDictionaryReaderQuotas(); binding.ReaderQuotas = quo; Console.WriteLine("binding init 4_1,ok."); #endif binding.ReaderQuotas.MaxArrayLength = 65536; //Console.WriteLine("binding init 4,ok."); binding.ReaderQuotas.MaxBytesPerRead = 10 * 1024 * 1024; binding.ReaderQuotas.MaxStringContentLength = 10 * 1024 * 1024; //65536; binding.ReceiveTimeout = TimeSpan.MaxValue; //设置连接自动断开的空闲时长; binding.MaxConnections = 100; binding.ListenBacklog = 200; //Console.WriteLine("binding init 5,ok."); binding.TransferMode = TransferMode.Buffered; //Console.WriteLine("binding init 6,ok."); //请参见 http://msdn.microsoft.com/zh-cn/library/ee767642 进行设置 //Console.WriteLine("binding init ok."); ListAllBindingElements(binding); ServiceHost host = new ServiceHost(typeof(MessagePublishServiceImpl)); Console.WriteLine("service config check all ok."); host.AddServiceEndpoint(typeof(IMessagePublishService), binding, uri); Console.WriteLine("=========PDF.NET.MSF (PWMIS Message Service) Ver {0} ==", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("启动消息发布服务……接入地址:{0}", uri); Console.WriteLine(); ChangeConsoleOut(); if (EnableConsoleOut) { ListAllBindingElements(binding); Console.WriteLine("启动消息发布服务……接入地址:{0}", uri); } Console.WriteLine("检查服务节点... ..."); ////////////////////向集群中写入节点 /////////////////////////////////////////////////////////////// //ServiceHostUri = uri; ServiceRegModel model = new ServiceRegModel(); model.RegServerIP = ip; model.RegServerPort = port; model.RegServerDesc = string.Format("Server://{0}:{1}", ip, port); model.ServerMappingIP = System.Configuration.ConfigurationManager.AppSettings["ServerMappingIP"]; Host = new ServiceHostInfo(); Host.RegServerDesc = model.RegServerDesc; Host.RegServerIP = model.RegServerIP; Host.RegServerPort = model.RegServerPort; Host.IsActive = model.IsActive; Host.ServerMappingIP = model.ServerMappingIP; RegServiceContainer container = new RegServiceContainer(); container.CurrentContext = new ServiceContext(""); if (container.RegService(model)) { Console.WriteLine("======注册集群节点成功,服务将以集群模式运行=================="); } else { Console.WriteLine("====== 未使用全局缓存,服务将以独立模式运行 =================="); } //////////////////////////////////////////////////////////////////////////////////////////////////////// MessageCenter.Instance.ListenerAdded += new EventHandler <MessageListenerEventArgs>(Instance_ListenerAdded); MessageCenter.Instance.ListenerRemoved += new EventHandler <MessageListenerEventArgs>(Instance_ListenerRemoved); MessageCenter.Instance.NotifyError += new EventHandler <MessageNotifyErrorEventArgs>(Instance_NotifyError); MessageCenter.Instance.ListenerAcceptMessage += new EventHandler <MessageListenerEventArgs>(Instance_ListenerAcceptMessage); MessageCenter.Instance.ListenerEventMessage += new EventHandler <MessageListenerEventArgs>(Instance_ListenerEventMessage); MessageCenter.Instance.ListenerRequestMessage += new EventHandler <MessageRequestEventArgs>(Instance_ListenerRequestMessage); #if (PrivateUse) if (ip.StartsWith("192.168.") || ip.StartsWith("127.0.0.1")) //测试,仅限于局域网使用 { host.Open(); Console.WriteLine("服务正在运行"); EnterMessageInputMode(); Console.WriteLine("正在关闭服务……"); host.Close(); Console.WriteLine("服务已关闭。"); } else { Console.WriteLine("服务已关闭,{0}。", UseDescrition); } #else host.Open(); Console.WriteLine("服务正在运行"); EnterMessageInputMode(); Console.WriteLine("正在关闭服务……"); host.Close(); calculatorHost.Close(); Console.WriteLine("服务已关闭。"); #endif host = null; Console.ReadLine(); }
static void Main(string[] args) { try { IPHostEntry ips = Dns.GetHostEntry(Dns.GetHostName()); IPAddress _ipAddress = ips.AddressList[0]; string endPointAddr = "net.tcp://" + _ipAddress.ToString() + ":8000/EvalService"; NetTcpBinding tcpBinding = new NetTcpBinding(); tcpBinding.TransactionFlow = false; tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; tcpBinding.Security.Mode = SecurityMode.None; EndpointAddress endpointAddress = new EndpointAddress(endPointAddr); Console.WriteLine("Attempt to connect to: " + endPointAddr); IEvalService proxy = ChannelFactory <IEvalService> .CreateChannel(tcpBinding, endpointAddress); using (proxy as IDisposable) { Eval eval; eval = new Eval { Comments = "CommentsField1", Submitter = "Submitter1", TimeSubmitted = DateTime.Now }; proxy.SubmitEval(eval); eval = new Eval { Comments = "CommentsField2", Submitter = "Submitter2", TimeSubmitted = DateTime.Now }; proxy.SubmitEval(eval); eval = new Eval { Comments = "CommentsField3", Submitter = "Submitter3", TimeSubmitted = DateTime.Now }; proxy.SubmitEval(eval); Eval[] evals = proxy.GetEvals(); foreach (Eval e in evals) { Console.WriteLine("{0}\t{1}\t{2}", e.Id, e.Submitter, e.TimeSubmitted); } } } catch (Exception eException) { Console.WriteLine("{1}{0}Message: \"{2}\"{3}{0}StackTrace:{0}{4}", Environment.NewLine, eException.GetType().FullName, eException.Message, eException.InnerException != null ? Environment.NewLine + "InnerException.Message: \"" + eException.InnerException.Message + "\"" : string.Empty, eException.StackTrace); } Console.ReadLine(); }