public void ShouldSetShieldingWithNonIncludeExceptionDetailInFaults()
 {
     // create a mock service and its endpoint.
     Uri serviceUri = new Uri("http://tests:30003");
     ServiceHost host = new ServiceHost(typeof(MockService), serviceUri);
     host.AddServiceEndpoint(typeof(IMockService), new WSHttpBinding(), serviceUri);
     host.Open();
     try
     {
         // check that we have no ErrorHandler loaded into each channel that
         // has IncludeExceptionDetailInFaults turned off.
         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
         {
             Assert.AreEqual(0, dispatcher.ErrorHandlers.Count);
             Assert.IsFalse(dispatcher.IncludeExceptionDetailInFaults);
         }
         ExceptionShieldingBehavior behavior = new ExceptionShieldingBehavior();
         behavior.ApplyDispatchBehavior(null, host);
         // check that the ExceptionShieldingErrorHandler was assigned to each channel
         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
         {
             Assert.AreEqual(1, dispatcher.ErrorHandlers.Count);
             Assert.IsTrue(dispatcher.ErrorHandlers[0].GetType().IsAssignableFrom(typeof(ExceptionShieldingErrorHandler)));
         }
     }
     finally
     {
         if (host.State == CommunicationState.Opened)
         {
             host.Close();
         }
     }
 }
Example #2
0
        static void Main(string[] args)
        {
            Uri address = new Uri("http://localhost:8080/Lab2.Service.Age");
            ServiceHost serviceHost = new ServiceHost(typeof(Days), address);
            try
            {
                serviceHost.AddServiceEndpoint(typeof(IDays),
                    new WSHttpBinding(),
                    "Days");
                ServiceMetadataBehavior smBehavior = new ServiceMetadataBehavior();
                smBehavior.HttpGetEnabled = true;
                serviceHost.Description.Behaviors.Add(smBehavior);

                serviceHost.Open();
                Console.WriteLine("Tjänsten är öppen!");
                Console.WriteLine("Tryck enter för att avsluta");
                Console.ReadLine();
            }
            catch (CommunicationException ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                throw;
            }
            finally
            {
                serviceHost.Close();
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            try
            {
                ServiceHost host = new ServiceHost(typeof(RESTService));
                host.Open();

                if (host.State == CommunicationState.Opened)
                {
                    Console.WriteLine("The service is available:");
                    foreach (var address in host.BaseAddresses)
                    {
                        Console.WriteLine(address);
                    }
                    Console.WriteLine();
                }
                else
                {
                    throw new System.Exception("The service is not in a state OPENED.");
                }
            }
            catch (System.Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey(true);
        }
Example #4
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Pokretanje servisa....");
            System.Console.WriteLine("");

            System.ServiceModel.ServiceHost hostAukcijeManager   = new System.ServiceModel.ServiceHost(typeof(AukcijeManager));
            System.ServiceModel.ServiceHost hostSystemManager    = new System.ServiceModel.ServiceHost(typeof(SystemManager));
            System.ServiceModel.ServiceHost hostPorukeManager    = new System.ServiceModel.ServiceHost(typeof(PorukeManager));
            System.ServiceModel.ServiceHost hostKomentariManager = new System.ServiceModel.ServiceHost(typeof(KomentariManager));

            PokreniService(hostAukcijeManager, "AukcijeService");
            PokreniService(hostSystemManager, "SystemService");
            PokreniService(hostPorukeManager, "PorukeService");
            PokreniService(hostKomentariManager, "KomentariService");

            System.Timers.Timer timer = new System.Timers.Timer(5000);
            timer.Elapsed += OnTimerElapsed;
            timer.Start();

            System.Console.WriteLine("");
            System.Console.WriteLine("[Enter] za zaustavljanje servisa.");
            System.Console.ReadLine();
            timer.Stop();

            ZaustaviService(hostAukcijeManager, "AukcijeService");
            ZaustaviService(hostSystemManager, "SystemService");
            ZaustaviService(hostPorukeManager, "PorukeService");
            ZaustaviService(hostKomentariManager, "KomentariService");

            System.Console.ReadLine();
        }
Example #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server Started and Listening.....");

            //Host service or Service Instance
            wcf.ServiceHost _wcfServiceHost = new wcf.ServiceHost(typeof(CalculatorLib.Calculator));
            //Add Endpoint
            System.Type _contract = typeof(CalculatorServiceContractLib.ICalculate);
            //Bidning
            wcf.NetNamedPipeBinding _localMachineBidning = new wcf.NetNamedPipeBinding();
            //Address
            string address = "net.pipe://localhost/onmachinecchannel";

            //wcf.Description.ServiceEndpoint _localMachineCommunicationChannel =
            //    new wcf.Description.ServiceEndpoint(
            //    new wcf.Description.ContractDescription(_contract.FullName),
            //    _localMachineBidning,
            //    new wcf.EndpointAddress(address)
            //    );
            //_wcfServiceHost.AddServiceEndpoint(_localMachineCommunicationChannel);
            _wcfServiceHost.AddServiceEndpoint(_contract, _localMachineBidning, address);

            //LAN Clients
            _wcfServiceHost.AddServiceEndpoint(_contract, new NetTcpBinding(), "net.tcp://localhost:5000/lanep");
            //WAN
            _wcfServiceHost.AddServiceEndpoint(_contract, new BasicHttpBinding(), "http://localhost:8001/wanep");

            _wcfServiceHost.Open();// ServiceHost availability for Client Requests

            Console.ReadKey();
        }
Example #6
0
        internal static void StartService()
        {
            //Consider putting the baseAddress in the configuration system
            //and getting it here with AppSettings
            Uri baseAddress = new Uri( "http://localhost:8080/FileService" );
            //Instantiate new ServiceHost 
            myServiceHost = new ServiceHost( typeof( PracticalWcf.FileService ), baseAddress );
            

            //The following for programatic addition
            //WSHttpBinding wsBinding = new WSHttpBinding();
            //wsBinding.MessageEncoding = WSMessageEncoding.Mtom;
            //myServiceHost.AddServiceEndpoint(
            //    typeof( MtomSvc.IMtomSample ),
            //    wsBinding,
            //    baseAddress );

            //the following for programatic addition of Basic Profile 1.1
            //BasicHttpBinding binding = new BasicHttpBinding();
            //myServiceHost.AddServiceEndpoint(
            //    typeof( MyService,
            //    binding,
            //    baseAddress);


            //Open myServiceHost
            myServiceHost.Open();
        }
Example #7
0
        static void Main()
        {
            //run the program and visit this URI to confirm the service is working
            Uri baseAddress = new Uri("http://localhost:8000/GPSSim");
            ServiceHost host = new ServiceHost(typeof(GPSSim), baseAddress);

            //basicHttpBinding is used because WS binding is currently unsupported
            host.AddServiceEndpoint(typeof(IGPSSim), new BasicHttpBinding(),   "GPS Sim Service");

            try
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(smb);
            }
            catch (CommunicationException e)
            {
                Console.WriteLine("An exception occurred: {0}", e.Message);
                host.Abort();
            }

            host.Open();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
		private void RegisterService(ServiceHost serviceHost, EndpointDiscoveryMetadata endpoint)
		{
			if (FilterService(serviceHost, endpoint) == false)
			{
				serviceCatalog.RegisterService(endpoint);
			}
		}
Example #9
0
        // Host the service within this EXE console application.
        public static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service");

            // Create a ServiceHost for the CalculatorService type and provide the base address.
            using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
            {
                // Create a custom binding containing two binding elements
                ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement();
                reliableSession.Ordered = true;

                HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
                httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
                httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

                CustomBinding binding = new CustomBinding(reliableSession, httpTransport);

                // Add an endpoint using that binding
                serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, "");
              
                // Open the ServiceHost 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();
            }
        }
Example #10
0
        static void StartService(SM.ServiceHost host, string serviceDescription)
        {
            //var behavior = host.Description.Behaviors.Find<QIQOServiceBehaviorAttribute>();
            //if (behavior == null)
            //{
            //    behavior = new QIQOServiceBehaviorAttribute(false);
            //    host.Description.Behaviors.Add(behavior);
            //}

            //behavior.ServiceOperationCalled += (s, e) =>
            //{

            //};
            //host.ImpersonateAll();
            host.Open();
            Log.Info("Service '{0}' started.", serviceDescription);

            foreach (var endpoint in host.Description.Endpoints)
            {
                Log.Info(string.Format("Listening on endpoint:"));
                Log.Info(string.Format("Address: {0}", endpoint.Address.Uri.ToString()));
                Log.Info(string.Format("Binding: {0}", endpoint.Binding.Name));
                Log.Info(string.Format("Contract: {0}", endpoint.Contract.ConfigurationName));
            }

            Console.WriteLine();
        }
		private void RemoveService(ServiceHost serviceHost, EndpointDiscoveryMetadata endpoint)
		{
			if (IsSelfDiscovery(serviceHost, endpoint) == false)
			{
				serviceCatalog.RemoveService(endpoint);
			}
		}
Example #12
0
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(ServiceA));
            host.Open();

            ServiceEndpointCollection endpoints = host.Description.Endpoints;
            foreach (ServiceEndpoint item in endpoints)
            {
                Console.WriteLine(item.Address);
            }

            ServiceHost host2 = new ServiceHost(typeof(ServiceA2));
            host2.Open();

            endpoints = host2.Description.Endpoints;
            foreach (ServiceEndpoint item in endpoints)
            {
                Console.WriteLine(item.Address);
            }

            Console.WriteLine();
            Console.WriteLine("Please press Enter to terminate the Host");
            Console.ReadLine();

            host.Close();
        }
        private static void Main()
        {
            var serviceAddress = new Uri("http://localhost:8881/strings");
            ServiceHost selfHost = new ServiceHost(
                typeof(StringsService),
                serviceAddress);

            var smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            selfHost.Open();
            Console.WriteLine("Running at " + serviceAddress);

            StringsServiceClient client = new StringsServiceClient();

            using (client)
            {
                var result = client.StringContainsOtherString("as", "asblablass"); // returns 2
                Console.WriteLine("Using the service: \"as\" is contained in \"asblablass\" {0} times\n", result);
            }

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
		private void ProbeInitialServices(ServiceHost serviceHost)
		{
			var probe = new DiscoveryClient(UdpDiscoveryEndpoint ?? new UdpDiscoveryEndpoint());
			probe.FindProgressChanged += (_, args) => RegisterService(serviceHost, args.EndpointDiscoveryMetadata);
			probe.FindCompleted += (_, args) => probe.Close();
			probe.FindAsync(ProbeCriteria ?? new FindCriteria());
		}
Example #15
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.ProtectionTokenParameters =
			new SslSecurityTokenParameters ();
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.SecureConversationAuthentication.SecurityStateEncoder =
			new MyEncoder ();
		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;
//		foreach (ServiceEndpoint se in host.Description.Endpoints)
//			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Example #16
0
        static void Main(string[] args)
        {
            // Create binding for the service endpoint.
            CustomBinding amqpBinding = new CustomBinding();
            amqpBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
            amqpBinding.Elements.Add(new AmqpTransportBindingElement());

            // Create ServiceHost.
            ServiceHost serviceHost = new ServiceHost(typeof(HelloService), new Uri[] { new Uri("http://localhost:8080/HelloService2") });

            // Add behavior for our MEX endpoint.
            ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
            mexBehavior.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(mexBehavior);

            // Add MEX endpoint.
            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "MEX");

            // Add AMQP endpoint.
            Uri amqpUri = new Uri("amqp:news");
            serviceHost.AddServiceEndpoint(typeof(IHelloService), amqpBinding, amqpUri.ToString());

            serviceHost.Open();

            Console.WriteLine();
            Console.WriteLine("The consumer is now listening on the queue \"news\".");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            if (serviceHost.State != CommunicationState.Faulted)
            {
                serviceHost.Close();
            }
        }
Example #17
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="cacheHostInformationPoller">The cache host information poller.</param>
        /// <param name="memCache">The mem cache to use for storing objects.</param>
        /// <param name="clientToCacheServiceHost">The client to cache service host.</param>
        /// <param name="cacheManagerClient">The cache manager client.</param>
        public CacheHostEngine(IRunnable cacheHostInformationPoller, MemCache memCache, ServiceHost clientToCacheServiceHost)
        {
            // Sanitize
            if (cacheHostInformationPoller == null)
            {
                throw new ArgumentNullException("cacheHostInformationPoller");
            }
            if (memCache == null)
            {
                throw new ArgumentNullException("memCache");
            }
            if (clientToCacheServiceHost == null)
            {
                throw new ArgumentNullException("clientToCacheServiceHost");
            }

            // Set the cache host information poller
            _cacheHostInformationPoller = cacheHostInformationPoller;

            // Set the mem cache container instance
            MemCacheContainer.Instance = memCache;

            // Initialize the service hosts
            _clientToCacheServiceHost = clientToCacheServiceHost;
        }
Example #18
0
        public Bootstrapper()
        {
            Naru.Core.UnhandledExceptionHandler.InstallDomainUnhandledException();
            Naru.TPL.UnhandledExceptionHandler.InstallTaskUnobservedException();

            IContainer container = null;

            var builder = new ContainerBuilder();

            builder.RegisterModule(new Log4NetModule
                                            {
                                                SectionName = "CommonLogging.Nitrogen.Server"
                                            });

            builder.RegisterModule(new AgathaServerModule
                                   {
                                       ContainerFactory = () => container,
                                       HandlerAssembly = typeof(AssemblyHook).Assembly,
                                       RequestResponseAssembly = typeof(Common.AssemblyHook).Assembly
                                   });

            container = builder.Build();

            Console.WriteLine("EndPoint - {0}", END_POINT);

            var baseAddress = new Uri(END_POINT);
            Host = new ServiceHost(typeof(WcfRequestProcessor), baseAddress);
            Host.Open();
        }
Example #19
0
        static void Main(string[] args)
        {
            // IoC注册数据库连接
            var container = ContainerManager.Current;

            container.RegisterInstance <IDbContext, EfMsSqlRepository.EfMsSqlDbContext>(new EfMsSqlRepository.EfMsSqlDbContext("EntitiesContainer"), ComponentLifeStyle.Singleton);
            //manager.RegisterInstance<IDbContext, Justin.BookShop.Entities.EntitiesContainer>(new Justin.BookShop.Entities.EntitiesContainer("EntitiesContainer"), ComponentLifeStyle.Singleton);
            container.RegisterType <IDbSession, EfMsSqlRepository.DbSession>();



            // 寄宿服务
            string        exePath      = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Justin.BookShop.ServiceHost.exe");
            Configuration config       = System.Configuration.ConfigurationManager.OpenExeConfiguration(exePath);
            var           serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);
            Assembly      ass          = Assembly.Load("Justin.BookShop.Services");
            var           hosts        = new List <System.ServiceModel.ServiceHost>();

            foreach (ServiceElement serviceElement in serviceModel.Services.Services)
            {
                string typeName = serviceElement.Name;
                Type   type     = ass.GetType(typeName);
                var    host     = new System.ServiceModel.ServiceHost(type);
                host.Opened += delegate
                {
                    Console.WriteLine("服务 {0} 已经启动...", type.ToString());
                };
                host.Open();
                hosts.Add(host);
            }

            Console.ReadKey();
        }
Example #20
0
        public static void Main()
        {
            var baseAddress = new Uri("http://localhost:3370/");

            // Create the ServiceHost.
            using (var host = new ServiceHost(typeof(Service), baseAddress))
            {
                // Enable metadata publishing.
                //var smb = new ServiceMetadataBehavior
                //{
                //    HttpGetEnabled = true,
                //    MetadataExporter = {PolicyVersion = PolicyVersion.Policy15}
                //};

                //host.Description.Behaviors.Add(smb);

                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                host.Close();
            }
        }
Example #21
0
 public static ITestRunner RegisterAsServer(ITestOutput output, Options options)
 {
     var host = new ServiceHost(output);
     int i;
     for (i = 0; i < 50; i += 10) {
         try {
             host.AddServiceEndpoint(typeof(ITestOutput), BindingFactory(), "http://localhost:" + (StartPort + i) + "/");
             break;
         } catch (AddressAlreadyInUseException) {
         }
     }
     host.Open();
     var start = DateTime.Now;
     Exception final = null;
     var res = new ChannelFactory<ITestRunner>(BindingFactory(), "http://localhost:" + (StartPort + i + 1) + "/").CreateChannel();
     while (DateTime.Now - start < TimeSpan.FromSeconds(5)) {
         try {
             res.Ping();
             return res;
         } catch (Exception e) {
             final = e;
         }
     }
     throw final;
 }
Example #22
0
        private void button_start_Click(object sender, RoutedEventArgs e)
        {
           
            
            try
            {
                if (service == null)
                {
                   

                    service = new ServiceHost(typeof(Service));

                    service.AddServiceEndpoint(typeof(IContract), binding, address);


                    service.Open();

                    textBox.Text += "Сервер запущений.         " + DateTime.Now + Environment.NewLine ;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        static void Main(string[] args)
        {
            Console.Title = "BasicHttp Service Host";
            Console.Write("\n  Starting Programmatic Basic Service");
            Console.Write("\n =====================================\n");

            var repo = new DbRepository();

            //repo.ClearAll();

            System.ServiceModel.ServiceHost host = null;
            try
            {
                host = CreateChannel("http://localhost:8080/RemoteRepositoryService");                 // Must match URL specified in client
                host.Open();
                Console.Write("\n  Started RemoteRepositoryService - Press key to exit:\n");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.Write("\n\n  {0}\n\n", ex.Message);
                return;
            }
            host.Close();
        }
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8773/BasicService");

            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Name = "Basic_Binding";
            binding.HostNameComparisonMode = HostNameComparisonMode.WeakWildcard;
            binding.Security.Mode = BasicHttpSecurityMode.None;

            using (ServiceHost host = new ServiceHost(typeof(BasicService), baseAddress))
            {
                host.AddServiceEndpoint(typeof(IBasicService), binding, "http://localhost:8773/BasicService/mex");
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
        static void StartService(SM.ServiceHost host, string serviceDescription)
        {
            try
            {
                host.Open();
            }
            catch (Exception ex)
            {
                logger.Error("Service {0} failed to start with following error message: {1}", serviceDescription, ex);
                throw;
            }

            Console.WriteLine("Service {0} started.", serviceDescription);
            logger.Info("Service {0} started.", serviceDescription);

            foreach (var endpoint in host.Description.Endpoints)
            {
                Console.WriteLine(string.Format("Listening on endpoint:"));
                Console.WriteLine(string.Format("Address: {0}", endpoint.Address.Uri.ToString()));
                Console.WriteLine(string.Format("Binding: {0}", endpoint.Binding.Name));
                Console.WriteLine(string.Format("Contract: {0}", endpoint.Contract.ConfigurationName));
            }

            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000/GlydeServiceModelExamples/Service");

            ServiceHost selfHost = new ServiceHost(typeof(StringManipulatorService), baseAddress);

            try
            {
                selfHost.AddServiceEndpoint(
                    typeof(IStringManipulator),
                    new WSHttpBinding(),
                    "StringManipulatorService");

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                selfHost.Description.Behaviors.Add(smb);

                // Step 5 of the hosting procedure: Start (and then stop) the service.
                selfHost.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                selfHost.Close();

            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {0}", ce.Message);
                selfHost.Abort();
            }
        }
Example #27
0
 static void Main(string[] args)
 {
     ServiceHost hostA = null;
     ServiceHost hostB = null;
     try
     {
         hostA = new ServiceHost(typeof(BusinessServices.ServiceA));
         hostB = new ServiceHost(typeof(BusinessServices.ServiceB));
         hostA.Open();
         hostB.Open();
         ServiceEndpointCollection listA = hostA.Description.Endpoints;
         foreach (ServiceEndpoint item in listA)
         {
             Console.WriteLine(item.Address);
         }
         Console.WriteLine();
         listA = hostB.Description.Endpoints;
         foreach (ServiceEndpoint item in listA)
         {
             Console.WriteLine(item.Address);
         }
         Console.WriteLine();
         Console.WriteLine("Press <ENTER> to terminate Host");
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         CloseHost(hostA);
         CloseHost(hostB);
     }
     Console.ReadLine();
     CloseHost(hostA);
     CloseHost(hostB);
 }
        public void Start()
        {
            _source = new CancellationTokenSource();
            var token = _source.Token;
            _listenerTask = new Task(() =>
            {
                BusListener.MessageReceivedEvent += (s, e) => Console.WriteLine("Received message at " + e.Endpoint + " of type " + e.MessageType);
                BusListener.MessageSentEvent += (s, e) => Console.WriteLine("Sent message " + e.MessageType);
                BusListener.BusStartedEvent += (s, e) => Console.WriteLine("Bus started " + e.Endpoint);
                BusListener.MessageExceptionEvent += (s, e) => Console.WriteLine("Exception with message " + e.Endpoint + " for type " + e.MessageType + " with value " + e.Exception);
                using (var host = new ServiceHost(_listener, new[] { new Uri("net.tcp://localhost:5050") }))
                {

                    host.AddServiceEndpoint(typeof(IBusListener), new NetTcpBinding(), "NServiceBus.Diagnostics");

                    host.Opened += (s, e) => Console.WriteLine("Listening for events...");
                    host.Closed += (s, e) => Console.WriteLine("Closed listening for events...");

                    host.Open();

                    while (!token.IsCancellationRequested) { }

                    host.Close();
                }
            }, token);

            _listenerTask.Start();
            _listenerTask.Wait(10000);

        }
Example #29
0
        protected override void OnStart(string[] args)
        {
            try
            {
                _log.Error("服务启动");


                _hostBroadcast         = new System.ServiceModel.ServiceHost(typeof(BroadcastService));
                _hostBroadcast.Opened += (sender, eventArgs) => Console.WriteLine("数据广播服务器启动完成!");
                if (_hostBroadcast.State != CommunicationState.Opened)
                {
                    _hostBroadcast.Open();
                }

                _hostCardRecognize         = new System.ServiceModel.ServiceHost(typeof(CardRecognizeService));
                _hostCardRecognize.Opened += (sender, eventArgs) => Console.WriteLine("扑克牌识别服务器启动完成!");
                if (_hostCardRecognize.State != CommunicationState.Opened)
                {
                    _hostCardRecognize.Open();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.InnerException ?? ex);
                throw;
            }
        }
Example #30
0
        static void PokreniService(System.ServiceModel.ServiceHost host, string nazivServisa)
        {
#if DEBUG
            ServiceDebugBehavior debug = host.Description.Behaviors.Find <ServiceDebugBehavior>();
            if (debug == null)
            {
                host.Description.Behaviors.Add(new ServiceDebugBehavior()
                {
                    IncludeExceptionDetailInFaults = true
                });
            }
            else
            {
                if (!debug.IncludeExceptionDetailInFaults)
                {
                    debug.IncludeExceptionDetailInFaults = true;
                }
            }
#endif
            host.Open();
            System.Console.WriteLine("Pokrenut {0}", nazivServisa);

            foreach (var endpoint in host.Description.Endpoints)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("Endpoint:");
                System.Console.WriteLine("Adresa: {0}", endpoint.Address.Uri);
                System.Console.WriteLine("Binding: {0}", endpoint.Binding.Name);
                System.Console.WriteLine("Contract: {0}", endpoint.Contract.Name);
                System.Console.WriteLine("");
            }
        }
Example #31
0
 /// <summary>
 /// 构造服务对象
 /// </summary>
 protected void CreateServiceHost()
 {
     //创建服务对象
     _host = new System.ServiceModel.ServiceHost(ServiceType, new Uri(BaseAddress));
     //添加终结点
     _host.AddServiceEndpoint(ContractType, Binding, ServiceAddress);
 }
Example #32
0
        public static void Main(string[] args)
        {
            if (System.Environment.UserInteractive)
            {
                string parameter = string.Concat(args);

                try
                {
                    ServiceHost serviceHost = new ServiceHost(typeof(InfoProviderService));

                    serviceHost.Open();
                    LogManager.Instance.WriteInfo("InfoProvider Server Starting...........");

                }
                catch (Exception ex)
                {
                    LogManager.Instance.WriteError(ex.Message);
                }
            }
            else
            {

                ServiceBase.Run(new Program());

            }

        }
Example #33
0
        static void Main(string[] args)
        {
            GenericPrincipal principal = new GenericPrincipal(
                new GenericIdentity("kapilb"), new string[] { "Administrators", "CarRentalAdmin" });

            Thread.CurrentPrincipal = principal;

            ObjectBase.Container = MEFLoader.Init();


            Console.WriteLine("Starting up the service...");
            Console.WriteLine("");

            SM.ServiceHost InventoryManagerHost = new SM.ServiceHost(typeof(InventoryManager));
            SM.ServiceHost AccountManagerHost   = new SM.ServiceHost(typeof(AccountManager));
            SM.ServiceHost RentalManagerHost    = new SM.ServiceHost(typeof(RentalManager));

            ServiceHost(InventoryManagerHost, "Inventory Manager");
            ServiceHost(AccountManagerHost, "Account Manager");
            ServiceHost(RentalManagerHost, "Rental Manager");


            Console.WriteLine("");
            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();

            StopService(InventoryManagerHost, "Inventory Manager");
            StopService(AccountManagerHost, "Account Manager");
            StopService(RentalManagerHost, "Rental Manager");
        }
Example #34
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (serverIsOn)
     {
         labelStatus.Text = "Turning off...";
         labelStatus.Update();
         host.Close();
         labelStatus.Text = "Server is Off";
         button1.Text = "Turn on Server";
         listView1.Visible = false;
         labelPos2.Visible = false;
         Server.saveDatabaseToFile();
         t.Stop();
     }
     else
     {
         labelStatus.Text = "Turning on...";
         labelStatus.Update();
         host = new ServiceHost(typeof(Server));
         host.Open();
         labelStatus.Text = "Server is On";
         button1.Text = "Turn off Server";
         listView1.Visible = true;
         labelPos2.Visible = true;
         Invalidate();
         t.Start();
     }
     serverIsOn = !serverIsOn;
 }
Example #35
0
        /// <summary>
        /// Initializes the host.
        /// </summary>
        /// <param name="callback">Callback.</param>
        public void InitializeHost(IntPtr callback)
        {
            if (callback != IntPtr.Zero)
            {
                ExternalCallback            = GCHandle.Alloc(Marshal.GetDelegateForFunctionPointer <Utilities.QtExternalCode> (callback));
                DaemonOperation.QtMessenger = new Action <string> (ShowMessage);
            }

            ShowMessage("Creating binding...");
            var binding = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.None;

            ShowMessage("Allocating endpoint addresses...");
            var address    = new Uri("http://localhost:8888/monodaemon");
            var addressMex = new Uri("http://localhost:8888/monodaemon/mex");

            ShowMessage("Creating host...");
            m_host = new System.ServiceModel.ServiceHost(typeof(DaemonOperation),
                                                         new Uri[] { new Uri("http://localhost:8888/monodaemon") });

            ShowMessage("Adding behaviors...");
            m_host.Description.Behaviors.Remove <System.ServiceModel.Description.ServiceMetadataBehavior> ();
            m_host.Description.Behaviors.Add(new System.ServiceModel.Description.ServiceMetadataBehavior {
                HttpGetEnabled = true, HttpsGetEnabled = false
            });

            ShowMessage("Adding endpoints...");
            m_host.AddServiceEndpoint(typeof(IDaemonOperation), binding, address);
            m_host.AddServiceEndpoint(System.ServiceModel.Description.ServiceMetadataBehavior.MexContractName,
                                      System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), addressMex);

            ShowMessage("Starting host...");
            m_host.Open();
        }
		protected void ConfigureServiceHost(ServiceHost serviceHost, IWcfServiceModel serviceModel, ComponentModel model)
		{
			serviceHost.Description.Behaviors.Add(
				new WindsorDependencyInjectionServiceBehavior(kernel, model)
				);

			var burden = new WcfBurden(kernel);
			var contracts = new HashSet<ContractDescription>();
			Dictionary<IWcfEndpoint, ServiceEndpoint> endpoints = null;

			if (serviceModel != null && serviceModel.Endpoints.Count > 0)
			{
				endpoints = new Dictionary<IWcfEndpoint, ServiceEndpoint>();
				var builder = new ServiceEndpointBuilder(this, serviceHost);

				foreach (var endpoint in serviceModel.Endpoints)
				{
					endpoints.Add(endpoint, builder.AddServiceEndpoint(endpoint));
				}
			}

			var extensions = new ServiceHostExtensions(serviceHost, kernel)
				.Install(burden, new WcfServiceExtensions());

			if (serviceModel != null)
			{
				extensions.Install(serviceModel.Extensions, burden);
			}

			extensions.Install(burden, new WcfEndpointExtensions(WcfExtensionScope.Services));

			if (endpoints != null)
			{
				foreach (var endpoint in endpoints)
				{
					var addContract = contracts.Add(endpoint.Value.Contract);
					new ServiceEndpointExtensions(endpoint.Value, addContract, kernel)
						.Install(endpoint.Key.Extensions, burden);
				}
			}

			if (serviceHost is IWcfServiceHost)
			{
				var wcfServiceHost = (IWcfServiceHost)serviceHost;

				wcfServiceHost.EndpointCreated += (_, e) =>
				{
					var addContract = contracts.Add(e.Endpoint.Contract);
					var endpointExtensions = new ServiceEndpointExtensions(e.Endpoint, addContract, kernel)
						.Install(burden, new WcfEndpointExtensions(WcfExtensionScope.Services));

					if (serviceModel != null)
					{
						endpointExtensions.Install(serviceModel.Extensions, burden);
					}
				};
			}

			serviceHost.Extensions.Add(new WcfBurdenExtension<ServiceHostBase>(burden));
		}
Example #37
0
        static void Main(string[] args)
        {
            GenericPrincipal principal = new GenericPrincipal(
                new GenericIdentity("Kabaji"), new string[] { "Administrators", "JobMtaaniAdmin" });

            Thread.CurrentPrincipal = principal;

            ObjectBase.Container = MEFLoader.Init();

            Console.WriteLine("Starting up services");
            Console.WriteLine("");

            SM.ServiceHost hostAdManager      = new SM.ServiceHost((typeof(AdManager)));
            SM.ServiceHost hostAccountManager = new SM.ServiceHost((typeof(AccountManager)));

            StartService(hostAdManager, "Ad Manager");
            StartService(hostAccountManager, "Account Manager");

            Console.WriteLine("");
            Console.WriteLine("Press [ ENTER ] to exit");
            Console.ReadLine();

            StopService(hostAdManager, "Ad Manager");
            StopService(hostAccountManager, "Account Manager");
        }
Example #38
0
        public static void Log_ServiceHost(ServiceHost host)
        {
            Console.WriteLine(" SERVICE :" + host.Description.Name);

            Console.WriteLine("     STATE:" + host.State.ToString());

            Console.WriteLine("....................................................");
            Console.WriteLine();
            Console.WriteLine("     BaseAddresses");

            Console.WriteLine("     ....................................................");
            Console.WriteLine();
            foreach (var url in host.BaseAddresses)
            {
                Console.WriteLine("      " + url.AbsoluteUri.ToString());
            }
            Console.WriteLine();
            Console.WriteLine("     Endpoints");
            Console.WriteLine("     ....................................................");
            Console.WriteLine();
            foreach (var ep in ((System.ServiceModel.ServiceHostBase)(host)).Description.Endpoints)
            {
                Console.WriteLine("     Name " + ep.Name);
                Console.WriteLine("     Address " + ep.Address.ToString());
                Console.WriteLine("     Binding type " + ep.Binding.Name);
                Console.WriteLine();
                Console.WriteLine("     ....................................................");
            }

        }
Example #39
0
        /// <summary>
        /// Starts listening at the specified port.
        /// </summary>
        public void Start()
        {
            lock (m_lock)
            {
                UriBuilder root = new UriBuilder(m_uri);

                string path = root.Path;
                root.Path = String.Empty;

                WebHttpBinding binding = null;

                if (root.Scheme == Utils.UriSchemeHttps)
                {
                    binding = new WebHttpBinding(WebHttpSecurityMode.Transport);
                }
                else
                {
                    binding = new WebHttpBinding();
                }

                Service service = new Service();
                service.Listener = this;
                m_host           = new System.ServiceModel.ServiceHost(service, m_uri);
                m_host.AddServiceEndpoint(typeof(ICrossDomainPolicy), binding, root.Uri).Behaviors.Add(new WebHttpBehavior());
                m_host.AddServiceEndpoint(typeof(IInvokeService), binding, "").Behaviors.Add(new WebHttpBehavior());
                m_host.Open();
            }
        }
Example #40
0
        // Host the service within this EXE console application.
        public static void Main()
        {
            WSHttpBinding binding = new WSHttpBinding();
            binding.Name = "binding1";
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.Security.Mode = SecurityMode.Message;
            binding.ReliableSession.Enabled = false;
            binding.TransactionFlow = false;
            
            Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service");

            // Create a ServiceHost for the CalculatorService type and provide the base address.
            using(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
            {
                serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, baseAddress);
                // 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();
                             
            }
                    
        }
Example #41
0
        static void Main(string[] args)
        {
            var gamesService = new GamesService(new EFRepository <Game>(new MonolithicStore.DataAccess.AppContext()));

            System.ServiceModel.ServiceHost host =
                new System.ServiceModel.ServiceHost(gamesService,
                                                    new Uri("http://localhost:8733/Design_Time_Addresses/GamesStore"));


            host.AddServiceEndpoint(typeof(IGamesService),
                                    new BasicHttpBinding(),
                                    "");

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            smb.HttpGetEnabled = true;
            smb.HttpGetUrl     = new Uri("http://localhost:8733/Design_Time_Addresses/GamesStore/mex");
            host.Description.Behaviors.Add(smb);

            Console.WriteLine("Opening...");
            host.Open();
            Console.WriteLine("Opened");

            Console.WriteLine("Press exit to exit");
            while (Console.ReadLine() != "exit")
            {
            }
        }
 protected override void OnStop()
 {
     #region Temperature Host
     _temperatureHost?.Close();
     _temperatureHost = null;
     #endregion
 }
Example #43
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting up services...");
            Console.WriteLine("");

            SM.ServiceHost hostIAlbumManager = new SM.ServiceHost(typeof(AlbumManager));

            StartService(hostIAlbumManager, "AlbumManager");


            //System.Timers.Timer timer = new System.Timers.Timer(10000);
            ////timer.Elapsed += OnTimerElapsed;
            //timer.Start();

            Console.WriteLine("Reservation monitor started.");

            Console.WriteLine("");
            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();
            Console.WriteLine();

            //timer.Stop();

            Console.WriteLine("Reservaton mointor stopped.");

            StopService(hostIAlbumManager, "InventoryManager");
        }
Example #44
0
 static void StartServiceHost()
 {
     _svcHost = new ServiceHost(_worldSvr);
     _svcHost.Faulted += new EventHandler(svcHost_Faulted);
     _svcHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(svcHost_UnknownMessageReceived);
     _svcHost.Open();
 }
Example #45
0
        static void Main(string[] args)
        {
            ServiceHost host = null;

            Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
            ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");

            foreach (ServiceElement el in svcmod.Services.Services)
            {
                Type type = Type.GetType(el.Name+",JJY.WCF.Service");
                if(type == null)
                {
                    Console.WriteLine(string.Format("服务{0}实例化失败"), el.Name);
                }
                host = new ServiceHost(type);
                //host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
                try
                {
                    host.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("服务{0}启动失败", el.Name));
                    Console.WriteLine(string.Format("错误内容:{0}", ex.ToString()));
                }
                Console.WriteLine(string.Format("{0}已经启动",el.Name));
            }
            Console.ReadLine();
        }
Example #46
0
 /// <summary>
 /// Fecha o canal http.
 /// </summary>
 private void CloseHttpChannel()
 {
     if (this._serviceHost != null)
     {
         ShutdownCommunicationObject(_serviceHost);
         _serviceHost = null;
     }
 }
Example #47
0
 /// <summary>
 /// Printing some info about listening endpoints for debugging purpose
 /// </summary>
 /// <param name="host">The host service</param>
 private void PrintServiceInfo(System.ServiceModel.ServiceHost host)
 {
     Console.WriteLine("{0} is up and running with these endpoints:",
                       host.Description.ServiceType);
     foreach (ServiceEndpoint se in host.Description.Endpoints)
     {
         eventLog1.WriteEntry(se.Address.ToString());
     }
 }
 /// <summary>
 /// Stops the service
 /// </summary>
 public void Stop()
 {
     if (host != null)
     {
         //subscriptionService.UnsubscribeAllClients();
         host.Close();
         host = null;
     }
 }
 static void Main(string[] args)
 {
     using (System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(ImageDownloadServiceLibrary.ImageDownloadService)))
     {
         host.Open();
         Console.WriteLine("Host Started, Press any key to stop...");
         Console.ReadLine();
     }
 }
Example #50
0
 static void Main(string[] args)
 {
     using (System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(HelloWCFService1.Service1)))
     {
         host.Open();
         Console.WriteLine("Host started @" + DateTime.Now.ToString());
         Console.ReadLine();
     }
 }
Example #51
0
        public ActionResult InvokeTCP()
        {
            System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(Assignment1_Section1.SayHello));
            host.Open();
            SayHelloProxy proxy = new SayHelloProxy();

            ViewBag.Message = proxy.DoWork("Hello World");
            host.Close();
            return(RedirectToAction("Home"));
        }
Example #52
0
 static void Main()
 {
     using (var host = new System.ServiceModel.ServiceHost(typeof(ServiceApp.MSSQLService)))//выделение памяти при запуске
     {
         host.Open();
         Console.WriteLine("Service started....\nInput something to close.");
         Console.ReadKey();
         host.Close();
     }
 }
Example #53
0
        public void Start()
        {
            _serviceCore = new TradingServerWCFService();

            _serviceHost = new System.ServiceModel.ServiceHost(_serviceCore, _uris);
            _serviceHost.AddServiceEndpoint(typeof(IWCFConnection), _netTcpBinding, _uris[0]);
            _serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
            _serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            _serviceHost.Open();
        }
        static System.ServiceModel.ServiceHost CreateChannel(string url)
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            Uri  address             = new Uri(url);
            Type service             = typeof(RemoteRepositoryService.RemoteRepositoryService);

            System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(service, address);
            host.AddServiceEndpoint(typeof(IRemoteRepositoryService), binding, address);
            return(host);
        }
Example #55
0
 static void Main()
 {
     using (System.ServiceModel.ServiceHost host = new
                                                   System.ServiceModel.ServiceHost(typeof(CalcSRV.SRV)))
     {
         host.Open();
         Console.WriteLine("Host started @ " + DateTime.Now.ToString());
         Console.ReadLine();
     }
 }
Example #56
0
        static void Main(string[] args)
        {
            var host = new System.ServiceModel.ServiceHost(typeof(MedicSchedulerService));

            //host.AddServiceEndpoint(typeof(IMedicSchedulerService), new BasicHttpBinding(), "");
            host.Open();
            Console.WriteLine("Service host start");
            Console.ReadLine();
            host.Close();
        }
 public void Stop()
 {
     if (serviceHost != null)
     {
         Logging.Log(LogLevelEnum.Info, "Stopping WCF service");
         serviceHost.Close();
         serviceHost = null;
         Logging.Log(LogLevelEnum.Info, "WCF service stopped");
     }
 }
Example #58
0
 static void Main(string[] args)
 {
     using (var serviceHost = new System.ServiceModel.ServiceHost(new SpeexStreamer()))
     {
         serviceHost.AddServiceEndpoint(typeof(ISpeexStreamer), new NetTcpBinding(), "net.tcp://localhost:8001/SpeexStreamer");
         //serviceHost.AddServiceEndpoint(typeof (ISpeexStreamerUp), new BasicHttpBinding(),
         //                               "http://localhost:8002/SpeexStreamer");
         serviceHost.Open();
         Console.WriteLine("Service open...");
         Console.ReadLine();
     }
 }
 public override void Stop()
 {
     lock (syncLock)
     {
         if (serviceHost.State != CommunicationState.Closed)
         {
             serviceHost.Close();
             serviceHost = null;
         }
         waitHandle.Set();
     }
 }
Example #60
0
        public ActionResult InvokeHTTP()
        {
            Uri httpURI = new Uri("http://localhost:55431/");

            System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(Assignment1_Section1.SayHello), httpURI);
            host.Open();
            SayHelloProxy proxy = new SayHelloProxy();

            ViewBag.Message = proxy.DoWork("Hello World");
            host.Close();
            return(RedirectToAction("Home"));
        }