protected override void OnStart(string[] args)
        {
            ////Just to be safe
            //myHost?.Close();
            ////Create the service
            //myHost = new ServiceHost(typeof(MathService));
            ////The ABCs in Code!
            //Uri address = new Uri("http://localhost:8080/MathServiceLibrary");
            //WSHttpBinding binding = new WSHttpBinding();
            //Type contract = typeof(IBasicMath);

            ////Add the endpoint
            //myHost.AddServiceEndpoint(contract, binding, address);

            ////Open the host
            //myHost.Open();

            //Using the defaults
            myHost?.Close();
            // Create the host and specify a URL for an HTTP binding.
            myHost = new ServiceHost(typeof(MathService),
                                     new Uri("http://localhost:8080/MathServiceLibrary"));
            myHost.AddDefaultEndpoints();

            // Open the host.
            myHost.Open();
        }
Exemplo n.º 2
0
        protected override void OnStart(string[] args)
        {
            _serviceHost?.Close();

            _serviceHost = new ServiceHost(typeof(LineService));
            _serviceHost.Open();
        }
Exemplo n.º 3
0
        private void StopService()
        {
            if (_tasks != null)
            {
                _logger.LogTextMessage("Stopping timer thread...");
                _timerCancellationToken.Cancel();
                try
                {
                    Task.WaitAll(_tasks.ToArray());
                }
                catch (Exception)
                {
                }
                _logger.LogTextMessage("Stopping timer thread - OK");
            }

            _logger.LogTextMessage("Closing host...");
            try
            {
                _host?.Close();
                _host = null;
            }
            catch (Exception exception)
            {
                _logger.LogTextMessage($"Error while closing host:\n{exception.Message}\nStack:\n{exception.StackTrace}");
            }
            _logger.LogTextMessage("Closing host - OK");
        }
Exemplo n.º 4
0
        protected override void OnStart(string[] args)
        {
            try
            {
                string serviceAddress = $"http://{new WebClient().DownloadString("http://icanhazip.com").TrimEnd(Environment.NewLine.ToCharArray())}:2001";

                Uri baseAddress = new Uri(serviceAddress);
                serviceHost?.Close();

                // Create a ServiceHost for the CalculatorService type and
                // provide the base address.
                serviceHost = new ServiceHost(typeof(BalboaHotTub), baseAddress);

                Trace.WriteLine(serviceHost.BaseAddresses[0].AbsoluteUri);

                // Open the ServiceHostBase to create listeners and start
                // listening for messages.
                serviceHost.Open();
            }
            catch (Exception ex)
            {
                Trace.AutoFlush = true;
                Trace.WriteLine(ex);
            }
        }
 protected override void OnStart(string[] args)
 {
     #region Temperature Host
     _temperatureHost?.Close();
     _temperatureHost = new ServiceHost(new HardwareMonitorTemperatureWinService(CURRENT_UPDATE_TIME_SPAN));
     _temperatureHost.Open();
     #endregion
 }
Exemplo n.º 6
0
        protected override void OnStop()
        {
#if !DEBUG
            Logger.Information("Close WCF hosting");
            _serviceHost?.Close();
            _serviceHost = null;
#endif
        }
        public override bool Pause(TimeSpan timeout)
        {
            if ((_host?.State ?? CommunicationState.Opened) == CommunicationState.Opened ||
                (_host?.State ?? CommunicationState.Opening) == CommunicationState.Opening)
            {
                _host?.Close(timeout);
            }

            return(_host != null);
        }
Exemplo n.º 8
0
        protected override void OnStart(string[] args)
        {
            _myHost?.Close();
//            _myHost = new ServiceHost(typeof(MathServiceLibrary.MathService));
//            var address = new Uri("http://localhost:8080/MathServiceLibrary");
//            var binding = new WSHttpBinding();
//            var contract = typeof(IBasicMath);
//            _myHost.AddServiceEndpoint(contract, binding, address);

            var address = new Uri("http://localhost:8080/MathServiceLibrary");

            _myHost = new ServiceHost(typeof(MathServiceLibrary.MathService), address);
            _myHost.AddDefaultEndpoints();
            _myHost.Open();
        }
Exemplo n.º 9
0
 protected override void OnStart(string[] args)
 {
     Service?.Close();
     Service = new ServiceHost(typeof(ServiceTest));
     Service.Open();
     new Thread(StartOutlook).Start();
 }
Exemplo n.º 10
0
 internal void Stop()
 {
     _service?.Close();
     _service = null;
     _sync?.Close();
     _sync = null;
 }
Exemplo n.º 11
0
        public bool Start(HostControl hostControl)
        {
            serviceHost?.Close();

            //Для создания и запуска WCF-службы не обязательно создавать конфигурационный файл для приложения
            //Это имеет смысл в службах, настройки которых никогда не будут меняться
            //Данный метод не является лучшей практикой использования WCF.
            //Для создания расширяемых и модульных приложений лучше использовать стандартный способ: комбинация app.config и запуска сервиса из кода.


            //Чтобы WCF-сервис заработал достаточно написать следующие строки:
            ServiceHost host = new ServiceHost(typeof(MyService));

            BasicHttpBinding binding = new BasicHttpBinding();

            binding.MaxReceivedMessageSize              = Int32.MaxValue;
            binding.ReaderQuotas.MaxArrayLength         = Int32.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

            host.AddServiceEndpoint(typeof(IMyService), binding, new Uri("http://127.0.0.1:12345/"));

            //нужно добавить "поведение" нашему сервису и указать точку подключения, через которую можно будет скачать WSDL. Делается это так:
            host.Description.Behaviors.Add(new ServiceMetadataBehavior());
            host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
                                    MetadataExchangeBindings.CreateMexHttpBinding(), "http://127.0.0.1:12345/mex");

            host.Open();

            return(true);
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            ServiceHost serviceHost = null;

            try
            {
                Console.WriteLine("Starting Host");


                try
                {
                    //konkreter type. muss instanzierbar sein
                    serviceHost = new ServiceHost(typeof(Demo.Implementation.Demo));
                    //BasicHttpBinding doesnt allow Sessions, so one Instance per Call
                    serviceHost.AddServiceEndpoint(typeof(IDemo), new WSHttpBinding(), "http://localhost:4711/DemoService");
                    serviceHost.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ServiceHost: " + ex.Message);
                }
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
                Console.ReadKey();
            }
            finally
            {
                serviceHost?.Close();
            }
        }
        protected override void OnStart(string[] args)
        {
            ServiceHost?.Close();

            ServiceHost = new ServiceHost(typeof(Receiver));
            ServiceHost.Open();
        }
Exemplo n.º 14
0
        protected override void OnStart(string[] args)
        {
            JLogger.LogInfo(this, "OnStart() Start");

            base.OnStart(args);
            _host?.Close();

            try
            {
                JLogger.LogDebug(this, "Se crea el service host con la direccion base.");
                var baseAddress = new Uri("http://localhost:8080/CommandService");
                _host = new ServiceHost(typeof(CommandService), baseAddress);

                JLogger.LogDebug(this, "Se configura para presentar el metadata.");
                var smb = new ServiceMetadataBehavior
                {
                    HttpGetEnabled   = true,
                    MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
                };
                _host.Description.Behaviors.Add(smb);

                JLogger.LogDebug(this, "Se Abre la comunicacion.");
                _host.Open();
            }
            catch (Exception ex)
            {
                JLogger.LogError(this, "Error al crear el host.", ex);
            }

            JLogger.LogInfo(this, "OnStart() End");
        }
        public void Stop()
        {
            try
            {
                vicinity_wcf_host?.Close();
                if (_eventThreads != null)
                {
                    foreach (var item in _eventThreads)
                    {
                        item.Abort();
                        item.Join();
                    }
                    _eventThreads?.Clear();
                    _eventThreads = null;
                }
                if (_devices != null)
                {
                    _devices.Clear();
                    _devices = null;
                }
                if (_actions != null)
                {
                    _actions.Clear();
                    _actions = null;
                }
            }
            catch (Exception e)
            {
                Logger.Log(LogMsgType.ERROR, e.ToString(), LogAuthor.Adapter);
            }

            Logger.Log(LogMsgType.INFO, "Service and events stopped!", LogAuthor.Adapter);
        }
Exemplo n.º 16
0
        static void Main()
        {
            //Console.WriteLine("Start legacy application");

            //IStockCheck stockCheck = new StockCheck();
            //stockCheck.Monitor(100);

            //Console.WriteLine("End legacy application");

            Console.WriteLine("Starting Service Host . . . ");
            ServiceHost serviceHost = new ServiceHost(typeof(MagicEightBallService));

            try
            {
                // Open the host and start listening for incoming messages.
                serviceHost.Open();
                DisplayHostInfo(serviceHost);
                // Keep the service running
                Console.WriteLine("The service is ready.");
                Thread.Sleep(Timeout.Infinite);
                // Console.WriteLine("Press the Enter key to terminate service.");
                // Console.ReadLine();
            }
            catch
            {
                serviceHost?.Close();
                Console.WriteLine("The service is closed");
            }
        }
        protected override void OnStart(string[] args)
        {
            Logger.Log("OnStart");
            RequestAdditionalTime(120 * 1000);

            try
            {
                _serviceHost?.Close();
            }
            catch (Exception e)
            {
                Logger.Log("Closing service in OnStart", e);
            }
            try
            {
                _serviceHost = new ServiceHost(typeof(RequestSimulatorService));
                _serviceHost.Open();
            }
            catch (Exception ex)
            {
                Logger.Log("OnStart", ex);
                throw;
            }
            Logger.Log("Service Started");
        }
Exemplo n.º 18
0
        protected override void OnStart(string[] args)
        {
            Logger.Log("OnStart");
            RequestAdditionalTime(120 * 1000);

            try
            {
                _serviceHost?.Close();
            }
            catch
            {
                // ignored
            }
            try
            {
                _serviceHost = new ServiceHost(typeof(WordsCountService));
                _serviceHost.Open();
            }
            catch (Exception ex)
            {
                _serviceEventLog.WriteEntry($"Opening The Host: {ex.Message}", EventLogEntryType.Error);
                Logger.Log("OnStart", ex);
                throw;
            }
            Logger.Log("Service Started");
        }
Exemplo n.º 19
0
        public static void Stop()
        {
            Log.Information("ServiceHelper Stop called");

            ISettings s = Settings.LoadSettings();

            CriticalProcessBase.SetProcessAsNotCritical(s);

            FirewallRule.AllowConnection(true);

            RegistryWrapper.StopRegistryMonitor();

            RegistryWrapper.RestoreDefaultSettings(true);

            Log.Information("Closing WCF Host");

            host?.Close();

            if (host is null)
            {
                Log.Information("Host was null");
            }

            if (host != null)
            {
                Log.Information("WCF Host status = " + host.State);
            }
        }
Exemplo n.º 20
0
 private void btnIniciar_Click(object sender, EventArgs e)
 {
     //Si esta null lo cerramos y abrimos
     _serviceHost?.Close();
     _serviceHost = new ServiceHost(typeof(ClienteService));
     _serviceHost.Open();
 }
Exemplo n.º 21
0
        public static bool StartService()
        {
            if (_serviceHost == null)
            {
                try
                {
                    var process = Process.GetCurrentProcess();
                    var service = new IPCService();
                    _serviceHost = new ServiceHost(
                        service,
                        new Uri($"net.pipe://localhost/HeliosDisplayManagement_IPC{process.Id}"));

                    _serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "Service");
                    _serviceHost.Open();

                    return(true);
                }
                catch (Exception)
                {
                    try
                    {
                        _serviceHost?.Close();
                    }
                    catch
                    {
                        // ignored
                    }

                    _serviceHost = null;
                }
            }

            return(false);
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            ServiceHost serviceHost = null;

            try
            {
                serviceHost = new ServiceHost(typeof(WcfServiceHost.WcfService));
                serviceHost.Open();
                Console.WriteLine("Host opened");

                //RunTestBatch(serviceHost);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n{ex.Message}");
                Console.WriteLine("\nPress any key to close the Service");
                Console.ReadKey();
                serviceHost?.Close();
                serviceHost = null;
            }

            if (serviceHost != null)
            {
                Console.WriteLine("\nPress any key to close the Service");
                Console.ReadKey();
                Console.WriteLine("\nService is shutting down...");
                serviceHost.Close();
                serviceHost = null;
            }
        }
Exemplo n.º 23
0
 public void Stop()
 {
     _host?.Abort();
     _host?.Close();
     _host     = null;
     IsStarted = false;
 }
Exemplo n.º 24
0
 protected override void OnStart(string[] args)
 {
     // C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WindowsServiceHostDll.exe
     serviceHost?.Close();
     serviceHost = new ServiceHost(typeof(DuplexSvc));
     serviceHost.Open();
 }
Exemplo n.º 25
0
        public void StartService()
        {
            try
            {
                _logger.Write(LogLevel.Info, "Server start");
                _host?.Close();

                CreateHost();
                _host?.Open();
            }
            catch (Exception ex)
            {
                _logger.Write(LogLevel.Error, "Не удалось создать хостинг", ex);
                StopService();
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates new instance of a service host.
        /// </summary>
        /// <param name="currentHost">Host variable to be set.</param>
        /// <returns>New instance of the host.</returns>
        public static ServiceHost CreateHost(ServiceHost currentHost = null)
        {
            try
            {
                currentHost?.Close();

                var binding = new WSDualHttpBinding
                {
                    OpenTimeout    = new TimeSpan(0, 1, 0),
                    CloseTimeout   = new TimeSpan(0, 1, 0),
                    SendTimeout    = new TimeSpan(0, 1, 0),
                    ReceiveTimeout = TimeSpan.MaxValue,
                    Security       = new WSDualHttpSecurity {
                        Mode = WSDualHttpSecurityMode.None
                    }
                };
                var address = new Uri("http://localhost:8000/ZombieService/Service.svc");

                currentHost = new ServiceHost(typeof(ZombieService), address);
                currentHost.AddServiceEndpoint(typeof(IZombieService), binding, address);
                currentHost.Open();
                return(currentHost);
            }
            catch (Exception e)
            {
                _logger.Fatal(e.Message);
                return(currentHost);
            }
        }
        protected override void OnStart(string[] args)
        {
            Logger.Log("OnStart");
            RequestAdditionalTime(60 * 1000);

        #if DEBUG
            //for (int i = 0; i < 100; i++)
            //{
            //    Thread.Sleep(1000);
            //}
        #endif

            try
            {
                _serviceHost?.Close();
            }
            catch
            {
                // ignore
            }

            try
            {
                _serviceHost = new ServiceHost(typeof(ClockSimulatorService));
                _serviceHost.Open();
            }
            catch (Exception ex)
            {
                Logger.Log(ex, nameof(OnStart));
                throw;
            }

            Logger.Log("Service Successfully Started");
        }
        protected override void OnStart(string[] args)
        {
            _complyHost?.Close();

            _complyHost = new ServiceHost(typeof(Demo));

            _complyHost.Open();
        }
Exemplo n.º 29
0
 public static void StopService()
 {
     if (_blServiceHost?.State == CommunicationState.Opened)
     {
         _blServiceHost?.Close();
     }
     LogService.LogInfo("SBListener service остановлен.");
 }
Exemplo n.º 30
0
 public override void NotifyProcessExit(int exitCode)
 {
     if (!CallbackChannelIsReady())
     {
         return; // нет подписчика
     }
     _eventChannel.ProcessExited(exitCode);
     _serviceHost?.Close();
 }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            string service_url = "http://localhost:2020/manufacturerservice/a";
            ServiceHost host = new ServiceHost(typeof(manufacturerAServiceImplementation));
            host.AddServiceEndpoint(typeof(ImanufacturerAService), new BasicHttpBinding(), service_url);

            try
            {
                host.Open();
                Console.WriteLine();
                host.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                host.Abort();
            }
        }
        private static void Main(string[] args)
        {
            // Use Thinktecture.ServiceModel.ServiceHost to host the ProductCatalog service.
            // IMPORTANT: In order to use Thinktecture.ServiceMode.ServiceHost you have to 
            // make sure that you specify the same XML namespace in the ServiceContractAttribute
            // attribute, ServiceBehaviorAttribute attribute and in the Namespace property
            // in the binding object.
            ServiceHost host = new ServiceHost(
                typeof (ProductCatalog), 
                Profile.Internet, 
                Flattening.Enabled);
            host.Open();

            Console.WriteLine("Service is running...");
            Process.Start("http://localhost:7777/Services?wsdl");
            Console.ReadKey();

            host.Close();
        }
Exemplo n.º 33
0
		static void Main( string[] args )
		{
			TextWriterTraceListener tr = new TextWriterTraceListener( System.Console.Out );
			Debug.Listeners.Add( tr ); Debug.AutoFlush = true; Debug.IndentSize = 3;
			ConsoleHelper.SetWindowPosition( 1, 32 * 12 + 30 );

			Console.WriteLine( "\n===== Press [Enter] to start the tests..." ); Console.ReadLine();

			Console.WriteLine( "\n===== Registering types for the WCF machinery ..." );
			KTypesWCF.AddType( typeof( CalendarDate ) );
			KTypesWCF.AddType( typeof( ClockTime ) );

			Console.WriteLine( "\n===== Starting the service host ..." );
			ServiceHost host = new ServiceHost( typeof( MyServer ) );
			host.Open();

			Console.WriteLine( "\n===== Press [Enter] to finish the service host ..." ); Console.ReadLine();
			try { host.Close( new TimeSpan( 0, 0, 5 ) ); }
			catch { host.Abort(); throw; }

			Console.WriteLine( "\n===== Press [Enter] to terminate program..." ); Console.ReadLine();
		}
Exemplo n.º 34
0
        static void Main(string[] args)
        {
            Console.WindowHeight = 30;
            Console.WindowWidth = 150;

            var bus = new InProcessEventBus(true);
            var eventStore = Program.GetBrowsableEventStore();
            var buffer = new InMemoryBufferedBrowsableElementStore(eventStore, 20 /*magic number found in ThresholdFetchPolicy*/);

            bus.RegisterAllHandlersInAssembly(typeof(MyNotes.Denormalizers.NoteDenormalizer).Assembly);
            BootStrapper.BootUp(buffer);

            var pipeline = Pipeline.Create("Default", new EventBusProcessor(bus), buffer);
            pipeline.Start();

            var commandServiceHost = new ServiceHost(typeof(CommandWebService));
            commandServiceHost.Open();

            Console.ReadLine();

            commandServiceHost.Close();
            pipeline.Stop();
        }
Exemplo n.º 35
0
 public void PipeChannel_openClose_fail()
 {
     var address = @"ipc:///test" + MethodBase.GetCurrentMethod().Name;
     var b = new LocalBinding();
     var serv = new Service(null);
     var host = new ServiceHost(serv, new Uri(address));
     host.AddServiceEndpoint(typeof(IService), b, address);
     host.Open();
     var f = new ChannelFactory<IService>(b);
     var c = f.CreateChannel(new EndpointAddress(address));
     c.DoWithParamsAndResult(null, Guid.Empty);
     host.Close();
     Exception comminicationEx = null;
     try
     {
         c.DoWithParamsAndResult(null, Guid.Empty);
     }
     catch (Exception ex)
     {
         comminicationEx = ex;
     }
     var obj = c as ICommunicationObject;
     var state = obj.State;
     Assert.AreEqual(CommunicationState.Faulted, state);
     Assert.That(comminicationEx, new ExceptionTypeConstraint(typeof(CommunicationException)));
 }
Exemplo n.º 36
0
        public static void Test()
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "");
            host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });

            host.Open();
            Console.WriteLine("Host opened");

            DynamicProxyFactory factory = new DynamicProxyFactory(baseAddress + "?wsdl");

            DynamicProxy dynamicProxy = factory.CreateProxy("IService");
            Console.WriteLine(dynamicProxy.CallMethod("GetData", 123));

            Type proxyType = dynamicProxy.ProxyType;
            MethodInfo getDataUsingDCMethod = proxyType.GetMethod("GetDataUsingDataContract");
            Type dcType = getDataUsingDCMethod.GetParameters()[0].ParameterType;
            DynamicObject obj = new DynamicObject(dcType);
            obj.CallConstructor();
            obj.SetProperty("BoolValue", true);
            obj.SetProperty("StringValue", "Hello world");

            DynamicObject result = new DynamicObject(
                dynamicProxy.CallMethod(
                    "GetDataUsingDataContract",
                    obj.ObjectInstance));

            Console.WriteLine(result.GetProperty("StringValue"));

            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }