Beispiel #1
0
        public static void Run()
        {
            // Open post as non-admin:
            // http://msdn.microsoft.com/en-us/library/ms733768.aspx
            // netsh http add urlacl url=http://+:9999/ user='******'

            var host = new ServiceHost (typeof (Server));
            AddMexEndpoint (host);
            host.AddServiceEndpoint (
                typeof (IMyService), new BasicHttpBinding (),
                new Uri ("http://provcon-faust:9999/service/"));
            host.AddServiceEndpoint (
                typeof (IMyService), new BasicHttpBinding (BasicHttpSecurityMode.Transport),
                new Uri ("https://provcon-faust:9998/secureservice/"));
            AddNetTcp (host);
            AddNetTcp2 (host);
            host.Open ();

            foreach (var endpoint in host.Description.Endpoints)
                Console.WriteLine (endpoint.Address);

            Console.WriteLine ("Service running.");
            Console.ReadLine ();

            host.Close ();
        }
        static void Main(string[] args)
        {
            try
            {
                ServiceHost dataExchangeService = null;
                Uri httpBaseAddress = new Uri(args.Length == 0 ? "http://127.0.0.1:8080" : args[0]);

                dataExchangeService = new ServiceHost(typeof(Service), httpBaseAddress);
                WSHttpBinding binding = new WSHttpBinding();
                binding.Security = new WSHttpSecurity { Mode = SecurityMode.None };

                binding.Security.Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.None };
                binding.MaxBufferPoolSize = 1073741824;
                binding.MaxReceivedMessageSize = 1073741824;
                binding.ReceiveTimeout = TimeSpan.FromHours(1);
                binding.SendTimeout = TimeSpan.FromHours(1);
                binding.ReaderQuotas.MaxArrayLength = 1073741824;
                binding.ReaderQuotas.MaxBytesPerRead = 1073741824;
                binding.ReaderQuotas.MaxDepth = 1073741824;
                binding.ReaderQuotas.MaxStringContentLength = 1073741824;

                dataExchangeService.AddServiceEndpoint(typeof(IDataTranslation), binding, "");
                dataExchangeService.AddServiceEndpoint(typeof(IDataSimulation), binding, "");
                dataExchangeService.Open();
                logger.log("Service is now at: " + httpBaseAddress);
                while (true)
                {
                    Thread.Sleep(10000);
                }
            }
            catch (Exception ex)
            {
                logger.log( ex.Message, Logger.LogType.ERROR);
            }
        }
        static void Main(string[] args)
        {
            IPHostEntry entry = Dns.GetHostEntry("");
            string addr = "localhost";

            for (int i = 0; i < entry.AddressList.Length; i++)
            {
                if (entry.AddressList[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    addr = entry.AddressList[i].ToString();
                    break;
                }
            }

            Uri baseAddress = new Uri("http://" + addr + ":8084/319D0A4D-2253-47DC-AC4A-C1951FF6667D");

            ServiceHost serviceHost = new ServiceHost(typeof(ServiceHelloWCF), baseAddress);
            try
            {
                ServiceEndpoint wsEndpoint = serviceHost.AddServiceEndpoint(typeof(IServiceHelloWCF), new WSHttpBinding(SecurityMode.None), string.Empty);
                EndpointDiscoveryBehavior endpointDiscoveryBehavior = new EndpointDiscoveryBehavior();

                // Add the discovery behavior to the endpoint.
                wsEndpoint.Behaviors.Add(endpointDiscoveryBehavior);
                
                // Make the service discoverable over UDP multicast
                serviceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
                serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint(DiscoveryVersion.WSDiscovery11));

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.HttpGetUrl = baseAddress;
                serviceHost.Description.Behaviors.Add(smb);

                serviceHost.Open();

                Console.WriteLine("Hello World WCF Service started at {0}", baseAddress);
                Console.WriteLine();
                Console.WriteLine("Press <ENTER> to terminate the service.");
                Console.WriteLine();
                Console.ReadLine();

                serviceHost.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);
            }

            if (serviceHost.State != CommunicationState.Closed)
            {
                Console.WriteLine("Aborting service...");
                serviceHost.Abort();
            }

        }
Beispiel #4
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();
            }
        }
        protected override void OnStart(string[] args)
        {
            var baseAddresses = new Uri[]
                                    {
                                        new Uri(Properties.Settings.Default.ServiceHttpUri),
                                        new Uri(Properties.Settings.Default.ServiceNamedPipeUri),
                                    };

            _serviceHost = new ServiceHost(_singletonService, baseAddresses);

            _serviceHost.AddServiceEndpoint(typeof(ILocationService),
            new BasicHttpBinding(),
            "Location");

            _serviceHost.AddServiceEndpoint(typeof(ILocationService),
              new NetNamedPipeBinding(),
              "Location");

            
            var smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            _serviceHost.Description.Behaviors.Add(smb);

            _serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
            
            _serviceHost.Open();
        }
Beispiel #6
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();
        }
Beispiel #7
0
        private static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof (EvalService));

            WSHttpBinding noSecurityPlusRMBinding = new WSHttpBinding();
            noSecurityPlusRMBinding.Security.Mode = SecurityMode.None;
            noSecurityPlusRMBinding.ReliableSession.Enabled = true;

            host.AddServiceEndpoint(typeof (IEvalService), new BasicHttpBinding(), "http://localhost:8080/evals/basic");
            host.AddServiceEndpoint(typeof(IEvalService), noSecurityPlusRMBinding, "http://localhost:8080/evals/ws");
            //host.AddServiceEndpoint(typeof (IEvalService), new NetTcpBinding(), "net.tcp://localhost:8081/evals");

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.HttpGetUrl = new Uri("http://localhost:8080/evals/basic/meta");
            host.Description.Behaviors.Add(smb);

            try
            {
                host.Open();
                PrintServiceInfo(host);
                Console.ReadLine();
                host.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                host.Abort();
            }

            Console.ReadLine();
        }
Beispiel #8
0
        private static ServiceHost HostDiscoveryEndpoint(string hostName)
        {
            // Create a new ServiceHost with a singleton ChatDiscovery Proxy
            ServiceHost myProxyHost = new
                ServiceHost(new ChatDiscoveryProxy());

            string proxyAddress = "net.tcp://" +
                hostName + ":8001/discoveryproxy";

            // Create the discovery endpoint
            DiscoveryEndpoint discoveryEndpoint =
                new DiscoveryEndpoint(
                    new NetTcpBinding(),
                    new EndpointAddress(proxyAddress));

            discoveryEndpoint.IsSystemEndpoint = false;

            // Add UDP Annoucement endpoint
            myProxyHost.AddServiceEndpoint(new UdpAnnouncementEndpoint());

            // Add the discovery endpoint
            myProxyHost.AddServiceEndpoint(discoveryEndpoint);

            myProxyHost.Open();
            Console.WriteLine("Discovery Proxy {0}",
                proxyAddress);

            return myProxyHost;
        }
Beispiel #9
0
        static void ServiceFromCode()
        {
            Console.Out.WriteLine("Testing Udp From Code.");

            Binding datagramBinding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new UdpTransportBindingElement());

            // using the 2-way calculator method requires a session since UDP is not inherently request-response
            SampleProfileUdpBinding calculatorBinding = new SampleProfileUdpBinding(true);
            calculatorBinding.ClientBaseAddress = new Uri("soap.udp://localhost:8003/");

            Uri calculatorAddress = new Uri("soap.udp://localhost:8001/");
            Uri datagramAddress = new Uri("soap.udp://localhost:8002/datagram");

            // we need an http base address so that svcutil can access our metadata
            ServiceHost service = new ServiceHost(typeof(CalculatorService), new Uri("http://localhost:8000/udpsample/"));
            ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();
            metadataBehavior.HttpGetEnabled = true;
            service.Description.Behaviors.Add(metadataBehavior);
            service.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

            service.AddServiceEndpoint(typeof(ICalculatorContract), calculatorBinding, calculatorAddress);
            service.AddServiceEndpoint(typeof(IDatagramContract), datagramBinding, datagramAddress);
            service.Open();

            Console.WriteLine("Service is started from code...");
            Console.WriteLine("Press <ENTER> to terminate the service and start service from config...");
            Console.ReadLine();

            service.Close();
        }
Beispiel #10
0
        public void StartService()
        {
            Uri baseAddress = new Uri("http://localhost:8001/MarkManagementService");
            Type contractType = typeof(IService);
            Type instanceType = typeof(OperationService);
            host = new ServiceHost(instanceType, baseAddress);

            // Create basicHttpBinding endpoint at http://localhost:8001/OperationService
                string relativeAddress = "OperationService";
                host.AddServiceEndpoint(contractType, new BasicHttpBinding(), relativeAddress);

                NetTcpBinding A = new NetTcpBinding(SecurityMode.Transport);
                host.AddServiceEndpoint(contractType, new NetTcpBinding(), "net.tcp://localhost:9000/MarkManagementService");
                host.AddServiceEndpoint(contractType, A, "net.tcp://localhost:9001/MarkManagementService");
                // Add behavior for our MEX endpoint
                //Add Mex endpoint can dung de khi client discovery thay duoc service

                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                host.Description.Behaviors.Add(behavior);

                // Add MEX endpoint at http://localhost:8000/MEX/
                host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "MEX");
                host.Open();
                lbl_mess.Text = "Service is starting";
                lbl_mess.ForeColor = Color.Green;
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            var baseAddress = new Uri(string.Format("http://localhost:11001/mixedservice/{0}/", Guid.NewGuid().ToString()));

            using (var host = new ServiceHost(typeof(MixedService), baseAddress))
            {
                host.Opened += (sender, e) =>
                {
                    host.Description.Endpoints.All((ep) =>
                    {
                        Console.WriteLine(ep.Contract.Name + ": " + ep.ListenUri);
                        return true;
                    });
                };

                var serviceMetadataBehavior = new ServiceMetadataBehavior();
                serviceMetadataBehavior.HttpGetEnabled = true;
                serviceMetadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(serviceMetadataBehavior);

                host.AddServiceEndpoint(typeof(IStringService), new BasicHttpBinding(), "string");
                host.AddServiceEndpoint(typeof(ICalculateService), new BasicHttpBinding(), "calculate");
                host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                host.Open();

                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
Beispiel #12
0
        public Form1()
        {
            InitializeComponent();
            IntPtr dummyHandle = Handle;

            lvMission.DoubleBuffer(true);
            lvNDock.DoubleBuffer(true);
            lvMission.LoadColumnWithOrder(Properties.Settings.Default.MissionColumnWidth);
            lvNDock.LoadColumnWithOrder(Properties.Settings.Default.DockColumnWidth);

            var host = new RemoteHost(this);
            servHost = new ServiceHost(host);
            if (Properties.Settings.Default.NetTcp)
            {
                var bind = new NetTcpBinding(SecurityMode.None);
                bind.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
                servHost.AddServiceEndpoint(typeof(KCB.RPC.IUpdateNotification), bind, new Uri("net.tcp://localhost/kcb-update-channel"));
                servHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new HogeFugaValidator();
                servHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
                Debug.WriteLine("Protocol:Net.Tcp");
                bTcpMode = true;
            }
            else
            {
                servHost.AddServiceEndpoint(typeof(KCB.RPC.IUpdateNotification), new NetNamedPipeBinding(), new Uri("net.pipe://localhost/kcb-update-channel"));
                Debug.WriteLine("Protocol:Net.Pipe");
            }
            servHost.Open();

            //起動し終えたのでシグナル状態へ
            Program._mutex.ReleaseMutex();

        }
Beispiel #13
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();
        }
Beispiel #14
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
		}
Beispiel #15
0
        static void Main(string[] args) {
            Uri tcpBaseAddress = new Uri("net.tcp://localhost:6789/");
            ServiceHost sh = new ServiceHost(typeof(TransactionService), new Uri[] { tcpBaseAddress });

            var netTcpBinding = new NetTcpBinding();
            netTcpBinding.TransactionFlow = true;

            ServiceEndpoint se = sh.AddServiceEndpoint(typeof(ITransactionService), netTcpBinding, tcpBaseAddress);

            ServiceMetadataBehavior smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (smb == null)
                smb = new ServiceMetadataBehavior();
            sh.Description.Behaviors.Add(smb);

            ServiceEndpoint httpSeMex = sh.AddServiceEndpoint(typeof(IMetadataExchange),
                MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://localhost:6789/mex");

            sh.Open();

            Console.WriteLine("Started...");
            foreach (var item in sh.Description.Endpoints) {
                Console.WriteLine("Address: " + item.Address.ToString());
                Console.WriteLine("Binding: " + item.Binding.Name.ToString());
                Console.WriteLine("Contract: " + item.Contract.Name.ToString());
                Console.WriteLine("------------------");
            }

            Console.ReadLine();

            sh.Close();
            Console.WriteLine("Closed...");
        }
        static void Main(string[] args)
        {
            // string address = "http://localhost:23456/TrustedServer/";


            if(args==null || args.Count() <1 )
            {
                Usage();
                return;
            }


            string address = args[0];
            BasicHttpBinding binding = new BasicHttpBinding();
            ServiceHost host = new ServiceHost(typeof(MetaDataServer), new Uri(address));
            host.AddServiceEndpoint(typeof(IMetaDataService), binding, address);

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            // host.AddDefaultEndpoints();

            MetaDataServer.initializeFromFile();
            host.Open();

            Console.WriteLine("Host is {0}.  Press enter to close.", host.State);
            Console.ReadLine();
            MetaDataServer.writeToFile();
            host.Close();
        }
Beispiel #17
0
        private ServiceHost BuildHost( IWcfServiceConfiguration configuration )
        {
            var serviceUri = configuration.Address;
            var host = new ServiceHost( configuration.ServiceType, new Uri( ServerConfiguration.BaseAddress ) );
            host.AddServiceEndpoint(
                configuration.ContractType,
                configuration.Binding,
                serviceUri );

            if ( configuration.EnableHttpMetadataExchange )
            {
                var mexUriString =
                    "{0}/{1}".AsFormat( configuration.MetadataExchangeUri ?? ServerConfiguration.BaseAddress,
                                        configuration.Address );

                host.Description.Behaviors.Add(
                    new ServiceMetadataBehavior
                        {
                            HttpGetEnabled = true,
                            HttpGetUrl = new Uri( mexUriString )
                        } );

                host.AddServiceEndpoint( typeof( IMetadataExchange ), configuration.Binding, "mex" );
            }

            host.CloseTimeout = TimeSpan.FromMilliseconds( configuration.Timeout );
            return host;
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), "soap");
            WebHttpBinding webBinding = new WebHttpBinding();
            webBinding.ContentTypeMapper = new MyRawMapper();
            host.AddServiceEndpoint(typeof(ITestService), webBinding, "json").Behaviors.Add(new NewtonsoftJsonBehavior());
            Console.WriteLine("Opening the host");
            host.Open();

            ChannelFactory<ITestService> factory = new ChannelFactory<ITestService>(new BasicHttpBinding(), new EndpointAddress(baseAddress + "/soap"));
            ITestService proxy = factory.CreateChannel();
            Console.WriteLine(proxy.GetPerson());

            SendRequest(baseAddress + "/json/GetPerson", "GET", null, null);
            SendRequest(baseAddress + "/json/EchoPet", "POST", "application/json", "{\"Name\":\"Fido\",\"Color\":\"Black and white\",\"Markings\":\"None\",\"Id\":1}");
            SendRequest(baseAddress + "/json/Add", "POST", "application/json", "{\"x\":111,\"z\":null,\"w\":[1,2],\"v\":{\"a\":1},\"y\":222}");

            Console.WriteLine("Now using the client formatter");
            ChannelFactory<ITestService> newFactory = new ChannelFactory<ITestService>(webBinding, new EndpointAddress(baseAddress + "/json"));
            newFactory.Endpoint.Behaviors.Add(new NewtonsoftJsonBehavior());
            ITestService newProxy = newFactory.CreateChannel();
            Console.WriteLine(newProxy.Add(444, 555));
            Console.WriteLine(newProxy.EchoPet(new Pet { Color = "gold", Id = 2, Markings = "Collie", Name = "Lassie" }));
            Console.WriteLine(newProxy.GetPerson());

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
            Console.WriteLine("Host closed");
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            //ServiceHost myHost = new ServiceHost(typeof(WCFService));

            ServiceHost myHost = new ServiceHost(typeof(WCFService),
                new Uri("http://localhost:9003/AI3"),
                new Uri("net.tcp://localhost:9004/AI4"));

            myHost.AddDefaultEndpoints();

            myHost.AddServiceEndpoint(typeof(IWCFService), new BasicHttpBinding(), "http://localhost:9001/AI");
            myHost.AddServiceEndpoint(typeof(IWCFService), new NetTcpBinding(), "net.tcp://localhost:9002/");

            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetUrl = new Uri("http://localhost:8090/WCFService");
            behavior.HttpGetEnabled = true;

            myHost.Description.Behaviors.Add(behavior);

            try
            {
                myHost.Open();
                Console.WriteLine("Service is worked ! Status : " + myHost.State);

                foreach (ServiceEndpoint ep in myHost.Description.Endpoints)
                {
                    Console.WriteLine("A : {0} - B : {1} - C : {2}", ep.Address, ep.Binding.Name, ep.Contract.Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
Beispiel #20
0
      public static void Open(string tibcoEndpointUri) {
         Uri uri;
         if (!Uri.TryCreate(tibcoEndpointUri, UriKind.Absolute, out uri)) {
            uri = new Uri("http://0.0.0.0:50701");
         }
         _host = new ServiceHost(typeof(OscarServices), uri);
         var smb = new ServiceMetadataBehavior { 
            HttpGetEnabled = true,
         };
         smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
         _host.Description.Behaviors.Add(smb);

         var sdb = _host.Description.Behaviors.Find<ServiceDebugBehavior>();
         if (sdb == null) {
            sdb = new ServiceDebugBehavior();
            _host.Description.Behaviors.Add(sdb);
         }
         sdb.IncludeExceptionDetailInFaults = false;
         sdb.HttpHelpPageEnabled = false;
         

         _host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
         var bhb = new BasicHttpBinding() { Namespace = "urn:Mpcr.Services.Oscar" };
         bhb.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
         bhb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
         _host.AddServiceEndpoint(typeof(IOscarServices), bhb, "");
         _host.Authorization.ServiceAuthorizationManager = new TibcoAuthManager();
         _host.Open();
      }
Beispiel #21
0
        public static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8000/" + Guid.NewGuid().ToString());

            ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);

            try
            {
                // Add an endpoint to the service
                ServiceEndpoint discoverableCalculatorEndpoint = serviceHost.AddServiceEndpoint(
                    typeof(ICalculatorService), 
                    new WSHttpBinding(), 
                    "/DiscoverableEndpoint");

                // Add a Scope to the endpoint
                EndpointDiscoveryBehavior discoverableEndpointBehavior = new EndpointDiscoveryBehavior();
                discoverableEndpointBehavior.Scopes.Add(new Uri("ldap:///ou=engineering,o=exampleorg,c=us"));
                discoverableCalculatorEndpoint.Behaviors.Add(discoverableEndpointBehavior);

                // Add an endpoint to the service
                ServiceEndpoint nonDiscoverableCalculatorEndpoint = serviceHost.AddServiceEndpoint
                    (typeof(ICalculatorService), 
                    new WSHttpBinding(), 
                    "/NonDiscoverableEndpoint");

                // Disable discoverability of the endpoint
                EndpointDiscoveryBehavior nonDiscoverableEndpointBehavior = new EndpointDiscoveryBehavior();
                nonDiscoverableEndpointBehavior.Scopes.Add(new Uri("ldap:///ou=engineering,o=exampleorg,c=us"));
                nonDiscoverableEndpointBehavior.Enabled = false;
                nonDiscoverableCalculatorEndpoint.Behaviors.Add(nonDiscoverableEndpointBehavior);

                // Make the service discoverable over UDP multicast
                serviceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
                serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

                serviceHost.Open();

                Console.WriteLine("Calculator Service started at {0}", baseAddress);
                Console.WriteLine();
                Console.WriteLine("Press <ENTER> to terminate the service.");
                Console.WriteLine();
                Console.ReadLine();

                serviceHost.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);
            }

            if (serviceHost.State != CommunicationState.Closed)
            {
                Console.WriteLine("Aborting the service...");
                serviceHost.Abort();
            }
        }
Beispiel #22
0
 static void Main(string[] args)
 {
     ServiceHost host = new ServiceHost(typeof(CustomerService), new Uri[]
         {
             new Uri("net.tcp://localhost:8383/CustomerMgmService/")
         }
     );
     ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
     host.AddServiceEndpoint(typeof(ICustomerMgmService), new NetTcpBinding(SecurityMode.Transport), "CMS");
     #if DEBUG
     //don't want to deploy metadata
     host.Description.Behaviors.Add(mexBehavior);
     host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
     #endif
     foreach (var ba in host.BaseAddresses)
     {
         Console.WriteLine("BaseAddress: \n" + ba);
     }
     foreach (var ep in host.Description.Endpoints)
     {
         Console.WriteLine("\n\nEndpoint: \n- {0}\n- {1}\n- {2}", ep.Address.Uri, ep.Name, ep.Binding.Name);
     }
     host.Open();
     Console.WriteLine("\n\nCustomerMgmService is open");
     Console.ReadKey();
     host.Close();
 }
Beispiel #23
0
        /// <summary>
        /// Hosting a service using managed code without any configuraiton information. 
        /// Please note that the related configuration data should be removed before calling the method.
        /// </summary>
        private static void HostCalculatorServiceViaCode()
        {
            var httpBaseAddress = new Uri("http://localhost:8888/generalCalculator");
            var tcpBaseAddress = new Uri("net.tcp://localhost:9999/generalCalculator");

            using (var calculatorSerivceHost = new ServiceHost(typeof(GeneralCalculatorService), httpBaseAddress, tcpBaseAddress))
            {
                var httpBinding = new BasicHttpBinding();
                var tcpBinding = new NetTcpBinding();

                calculatorSerivceHost.AddServiceEndpoint(typeof(IGeneralCalculator), httpBinding, string.Empty);
                calculatorSerivceHost.AddServiceEndpoint(typeof(IGeneralCalculator), tcpBinding, string.Empty);

                var behavior = calculatorSerivceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                {
                    if (behavior == null)
                    {
                        behavior = new ServiceMetadataBehavior();
                        behavior.HttpGetEnabled = true;
                        calculatorSerivceHost.Description.Behaviors.Add(behavior);
                    }
                    else
                    {
                        behavior.HttpGetEnabled = true;
                    }
                }

                calculatorSerivceHost.Opened +=
                    delegate { Console.WriteLine("Calculator Service has begun to listen ... ..."); };

                calculatorSerivceHost.Open();

                Console.Read();
            }
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000/CalculatorService/");
            ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

            try
            {
                selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService");

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

                selfHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
                selfHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());
                selfHost.Open();

                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
                selfHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {0}", ce.Message);
                selfHost.Abort();
            }
        }
Beispiel #25
0
        public override ServiceHostBase CreateServiceHost
                (string service, Uri[] baseAddresses)
        {
            ServiceHost host = new ServiceHost(typeof(IssHosted.ServiceInterfaces.EchoService),
                baseAddresses);

            host.AddServiceEndpoint(typeof(IEchoService), new ServiceproviderBinding(true), "");
            host.AddServiceEndpoint(typeof(IEchoService), new ServiceproviderBinding(false), "");

            // Configure our certificate and issuer certificate validation settings on the service credentials
            host.Credentials.ServiceCertificate.SetCertificate(SigningCertificateNameGenevaService, StoreLocation.LocalMachine, StoreName.My);
            // Enable metadata generation via HTTP GET
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpsGetEnabled = true;
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);

            host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpsBinding(), "mex");
            host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");


            // Configure the service host to use the Geneva Framework
            ServiceConfiguration configuration = new ServiceConfiguration();
            configuration.IssuerNameRegistry = new TrustedIssuerNameRegistry();
            configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost/Echo/service.svc/Echo"));
            configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost:6020/Echo"));
            configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://172.30.161.162:8181/poc-provider/ProviderService"));
            configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://172.16.232.1:8181/poc-provider/ProviderService"));
            configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://csky-pc/test/Service1.svc"));
            FederatedServiceCredentials.ConfigureServiceHost(host, configuration);
            return host;
        }
 public void StartStopService()
 {
     var baseUri = new Uri("http://localhost:8080/MyWebPage.WCF_Lab2");
     var selfServiceHost = new ServiceHost(typeof(MyWebPageEntryPoint), baseUri);
     using (selfServiceHost)
     {
         selfServiceHost.AddServiceEndpoint(typeof(ICalculateAge),
             new WSHttpBinding(),
             "CalculateAgeService");
         selfServiceHost.AddServiceEndpoint(typeof(ICalculateBmi),
             new WSHttpBinding(),
             "CalculateBmiService");
         selfServiceHost.AddServiceEndpoint(typeof(ICalculateEvenBirthday),
             new WSHttpBinding(),
             "CalculateEvenBirthdayService");
         selfServiceHost.AddServiceEndpoint(typeof(ICalculateCalories),
             new WSHttpBinding(),
             "CalculateCaloriesBurned");
         var smBehavior = new ServiceMetadataBehavior { HttpGetEnabled = true };
         selfServiceHost.Description.Behaviors.Add(smBehavior);
         selfServiceHost.Open();
         Console.WriteLine($"Service opened: {DateTime.Now} at: {baseUri}");
         Console.WriteLine("Press enter to shut down selfservice.");
         Console.ReadKey();
     }
 }
Beispiel #27
0
        static void ServicoProtocoloNETTCP()
        {
            //Configuro a URL que vou SUBIR(DISPONIBILIZAR) O SERVIÇO WCF
            Uri EnderecoServico = new Uri("net.tcp://localhost:8181/Demonstracao2/MeuServico");

            //Classe serve para (HOSPEDAR, ARMAZENAR) O SERVIÇO WCF
            //Informo o nome do SERVIÇO (Servicos.Contato)
            //Informo o endereço que vou SUBIR O SERVIÇO
            ServiceHost Host = new ServiceHost(typeof(Servicos.Contato), EnderecoServico);

            //Habilitei o WSDL para os clientes
            //WSDL = MEX no protocolo NET.TCP
            Host.Description.Behaviors.Add(new ServiceMetadataBehavior());

            //Configuração do WSDL(MEX)
            Host.AddServiceEndpoint(typeof(IMetadataExchange),
                                    MetadataExchangeBindings.CreateMexTcpBinding(),
                                    "MEX/");

            //Adicionei o ENDPOINT (Contrato que vai ser trafegado para o cliente)
            //Adicionei o ENDPOINT (Tipo de Binding (PROTOCOLO))
            //Adicionei o ENDPOINT (Nome do SERVIÇO)
            Host.AddServiceEndpoint(typeof(Servicos.IContato),
                                    new NetTcpBinding(),
                                    "Servicos.Contato");

            //Liguei o SERVIÇO
            Host.Open();
        }
        static void Main(string[] args)
        {
            ServiceHost sh = new ServiceHost(typeof(StringReverser));

            sh.AddServiceEndpoint(
               typeof(IStringReverser), new NetTcpBinding(),
               "net.tcp://localhost:9358/reverse");

            sh.AddServiceEndpoint(
               typeof(IStringReverser), new NetTcpRelayBinding(),
               ServiceBusEnvironment.CreateServiceUri("sb", "ckdemo", "solver"))
                .Behaviors.Add(new TransportClientEndpointBehavior
                {
                    TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(
                    ConfigurationManager.AppSettings["issuerName"],
                    ConfigurationManager.AppSettings["issuerSecret"])
                });

            sh.Open();

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();

            sh.Close();
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            Uri httpBaseAddress = new Uri("http://localhost:6789/");
            ServiceHost sh = new ServiceHost(typeof (MEP), new Uri[] {httpBaseAddress});
            
            //ServiceEndpoint se = sh.AddServiceEndpoint(typeof (IMEP), new BasicHttpBinding(), httpBaseAddress);
            ServiceEndpoint se = sh.AddServiceEndpoint(typeof(IMEP), new WSDualHttpBinding(), httpBaseAddress);

            ServiceMetadataBehavior smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if(smb == null)
                smb = new ServiceMetadataBehavior();
            sh.Description.Behaviors.Add(smb);

            ServiceEndpoint httpSeMex = sh.AddServiceEndpoint(typeof (IMetadataExchange),
                MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:6789/mex");

            sh.Open();

            Console.WriteLine("Started...");
            foreach (var item in sh.Description.Endpoints)
            {
                Console.WriteLine("Address: " + item.Address.ToString());
                Console.WriteLine("Binding: " + item.Binding.Name.ToString());
                Console.WriteLine("Contract: " + item.Contract.Name.ToString());
                Console.WriteLine("------------------");
            }

            Console.ReadLine();

            sh.Close();
            Console.WriteLine("Closed...");
        }
        public ServiceHost CreateServiceHost(ClusterConfiguration clusterConfiguration)
        {
            var managerNode = new ManagerNode(clusterConfiguration);
            managerNode.Start();
            var serviceHost = new ServiceHost(managerNode,
                                              new[]
                                                  {
                                                      new Uri(string.Format("http://localhost:{0}/brightstarcluster",
                                                                            Configuration.HttpPort)),
                                                      new Uri(string.Format("net.tcp://localhost:{0}/brightstarcluster",
                                                                            Configuration.TcpPort)),
                                                      new Uri(string.Format("net.pipe://localhost/{0}",
                                                                            Configuration.NamedPipeName))
                                                  });

            var basicHttpBinding = new BasicHttpContextBinding { TransferMode = TransferMode.StreamedResponse, MaxReceivedMessageSize = int.MaxValue, SendTimeout = TimeSpan.FromMinutes(30), ReaderQuotas = XmlDictionaryReaderQuotas.Max, Namespace = "http://www.networkedplanet.com/schemas/brightstar" };
            var netTcpContextBinding = new NetTcpContextBinding { TransferMode = TransferMode.StreamedResponse, MaxReceivedMessageSize = int.MaxValue, SendTimeout = TimeSpan.FromMinutes(30), ReaderQuotas = XmlDictionaryReaderQuotas.Max, Namespace = "http://www.networkedplanet.com/schemas/brightstar" };
            var netNamedPipeBinding = new NetNamedPipeBinding { TransferMode = TransferMode.StreamedResponse, MaxReceivedMessageSize = int.MaxValue, SendTimeout = TimeSpan.FromMinutes(30), ReaderQuotas = XmlDictionaryReaderQuotas.Max, Namespace = "http://www.networkedplanet.com/schemas/brightstar" };

            serviceHost.AddServiceEndpoint(typeof(IBrightstarClusterManagerService), basicHttpBinding, "");
            serviceHost.AddServiceEndpoint(typeof(IBrightstarClusterManagerService), netTcpContextBinding, "");
            serviceHost.AddServiceEndpoint(typeof(IBrightstarClusterManagerService), netNamedPipeBinding, "");

            var throttlingBehavior = new ServiceThrottlingBehavior { MaxConcurrentCalls = int.MaxValue };

            serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
            serviceHost.Description.Behaviors.Add(throttlingBehavior);

            serviceHost.Closed += StopNode;
            return serviceHost;
            
        }
        public ServiceHost createLobby(string ip, Lobby lobby)
        {
            string uri = TCP_CONN_STR + ip;

            ServiceHost host = new ServiceHost(
                lobby,
                new Uri[]{
                    new Uri(uri)
                });

            host.AddServiceEndpoint(typeof(ILobby),
                new NetTcpBinding(SecurityMode.None),
                LOBBY_NAME);

            ServiceHost discoveryHost = new ServiceHost(
                new DiscoveryTest(),
                new Uri[]{
                    new Uri(uri + "/Discovery")
                });

            discoveryHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
            discoveryHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

            discoveryHost.AddServiceEndpoint(typeof(IDiscoveryTest),
                new NetTcpBinding(SecurityMode.None),
                "");

            discoveryHost.Open();

            return host;
        }
Beispiel #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();
            }
        }
        static void Main(string[] args)
        {
            var logger = new Logger(typeof(WordCounter));
            var svcHost = new ServiceHost(typeof(WordCounter), new Uri("http://localhost:50000/WordCount"));
            var smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
            // If not, add one
            if (smb == null)
                smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            svcHost.Description.Behaviors.Add(smb);
            // Add MEX endpoint
            svcHost.AddServiceEndpoint(
              ServiceMetadataBehavior.MexContractName,
              MetadataExchangeBindings.CreateMexHttpBinding(),
              "mex"
            );

            var ep = svcHost.AddServiceEndpoint(typeof(IWordCount), new BasicHttpBinding(), "");

            svcHost.Open();
            Console.WriteLine("Service is running on: ");
            foreach (var endPoint in  svcHost.Description.Endpoints)
            {
                Console.WriteLine(endPoint.Address);
            }
            Console.WriteLine("Press enter to quit...");
            Console.ReadLine();
            svcHost.Close();
        }
Beispiel #34
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();
        }
Beispiel #35
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();
        }
Beispiel #36
0
 /// <summary>
 /// 构造服务对象
 /// </summary>
 protected void CreateServiceHost()
 {
     //创建服务对象
     _host = new System.ServiceModel.ServiceHost(ServiceType, new Uri(BaseAddress));
     //添加终结点
     _host.AddServiceEndpoint(ContractType, Binding, ServiceAddress);
 }
        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")
            {
            }
        }
        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);
        }
Beispiel #39
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");
        }
Beispiel #40
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();
     }
 }
Beispiel #41
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);
        }
Beispiel #42
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();
        }
        public void Start()
        {
            Logging.Log(LogLevelEnum.Info, "Starting WCF service");
            ServiceAddress    = string.Format("net.tcp://{0}:{1}/", Utilities.GetIPv4Address(Settings.Instance.UseLoopback).ToString(), Settings.Instance.WcfPort);
            MexServiceAddress = string.Format("net.tcp://{0}:{1}/mex/", Utilities.GetIPv4Address().ToString(), Settings.Instance.WcfMexPort);
            Logging.Log(LogLevelEnum.Debug, string.Format("Service host address: {0}", ServiceAddress));
            Logging.Log(LogLevelEnum.Debug, string.Format("MEX Service host address: {0}", MexServiceAddress));
            serviceHost = new ServiceModel.ServiceHost(typeof(TService), new Uri(ServiceAddress));
            serviceHost.AddServiceEndpoint(typeof(TContract), new ServiceModel.NetTcpBinding(ServiceModel.SecurityMode.None), "");

            // Add TCP MEX endpoint
            ServiceModelChannels.BindingElement             bindingElement   = new ServiceModelChannels.TcpTransportBindingElement();
            ServiceModelChannels.CustomBinding              binding          = new ServiceModelChannels.CustomBinding(bindingElement);
            ServiceModelDescription.ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find <ServiceModelDescription.ServiceMetadataBehavior>();
            if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceModelDescription.ServiceMetadataBehavior();
                serviceHost.Description.Behaviors.Add(metadataBehavior);
            }
            serviceHost.AddServiceEndpoint(typeof(ServiceModelDescription.IMetadataExchange), binding, MexServiceAddress);

            serviceHost.Open();
            Logging.Log(LogLevelEnum.Info, "WCF service started");
        }
Beispiel #44
0
 static void Main(string[] args)
 {
     System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(ClienteService));
     host.AddServiceEndpoint(typeof(IClienteService), new BasicHttpBinding(), new Uri("http://localhost:8080/clientes"));
     try
     {
         host.Open();
         Console.ReadLine();
         host.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         host.Abort();
         Console.ReadLine();
     }
 }
Beispiel #45
0
        public void TestTimeoutSet()
        {
            var uri     = "net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;
            var binding = new System.ServiceModel.NetNamedPipeBinding()
            {
                MaxConnections = 5
            };
            var timeout = 700;

            binding.ReceiveTimeout = TimeSpan.FromMilliseconds(timeout);
            var hang = TimeSpan.FromMilliseconds(timeout * 2);

            using (var server = new System.ServiceModel.ServiceHost(new Service(), new Uri(uri)))
            {
                server.AddServiceEndpoint(typeof(IService), binding, uri);
                server.Open();
                var channelFactory = new System.ServiceModel.ChannelFactory <IService>(binding);

                var client = channelFactory.CreateChannel(new EndpointAddress(uri));
                var result = client.Execute(TimeSpan.FromMilliseconds(0));
                Assert.AreEqual(TimeSpan.FromMilliseconds(0), result);
                CommunicationException timeoutHappenedException = null;
                try
                {
                    result = client.Execute(hang);
                }
                catch (CommunicationException ex)
                {
                    timeoutHappenedException = ex;
                }
                Assert.NotNull(timeoutHappenedException);
                Assert.AreEqual(typeof(System.IO.IOException), timeoutHappenedException.InnerException.GetType());
                var channel = client as IContextChannel;
                Assert.AreEqual(CommunicationState.Faulted, channel.State);
                try
                {
                    result = client.Execute(TimeSpan.FromMilliseconds(0));
                }
                catch (CommunicationObjectFaultedException afterTimeoutExeption)
                {
                }
                client = channelFactory.CreateChannel(new EndpointAddress(uri));
                result = client.Execute(TimeSpan.FromMilliseconds(0));
            }
        }
Beispiel #46
0
 public void TestTcpUrl()
 {
     using (var server = new System.ServiceModel.ServiceHost(new Service(), new Uri("net.tcp://127.0.0.1:6782")))
     {
         var binding = new System.ServiceModel.NetTcpBinding()
         {
             MaxConnections = 5
         };
         server.AddServiceEndpoint(typeof(IService), binding, "net.tcp://127.0.0.1:6782");
         server.Open();
         Thread.Sleep(100);
         using (var channelFactory = new System.ServiceModel.ChannelFactory <IService>(binding))
         {
             var client = channelFactory.CreateChannel(new EndpointAddress("net.tcp://127.0.0.1:6782"));
             var result = client.Execute(new byte[] { 1 });
             Assert.AreEqual(1, result[0]);
         }
     }
 }
Beispiel #47
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:9001/TheService");

            using (System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(TheService), baseAddress))
            {
                host.AddServiceEndpoint(typeof(ITheService), new WSHttpBinding(), "");
                ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                serviceBehavior.HttpGetEnabled = true;
                host.Description.Behaviors.Add(serviceBehavior);

                host.Open();

                Console.WriteLine("Hit enter to exit ...");
                Console.Read();

                host.Close();
            }
        }
Beispiel #48
0
        private static bool ExecuteTestWithCoverageDataCollection(Func <bool> runTests, string codeCoverageStore)
        {
            bool allTestsPassed = true;
            var  ccServer       = new CoverageDataCollector();

            using (System.ServiceModel.ServiceHost serviceHost = new System.ServiceModel.ServiceHost(ccServer))
            {
                LogInfo("TestHost: Created Service Host.");
                string address = MarkerV1.CreateCodeCoverageDataCollectorEndpointAddress();
                NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
                serviceHost.AddServiceEndpoint(typeof(ICoverageDataCollector), binding, address);
                serviceHost.Open();
                LogInfo("TestHost: Opened _channel.");

                allTestsPassed = runTests();
                LogInfo("TestHost: Finished running test cases.");
            }
            ccServer.CoverageData.Serialize(FilePath.NewFilePath(codeCoverageStore));
            return(allTestsPassed);
        }
Beispiel #49
0
        public static void Main(string[] args)
        {
            var httpBaseAddress = new Uri("http://localhost:13666/MessageService");

            using (var messageQueueHost = new System.ServiceModel.ServiceHost(typeof(MessageQueue), httpBaseAddress))
            {
                messageQueueHost.AddServiceEndpoint(typeof(IMessageQueue), new WSHttpBinding(), "");

                var serviceBehavior = new ServiceMetadataBehavior
                {
                    HttpGetEnabled = true
                };
                messageQueueHost.Description.Behaviors.Add(serviceBehavior);

                messageQueueHost.Open();
                Console.WriteLine($"Service is live now at: {httpBaseAddress}\n\n");
                Console.ReadKey();
                messageQueueHost.Close();
            }
        }
Beispiel #50
0
        public void IContextChannel_operationTimeoutSetGet_Ok()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            using (var server = new System.ServiceModel.ServiceHost(new SimpleService(), new Uri(address)))
            {
                server.AddServiceEndpoint(typeof(ISimpleService), binding, address);
                server.Open();
                Thread.Sleep(100);
                using (var channelFactory = new System.ServiceModel.ChannelFactory <ISimpleService>(binding))
                {
                    var client         = channelFactory.CreateChannel(new EndpointAddress(address));
                    var contextChannel = client as IContextChannel;
                    var newTimeout     = TimeSpan.FromSeconds(123);
                    contextChannel.OperationTimeout = newTimeout;
                    var timeout = contextChannel.OperationTimeout;
                    Assert.AreEqual(newTimeout, timeout);
                }
            }
        }
        static void Main(string[] args)
        {
            //Code
            wcf.ServiceHost _serverStatusServiceHost =
                new wcf.ServiceHost(typeof(ServerStatusServiceLib.ServerStatusService));
            //rest client (web client) endpoint

            var endpoint = _serverStatusServiceHost.AddServiceEndpoint(
                typeof(ServerStatusServiceContractLib.IServerStatusService),
                new wcf.WebHttpBinding(),
                "http://localhost:8007/restservice");

            //add endpointbehavior to process incoming http request as a rest api request
            //enable web programming model

            endpoint.EndpointBehaviors.Add(new WebHttpBehavior());

            _serverStatusServiceHost.Open();
            Console.WriteLine("Restserver Started");
            Console.ReadKey();
        }