public void TestOneWayCallbackConcurencyOnNamedPipe() { var address = @"net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name; var srv = new CallbackService(); var callback = new CallbackServiceCallback(); using (var server = new ServiceHost(srv, new Uri(address))) { server.AddServiceEndpoint(typeof(ICallbackService), new NetNamedPipeBinding { }, address); server.Open(); using (var channelFactory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), new NetNamedPipeBinding { })) { var client = channelFactory.CreateChannel(new EndpointAddress(address)); for (int i = 0; i < 20; i++) client.OneWayExecute(); while (callback.Count != 20) { Thread.Sleep(10); } } } }
public static void MyClassInitialize(TestContext testContext) { binding = new NetNamedPipeBinding(); host = new ServiceHost(typeof(MyService)); host.AddServiceEndpoint(typeof(IChangeResource), binding, address); host.Open(); }
public void SingletonSessionsTests() { Binding binding = new WSHttpBinding(); string address = "http://localhost/" + Guid.NewGuid().ToString(); using (ServiceHost host = new ServiceHost(typeof(SingletonCounter), new Uri(address))) { host.AddServiceEndpoint(typeof(ISessionRequired), binding, "withSession"); host.AddServiceEndpoint(typeof(ISessionNotAllowed), binding, "woutSession"); host.Open(); ISessionRequired withSession = ChannelFactory<ISessionRequired>.CreateChannel( binding, new EndpointAddress(address + "/withSession")); withSession.IncrementCounter(); ((ICommunicationObject)withSession).Close(); ISessionNotAllowed woutSession = ChannelFactory<ISessionNotAllowed>.CreateChannel( binding, new EndpointAddress(address + "/woutSession")); woutSession.IncrementCounter(); ((ICommunicationObject)woutSession).Close(); } }
public void ServerAncClientExceptionsEndpointBehavior() { var hook = new ExceptionsEndpointBehaviour(); var address = @"net.pipe://127.0.0.1/test" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name; var serv = new ExceptionService(); using (var host = new ServiceHost(serv, new Uri[] { new Uri(address), })) { var b = new NetNamedPipeBinding(); var serverEndpoint = host.AddServiceEndpoint(typeof(IExceptionService), b, address); serverEndpoint.Behaviors.Add(hook); host.Open(); var f = new ChannelFactory<IExceptionService>(b); f.Endpoint.Behaviors.Add(hook); var c = f.CreateChannel(new EndpointAddress(address)); try { c.DoException("message"); } catch (InvalidOperationException ex) { StringAssert.AreEqualIgnoringCase("message", ex.Message); } host.Abort(); } }
public void CallAsync_wait_done() { var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name; var binding = new NetNamedPipeBinding(); var done = new ManualResetEvent(false); var srv = new AsyncService(done); var callback = new AsyncServiceCallback(); using (var host = new ServiceHost(srv, new Uri(address))) { host.AddServiceEndpoint(typeof(IAsyncService), binding, address); host.Open(); ThreadPool.QueueUserWorkItem(_ => { using (var factory = new DuplexChannelFactory<IAsyncService>(new InstanceContext(callback), binding)) { var client = factory.CreateChannel(new EndpointAddress(address)); AsyncCallback act = (x) => { Assert.AreEqual(x.AsyncState, 1); }; var result = client.BeginServiceAsyncMethod(act, 1); result.AsyncWaitHandle.WaitOne(); Assert.AreEqual(result.AsyncState, 1); client.EndServiceAsyncMethod(result); } }); done.WaitOne(); } }
public void CallServiceReturningSession2Times_sessionAreEqual() { var address = @"net.pipe://127.0.0.1/1/test.test/test" + MethodBase.GetCurrentMethod().Name; var binding = new NetNamedPipeBinding(); var data = new CallbackData { Data = "1" }; var srv = new CallbackService(data); var callback = new CallbackServiceCallback(); using (var host = new ServiceHost(srv, new Uri(address))) { host.AddServiceEndpoint(typeof(ICallbackService), binding, address); host.Open(); using (var factory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), binding)) { var client = factory.CreateChannel(new EndpointAddress(address)); client.Call(); } callback.Wait.WaitOne(); Assert.AreEqual(data.Data, callback.Called.Data); } }
public void CallbackToSyncContext() { var path = @"net.pipe://127.0.0.1/" + this.GetType().Name + MethodBase.GetCurrentMethod().Name; var binding = new NetNamedPipeBinding() { MaxConnections = 5 }; using (var server = new ServiceHost(new SyncCallbackService(), new Uri(path))) { server.AddServiceEndpoint(typeof(ISyncCallbackService), binding, path); server.Open(); using (var syncContext = new StaSynchronizationContext()) { InstanceContext context = null; NDceRpc.ServiceModel.DuplexChannelFactory<ISyncCallbackService> channelFactory = null; ISyncCallbackService client = null; syncContext.Send(_ => SynchronizationContext.SetSynchronizationContext(syncContext), null); syncContext.Send(_ => context = new InstanceContext(new SyncCallbackServiceCallback()), null); syncContext.Send(_ => channelFactory = new NDceRpc.ServiceModel.DuplexChannelFactory<ISyncCallbackService>(context, binding),null); syncContext.Send(_ => client = channelFactory.CreateChannel(new EndpointAddress(path)),null); using (channelFactory) { var callbackThread = client.Call(); Assert.AreEqual(syncContext.ManagedThreadId, callbackThread); } } } }
public void Ipc_byteArray() { var uri = "ipc:///" + MethodBase.GetCurrentMethod().Name; using (var server = new ServiceHost(new Service(), new Uri(uri))) { var binding = new LocalBinding { MaxConnections = 5 }; server.AddServiceEndpoint(typeof(IService), binding, uri); server.Open(); Thread.Sleep(100); using (var channelFactory = new ChannelFactory<IService>(binding)) { var client = channelFactory.CreateChannel(new EndpointAddress(uri)); client.Execute(new byte[0]); byte[] bytes = new byte[512]; new Random().NextBytes(bytes); var timer = new Stopwatch(); timer.Start(); for (int i = 0; i < 5000; i++) client.Execute(bytes); timer.Stop(); Trace.WriteLine(timer.ElapsedMilliseconds.ToString() + " ms", MethodBase.GetCurrentMethod().Name); } } }
public void CallServiceReturningSession2TimesFor2Channels_sessionAreDifferentForDifferentChannels() { var address = @"net.pipe://127.0.0.1/1/test.test/test" + MethodBase.GetCurrentMethod().Name; var serv = new SessionService(); var host = new ServiceHost(serv, new Uri(address)); var b = new NetNamedPipeBinding(); host.AddServiceEndpoint(typeof(ISessionService), b, address); var f1 = new ChannelFactory<ISessionService>(b); var f2 = new ChannelFactory<ISessionService>(b); var client1 = f1.CreateChannel(new EndpointAddress(address)); var client2 = f2.CreateChannel(new EndpointAddress(address)); host.Open(); var session11 = client1.Call(); var session21 = client2.Call(); var session22 = client2.Call(); var session12 = client1.Call(); f1.Dispose(); f2.Dispose(); host.Dispose(); Assert.AreEqual(session11, session12); Assert.AreEqual(session21, session22); Assert.AreNotEqual(session11, session21); }
protected NuGetService(ServiceName serviceName, ServiceHost host) { Host = host; ServiceName = serviceName; TempDirectory = Path.Combine(Path.GetTempPath(), "NuGetServices", serviceName.Name); }
protected override void OnStop() { if (myServiceHost != null) { myServiceHost.Close(); myServiceHost = null; } }
public WorkService(ServiceName name, ServiceHost host) : base(name, host) { var workConfig = host.Config.GetSection<WorkConfiguration>(); MaxWorkers = MaxWorkers ?? workConfig.MaxWorkers; WorkersPerCore = WorkersPerCore ?? (workConfig.WorkersPerCore ?? DefaultWorkersPerCore); }
internal PluginHost( CatchExceptionGeneration catchMode ) { _plugins = new Dictionary<IPluginInfo, PluginProxy>(); _loadedPlugins = new Dictionary<Guid, PluginProxy>(); _loadedPluginsEx = new ReadOnlyCollectionOnICollection<PluginProxy>( _loadedPlugins.Values ); _serviceHost = new ServiceHost( catchMode ); _newlyLoadedPlugins = new List<PluginProxy>(); }
protected override void OnStop() { if (_serviceHost != null) { _serviceHost.Close(); _serviceHost = null; } }
public void FlowRequiredButNotSupported() { ServiceHost host = new ServiceHost(typeof(TestService2)); BasicHttpBinding binding = new BasicHttpBinding(); // Does not support transactions string address = "http://localhost:8080/" + Guid.NewGuid().ToString(); host.AddServiceEndpoint(typeof(ITestContract2), binding, address); host.Open(); }
public void FlowRequiredButNotEnabled() { ServiceHost<TestService2> host = new ServiceHost<TestService2>(); NetNamedPipeBinding binding = new NetNamedPipeBinding(); binding.TransactionFlow = false; // default string address = "net.pipe://localhost/" + Guid.NewGuid().ToString(); host.AddServiceEndpoint(typeof(ITestContract2), binding, address); host.Open(); }
private ServiceHost CreateHost() { NetNamedPipeBinding netNamedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); ServiceHost eventServiceHost = new ServiceHost(typeof(EventService)); eventServiceHost.AddServiceEndpoint(typeof(IEventService), netNamedPipeBinding, Config.Communincation.ServiceURI); eventServiceHost.AddDefaultMEXEndPoint(); eventServiceHost.EnableIncludeExceptionInFaultBehavior(); return eventServiceHost; }
public void ShouldSucceedToCreateInstance() { var serviceType = typeof (TestService); var serviceHost = new ServiceHost(ServiceLocator.Default, serviceType, _endpoints); Assert.AreEqual(serviceHost.ServiceType, serviceType); Assert.IsTrue(serviceHost.Description.Behaviors.Any()); }
internal void Start() { Console.WriteLine("Starting EventService Host..."); eventServiceHost = CreateHost(); eventServiceHost.Open(); Console.WriteLine(eventServiceHost.GetHostedServiceEndPoints()); Console.WriteLine("EventService Host Running..."); }
protected override void OnStart(string[] args) { if (myServiceHost != null) { myServiceHost.Close(); } myServiceHost = new ServiceHost(typeof(MembershipServices)); myServiceHost.Open(); }
public void FlowRequiredAndEnabled() { using (ServiceHost<TestService2> host = new ServiceHost<TestService2>()) { NetNamedPipeBinding binding = new NetNamedPipeBinding(); binding.TransactionFlow = true; string address = "net.pipe://localhost/" + Guid.NewGuid().ToString(); host.AddServiceEndpoint<ITestContract2>(binding, address); host.Open(); } }
public void EnableMetadataExchange_MultipleBaseAddresses() { ServiceHost<TestService> host; using (host = new ServiceHost<TestService>("http://localhost:8080", "net.tcp://localhost:8081")) { host.AddServiceEndpoint(typeof(ITestContract), new WSHttpBinding(), "Test"); Assert.IsFalse(host.MetadataExchangeEnabled); host.EnableMetadataExchange(); Assert.AreEqual(2, host.Description.Endpoints.Count<ServiceEndpoint>(ep => ep.Contract.ContractType == typeof(IMetadataExchange))); } }
public static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(CalculatorService))) { host.Opened += (object sender, EventArgs e) => { Console.WriteLine("CalculatorService已经启动,按任意键终止服务!"); }; host.Open (); Console.Read (); } }
internal QueueProcessor(SimpleInMemConnection connection, ServiceHost serviceHost, SimpleInMemTransport transport, Logger logger) { if (connection == null) throw new ArgumentNullException(nameof(connection)); if (serviceHost == null) throw new ArgumentNullException(nameof(serviceHost)); if (transport == null) throw new ArgumentNullException(nameof(transport)); this.connection = connection; this.serviceHost = serviceHost; this.transport = transport; this.logger = logger; }
public void PerSessionTransactionService() { var address = "net.pipe://localhost/" + Guid.NewGuid(); using (var host = new ServiceHost(typeof(PerSessionService))) using (var proxy = new ServiceClient(binding, address)) { host.AddServiceEndpoint(typeof(IInstanceIdGetter), binding, address); host.Open(); var first = proxy.GetInstanceId(); var second = proxy.GetInstanceId(); Assert.AreEqual(second, first); } }
public void Host() { _log.Info("Starting up as a winservice application"); if (!WinServiceHelper.IsInstalled(_fullServiceName.FullName)) { string message = string.Format("The {0} service has not been installed yet. Please run '{1} install'.", _fullServiceName, Assembly.GetEntryAssembly().GetName()); _log.Fatal(message); throw new ConfigurationException(message); } var inServiceHost = new ServiceHost(_coordinator); inServiceHost.Run(); }
public void InterfaceInheritance() { var address = @"ipc:///test" + MethodBase.GetCurrentMethod().Name; var serv = new InheritanceService(); var host = new ServiceHost(serv, new Uri(address)); var b = new LocalBinding(); host.AddServiceEndpoint(typeof(IInheritanceService), b, address); host.Open(); var f = new ChannelFactory<IInheritanceService>(b); var c = f.CreateChannel(new EndpointAddress(address)); c.Do(); c.DoBase(); host.Dispose(); }
protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } // Create a ServiceHost for the CalculatorService type and // provide the base address. serviceHost = new ServiceHost(typeof(CalculatorService)); // Open the ServiceHostBase to create listeners and start // listening for messages. serviceHost.Open(); }
public void InvokenBlockingWithParams_resultObtained() { var address = @"net.pipe://127.0.0.1/1/test.test/test"; var serv = new Service(null); var host = new ServiceHost(serv, new Uri(address)); var b = new NetNamedPipeBinding(); 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(); }
public void DisposedChannelFactory_call() { var address = @"net.pipe://127.0.0.1/" + Guid.NewGuid().ToString("N"); var serv = new SimpleService(); var b = new NetNamedPipeBinding(); using (var host = new ServiceHost(serv, new Uri[] { new Uri(address), })) { host.AddServiceEndpoint(typeof(ISimpleService), b, address); host.Open(); var f = new ChannelFactory<ISimpleService>(b); var c = f.CreateChannel(new EndpointAddress(address)); using (f) { } c.Do(); } }
public MyContractBehavior(HostState state, ServiceHost h) { _state = state; _host = h; }
public MyServiceBehavior(HostState state, ServiceHost h) { _state = state; _host = h; }
private void ApplySettings() { if (_host != null) { _host.Close(); _host.Instance.Dispose(); _logManager.Sources.Remove(_host.Instance); } if (_entityRegistry.Settings.IsServer) { IRemoteStorageAuthorization authorization; switch (_entityRegistry.Settings.Authorization) { case AuthorizationModes.Anonymous: authorization = new AnonymousRemoteStorageAuthorization(); break; case AuthorizationModes.Windows: authorization = new WindowsRemoteStorageAuthorization(); break; case AuthorizationModes.Community: authorization = new CommunityRemoteStorageAuthorization(); break; case AuthorizationModes.Custom: authorization = _customAutorization; break; default: throw new ArgumentOutOfRangeException(); } var server = new HydraServer(_storageRegistry, _entityRegistry, Sources) { Authorization = authorization, MaxSecurityCount = _entityRegistry.Settings.MaxSecurityCount }; _logManager.Sources.Add(server); _host = new ServiceHost <HydraServer>(server); _host.Open(); } if (_timer != null) { _timer.Stop(); if (_killTimer != null) { _killTimer.Stop(); } } if (_entityRegistry.Settings.AutoStop) { _timer = new Timer(TimeSpan.FromSeconds(30).TotalMilliseconds) { AutoReset = true }; _timer.Elapsed += (s, args) => { var time = DateTime.Now.TimeOfDay; if (time >= _entityRegistry.Settings.StopTime && time < _entityRegistry.Settings.StopTime + TimeSpan.FromMinutes(5)) { GuiDispatcher.GlobalDispatcher.AddAction(AutoStopAndKill); } }; _timer.Start(); } //if (!CurrentSources.IsNull()) //{ // DockSite.DocumentWindows // .Where(d => d is SourceWindow) // .ForEach(d => ((SourceWindow)d).TaskControl.SecuritiesCtrl.ChangeExtendedColumnVisible()); //} }
/// <summary> /// analyze data object event flow /// </summary> public void App(int TimeStamp) { Console.WriteLine("Starting observable source..."); using (var source = new RandomObject <Car>(NoSeconds, NoValues, CountMax, NoSegments, TimeStamp))//genereaza o data la fiecare 500 milisecunde { Console.WriteLine("Started observable source."); using (var server = Server.Create("Default")) { var host = new ServiceHost(server.CreateManagementService()); host.AddServiceEndpoint(typeof(IManagementService), new WSHttpBinding(SecurityMode.Message), "http://localhost/MyStreamInsightApp"); host.Open(); var myApp = server.CreateApplication("serverApp"); Console.WriteLine("convert source to stream"); var stream = source.ToPointStream(myApp, e => PointEvent.CreateInsert(DateTime.Now, new Payload <Car> { Value = e }), AdvanceTimeSettings.StrictlyIncreasingStartTime, "Observable Stream"); //Console.ReadLine() ; //query that sums of events within 2 second tumbling windows var thumblingResult = from ob in stream.TumblingWindow(TimeSpan.FromSeconds(2), HoppingWindowOutputPolicy.ClipToWindowEnd) select new { avreageT = ob.Avg(e => e.Value.Speed), }; //List<double> list; //var query = from ob in stream // where ob.Value.Speed < 50 // select ob.Value; //var query = from cars in stream.SnapshotWindow() // select new { // avreage = cars.Avg(e => e.Value.Speed), // groupId=1 // }; //var query = from ob in stream.HoppingWindow(TimeSpan.FromSeconds(WinSize), TimeSpan.FromSeconds(1)) // select new // { // avreage = ob.Avg(e => e.Value.Speed), // groupId = 1 // }; var query = from rs in stream group rs by rs.Value.RoadSegment into roadSeg from ob in roadSeg.HoppingWindow(TimeSpan.FromSeconds(WinSize), TimeSpan.FromSeconds(5)) select new { avreage = ob.Avg(e => e.Value.Speed), groupId = roadSeg.Key }; //var query = from rs in stream // group rs by rs.Value.RoadSegment into roadSeg // from ob in roadSeg.SnapshotWindow() // select new // { // avreage = ob.Avg(e => e.Value.Speed), // groupId = roadSeg.Key // }; var enumerator = query.ToPointEnumerable().GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.EventKind == EventKind.Insert) { var s = enumerator.Current.Payload.ToString(); //if (s.Length > 0) // DB.Write(s); //Console.WriteLine(s); DB.Write(TimeStamp, s); RetrieveDiagnostics rD = new RetrieveDiagnostics(); DiagnosticSettings settings = new DiagnosticSettings(DiagnosticAspect.GenerateErrorReports, DiagnosticLevel.Always); server.SetDiagnosticSettings(new Uri("cep:/Server"), settings); rD.FileWrite(server.GetDiagnosticView(new Uri("cep:/Server/EventManager")), WinSize); rD.FileWrite(server.GetDiagnosticView(new Uri("cep:/Server/Query")), WinSize); } } host.Close(); } //Count<Car> count = new Count<Car>(50); //Console.WriteLine("-------------" + count.NoOptimal); Console.WriteLine("The end"); source.OnCompleted(); } Console.WriteLine("Stopped observable source."); //Console.ReadLine(); }
public static void StartService <T>(string base_url, params Assembly[] ass) where T : IClientMessageInspector, IDispatchMessageInspector, new() { if (ValidateHelper.IsPlumpList(_hosts)) { throw new Exception("服务已经启动"); } base_url = base_url ?? string.Empty; if (!base_url.EndsWith("/")) { throw new Exception("base_url必须以/结尾"); } if (!ValidateHelper.IsPlumpList(ass)) { throw new ArgumentNullException(nameof(ass)); } try { foreach (var a in ass) { foreach (var service in a.FindServiceContractsImpl()) { var contracts = service.FindServiceContracts(); if (!ValidateHelper.IsPlumpList(contracts)) { continue; } var host = new ServiceHost(service, new Uri(base_url + service.Name)); foreach (var c in contracts) { host.AddServiceEndpoint(c, new BasicHttpBinding(), c.Name); } foreach (var ep in host.Description.Endpoints) { ep.EndpointBehaviors.Add(new MyEndPointBehavior <T>()); } var metaBehavior = host.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (metaBehavior != null) { metaBehavior.HttpGetEnabled = true; metaBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; } else { metaBehavior = new ServiceMetadataBehavior(); metaBehavior.HttpGetEnabled = true; metaBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(metaBehavior); } var dataContractBehavior = host.Description.Behaviors.Find <DataContractSerializerOperationBehavior>(); if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = 65536000; } var debugBehavior = host.Description.Behaviors.Find <ServiceDebugBehavior>(); if (debugBehavior != null) { debugBehavior.IncludeExceptionDetailInFaults = true; } else { debugBehavior = new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true }; host.Description.Behaviors.Add(debugBehavior); } host.Open(); _hosts.Add(host); } } } catch (Exception e) { DisposeService(); throw new Exception("一个或多个服务启动失败,已经销毁所有已经启动的服务", e); } }
protected virtual void AddServiceEndpointBehaviors(ServiceHost serviceHost) { }
public async Task <ResultStatus> TryExecuteRemote(Command command, BuilderContext builderContext, IExecuteContext executeContext, LocalCommandContext commandContext) { while (!CanSpawnParallelProcess()) { await Task.Delay(1, command.CancellationToken); } var address = "net.pipe://localhost/" + Guid.NewGuid(); var arguments = $"--slave=\"{address}\" --build-path=\"{builderOptions.BuildDirectory}\""; using (var debugger = VisualStudioDebugger.GetAttached()) { if (debugger != null) { arguments += $" --reattach-debugger={debugger.ProcessId}"; } } // Start WCF pipe for communication with process var processBuilderRemote = new ProcessBuilderRemote(assemblyContainer, commandContext, command); var host = new ServiceHost(processBuilderRemote); host.AddServiceEndpoint(typeof(IProcessBuilderRemote), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { MaxReceivedMessageSize = int.MaxValue }, address); var startInfo = new ProcessStartInfo { // Note: try to get exec server if it exists, otherwise use CompilerApp.exe FileName = (string)AppDomain.CurrentDomain.GetData("RealEntryAssemblyFile") ?? typeof(PackageBuilder).Assembly.Location, Arguments = arguments, WorkingDirectory = Environment.CurrentDirectory, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; host.Open(); var output = new List <string>(); var process = new Process { StartInfo = startInfo }; process.Start(); process.OutputDataReceived += (_, args) => LockProcessAndAddDataToList(process, output, args); process.ErrorDataReceived += (_, args) => LockProcessAndAddDataToList(process, output, args); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Note: we don't want the thread to schedule another job since the CPU core will be in use by the process, so we do a blocking WaitForExit. process.WaitForExit(); host.Close(); NotifyParallelProcessEnded(); if (process.ExitCode != 0) { executeContext.Logger.Error($"Remote command crashed with output:{Environment.NewLine}{string.Join(Environment.NewLine, output)}"); } if (processBuilderRemote.Result != null) { // Register results back locally foreach (var outputObject in processBuilderRemote.Result.OutputObjects) { commandContext.RegisterOutput(outputObject.Key, outputObject.Value); } // Register log messages foreach (var logMessage in processBuilderRemote.Result.LogMessages) { commandContext.Logger.Log(logMessage); } // Register tags foreach (var tag in processBuilderRemote.Result.TagSymbols) { commandContext.AddTag(tag.Key, tag.Value); } } return(command.CancellationToken.IsCancellationRequested ? ResultStatus.Cancelled : (process.ExitCode == 0 ? ResultStatus.Successful : ResultStatus.Failed)); }
public ServiceModelConnectorServer(Uri serviceUrl, IMBeanServer beanServer) { _beanServer = beanServer; _serviceUrl = serviceUrl; _serviceHost = new ServiceHost(new MBeanServerService(beanServer), _serviceUrl); }
protected WindowsManagedService(Type serviceType) { serviceHost = new ServiceHost(serviceType); }
public static void StartServer(int port, string dnsIdentity, bool isHttp) { string prefix; if (isHttp) { prefix = "http://"; } else { prefix = "net.tcp://"; } //--------------------------------------------------------------------------------- try { CoreConfiguration.TryConfiguration(); } catch (Exception ex) { SystemMessage.Log(ex); } //--------------------------------------------------------------------------------- string editServiceUrl = String.Format("{0}localhost:{1}/Services/TestEdit.svc", prefix, port); string clientServiceUrl = String.Format("{0}localhost:{1}/Services/TestClient.svc", prefix, port); string userServiceUrl = String.Format("{0}localhost:{1}/Services/UserManagement.svc", prefix, port); string helperServiceUrl = String.Format("{0}localhost:{1}/Services/HelperService.svc", prefix, port); editHost = new ServiceHost(typeof(TestEdit)); clientHost = new ServiceHost(typeof(TestClient)); userHost = new ServiceHost(typeof(UserManagement)); helperHost = new ServiceHost(typeof(HelperService)); //---------------------------------------------------------- Binding binding; if (isHttp) { binding = new WSHttpBinding(SecurityMode.Message, true); WSHttpBinding httpBinding = (binding as WSHttpBinding); httpBinding.TransactionFlow = false; httpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; httpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue; httpBinding.MaxReceivedMessageSize = int.MaxValue; httpBinding.MaxBufferPoolSize = int.MaxValue; } else { binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true); NetTcpBinding tcpBinding = (binding as NetTcpBinding); tcpBinding.TransactionFlow = false; tcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; tcpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue; tcpBinding.MaxReceivedMessageSize = int.MaxValue; tcpBinding.MaxBufferPoolSize = int.MaxValue; tcpBinding.MaxConnections = 150000; } //---------------------------------------------------------- //makecert.exe -n CN=localhost -ss My -pe -sky exchange -sr LocalMachine ServiceEndpoint editServiceEndpoint = editHost.AddServiceEndpoint( typeof(ITestEdit), binding, editServiceUrl); ServiceEndpoint clientServiceEndpoint = clientHost.AddServiceEndpoint( typeof(ITestClient), binding, clientServiceUrl); ServiceEndpoint userServiceEndpoint = userHost.AddServiceEndpoint( typeof(IUserManagement), binding, userServiceUrl); ServiceEndpoint helperServiceEndpoint = helperHost.AddServiceEndpoint( typeof(IHelperService), binding, helperServiceUrl); //---------------------------------------------------------- EndpointAddress editEndpointAdd = new EndpointAddress(new Uri(editServiceUrl), EndpointIdentity.CreateDnsIdentity(dnsIdentity)); editServiceEndpoint.Address = editEndpointAdd; EndpointAddress clientEndpointAdd = new EndpointAddress(new Uri(clientServiceUrl), EndpointIdentity.CreateDnsIdentity(dnsIdentity)); clientServiceEndpoint.Address = clientEndpointAdd; EndpointAddress userEndpointAdd = new EndpointAddress(new Uri(userServiceUrl), EndpointIdentity.CreateDnsIdentity(dnsIdentity)); userServiceEndpoint.Address = userEndpointAdd; EndpointAddress helperEndpointAdd = new EndpointAddress(new Uri(helperServiceUrl), EndpointIdentity.CreateDnsIdentity(dnsIdentity)); helperServiceEndpoint.Address = helperEndpointAdd; //---------------------------------------------------------- if (isHttp) { ServiceMetadataBehavior editServiceMetadataBehavior = new ServiceMetadataBehavior(); editServiceMetadataBehavior.HttpGetUrl = new Uri(editServiceUrl); editServiceMetadataBehavior.HttpGetEnabled = true; editHost.Description.Behaviors.Add(editServiceMetadataBehavior); ServiceMetadataBehavior clientServiceMetadataBehavior = new ServiceMetadataBehavior(); clientServiceMetadataBehavior.HttpGetUrl = new Uri(clientServiceUrl); clientServiceMetadataBehavior.HttpGetEnabled = true; clientHost.Description.Behaviors.Add(clientServiceMetadataBehavior); ServiceMetadataBehavior userServiceMetadataBehavior = new ServiceMetadataBehavior(); userServiceMetadataBehavior.HttpGetUrl = new Uri(userServiceUrl); userServiceMetadataBehavior.HttpGetEnabled = true; userHost.Description.Behaviors.Add(userServiceMetadataBehavior); ServiceMetadataBehavior helperServiceMetadataBehavior = new ServiceMetadataBehavior(); helperServiceMetadataBehavior.HttpGetUrl = new Uri(helperServiceUrl); helperServiceMetadataBehavior.HttpGetEnabled = true; helperHost.Description.Behaviors.Add(helperServiceMetadataBehavior); } //---------------------------------------------------------- ServiceCredentials serviceCredintails = new ServiceCredentials(); serviceCredintails.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredintails.UserNameAuthentication.CustomUserNamePasswordValidator = new TestorUserNameValidator(); serviceCredintails.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, dnsIdentity); editHost.Description.Behaviors.Add(serviceCredintails); clientHost.Description.Behaviors.Add(serviceCredintails); userHost.Description.Behaviors.Add(serviceCredintails); helperHost.Description.Behaviors.Add(serviceCredintails); //---------------------------------------------------------- editHost.Open(); clientHost.Open(); userHost.Open(); helperHost.Open(); }
protected override void OnStart(string[] args) { _host?.Close(); //just to be safe _host = new ServiceHost(typeof(EDITranslatorService)); _host.Open(); }
static void Main(string[] args) { try { if (args.Length < 2) { PrintUsage(); return; } int parentProcId; if (!int.TryParse(args[0], out parentProcId)) { PrintUsage(); return; } PipeName = args[1]; parentCheckTimer = new System.Timers.Timer(); parentCheckTimer.Interval = ParentCheckInterval; parentCheckTimer.AutoReset = true; parentCheckTimer.Elapsed += (o, e) => { try { if (!ProcessExists(parentProcId)) { // If we couldn't stop the process, just wait until next tick. May have not started yet or may // already be in the process of closing. if (HandBrakeEncoder.CurrentEncoder != null && HandBrakeEncoder.CurrentEncoder.StopEncodeIfPossible()) { // If we are able to stop the encode, we will do so. Cleanup should // happen with the encode complete callback. Console.WriteLine("Parent no longer exists, stopping encode."); } } } catch (Exception exception) { WorkerLogger.Log("Exception in parentCheckTimer.Elapsed: " + exception.ToString(), isError: true); throw; } }; parentCheckTimer.Start(); ServiceHost host = null; try { host = new ServiceHost(typeof(HandBrakeEncoder)); host.AddServiceEndpoint( typeof(IHandBrakeEncoder), new NetNamedPipeBinding(), "net.pipe://localhost/" + PipeName); host.Open(); encodeComplete = new ManualResetEventSlim(false); Console.WriteLine("Service state is " + host.State + " on pipe " + PipeName); encodeComplete.Wait(); host.Close(); } catch (CommunicationException exception) { WorkerLogger.Log("Exception when trying to establish pipe service: " + exception, isError: true); if (host != null) { host.Abort(); } } catch (TimeoutException exception) { WorkerLogger.Log("Exception when trying to establish pipe service: " + exception, isError: true); if (host != null) { host.Abort(); } } catch (Exception) { if (host != null) { host.Abort(); } throw; } } catch (Exception exception) { WorkerLogger.Log("Exception in Main: " + exception, isError: true); throw; } }
static void Main(string[] args) { //string srvCertCN = "sbesservice"; string srvCertCN = CertManager.Formatter.ParseName(WindowsIdentity.GetCurrent().Name); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; ServiceHost host = new ServiceHost(typeof(WCFService)); string address = "net.tcp://localhost:9999/Receiver"; host.AddServiceEndpoint(typeof(IWCFContract), binding, address); host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; host.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new ServiceCertValidator(); host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; host.Credentials.ServiceCertificate.Certificate = Manager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine, srvCertCN); host.Description.Behaviors.Remove(typeof(ServiceDebugBehavior)); host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true }); host.Authorization.ServiceAuthorizationManager = new CustomServiceAuthorizationManager(); host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom; List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(); policies.Add(new CustomAuthorizationPolicy()); host.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly(); // log event podesavanja ServiceSecurityAuditBehavior newAudit = new ServiceSecurityAuditBehavior(); newAudit.AuditLogLocation = AuditLogLocation.Application; newAudit.ServiceAuthorizationAuditLevel = AuditLevel.SuccessOrFailure; newAudit.SuppressAuditFailure = true; host.Description.Behaviors.Remove <ServiceSecurityAuditBehavior>(); host.Description.Behaviors.Add(newAudit); Console.WriteLine("Korisnik {0} je pokrenuo servera", WindowsIdentity.GetCurrent().Name); try { host.Open(); Console.WriteLine("WCFService is started.\nPress <enter> to stop ..."); Console.ReadLine(); } catch (Exception e) { Console.WriteLine("[ERROR] {0}", e.Message); Console.WriteLine("[StackTrace] {0}", e.StackTrace); } finally { host.Close(); } }
private void InitializeHosts() { host = new ServiceHost(casSubscriber); }
public Result OnStartup(UIControlledApplication application) { _instance = this; _application = application; try { _serviceHost = new ServiceHost(typeof(SockeyeService), new Uri("net.pipe://localhost/mcneel/sockeyeserver/1/server")); } catch { TaskDialog.Show("Sockeye", "Failed to create Sockeye service host."); throw; } try { _serviceHost.AddServiceEndpoint(typeof(ISockeyeService), new NetNamedPipeBinding(), "pipe"); } catch { TaskDialog.Show("Sockeye", "Failed to create Sockeye service end point."); throw; } try { ServiceDebugBehavior debugBehavior = _serviceHost.Description.Behaviors.Find <ServiceDebugBehavior>(); if (null == debugBehavior) { debugBehavior = new ServiceDebugBehavior(); debugBehavior.IncludeExceptionDetailInFaults = true; _serviceHost.Description.Behaviors.Add(debugBehavior); } else { debugBehavior.IncludeExceptionDetailInFaults = true; } } catch { TaskDialog.Show("Sockeye", "Failed to create Sockeye service debug behavior."); throw; } try { _serviceHost.Open(); } catch { TaskDialog.Show("Sockeye", "Failed to open Sockeye service."); throw; } RibbonPanel ribbonPanel = application.CreateRibbonPanel(_assemblyTitle); PushButton pushButton = ribbonPanel.AddItem(new PushButtonData( _assemblyTitle, _assemblyTitle, _assemblyLocation, "SockeyeServer.Commands.CmdAbout")) as PushButton; Bitmap logo = SockeyeServer.Properties.Resources.Logo_32_32; BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( logo.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; return(Result.Succeeded); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { ServiceHost.Run( host => { host.RegisterStatefulActorService <SubscriptionActor>("SubscriptionActor"); host.RegisterStatefulActorService <PullRequestActor>("PullRequestActor"); host.ConfigureContainer( builder => { builder.AddServiceFabricActor <IPullRequestActor>(); builder.AddServiceFabricActor <ISubscriptionActor>(); }); host.ConfigureServices( services => { services.AddSingleton <IActionRunner, ActionRunner>(); services.AddSingleton <IMergePolicyEvaluator, MergePolicyEvaluator>(); services.AddSingleton <IRemoteFactory, DarcRemoteFactory>(); services.AddSingleton <TemporaryFiles>(); services.AddGitHubTokenProvider(); services.AddAzureDevOpsTokenProvider(); // We do not use AddMemoryCache here. We use our own cache because we wish to // use a sized cache and some components, such as EFCore, do not implement their caching // in such a way that will work with sizing. services.AddSingleton <DarcRemoteMemoryCache>(); services.AddKeyVaultMappedConfiguration(); services.AddBuildAssetRegistry( (provider, options) => { var config = provider.GetRequiredService <IConfigurationRoot>(); options.UseSqlServer(config.GetSection("BuildAssetRegistry")["ConnectionString"]); }); services.Configure <GitHubClientOptions>(o => { o.ProductHeader = new ProductHeaderValue("Maestro", Assembly.GetEntryAssembly() .GetCustomAttribute <AssemblyInformationalVersionAttribute>() ?.InformationalVersion); }); services.Configure <GitHubTokenProviderOptions>( (options, provider) => { var config = provider.GetRequiredService <IConfigurationRoot>(); IConfigurationSection section = config.GetSection("GitHub"); section.Bind(options); }); services.Configure <AzureDevOpsTokenProviderOptions>( (options, provider) => { var config = provider.GetRequiredService <IConfigurationRoot>(); var tokenMap = config.GetSection("AzureDevOps:Tokens").GetChildren(); foreach (IConfigurationSection token in tokenMap) { options.Tokens.Add(token.GetValue <string>("Account"), token.GetValue <string>("Token")); } }); services.AddMergePolicies(); }); }); }
public HostRecord(ServiceHost host, string address) { Host = host; Address = address; }
/// <summary> /// Главная точка входа для приложения. /// </summary> static void Main() { XmlConfigurator.Configure(); logger.Info("Starting service"); String baseURL = ""; Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); logger.Info("Getting Base URL"); bool isService = true; try { baseURL = ConfigurationManager.AppSettings["baseURL"]; } catch (Exception e) { logger.Fatal("Error while starting service", e); throw e; } try { isService = ConfigurationManager.AppSettings["runAsService"].ToLower().Equals("true"); } catch (Exception e) { logger.Fatal("Error while starting service", e); throw e; } logger.Info(String.Format("Base URL is: {0}", baseURL)); UriBuilder builder = new UriBuilder(baseURL); builder.Path = "win32lib"; String baseHost = builder.ToString(); ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig); ServicesSection services = serviceModel.Services; List <ServiceHost> hosts = new List <ServiceHost>(); logger.Info("Initializing hosts"); try { foreach (ServiceElement svc in services.Services) { logger.Info("Getting configuration information"); //svc.Name String svcName = svc.Name; logger.Info(String.Format("Service Name: {0}", svcName)); Type type = Type.GetType(svc.Name); logger.Info(String.Format("Type: {0}", type)); String url = baseHost + "/" + type.Name.ToLower(); Uri[] URIs = { new Uri(url) }; //System.Console.WriteLine(String.Format("Initializing host for URL: {0}", url)); logger.Info(String.Format("Initializing host for URL: {0}", url) + ""); //Type type = Type.GetType(svc.Name); ServiceHost host = new ServiceHost(type, URIs); hosts.Add(host); } } catch (Exception e) { logger.Fatal("Error while starting service", e); throw e; } logger.Info("Running Hosts"); foreach (ServiceHost host in hosts) { host.Open(); } logger.Info("Starting Windows Service"); //while (Console.ReadKey(true).KeyChar != 'q') { ;} if (isService) { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Win32Service() }; ServiceBase.Run(ServicesToRun); } else { while (Console.ReadKey(true).KeyChar != 'q') { ; } } logger.Info("Stopping Service"); foreach (ServiceHost host in hosts) { host.Close(); } logger.Info("Service exit"); }
private void Form1_Load(object sender, EventArgs e) { host = new ServiceHost(typeof(EmployeeServiceRepository.EmployeeRepository)); }
private void Form1_Load(object sender, EventArgs e) { Host = new ServiceHost(typeof(ABService)); Host.Open(); }
public void AddServiceMetadataEndpoint() { var host = new ServiceHost(typeof(DummyService)); host.AddServiceEndpoint(new ServiceMetadataEndpoint()); }
public void Start() { if (!IsActive) { try { InstanceManager.Load(); ServerConfiguration instance = InstanceManager.Instances[_instanceName]; if (instance == null) { // Establish a default configuration instance = ServerConfiguration.DefaultInstance(_instanceName); InstanceManager.Instances.Add(instance); InstanceManager.Save(); } _server = new Server(); instance.ApplyTo(_server); _remoteServer = new RemoteServer(_server); _nativeServer = new NativeServer(_server); _server.Start(); try { _server.LogMessage("Creating WCF Service..."); _service = new DataphorService(_remoteServer); _server.LogMessage("Creating Native CLI Service..."); _nativeService = new NativeCLIService(_nativeServer); _server.LogMessage("Configuring Service Host..."); _serviceHost = instance.UseServiceConfiguration ? new CustomServiceHost(_service) : new ServiceHost(_service); if (!instance.UseServiceConfiguration) { _serviceHost.AddServiceEndpoint ( typeof(IDataphorService), DataphorServiceUtility.GetBinding(), DataphorServiceUtility.BuildInstanceURI(Environment.MachineName, instance.PortNumber, instance.Name) ); } _server.LogMessage("Opening Service Host..."); _serviceHost.Open(); _server.LogMessage("Configuring Native CLI Service Host..."); _nativeServiceHost = instance.UseServiceConfiguration ? new CustomServiceHost(_nativeService) : new ServiceHost(_nativeService); if (!instance.UseServiceConfiguration) { _nativeServiceHost.AddServiceEndpoint ( typeof(INativeCLIService), DataphorServiceUtility.GetBinding(), DataphorServiceUtility.BuildNativeInstanceURI(Environment.MachineName, instance.PortNumber, instance.Name) ); } _server.LogMessage("Opening Native CLI Service Host..."); _nativeServiceHost.Open(); // Start the listener if (instance.ShouldListen) { _server.LogMessage("Starting Listener Service..."); _listenerServiceHost = new ListenerServiceHost(instance.OverrideListenerPortNumber, instance.RequireSecureListenerConnection, instance.AllowSilverlightClients, instance.UseServiceConfiguration); } } catch (Exception exception) { _server.LogError(exception); throw; } } catch { Stop(); throw; } } }
public MyEndpointBehavior(HostState state, ServiceHost h) { _state = state; _host = h; }
protected override void OnStart(string[] args) { try { //if (!SecureWebConfig.Secured) //{ // SecureWebConfig.Secure(); //} } catch (Exception ex) { ServiceLogger.Error("Configuration cannot be read, reason: " + ex.Message); } ServiceTasks.LoadConfig(); // collect and pass back the list of known types WebServiceKnownTypesProvider.KnownTypes.Add(typeof(WebServiceStatus)); oServiceHost = new ServiceHost(oServiceType); try { if (oServiceHost.BaseAddresses.Count == 0) { string ba = DefaultHTTPUrl; //ExtensionHelpers.GetConfigString("WebServiceBaseURL"); if (string.IsNullOrEmpty(ba)) { if (UseHTTPS) { ba = DefaultHTTPSUrl; } else { ba = DefaultHTTPUrl; } } else { if (ba.Contains("http://")) { UseHTTPS = false; } } var baseAddresses = new Uri[] { new Uri(ba) }; oServiceHost = new ServiceHost(oServiceType, baseAddresses); var endpoint = CreateEndpoint(oServiceInterfaceType, ba); oServiceHost.AddServiceEndpoint(endpoint); ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior(); //metadataBehavior.HttpGetEnabled = true; oServiceHost.Description.Behaviors.Add(metadataBehavior); } oServiceHost.Authorization.ServiceAuthorizationManager = new RestAuthorizationManager(); oServiceHost.Open(); } catch (Exception ex) { ServiceLogger.Error("Service cannot be started, reason: " + ex.Message); return; } //Tasks.StartTimer(); StartHTTPCompanionService(oServiceHost.BaseAddresses[0].ToString()); ServiceLogger.Info("SERVICE STARTED"); foreach (var uri in oServiceHost.BaseAddresses) { ServiceLogger.Info("Listening on: " + uri); } }
private void Run() { // Get base address from app settings in configuration Uri baseAddress = new Uri(ConfigurationManager.AppSettings["baseAddress"]); //Create new address headers for special services and add them to an array AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader( "specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader( "specialservice2", "http://localhost:8000/service", 2); // Enumerate address headers and their properties from the array. AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; foreach (AddressHeader addressHeader in addressHeaders) { Console.WriteLine("AddressHeader - namespace:\t\t{0}", addressHeader.Namespace); Console.WriteLine(" - name:\t\t\t{0}", addressHeader.Name); Console.WriteLine(" - value:\t\t\t{0}", addressHeader.GetValue <int>()); Console.WriteLine(" - type:\t\t\t{0}", addressHeader.GetType()); Console.WriteLine(" - hashcode:\t\t{0}", addressHeader.GetHashCode()); Console.WriteLine(" - equals addressHeader1:\t{0}", addressHeader.Equals(addressHeader1)); // Console.WriteLine(" - Is SOAP1.1 supported:\t{0}", addressHeader.ToMessageHeader().IsMessageVersionSupported(MessageVersion.WSAddressingSoap10)); Console.WriteLine(); } Console.WriteLine(); //Add the array of address headers to an endpoint address EndpointAddress endpointAddress = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service"), addressHeaders); //Create a "special" service endpoint that uses the endpointAddress. string WSHttpBindingName = "Binding1"; ServiceEndpoint specialServiceEndpoint = new ServiceEndpoint( ContractDescription.GetContract(typeof(CalculatorService)), new WSHttpBinding(WSHttpBindingName), endpointAddress ); // Create a ServiceHost for the CalculatorService type that uses the base address. ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress); //Add the specialServiceEndpoint to the serviceHost. serviceHost.Description.Endpoints.Add(specialServiceEndpoint); // Enumerate the service endpoints and some of their properties from the serviceHost. Console.WriteLine("Service endpoints:"); ServiceDescription desc = serviceHost.Description; foreach (ServiceEndpoint endpoint in desc.Endpoints) { Console.WriteLine("Endpoint - address: {0}", endpoint.Address); Console.WriteLine(" - binding name:\t\t{0}", endpoint.Binding.Name); // Console.WriteLine(" - binding name:\t\t{0}", endpoint.); Console.WriteLine(" - contract name:\t\t{0}", endpoint.Contract.Name); Console.WriteLine(" - contains addressHeader1:\t{0}", endpoint.Address.Headers.Contains(addressHeader1)); Console.WriteLine(" - count of address headers:\t{0}", endpoint.Address.Headers.Count); Console.WriteLine(); } Console.WriteLine(); // Open the ServiceHostBase to create listeners and start listening for messages. serviceHost.Open(); // The service can now be accessed. Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. serviceHost.Close(); }
private static void StartService() { host = WcfServiceHostFactory.CreateServiceHost <Service>(); host.Open(); }
protected override void OnStart(string[] args) { _remoteSessionProcess = OpenService(typeof(RemoteSessionProcess)); _localFileStorage = OpenService(typeof(FileStorage)); }
static int Main(string[] args) { Options options = new Options(); Plossum.CommandLine.CommandLineParser parser = new Plossum.CommandLine.CommandLineParser(options); parser.Parse(); Console.WriteLine(parser.UsageInfo.GetHeaderAsString(78)); if (options.Help) { Console.WriteLine(parser.UsageInfo.GetOptionsAsString(20, 56)); return(0); } else if (parser.HasErrors) { Console.WriteLine(parser.UsageInfo.GetErrorsAsString(78)); Console.WriteLine("type --help for list of available options."); return(-1); } Console.Write("Initializing communication plugins... "); Env.Initialize(null, new Commands(), FreeSCADA.Interfaces.EnvironmentMode.Runtime); Env.Current.Project.Load(options.ProjectFile); CommunationPlugs plugs = Env.Current.CommunicationPlugins; if (plugs.Connect() == false) { Env.Deinitialize(); return(-1); } Console.WriteLine("Done."); Uri baseAddress = new Uri(string.Format("http://{0}:{1}/", System.Windows.Forms.SystemInformation.ComputerName, options.Port)); ServiceHost host = new ServiceHost(typeof(Service), baseAddress); try { host.AddServiceEndpoint(typeof(IChannelInformationRetriever), new WSDualHttpBinding(WSDualHttpSecurityMode.None), "ChannelInformationRetriever"); host.AddServiceEndpoint(typeof(IDataRetriever), new WSDualHttpBinding(WSDualHttpSecurityMode.None), "DataRetriever"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); ServiceThrottlingBehavior throttlingBehavior = new ServiceThrottlingBehavior(); throttlingBehavior.MaxConcurrentCalls = Int32.MaxValue; throttlingBehavior.MaxConcurrentInstances = Int32.MaxValue; throttlingBehavior.MaxConcurrentSessions = Int32.MaxValue; host.Description.Behaviors.Add(throttlingBehavior); host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.None; host.Open(); Console.WriteLine("Server address {0}", baseAddress.AbsoluteUri); Console.WriteLine("Press <ENTER> to terminate"); Console.ReadLine(); Console.WriteLine("Terminating. Please wait..."); host.Close(); } catch (CommunicationException cex) { Console.WriteLine("Error occured: {0}", cex.Message); host.Abort(); } plugs.Disconnect(); Env.Deinitialize(); return(0); }
/// <summary> /// Initializes the Server to receive follower connections /// </summary> internal static void ServerInitialize() { if (!AutoFollow.Enabled) { return; } if (Service.ConnectionMode != ConnectionMode.Server) { return; } if (DateTime.UtcNow < DontAttemptServerModeUntil) { return; } if (DateTime.UtcNow.Subtract(LastFailTime).TotalSeconds < 5) { return; } ServerStartAttempts++; try { var portIsTaken = true; ServerUri = new Uri(ServerUri.AbsoluteUri.Replace(_basePort.ToString(), Settings.Network.ServerPort.ToString())); _basePort = Settings.Network.ServerPort; var serverPort = _basePort; while (portIsTaken && AutoFollow.Enabled) { var ipgp = IPGlobalProperties.GetIPGlobalProperties(); var tcpListeners = ipgp.GetActiveTcpListeners(); if (tcpListeners.Any(listner => listner.Port == serverPort)) { portIsTaken = false; serverPort += 1; } else { portIsTaken = false; } } Log.Info("Initializing Server Service @ {0} Attempt={1}", ServerUri.AbsoluteUri, ServerStartAttempts); ServiceHost = new ServiceHost(typeof(Service), ServerUri); ServiceHost.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Follow"); ServiceHost.Open(); ServerInitialized = true; if (OnServerInitialized != null) { OnServerInitialized.Invoke(); } } catch (AddressAlreadyInUseException ex) { Log.Verbose("Address already in use. Attempt={0}", ServerStartAttempts); Log.Debug(ex.ToString()); DontAttemptServerModeUntil = DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)); LastFailTime = DateTime.UtcNow; Server.ShutdownServer(); Client.ShutdownClient(); Service.ConnectionMode = ConnectionMode.Client; } catch (Exception ex) { Log.Verbose("Could not initialize service. Do you already have a leader started? Attempt={0}", ServerStartAttempts); Log.Debug(ex.ToString()); LastFailTime = DateTime.UtcNow; } if (ServerStartAttempts > 5 && !IsValid) { Service.ConnectionMode = ConnectionMode.Client; } }
public SmapiSoapServiceBootstrapper(ServerBuilder serverBuilder, ServerConfiguration config) { _server = serverBuilder.HostedAt(new Uri(config.BaseUrl + ":" + config.BasePort)); }