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();
         }
     }
 }
Ejemplo n.º 2
0
 public void Open_Open_error()
 {
     var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + MethodBase.GetCurrentMethod().Name;
     var serv = new Service(null);
     using (var host = new ServiceHost(serv, new Uri[] { new Uri(address) }))
     {
         var b = new NetNamedPipeBinding();
         host.AddServiceEndpoint(typeof(IService), b, address);
         host.Open();
         host.Open();
     }
 }
 private void OpenServiceHost()
 {
     cacheServiceHost = new ServiceHost(new InvalidateCacheService(CacheInvalidated, () => cacheServiceHost.Close()), invalidateCacheUri);
     cacheServiceHost.AddServiceEndpoint(typeof(IInvalidateCacheService), new NetNamedPipeBinding(), invalidateCacheUri);
     try
     {
         cacheServiceHost.Open();
     }
     catch (Exception ex)
     {
         cacheServiceHost.Close();
         cacheServiceHost.Open();
     }
 }
Ejemplo n.º 4
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();
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Override ServiceBase OnStart, trigger when the service is started
 /// </summary>
 /// <param name="args"></param>
 protected override void OnStart(string[] args)
 {
     //Thread.Sleep(30000); //Debugging purpose
     try
     {
         base.OnStart(args);
         _gameHost.Open();
         PrintServiceInfo(_gameHost);
         eventLog1.WriteEntry("The poker game service has started.");
     }
     catch (Exception e)
     {
         eventLog1.WriteEntry(e.StackTrace, EventLogEntryType.Error);
         _gameHost.Abort();
     }
 }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8290/MyAgeService");

            using (var selfServiceHost = new ServiceHost(typeof(MyAgeService), baseAddress))
            {
                try
                {

                    selfServiceHost.AddServiceEndpoint(typeof(IMyAgeService), new WSHttpBinding(), "MyAgeService");

                    ServiceMetadataBehavior smBehavior = new ServiceMetadataBehavior();
                    smBehavior.HttpGetEnabled = true;
                    selfServiceHost.Description.Behaviors.Add(smBehavior);

                    selfServiceHost.Open();
                    Console.WriteLine("Tjänsten är ööppppeennnnn!");
                    Console.WriteLine("Tryck ENTER för att avsluta selfservice");
                    Console.ReadLine();
                }
                catch (CommunicationException ex)
                {
                    Console.WriteLine($"Ett kommunikationsfel har inträffat! {ex.Message}");
                    selfServiceHost.Abort();
                    Console.ReadLine();
                    throw;
                }
            }
        }
Ejemplo n.º 7
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();
            }
        }
Ejemplo n.º 8
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();
        }
Ejemplo n.º 9
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);
            }

        }
Ejemplo n.º 10
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());

            }

        }
Ejemplo n.º 11
0
 protected override IDisposable StartServer(int responseSize)
 {
     ServiceHost host = new ServiceHost(CreateService(responseSize), UriBase);
     host.AddServiceEndpoint(typeof(IWcfSampleService), GetBinding(BindingName), BindingName);
     host.Open();
     return host;
 }
Ejemplo n.º 12
0
        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();
        }
Ejemplo n.º 13
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 ();
	}
Ejemplo n.º 14
0
        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();
        }
Ejemplo n.º 15
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();
        }
Ejemplo n.º 16
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();
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8733/Design_Time_Addresses/GetDate/");

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

            try
            {
                selfHost.AddServiceEndpoint(typeof(IDateService), new WSHttpBinding(), "Date Service");
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                selfHost.Description.Behaviors.Add(smb);

                using (selfHost)
                {
                    selfHost.Open();
                    Console.WriteLine("Service is ready\nPress any key  to exit");
                    Console.WriteLine();
                    Console.ReadKey();
                }
            }
            catch (CommunicationException ex)
            {
                Console.WriteLine("An exception occured: {0}", ex.Message);
                selfHost.Abort();
            }
        }
Ejemplo n.º 18
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("");
            }
        }
Ejemplo n.º 19
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;
            }
        }
Ejemplo n.º 20
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;
 }
Ejemplo n.º 21
0
 static void StartServiceHost()
 {
     _svcHost = new ServiceHost(_worldSvr);
     _svcHost.Faulted += new EventHandler(svcHost_Faulted);
     _svcHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(svcHost_UnknownMessageReceived);
     _svcHost.Open();
 }
Ejemplo n.º 22
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();
            }
        }
Ejemplo n.º 23
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();
        }
Ejemplo n.º 24
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")
            {
            }
        }
Ejemplo n.º 25
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());
        }
Ejemplo n.º 26
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);
 }
Ejemplo n.º 27
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();
            }
        }
Ejemplo n.º 28
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();
        }
Ejemplo n.º 29
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;
 }
Ejemplo n.º 30
0
        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();
        }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            string command;
            Uri baseAddress = new Uri("http://localhost:8000/wob/Login");
            ServiceHost selfHost = null;
            try
            {
                selfHost = new ServiceHost(typeof(LoginService), baseAddress);
                selfHost.AddServiceEndpoint(typeof(ILogin), new WSDualHttpBinding(), "LoginService");

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

                selfHost.Open();
                Console.WriteLine("Open");
                while (true)
                {
                    command = Console.ReadLine();
                    if (command == "e")
                        break;
                }
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("Failure!");
                Console.WriteLine(ce);
                Console.ReadLine();
                selfHost.Abort();
            }
        }
Ejemplo n.º 32
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();
            }
        }
Ejemplo n.º 33
0
        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();
            }
        }
Ejemplo n.º 34
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();
            }
        }
        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);

        }
Ejemplo n.º 36
0
        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();
            }
        }
Ejemplo n.º 37
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);
        }
Ejemplo n.º 38
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();
                             
            }
                    
        }
Ejemplo n.º 39
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();
        }
Ejemplo n.º 40
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();
        }
Ejemplo n.º 41
0
		static void Main()
		{
			// только не null, ибо возникнет исключение
			//var baseAddress = new Uri("http://localhost:8002/MyService");
			var host = new ServiceHost(typeof(MyContractClient));//, baseAddress);

			host.Open();

			//var otherBaseAddress = new Uri("http://localhost:8001/");
			var otherHost = new ServiceHost(typeof(MyOtherContractClient));//, otherBaseAddress);
			var wsBinding = new BasicHttpBinding();
			var tcpBinding = new NetTcpBinding();
			otherHost.AddServiceEndpoint(typeof(IMyOtherContract), wsBinding, "http://localhost:8001/MyOtherService");
			otherHost.AddServiceEndpoint(typeof(IMyOtherContract), tcpBinding, "net.tcp://localhost:8003/MyOtherService");

			//AddHttpGetMetadata(otherHost);
			AddMexEndpointMetadata(otherHost);

			otherHost.Open();


			// you can access http://localhost:8002/MyService
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Host());

			otherHost.Close();

			host.Close();

			// you can not access http://localhost:8002/MyService
		}
Ejemplo n.º 42
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();
     }
 }
 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();
     }
 }
Ejemplo n.º 44
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();
     }
 }
Ejemplo n.º 45
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();
        }
Ejemplo n.º 46
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();
     }
 }
Ejemplo n.º 47
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();
        }
Ejemplo n.º 48
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"));
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Starts the MarketMiner tcp services
        /// </summary>
        /// <param name="host"></param>
        /// <param name="serviceDescription"></param>
        static void StartService(SM.ServiceHost host, string serviceDescription)
        {
            host.Open();
            Console.WriteLine("\nService {0} started.", serviceDescription);

            foreach (var endpoint in host.Description.Endpoints)
            {
                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}\n", endpoint.Contract.ConfigurationName));
            }
        }
Ejemplo n.º 50
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();
     }
 }
Ejemplo n.º 51
0
        static void Main(string[] args)
        {
            var baseAddress = new Uri("net.pipe://localhost/WCFIssue");

            System.ServiceModel.ServiceHost serviceHost = new System.ServiceModel.ServiceHost(typeof(AdditionService), baseAddress);
            NetNamedPipeBinding             binding     = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);

            serviceHost.AddServiceEndpoint(typeof(IAdditionService), binding, "AdditionService");
            serviceHost.Open();

            Console.WriteLine($"ServiceHost running at {baseAddress}. Press Return to Exit");
        }
Ejemplo n.º 52
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"));
        }
Ejemplo n.º 53
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server Started and Listening.....");

            #region CalculatorService Registration
            //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");

            //Service Behavior to publish metadata (WSDL Document)
            wcf.Description.ServiceMetadataBehavior _metadataBehavior = new wcf.Description.ServiceMetadataBehavior();
            //Configure Behavior to publish metadata when ServiceHost recieves http-get request
            _metadataBehavior.HttpGetEnabled = true;
            //Define URL to download metadata;
            _metadataBehavior.HttpGetUrl = new Uri("http://localhost:8002/metadata"); // this address used only for metadata download

            //Add Behavior -> ServieHost
            _wcfServiceHost.Description.Behaviors.Add(_metadataBehavior);

            _wcfServiceHost.Open();// ServiceHost availability for Client Requests
            #endregion
            #region PatientDataServiceRegistration


            wcf.ServiceHost _patientDataServiceHost =
                /* References Behvaior  End Point Details From app.config file */
                new ServiceHost(typeof(PatientDataServiceLib.PatientDataService));
            _patientDataServiceHost.Description.Behaviors.Add(new CustomServiceBehavior());
            _patientDataServiceHost.Open();
            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 54
0
 private static void StartService(SM.ServiceHost host, string serviceDescription)
 {
     host.Open();
     System.Console.WriteLine($"service {serviceDescription} started");
     foreach (var endpoints in host.Description.Endpoints)
     {
         System.Console.WriteLine("Listening of endpoint:");
         System.Console.WriteLine($" address: {endpoints.Address.Uri.ToString()}");
         System.Console.WriteLine($" binding: {endpoints.Binding}");
         System.Console.WriteLine($" contract: {endpoints.Contract.ConfigurationName}");
     }
     System.Console.WriteLine();
 }
Ejemplo n.º 55
0
        static void Main(string[] args)
        {
            System.ServiceModel.ServiceHost internetServiceHost = new System.ServiceModel.ServiceHost(typeof(EOS.InternetService.InternetService));
            internetServiceHost.Open();

            System.ServiceModel.ServiceHost merkezServiceHost = new System.ServiceModel.ServiceHost(typeof(EOS.MerkezService.MerkezService));
            merkezServiceHost.Open();

            System.ServiceModel.ServiceHost NufusMudurluguServiceHost = new System.ServiceModel.ServiceHost(typeof(TCNufusMudurlugu.srvPopulation));
            NufusMudurluguServiceHost.Open();

            Console.ReadLine();
        }
Ejemplo n.º 56
0
 static void StartService(SM.ServiceHost host, string serviceDescription)
 {
     host.Open();
     Console.WriteLine("Service {0} started", serviceDescription);
     foreach (var endpoint in host.Description.Endpoints)
     {
         Console.WriteLine(string.Format("Listening on endpoint:"));
         Console.WriteLine($"Address: {endpoint.Address.Uri}");
         Console.WriteLine($"Binding: {endpoint.Binding.Name}");
         Console.WriteLine($"Contract: {endpoint.Contract.Name}");
     }
     Console.WriteLine();
 }
Ejemplo n.º 57
0
        private ServiceHost start(Type wcfType)
        {
            Type interfaceType = getContractType(wcfType);

            String protocolPrefix = null;
            ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
            Binding mexBinding = null;

            if (baseAddress.StartsWith("http://"))
            {
                serviceBehavior.HttpGetEnabled = true;
                mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
            }
            else if (baseAddress.StartsWith("net.tcp://"))
            {
                mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
            }
            else
            {
                throw new NotSupportedException("不支持的协议前缀。" + baseAddress);
            }

            //事件参数
            ServiceBindingEventArgs args = new ServiceBindingEventArgs();

            args.Address                 = interfaceType.Name;
            args.ContractInterface       = interfaceType;
            args.ServiceClass            = wcfType;
            args.ServiceMetadataBehavior = serviceBehavior;
            args.MexEndpointAddress      = "mex";
            //触发“服务绑定时”事件
            if (ServiceBinding != null)
            {
                ServiceBinding(this, args);
            }

            //得到URL
            String url = baseAddress + args.Address + "/";

            System.ServiceModel.ServiceHost serviceHost = new System.ServiceModel.ServiceHost(wcfType, new Uri(url));
            serviceHost.Description.Behaviors.Add(args.ServiceMetadataBehavior);
            ServiceEndpoint mexEndpoint = new ServiceMetadataEndpoint(mexBinding, new EndpointAddress(url + args.MexEndpointAddress));

            serviceHost.AddServiceEndpoint(mexEndpoint);

            serviceHost.AddDefaultEndpoints();
            //打开
            serviceHost.Open();
            return(serviceHost);
        }
Ejemplo n.º 58
0
        static void ServiceHost(SM.ServiceHost host, string description)
        {
            host.Open();
            Console.WriteLine("Service {0} started", description);

            foreach (var endpoint in host.Description.Endpoints)
            {
                Console.WriteLine(string.Format("Listening on endpoints"));
                Console.WriteLine(string.Format("Address : {0}", endpoint.Address.Uri));
                Console.WriteLine(string.Format("Binding : {0}", endpoint.Binding.Name));
                Console.WriteLine(string.Format("Binding : {0}", endpoint.Contract.Name));
            }
            Console.WriteLine();
        }
Ejemplo n.º 59
0
        static void Main(string[] args)
        {
            //Uri baseAddress = new Uri("http://localhost:8081/User");

            Binding wsBinding = new WSHttpBinding();

            System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(UserProvider));
            host.AddServiceEndpoint(typeof(IUserProvider), wsBinding,
                                    "http://localhost:8081/User");
            host.Open();
            Console.WriteLine("Service Open");
            Console.ReadLine();
            host.Close();
        }
        static void StartService(SM.ServiceHost host, string description)
        {
            host.Open();
            Console.WriteLine("Service {0} started.", description);

            foreach (var endopint in host.Description.Endpoints)
            {
                Console.WriteLine("Listing on endpoints:");
                Console.WriteLine("    Address: {0}", endopint.Address.Uri);
                Console.WriteLine("    Bindings: {0}", endopint.Binding.Name);
                Console.WriteLine("    Contracts: {0}", endopint.Contract.ConfigurationName);
            }
            Console.WriteLine();
        }