public void should_add_the_servicebehavior_to_the_behavior_collection()
        {
            var host =
                new WebServiceHost(typeof(FakeService), new[] { new Uri("net.tcp://localhost:8081") });

            host.AddServiceEndpoint(typeof(IFakeService), new NetTcpBinding(), "net.tcp://localhost:8081/MyService");
            host.Open();

            host.Description.Behaviors.ShouldContainType<ServiceBehavior>();
            host.Close();
        }
Esempio n. 2
0
        public void WebMessageFormats()
        {
            var host = new WebServiceHost(typeof(Hello));
            var port = NetworkHelpers.FindFreePort();

            host.AddServiceEndpoint(typeof(IHello), new WebHttpBinding(), "http://localhost:" + port + "/");
            host.Description.Behaviors.Find <ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
            host.Open();
            try {
                // run client
                using (ChannelFactory <IHello> factory = new ChannelFactory <IHello> (new WebHttpBinding(), "http://localhost:" + port + "/"))
                {
                    factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
                    IHello h = factory.CreateChannel();
                    //Console.WriteLine(h.SayHi("Joe", 42, null));
                    Assert.AreEqual("Hi Joe.", h.SayHi2(new User {
                        Name = "Joe"
                    }), "#1");
                }
            } finally {
                host.Close();
            }
        }
        static void Main()
        {
            WebServiceHost host = new WebServiceHost(typeof(HelloRestService.HelloRestService),
                                                     new Uri("http://localhost:8082"));

            ServiceEndpoint ep = host.AddServiceEndpoint(
                typeof(HelloRestService.IHelloRestService), new WebHttpBinding(), "");

            host.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior {
                HelpEnabled = true
            });
            //Visar vilka metoder som använder vilken metod, vilket språk den kommunicerar på, om body är wrapped eller inte

            ServiceDebugBehavior sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>();

            sdb.IncludeExceptionDetailInFaults = true;
            //sdb.HttpHelpPageEnabled = true;

            host.Open();
            Console.WriteLine("Service is running ;)");
            Console.ReadKey();
            host.Close();
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(MyRest.RestService),
                                                     new Uri("http://localhost:8080"));

            ServiceEndpoint ep = host.AddServiceEndpoint(
                typeof(MyRest.IRestService), new WebHttpBinding(), "");

            host.Description.Endpoints[0].Behaviors.Add(
                new WebHttpBehavior {
                HelpEnabled = true
            });

            ServiceDebugBehavior sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>();

            sdb.IncludeExceptionDetailInFaults = true;
            //sdb.HttpsHelpPageEnabled = true;

            host.Open();
            Console.WriteLine("Service is running");
            Console.ReadLine();
            host.Close();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            RestDemoServices DemoServices = new RestDemoServices();
            WebHttpBinding   binding      = new WebHttpBinding();
            WebHttpBehavior  behavior     = new WebHttpBehavior();

            WebServiceHost _serviceHost = new WebServiceHost(DemoServices, new Uri("http://localhost:8000/DEMOService"));

            _serviceHost.AddServiceEndpoint(typeof(IRESTDemoServices), binding, "");
            _serviceHost.Open();
            Console.ReadKey();
            _serviceHost.Close();

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("---- MyConcert ---- Servidor API -----");
                Console.WriteLine("Presione ENTER para cerrar.");
                Console.ReadLine();
                Console.WriteLine("Confirmacion...");
                Console.ReadLine();
            }
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            // open web service host which serves cross-domain policy files
            var webServiceHost = new WebServiceHost(typeof(CrossDomainPolicyServer), new Uri("http://localhost:8000"));

            webServiceHost.Open();

            //var webServiceHost2 = new WebServiceHost(typeof(CrossDomainPolicyServer), new Uri("http://localhost:943"));
            //webServiceHost2.Open();

            var policyServer = new PolicyServer();

            // open log receiver server
            var host = new ServiceHost(typeof(LogReceiverServer), new Uri("http://localhost:8000/"));

            host.Open();
            Console.WriteLine("Host opened");
            Console.Write("Press ENTER to close");
            Console.ReadLine();
            webServiceHost.Close();
            //webServiceHost2.Close();
            host.Close();
        }
Esempio n. 7
0
        private static WebServiceHost CreateAndOpenWebServiceHost(INancyBootstrapper nancyBootstrapper = null)
        {
            if (nancyBootstrapper == null)
            {
                nancyBootstrapper = new DefaultNancyBootstrapper();
            }

            var host = new WebServiceHost(
                new NancyWcfGenericService(nancyBootstrapper),
                BaseUri);

            host.AddServiceEndpoint(typeof(NancyWcfGenericService), new WebHttpBinding(), "");
            try
            {
                host.Open();
            }
            catch (System.ServiceModel.AddressAccessDeniedException)
            {
                throw new SkipException("Skipped due to no Administrator access - please see test fixture for more information.");
            }

            return(host);
        }
        /// <summary>
        /// Needs to be started as admin!
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                WebServiceHost host = new WebServiceHost(typeof(MainService));

                host.Open();

                Console.WriteLine("Service started!");

                Console.ReadLine();

                host.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("Bye!");

            Console.ReadLine();
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            string uriBaseAddress = args[0];
            string waitHandleName = null;
            if(args.Length > 1)
                 waitHandleName = args[1];

            Uri[] uriArray = { new Uri(uriBaseAddress) };

            Type serviceType = Assembly.GetExecutingAssembly().GetTypes().Single(t => !t.IsAbstract && typeof(Microsoft.OData.Service.IRequestHandler).IsAssignableFrom(t));

            using(WebServiceHost host = new WebServiceHost(serviceType, uriArray))
            {
                try
                {    
                    host.Open();
                    if(waitHandleName == "Debug" || string.IsNullOrEmpty(waitHandleName)) 
                    { 
                        Console.WriteLine("Running in Debug mode , please press any key to exit");
                        Console.Read();
                    }
                    else
                    {
                        EventWaitHandle waitHandle = EventWaitHandle.OpenExisting(waitHandleName);
                        waitHandle.WaitOne();
                    }
                    host.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An exception occurred:");
                    Console.WriteLine(ex.ToString());
                    host.Abort();
                    Console.ReadLine();
                }
            }
        }
Esempio n. 10
0
        protected override void OnStart(string[] args)
        {
            _appLog = ApplicationLog.OpenLogSession(ApplicationLogConfiguration.GetDefault());

            var providerConfiguration = ConfigManager.GetDefaultConfiguration();

            if (_vasaHost == null)
            {
                _vasaHost =
                    new VasaServiceHost(typeof(VasaService));
                var customHttpsBinding = new CustomBinding(
                    new TextMessageEncodingBindingElement {
                    MessageVersion = MessageVersion.Soap12
                },
                    new HttpsTransportBindingElement());
                _vasaHost.AddServiceEndpoint(typeof(vasaServicePortType), customHttpsBinding, providerConfiguration.VasaUri);
            }

            if (_versioningHost == null)
            {
                _versioningHost =
                    new WebServiceHost(typeof(VasaVersioningService), providerConfiguration.VasaVersionUri);
            }

            if (_taskManager == null)
            {
                _taskManager = TaskManager.Instance;
            }

            _vasaHost.Open();
            _appLog.WriteMessage(ApplicationLogMessageType.Information, Resources.ProviderRun);

            _versioningHost.Open();
            _appLog.WriteMessage(ApplicationLogMessageType.Information, Resources.VersioningRun);

            _taskManager.Open();
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));

            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
                host.Open();
                using (ChannelFactory <IService> cf = new ChannelFactory <IService>(new WebHttpBinding(), "http://localhost:8000"))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());

                    IService channel = cf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                    s = channel.Echo("Hello, WCF!");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");
                    Console.WriteLine("This can also be accomplished by navigating to");
                    Console.WriteLine("http://localhost:8000/EchoFromBrowser?message=Hello, WCF!");
                    Console.WriteLine("in a web browser while this sample is running.");
                }

                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();

                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}", cex.Message);
                host.Abort();
            }
        }
        // Rule ID: azure_sbr_no_client_authentication
        public void RunUsingRelay(string httpAddress, string listenToken)
        {
            using (var host = new WebServiceHost(this.GetType()))
            {
                // Warning generate due to usage of insecure [None] RelayClientAuthenticationType

                var webHttpRelayBinding = new WebHttpRelayBinding(EndToEndWebHttpSecurityMode.Transport,
                                                                  RelayClientAuthenticationType.None)
                {
                    IsDynamic = false
                };

                // Safe
                webHttpRelayBinding = new WebHttpRelayBinding(EndToEndWebHttpSecurityMode.Transport,
                                                              RelayClientAuthenticationType.RelayAccessToken)
                {
                    IsDynamic = false
                };

                host.AddServiceEndpoint(this.GetType(),
                                        webHttpRelayBinding,
                                        httpAddress)
                .EndpointBehaviors.Add(
                    new TransportClientEndpointBehavior(
                        TokenProvider.CreateSharedAccessSignatureTokenProvider(listenToken)));

                host.Open();

                Console.WriteLine("Copy the following address into a browser to see the image: ");
                Console.WriteLine(httpAddress + "/Image");
                Console.WriteLine();
                Console.WriteLine("Press [Enter] to exit");
                Console.ReadLine();

                host.Close();
            }
        }
Esempio n. 13
0
        void service_task()
        {
            CCommand.OnExecute += new CCommand.CCommnadEvent(cmd_OnExecute);
            // Zugriff erlauben mit: netsh http add urlacl url=http://+:8000/ user=till
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));

            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
                host.Open();
                using (ChannelFactory <IService> cf = new ChannelFactory <IService>(new WebHttpBinding(), "http://localhost:8000"))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());

                    IService channel = cf.CreateChannel();

                    string s;


                    Console.WriteLine("call http://localhost:8000/sendCommand?cmd=speak(args=\"Hello world\")");

                    Console.WriteLine("");
                }

                while (true)
                {
                    Task.Delay(10).Wait();
                }

                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}", cex.Message);
                host.Abort();
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 开启REST服务
        /// </summary>
        private void OpenServices()
        {
            try
            {
                AgvCallBackService service   = new AgvCallBackService();
                Uri            baseAddress   = new Uri($"http://{wcsip}:{wcsport}/");
                WebServiceHost _servicesHost = new WebServiceHost(service, baseAddress);

                WebHttpBinding binding = new WebHttpBinding
                {
                    TransferMode           = TransferMode.Buffered,
                    MaxBufferPoolSize      = (long)2 * 1024 * 1024 * 1024,
                    MaxReceivedMessageSize = (long)2 * 1024 * 1024 * 1024,
                    MaxBufferSize          = 2147483647,
                    ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max,
                    Security = { Mode = WebHttpSecurityMode.None }
                };

                _servicesHost.AddServiceEndpoint(typeof(IAgvResultCallBack), binding, baseAddress);
                //_servicesHost.Opened += (sender, e) =>
                //{
                //    NotifyEvent?.Invoke("R", "web服务开启...");
                //    log.WriteLog("web服务开启...");
                //};
                _servicesHost.Opened += delegate
                {
                    NotifyEvent?.Invoke("R", "web服务开启...");
                    log.WriteLog("web服务开启...");
                };
                _servicesHost.Open();
            }
            catch (Exception ex)
            {
                NotifyEvent?.Invoke("R", $"web服务异常,异常信息为:{ex.Message}");
                log.WriteLog($"web服务异常,异常信息为:{ex.Message}");
            }
        }
Esempio n. 15
0
        public static ServiceHost StartRestHost <T>(string url, T component)
        {
            var restHost = new WebServiceHost(component, new Uri(url));

            var debugBehavior = restHost.Description.Behaviors.Find <ServiceDebugBehavior>();

            debugBehavior.IncludeExceptionDetailInFaults = true;

            var sep = restHost.AddServiceEndpoint(typeof(T), new WebHttpBinding(), "");
            var whb = sep.Behaviors.Find <WebHttpBehavior>();

            if (whb == null)
            {
                whb = new WebHttpBehavior();
                sep.Behaviors.Add(whb);
            }

            foreach (var operation in sep.Contract.Operations)
            {
                if (!operation.Behaviors.OfType <ClientJsonDateFormatter>().Any())
                {
                    operation.Behaviors.Add(new ClientJsonDateFormatter());
                }
            }

            whb.AutomaticFormatSelectionEnabled = true;
            whb.DefaultOutgoingRequestFormat    = WebMessageFormat.Json;
            whb.DefaultOutgoingResponseFormat   = WebMessageFormat.Json;
            var serviceBehaviour = restHost.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            if (serviceBehaviour != null)
            {
                serviceBehaviour.InstanceContextMode = InstanceContextMode.Single;
            }
            restHost.Open();
            return(restHost);
        }
Esempio n. 16
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <remarks>N/A</remarks>
        static void Main(string[] args)
        {
            InitializeDatabase();


            string url = String.Format("http://localhost:8732/Design_Time_Addresses/fhir");

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
            var name    = Assembly.GetExecutingAssembly().GetName().Name;

            var header = String.Format("FHIR Server - {0} version {1}", name, version);
            var line   = new string('-', header.Length);

            Console.WriteLine(header);
            Console.WriteLine(line);
            Console.WriteLine();

            // Create an instance of our REST service and pass it to WCF
            var repository = new Repository();
            var service    = new RestService(repository);

            var server = new WebServiceHost(service, new Uri(url));

            server.Opened += server_Opened;
            try
            {
                server.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
    /// <summary>
    /// https webhttpbinding.
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        Uri            uri     = new Uri("https://localhost:4386");
        WebHttpBinding binding = new WebHttpBinding();

        binding.Security.Mode = WebHttpSecurityMode.Transport;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;


        using (WebServiceHost sh = new WebServiceHost(typeof(TestService), uri))
        {
            sh.AddServiceEndpoint(typeof(ITestService), binding, "");
            ServiceMetadataBehavior smb;
            smb = sh.Description.Behaviors.Find <ServiceMetadataBehavior>();
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior()
                {
                    //HttpsGetEnabled = true
                };
                sh.Description.Behaviors.Add(smb);
            }
            Binding mexbinding = MetadataExchangeBindings.CreateMexHttpsBinding();
            sh.AddServiceEndpoint(typeof(IMetadataExchange), mexbinding, "mex");
            sh.Opened += delegate
            {
                Console.WriteLine("service is ready");
            };
            sh.Closed += delegate
            {
                Console.WriteLine("service is closed");
            };
            sh.Open();
            Console.ReadLine();
            sh.Close();
        }
    }
    public static void Test()
    {
        string         baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host        = new WebServiceHost(typeof(Service), new Uri(baseAddress));

        host.Open();
        Console.WriteLine("Host opened");
        Console.WriteLine("Accessing via WebChannelFactory<T>");
        WebChannelFactory <ITest> factory = new WebChannelFactory <ITest>(new Uri(baseAddress));
        ITest proxy = factory.CreateChannel();

        proxy.RegisterPerson(new Person
        {
            Name    = "John Doe",
            Age     = 32,
            Address = new Address
            {
                City   = "Springfield",
                Street = "123 Main St",
                Zip    = "12345"
            }
        });
        Console.WriteLine(proxy.FindPerson("John Doe").Age);
        Console.WriteLine();
        Console.WriteLine("Accessing via \"normal\" HTTP client");
        string    jsonInput = "{'Name':'Jane Roe','Age':30,'Address':{'Street':'1 Wall St','City':'Springfield','Zip':'12346'}}".Replace('\'', '\"');
        WebClient c         = new WebClient();

        c.Headers[HttpRequestHeader.ContentType] = "application/json";
        c.UploadString(baseAddress + "/RegisterPerson", jsonInput);
        c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/FindPerson?name=Jane Roe"));
        Console.WriteLine();
        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
Esempio n. 19
0
    /**
     * Start the web server on the given port, and host the expected service
     */
    public void Start()
    {
        Console.WriteLine("Starting a WCF self-hosted .Net server... ");

        WebHttpBinding b = new WebHttpBinding();

        Host = new WebServiceHost(typeof(ParcelService), new Uri(url));

        // Adding the service to the host
        Host.AddServiceEndpoint(typeof(IParcelService), b, "");

        // Staring the Host server
        Host.Open();
        Console.WriteLine(string.Format("\nListening to {0}:{1}", HostName, Port));

        if (Standalone)
        {
            LockServer();
        }
        else
        {
            Interactive();
        }
    }
Esempio n. 20
0
        internal static ICameraStatusService Initialise()
        {
            try
            {
                _logger.Info(" ");
                _logger.Info("-----------------------------------l-");
                _logger.Info("starting Camera Status service");



                Uri httpUrl = new Uri("https://localhost:6530/CameraStatusService");
                //Create ServiceHost
                WebServiceHost host
                    = new WebServiceHost(typeof(CameraStatusService), httpUrl);
                //Add a service endpoint
                host.AddServiceEndpoint(typeof(ICameraStatusService)
                                        , new WebHttpBinding(WebHttpSecurityMode.Transport), "");//WSHttpBinding

                ServiceThrottlingBehavior throttleBehavior = new ServiceThrottlingBehavior
                {
                    MaxConcurrentCalls     = 500,
                    MaxConcurrentInstances = 500,
                    MaxConcurrentSessions  = 500,
                };
                host.Description.Behaviors.Add(throttleBehavior);
                host.Open();

                _logger.Info("Camera Status service started successfully");
                return(null);//service;
            }
            catch (Exception ex)
            {
                _logger.Info("CameraStatusService Initialise() Exception" + ex.Message);
            }
            return(null);
        }
        public void OnStart(string[] args)
        {
            using (new BeginEndTracer(GetType().Name))
            {
                try
                {
                    _serviceHost = new WebServiceHost(typeof(WeatherServiceDuplex));
                    _serviceHost.Open();

                    _signalR = WebApp.Start <Startup>(Settings.Default.SignalR_ListenUrl);
                    Trace.Listeners.Remove("HostingTraceListener");

                    Program.Session = new Session();

                    Program.Session.Initialize();
                    Program.Session.StartRefresh();
                }
                catch (Exception exception)
                {
                    Tracer.WriteException("ServiceImplementation.OnStart", exception);
                    throw;
                }
            }
        }
Esempio n. 22
0
        public static void RunService()
        {
            try
            {
                // Start WCF REST Service
                ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IWebRobotService), new WebHttpBinding(), "");
                host.Description.Behaviors.Find <ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
                host.Description.Behaviors.Find <ServiceDebugBehavior>().HttpHelpPageEnabled            = false;

                host.Open();
                PingService();
                Log.Info("OsoFx Service is running at " + ConfigurationManager.AppSettings["OsoFx.ServiceUrl"]);
                Console.WriteLine("OsoFx Service is running at {0}", ConfigurationManager.AppSettings["OsoFx.ServiceUrl"]);
                Console.WriteLine("Press ANY KEY to exit");
                Console.Read();
                host.Close();

                LogServiceClient logclient = new LogServiceClient();
                logclient.WriteLog(new WebRobotStreamLogLine[]
                {
                    new WebRobotStreamLogLine
                    {
                        Line      = "service closed",
                        RobotName = "all",
                        Timestamp = DateTime.Now
                    }
                });
                logclient.PingStatus("all", WebRobotManagementStatus.STOPPED);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                Log.Error(ex);
            }
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(NotificationService));

            try {
                host.Open();
                var port    = host.Description.Endpoints[0].Address.Uri.Port;
                var address = Dns.GetHostAddresses(Dns.GetHostName())
                              .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)
                              .First();

                Console.WriteLine("The service is ready and listening on: {0}:{1}\n", address, port);
                Console.WriteLine("Press <ENTER> to terminate service");
                Console.ReadLine();
            } catch (System.TimeoutException ex) {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            } catch (CommunicationException ex) {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            } finally {
                host.Close();
            }
        }
Esempio n. 24
0
        static void Main()
        {
            Data.GParams.Instance.Initialice(Program.LocalAppDir, Program.LocalAppDataDir);

            Program.CfgFile = new CfgFile(System.IO.Path.Combine(Program.LocalAppDir, "Params.xml"));

            Program.PcCode = Data.Security.GandingSecurity.CreateBaseAccessCode();
            Program.ActivateLizence();

            ServiceHost _serviceHost      = new WebServiceHost(new RestService());
            var         _serviceEndBpoint = _serviceHost.AddServiceEndpoint(typeof(IRestService), new WebHttpBinding(), new Uri("http://localhost:8181/DEMOService"));

            _serviceEndBpoint.Behaviors.Add(new EnableCrossOriginResourceSharingBehavior());
            _serviceHost.Open();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Program.MainFormHwnd = new MainForm();
            Application.Run(Program.MainFormHwnd);


            _serviceHost.Close();
        }
Esempio n. 25
0
    // mono server.exe               ==> localhost:9090
    // mono server.exe HOSTNAME      ==> HOSTNAME:9090
    // mono server.exe HOSTNAME PORT ==> HOSTNAME:PORT

    public static void Main(string[] args)
    {
        Console.Write("Starting server... ");
        string hostname = "localhost";
        string port     = "9090";
        string url      = "http://localhost:9090";
        string url2     = "http://localhost:9091";

        WebHttpBinding binding = new WebHttpBinding();
        WebServiceHost host    = new WebServiceHost(typeof(PaymentService), new Uri(url));
        WebServiceHost host2   = new WebServiceHost(typeof(NotifyService), new Uri(url2));

        host.AddServiceEndpoint(typeof(IPaymentService), binding, "");
        host2.AddServiceEndpoint(typeof(INotify), binding, "");
        host.Open();
        host2.Open();
        Console.WriteLine("Server ready\n");
        Console.WriteLine("  Listening to " + url + "\n\n");
        Console.WriteLine("  Listening to " + url2 + "\n\n");
        Console.ReadLine();
        host2.Close();
        host.Close();
        Console.WriteLine("Server shutdown complete!");
    }
        public static ServiceHost StartRestHost <T>(string url, T component)
        {
            var restHost = new WebServiceHost(component, new Uri(url));
            var sep      = restHost.AddServiceEndpoint(typeof(T), new WebHttpBinding(), "");
            var whb      = sep.Behaviors.Find <WebHttpBehavior>();

            if (whb == null)
            {
                whb = new WebHttpBehavior();
                sep.Behaviors.Add(whb);
            }

            whb.AutomaticFormatSelectionEnabled = true;
            whb.DefaultOutgoingRequestFormat    = WebMessageFormat.Json;
            whb.DefaultOutgoingResponseFormat   = WebMessageFormat.Json;
            var serviceBehaviour = restHost.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            if (serviceBehaviour != null)
            {
                serviceBehaviour.InstanceContextMode = InstanceContextMode.Single;
            }
            restHost.Open();
            return(restHost);
        }
Esempio n. 27
0
    // mono server.exe               ==> localhost:9090
    // mono server.exe HOSTNAME      ==> HOSTNAME:9090
    // mono server.exe HOSTNAME PORT ==> HOSTNAME:PORT

    public static void Main(string[] args)
    {
        Console.Write("Starting a WCF self-hosted .Net server... ");
        string hostname = "localhost";
        string port     = "9090";

        if (args.Length >= 1)
        {
            hostname = args[0];
        }
        if (args.Length == 2)
        {
            port = args[1];
        }
        // Decalring an HTTP Binding and instantiating an host
        string url = "http://" + hostname + ":" + port;

        WebHttpBinding b    = new WebHttpBinding();
        var            host = new WebServiceHost(typeof(PaymentService), new Uri(url));

        // Adding the service to the host
        host.AddServiceEndpoint(typeof(IPaymentService), b, "");

        // Staring the Host server
        host.Open();
        Console.WriteLine("done!\n");
        Console.WriteLine("  Listening to " + hostname + ":" + port + "\n\n");

        //~ Lignes supprimées pour docker-compose : le serveur .Net s'arretait automatiquement lorsque "docker-composé"
        //~ Console.WriteLine("Hit Return to shutdown the server.");
        //~ Console.ReadLine();
//~
        //~ // Cleaning up and ending the hosting
        //~ host.Close ();
        //~ Console.WriteLine("Server shutdown complete!");
    }
Esempio n. 28
0
        public static void Snippet4()
        {
            // <Snippet4>
            Uri            baseAddress = new Uri("http://localhost:8000");
            WebServiceHost host        = new WebServiceHost(typeof(Service), baseAddress);

            try
            {
                host.Open();

                WebChannelFactory <IService> cf = new WebChannelFactory <IService>(new Uri("http://localhost:8000"));
                IService channel = cf.CreateChannel();
                string   s;

                Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);
            }
            catch (CommunicationException ex)
            {
                Console.WriteLine("An exception occurred: " + ex.Message);
            }
            // </Snippet4>
        }
Esempio n. 29
0
 static void Main(string[] args)
 {
     using (WebServiceHost host = new WebServiceHost(typeof(DataReaderService)))
     {
         try
         {
             host.Open();
             Console.WriteLine("服务已经启动,输入exit退出...");
             while (true)
             {
                 string temp = Console.ReadLine();
                 if (temp.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
                 {
                     break;
                 }
             }
             host.Close();
         }
         catch (Exception ex)
         {
             Console.WriteLine("服务启动异常{0},输入exit退出...", ex.Message);
         }
     }
 }
Esempio n. 30
0
 private void startService()
 {
     try
     {
         Uri   u             = new Uri("http://localhost:" + SerialPortConfig.ServicePort + "/led");
         Uri[] baseAddresses = { new Uri("http://localhost:" + SerialPortConfig.ServicePort + "/led") };
         if (host == null)
         {
             host = new WebServiceHost(typeof(LedService), baseAddresses);
         }
         host.Open();
         LogUtil.Logger.Info("LED服务启动");
     }
     catch (AddressAlreadyInUseException e)
     {
         LogUtil.Logger.Error(e.Message);
         MessageBox.Show("端口" + SerialPortConfig.ServicePort + "被占用,请重新配置后重启本程序", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         LogUtil.Logger.Error(e.Message);
     }
 }
Esempio n. 31
0
        public void CreateTodo()
        {
            using (var server = new WebServiceHost(new TodoService(), new Uri(_hostAddress)))
                using (var client = new WebChannelFactory <ITodoApi>(new WebHttpBinding(), new Uri(_hostAddress)))
                {
                    server.Open();
                    client.Open();
                    var channel = client.CreateChannel();

                    var todo = new TodoType {
                        id = 6, idSpecified = true, IsDone = false, Name = "New Item", Description = "This items should be fixed!", ExpirationDate = DateTime.Now.AddDays(2)
                    };

                    using (new OperationContextScope((IContextChannel)channel))
                    {
                        try
                        {
                            var newId = channel.CreateTodo(todo);
                        }
                        catch (CommunicationException ex)
                        {
                            ValidateHttpStatusResponse(ex, HttpStatusCode.BadRequest);
                        }
                    }

                    todo.idSpecified = false;

                    using (new OperationContextScope((IContextChannel)channel))
                    {
                        var newId = channel.CreateTodo(todo);
                        ValidateHttpStatusResponse(HttpStatusCode.OK);

                        Assert.AreEqual(4, newId);
                    }
                }
        }
Esempio n. 32
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            WebServiceHost host = new WebServiceHost(typeof(Service1),
                                                     new Uri("http://localhost:8099/"));
            ServiceEndpoint ep = host.AddServiceEndpoint(typeof(Service1),
                                                         new WebHttpBinding(), "");

            try
            {
                host.Open();
                Console.WriteLine("Service is running:");
                Console.WriteLine("Press enter to quit...");
                Console.ReadLine();
                host.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine("An exception occured: {0}", e.Message);
                host.Abort();
            }
        }
Esempio n. 33
0
        public int StartProcess()
        {
            int result = 1;
              #region Pobranie i walidacja konfiguracji procesu

              ITNWebServiceCfgNode config = ITNWebServiceCfgHelper.GetITNWebServiceCfg(core.ProcessConfigurationXml);

              if (String.IsNullOrEmpty(config.endpointAddress.Trim()))
            throw new Exception("Processing canceled - endpoint address empty.");

              #endregion Pobranie i walidacja konfiguracji procesu
              SqlDatabase dbPTRConfig = null;
              TaskInserter.core = core;
              TaskInserter.dbPTRConfig = ConverterUtils.GetDBConfig(core);
              TaskInserter.taskId = config.graphBeginNodeId;
              TaskInserter.runningTaskId = TaskInserter.lastRunningTaskId = ConverterUtils.GetRunningTaskId(core);
              TaskInserter.connectionString = ConverterUtils.GetDBConvertersConnectionString(core);
              if(config.longTimer<= config.shortTimer)
              {
            throw new Exception("Processing canceled - maximum delay is shorter than task delay.");
              }
              else if(config.shortTimer == 0)
              {
            throw new Exception("Processing canceled - delay cannot be zero.");
              }
              else if (config.longTimer == 0)
              {
            throw new Exception("Processing canceled - maximum delay cannot be zero.");
              }
              TaskInserter.shortTimer = new PtrTimer(TaskInserter.ShortTimerHandler, config.shortTimer * 1000);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Task delay {0} seconds.", config.shortTimer);
              TaskInserter.longTimer = new PtrTimer(TaskInserter.LongTimerHandler, config.longTimer * 1000);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Maximum delay {0} seconds.", config.longTimer);

              try
              {
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Start processing");

            PTR3Core.DB_POOL.InitMSSqlPool(core, "database-converters");

            String endpointAddress = config.endpointAddress;
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Endpoint address is {0}", config.endpointAddress);
            //endpointAddress = "http://localhost/ITNWebService"; //odkomentować przy testowaniu na lokalnym hoście
            string singleWsdl = ConfigXmlReader.XmlGetConfigParam(core, "single-wsdl");
            if (String.IsNullOrEmpty(singleWsdl))
              singleWsdl = ConfigXmlReader.XmlGetConfigParam(core.OptionalConfigurationXml, "single-wsdl");

            string locationWsdl = ConfigXmlReader.XmlGetConfigParam(core, "location-wsdl");
            if (String.IsNullOrEmpty(locationWsdl))
              locationWsdl = ConfigXmlReader.XmlGetConfigParam(core.OptionalConfigurationXml, "location-wsdl");

            Uri uri = new Uri(endpointAddress);

            if (uri.Scheme != "http")
            {
              throw new Exception("Endpoint address has wrong schema: " + uri.Scheme);
            }

            int start = Environment.TickCount;
            int i = 0;
            bool bWorking = true;

            WebServiceHost<ITNWebServiceContract> host = new WebServiceHost<ITNWebServiceContract>(endpointAddress);
            host.EnableMetadataExchange(true);
            ServiceEndpoint endpoint = host.AddServiceHttpEndpoint((Type)typeof(IITNWebServiceContract), "");
            if (singleWsdl == "1" || !String.IsNullOrEmpty(locationWsdl))
              endpoint.Behaviors.Add(new WCFExtras.Wsdl.WsdlExtensions(null
            , String.IsNullOrEmpty(locationWsdl) ? null : new Uri(locationWsdl)
            , singleWsdl == "1"));
            ServiceDebugBehavior behavior =
              host.Description.Behaviors.Find<ServiceDebugBehavior>();

            if(behavior != null)
            {
              behavior.IncludeExceptionDetailInFaults = true;
            }
            else
            {
              host.Description.Behaviors.Add(
              new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
            }
            host.Open();
            Thread.Sleep(500);
            if (dbPTRConfig == null)
              dbPTRConfig = ConverterUtils.GetDBConfig(core);
            while (PTR3Wrapper.ShouldClose() == 0 && PTR3Wrapper.ShouldSuspend() == 0 && host.State == CommunicationState.Opened && bWorking)
            {
              if ((i++ % 50) == 0)
              {
            //PTR3Core.LOG.Log(MsgStatusEnum.MS_Deb3, "Online wait processing...");

            bWorking = host.HeartBeat();
              }
              Thread.Sleep(100);
            }
            host.Close();
            Thread.Sleep(500);
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Finish processing");
              }
              catch (Exception ex)
              {
            result = 0;
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Error, ex, "");
              }

              return result;
        }