public void StartService() { StopService(); Trace.WriteLine("create ServiceHost(typeof(Service1))"); if (!__configureService) _serviceHost = new ServiceHost(typeof(Service1)); else { _serviceHost = new ServiceHost(typeof(Service1), new Uri("http://localhost:8701/Test_wcf_service/")); WebHttpBinding webHttpBinding = new WebHttpBinding(); webHttpBinding.CrossDomainScriptAccessEnabled = true; ServiceEndpoint serviceEndpoint = _serviceHost.AddServiceEndpoint(typeof(Service1), webHttpBinding, "service1"); serviceEndpoint.Behaviors.Add(new WebHttpBehavior()); //serviceEndpoint.Behaviors.Add(new CorsEnablingBehavior()); ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior(); serviceMetadataBehavior.HttpGetEnabled = true; serviceMetadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; _serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); } if (__trace) TraceServiceDescription(_serviceHost.Description); Trace.WriteLine("open ServiceHost"); _serviceHost.Open(); Trace.WriteLine("service is started"); Trace.WriteLine(); }
static void StartServer() { string serviceUrl = "http://127.0.0.1:23232/myservices/calculatorservice"; using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))) { serviceHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://127.0.0.1:23232/myservices/calculatorservice"); if (serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri(string.Format("{0}/{1}", serviceUrl, "metadata")); serviceHost.Description.Behaviors.Add(behavior); } serviceHost.Opened += delegate { Console.WriteLine("CalculatorService is opened."); StartClient(); }; serviceHost.Open(); while (true) { Thread.Sleep(1000000); } } }
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(); } }
static void Main(string[] args) { string httpAddr = "http://127.0.0.1:6001/AddStuff"; string netAddr = "net.tcp://127.0.0.1:5001/AddStuff"; System.ServiceModel.ServiceHost SH = new ServiceHost(typeof(opAddStuff), new Uri(httpAddr)); BasicHttpBinding B = new BasicHttpBinding(); NetTcpBinding NB = new NetTcpBinding(); SH.AddServiceEndpoint(typeof(AddStuff), B, httpAddr); SH.AddServiceEndpoint(typeof(AddStuff), NB, netAddr); System.ServiceModel.Description.ServiceMetadataBehavior smb = SH.Description.Behaviors.Find <ServiceMetadataBehavior>(); // If not, add one if (smb == null) { smb = new ServiceMetadataBehavior(); } smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; SH.Description.Behaviors.Add(smb); SH.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); SH.Open(); Console.WriteLine("Service at your service"); string crap = Console.ReadLine(); }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8773/BasicService"); BasicHttpBinding binding = new BasicHttpBinding(); binding.Name = "Basic_Binding"; binding.HostNameComparisonMode = HostNameComparisonMode.WeakWildcard; binding.Security.Mode = BasicHttpSecurityMode.None; using (ServiceHost host = new ServiceHost(typeof(BasicService), baseAddress)) { host.AddServiceEndpoint(typeof(IBasicService), binding, "http://localhost:8773/BasicService/mex"); // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(smb); host.Open(); Console.WriteLine("The service is ready at {0}", baseAddress); Console.WriteLine("Press <Enter> to stop the service."); Console.ReadLine(); // Close the ServiceHost. host.Close(); } }
private static void Main() { var serviceAddress = new Uri("http://localhost:8881/strings"); ServiceHost selfHost = new ServiceHost( typeof(StringsService), serviceAddress); var smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); selfHost.Open(); Console.WriteLine("Running at " + serviceAddress); StringsServiceClient client = new StringsServiceClient(); using (client) { var result = client.StringContainsOtherString("as", "asblablass"); // returns 2 Console.WriteLine("Using the service: \"as\" is contained in \"asblablass\" {0} times\n", result); } Console.WriteLine("Press enter to exit"); Console.ReadLine(); }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8290/MyAgeService"); using (var selfServiceHost = new ServiceHost(typeof(MyAgeService), baseAddress)) { try { selfServiceHost.AddServiceEndpoint(typeof(IMyAgeService), new WSHttpBinding(), "MyAgeService"); ServiceMetadataBehavior smBehavior = new ServiceMetadataBehavior(); smBehavior.HttpGetEnabled = true; selfServiceHost.Description.Behaviors.Add(smBehavior); selfServiceHost.Open(); Console.WriteLine("Tjänsten är ööppppeennnnn!"); Console.WriteLine("Tryck ENTER för att avsluta selfservice"); Console.ReadLine(); } catch (CommunicationException ex) { Console.WriteLine($"Ett kommunikationsfel har inträffat! {ex.Message}"); selfServiceHost.Abort(); Console.ReadLine(); throw; } } }
static void Main() { //run the program and visit this URI to confirm the service is working Uri baseAddress = new Uri("http://localhost:8000/GPSSim"); ServiceHost host = new ServiceHost(typeof(GPSSim), baseAddress); //basicHttpBinding is used because WS binding is currently unsupported host.AddServiceEndpoint(typeof(IGPSSim), new BasicHttpBinding(), "GPS Sim Service"); try { ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); } catch (CommunicationException e) { Console.WriteLine("An exception occurred: {0}", e.Message); host.Abort(); } host.Open(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
private void BtStartServiceClick(object sender, EventArgs e) { if (ServiceStarted) { host.Close(); ServiceStarted = false; } else { baseAddress = new Uri(txbaseaddress.Text); host = new ServiceHost(instanceType, baseAddress); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; host.Description.Behaviors.Add(behavior); host.AddServiceEndpoint(contractType, new WSDualHttpBinding(), ""); if (cbMex.Checked) { host.AddServiceEndpoint(typeof(IMetadataExchange), new WSDualHttpBinding(), "MEX"); } host.Open(); lbmessage.Visible = true; lbmessage.Text = "Host Option is running..."; //MessageBox.Show(" " + svcEndpoint.Address); ServiceStarted = true; } }
static void Main(string[] args) { //BaseAddress Uri baseAddress = new Uri("http://localhost:8080/SelfService.HarryPotter"); //ServiceHost ServiceHost selfServiceHost = new ServiceHost(typeof(HarryPotterBooksCheckerService), baseAddress); try { //ABC-Endpoint selfServiceHost.AddServiceEndpoint(typeof(IHarryPotterBooks), new WSHttpBinding(), "HarryPotterCheckerService"); ServiceMetadataBehavior smBehavior = new ServiceMetadataBehavior {HttpGetEnabled = true}; selfServiceHost.Description.Behaviors.Add(smBehavior); selfServiceHost.Open(); Console.WriteLine("Tjänsten är öppen"); Console.ReadKey(); } catch (CommunicationException ex) { selfServiceHost.Close(); Console.WriteLine($"Ett kommunikationsfel har uppstått.: {ex.Message}"); Console.ReadKey(); throw; } }
public void InitializeService() { BasicHttpBinding libraryBinding = new BasicHttpBinding(BasicHttpSecurityMode.None); libraryBinding.MaxReceivedMessageSize = 67108864; libraryServiceHost.AddServiceEndpoint(typeof(IMediaLibraryService), libraryBinding, string.Empty); BasicHttpBinding playbackBinding = new BasicHttpBinding(BasicHttpSecurityMode.None); playbackBinding.MaxReceivedMessageSize = 67108864; playbackServiceHost.AddServiceEndpoint(typeof(IMediaPlaybackService), playbackBinding, string.Empty); ServiceMetadataBehavior libraryBehavior = new ServiceMetadataBehavior(); libraryBehavior.HttpGetEnabled = true; libraryServiceHost.Description.Behaviors.Add(libraryBehavior); libraryServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), @"mex"); ServiceMetadataBehavior playbackBehavior = new ServiceMetadataBehavior(); playbackBehavior.HttpGetEnabled = true; playbackServiceHost.Description.Behaviors.Add(playbackBehavior); playbackServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), @"mex"); libraryServiceHost.Open(); playbackServiceHost.Open(); }
private void btnStartStop_Click(object sender, EventArgs e) { if (ServiceStarted) { host.Close(); ServiceStarted = false; lblMessage.Text = "Service is not running!"; btnStartStop.Text = "Start service"; } else { using (host) { Uri baseAddress = new Uri(txtBaseLocation.Text); host = new ServiceHost(typeof(Service), baseAddress); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; host.Description.Behaviors.Add(behavior); host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Service"); if (chkShowMess.Checked) { host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "MEX"); } host.Open(); lblMessage.Visible = true; lblMessage.Text = "Service is running!"; ServiceStarted = true; btnStartStop.Text = "Stop service"; } } }
static void Main(string[] args) { var baseAddress = new Uri("https://localhost:44355"); using (var host = new ServiceHost(typeof(HelloWorldService), baseAddress)) { var binding = new WSHttpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "localhost"); host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; host.Credentials.ClientCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine; host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.ChainTrust; var endpoint = typeof(IHelloWorldService); host.AddServiceEndpoint(endpoint, binding, baseAddress); var metaBehavior = new ServiceMetadataBehavior(); metaBehavior.HttpGetEnabled = true; metaBehavior.HttpGetUrl = new Uri("http://localhost:9000/mex"); metaBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(metaBehavior); host.Open(); Console.WriteLine("Service is ready. Hit enter to stop service."); Console.ReadLine(); host.Close(); } }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8080/hello"); // Create the ServiceHost. using (ServiceHost host = new ServiceHost(typeof(Service1))) { // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; //host.Description.Behaviors.Add(smb); // Open the ServiceHost to start listening for messages. Since // no endpoints are explicitly configured, the runtime will create // one endpoint per base address for each service contract implemented // by the service. host.Open(); host.Faulted += Host_Faulted; Console.WriteLine("The service is ready at {0}", baseAddress); Console.WriteLine("Press <Enter> to stop the service."); Console.ReadLine(); // Close the ServiceHost. host.Close(); } }
static void Main(string[] args) { //BaseAddress var baseAddress = new Uri("http://localhost:8080/SelfService.NextThousand"); //ServiceHost ServiceHost selfServiceHost = new ServiceHost(typeof(NextThousandCheckerService),baseAddress); try { //Abc - endpoint selfServiceHost.AddServiceEndpoint(typeof(INextThousand), new WSHttpBinding(), "NextThousandCheckerService"); //Metadata ServiceMetadataBehavior smBehavior = new ServiceMetadataBehavior { HttpGetEnabled = true }; selfServiceHost.Description.Behaviors.Add(smBehavior); //startar tjänsten selfServiceHost.Open(); Console.WriteLine("Tjänsten är öppen!"); Console.ReadKey(); } catch (CommunicationException ex) { Console.WriteLine($"Kommunikations fel{ex.Message}"); selfServiceHost.Abort(); Console.ReadKey(); throw; } }
public void Open() { urlservice = string.Format("http://{0}:{1}/{2}", channel.listener_host, channel.service_port - 1, channel._id); urlmeta = string.Format("http://{0}:{1}/{2}", channel.listener_host, channel.service_port, channel._id); host = new ServiceHost(new ChannelAPI(channel)); host.Opening += new EventHandler(host_Opening); host.Opened += new EventHandler(host_Opened); host.Closing += new EventHandler(host_Closing); host.Closed += new EventHandler(host_Closed); BasicHttpBinding httpbinding = new BasicHttpBinding(); httpbinding.Security.Mode = BasicHttpSecurityMode.None; host.AddServiceEndpoint(typeof(IChannelAPI), httpbinding, urlservice); //host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); ServiceMetadataBehavior metaBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (metaBehavior == null) { metaBehavior = new ServiceMetadataBehavior(); metaBehavior.HttpGetUrl = new Uri(urlmeta); metaBehavior.HttpGetEnabled = true; host.Description.Behaviors.Add(metaBehavior); } Append(string.Format("{0} channel starting .....", channel._id)); host.Open(); }
static void StartService() { var localV4Address = GetLocalV4Address(); var localAddress = "http://" + localV4Address + ":8000/zpd"; var baseAddress = new Uri(localAddress); var host = new ServiceHost(typeof(ZPDService), baseAddress); try { //host.AddServiceEndpoint(typeof(IZPDService), new WSHttpBinding(), "Service"); var smb = new ServiceMetadataBehavior {HttpGetEnabled = true, MetadataExporter = {PolicyVersion = PolicyVersion.Policy15}}; host.Description.Behaviors.Add(smb); host.Open(); Console.WriteLine("Service is ready at {0}. Press <ENTER> to terminate", localAddress); Console.ReadLine(); host.Close(); ZuneMediaPlayerManager.ClosePlayer(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); host.Abort(); } Console.WriteLine("Press <ENTER> to close"); Console.ReadLine(); }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service"); 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.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(); } }
Uri baseAddress { get; set; } = new Uri("http://localhost:8000/hello");//Uri("http://192.168.14.86:8000/hello"); private void button1_Click(object sender, EventArgs e) { var baseAddress = new Uri("http://" + localHostIps.Text);// + ":/hello"); host = new ServiceHost(typeof(VentsService), baseAddress); var smb = new ServiceMetadataBehavior { HttpGetEnabled = true, MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 } }; host.Description.Behaviors.Add(smb); try { host.Open(); Status.Text = $"The service is ready at {baseAddress}"; button1.Enabled = false; button2.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
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(); }
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(); } }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8000/GlydeServiceModelExamples/Service"); ServiceHost selfHost = new ServiceHost(typeof(StringManipulatorService), baseAddress); try { selfHost.AddServiceEndpoint( typeof(IStringManipulator), new WSHttpBinding(), "StringManipulatorService"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); // Step 5 of the hosting procedure: Start (and then stop) the service. selfHost.Open(); Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); selfHost.Abort(); } }
static void Main(string[] args) { ServiceHost MathServiceHost = null; try { //Base Address for MathService Uri httpBaseAddress = new Uri("http://localhost:8090/MathService/Calculator"); Uri tcpBaseAddress = new Uri("net.tcp://localhost:8081/MathService/Calculator"); //Instantiate ServiceHost MathServiceHost = new ServiceHost(typeof(MathService.Calculator), httpBaseAddress); //Add Endpoint to Host MathServiceHost.AddServiceEndpoint(typeof(MathService.ICalculator), new WSHttpBinding(), ""); //Metadata Exchange ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior(); serviceBehavior.HttpGetEnabled = true; MathServiceHost.Description.Behaviors.Add(serviceBehavior); //Open MathServiceHost.Open(); Console.WriteLine("Service is live now at : {0}", httpBaseAddress); Console.ReadKey(); } catch (Exception ex) { MathServiceHost = null; Console.WriteLine("There is an issue with MathService" + ex.Message); } }
static void Main(string[] args) { var baseAddress = new Uri("http://localhost:8080/Calculator"); using (var host = new ServiceHost(typeof(Calculator), baseAddress)) { host.AddServiceEndpoint(typeof(ICalculator), new BasicHttpBinding(), "Calculator"); var serviceMetadataBehavior = new ServiceMetadataBehavior { HttpGetEnabled = true, MetadataExporter = { PolicyVersion = PolicyVersion .Policy15 } }; host.Description.Behaviors.Add(serviceMetadataBehavior); host.Open(); Console.WriteLine("The host is ready at: {0}", baseAddress); Console.WriteLine("Press <Enter> to stop the host"); Console.ReadKey(); host.Close(); } }
public static void Main () { SymmetricSecurityBindingElement sbe = new SymmetricSecurityBindingElement (); sbe.ProtectionTokenParameters = new SslSecurityTokenParameters (); ServiceHost host = new ServiceHost (typeof (Foo)); HttpTransportBindingElement hbe = new HttpTransportBindingElement (); CustomBinding binding = new CustomBinding (sbe, hbe); binding.ReceiveTimeout = TimeSpan.FromSeconds (5); host.AddServiceEndpoint ("IFoo", binding, new Uri ("http://localhost:8080")); ServiceCredentials cred = new ServiceCredentials (); cred.SecureConversationAuthentication.SecurityStateEncoder = new MyEncoder (); cred.ServiceCertificate.Certificate = new X509Certificate2 ("test.pfx", "mono"); cred.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; host.Description.Behaviors.Add (cred); host.Description.Behaviors.Find<ServiceDebugBehavior> () .IncludeExceptionDetailInFaults = true; // foreach (ServiceEndpoint se in host.Description.Endpoints) // se.Behaviors.Add (new StdErrInspectionBehavior ()); ServiceMetadataBehavior smb = new ServiceMetadataBehavior (); smb.HttpGetEnabled = true; smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl"); host.Description.Behaviors.Add (smb); host.Open (); Console.WriteLine ("Hit [CR] key to close ..."); Console.ReadLine (); host.Close (); }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8733/Design_Time_Addresses/GetDate/"); ServiceHost selfHost = new ServiceHost(typeof(DateService), baseAddress); try { selfHost.AddServiceEndpoint(typeof(IDateService), new WSHttpBinding(), "Date Service"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); using (selfHost) { selfHost.Open(); Console.WriteLine("Service is ready\nPress any key to exit"); Console.WriteLine(); Console.ReadKey(); } } catch (CommunicationException ex) { Console.WriteLine("An exception occured: {0}", ex.Message); selfHost.Abort(); } }
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(); } }
static void Main(string[] args) { string command; Uri baseAddress = new Uri("http://localhost:8000/wob/Login"); ServiceHost selfHost = null; try { selfHost = new ServiceHost(typeof(LoginService), baseAddress); selfHost.AddServiceEndpoint(typeof(ILogin), new WSDualHttpBinding(), "LoginService"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); selfHost.Open(); Console.WriteLine("Open"); while (true) { command = Console.ReadLine(); if (command == "e") break; } } catch (CommunicationException ce) { Console.WriteLine("Failure!"); Console.WriteLine(ce); Console.ReadLine(); selfHost.Abort(); } }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8080/WCF_Service_1000"); using (ServiceHost selfServiceHost = new ServiceHost(typeof(Birthday1000Service), baseAddress)) { try { selfServiceHost.AddServiceEndpoint( typeof(IBirthday), new WSHttpBinding(), "Birthday1000Service"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfServiceHost.Description.Behaviors.Add(smb); selfServiceHost.Open(); Console.WriteLine("Nu är tjänsten öppen"); Console.WriteLine("Tryck på ENTER för att stänga tjänsten"); Console.ReadLine(); } catch (CommunicationException exception) { Console.WriteLine($"Ett fel inträffade {exception.Message}"); selfServiceHost.Abort(); Console.ReadLine(); } } }
static void Main(string[] args) { Uri address = new Uri("http://localhost:8080/Lab2.Service.Age"); ServiceHost serviceHost = new ServiceHost(typeof(Days), address); try { serviceHost.AddServiceEndpoint(typeof(IDays), new WSHttpBinding(), "Days"); ServiceMetadataBehavior smBehavior = new ServiceMetadataBehavior(); smBehavior.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(smBehavior); serviceHost.Open(); Console.WriteLine("Tjänsten är öppen!"); Console.WriteLine("Tryck enter för att avsluta"); Console.ReadLine(); } catch (CommunicationException ex) { Console.WriteLine(ex.Message); Console.ReadLine(); throw; } finally { serviceHost.Close(); } }
protected override void OnStart(string[] args) { eventLog1.WriteEntry("Service Starting"); // perform rename worker starting functions eventLog1.WriteEntry("Entering the startup routine"); _RenameWorker.Startup(); eventLog1.WriteEntry("Finished startup routine"); // Create the Uri to be accessed Uri baseAddress = new Uri("http://" + NetOps.GetLocalIP() + ":8080/SystemRenameService"); // Create Binding to be used by the service WSHttpBinding binding = new WSHttpBinding(); // begin the self-hosting of the service // Create a ServiceHost for the SystemRenameService type. serviceHost = new ServiceHost(myService, baseAddress); { serviceHost.AddServiceEndpoint(typeof(ISystemRenameService), binding, baseAddress); // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.HttpGetUrl = baseAddress; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; serviceHost.Description.Behaviors.Add(smb); // Open the ServiceHost to create listeners // and start listening for messages. eventLog1.WriteEntry("Opening listening port"); serviceHost.Open(); } }
static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8000/Service"); ServiceHost selfHost = new ServiceHost(typeof(myService), baseAddress); try { selfHost.AddServiceEndpoint(typeof(myInterface), new WSHttpBinding(), "myService"); System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); selfHost.Open(); Console.WriteLine("Service ready to take requests"); Console.ReadLine(); selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An Exception occured: {0}", ce.Message); selfHost.Abort(); } }
/// <summary> 用代码注册(完全脱离配置文件) </summary> public void RegisterWithCode <T>() { try { Uri uri = new Uri("http://LocalHost:22999/"); ServiceHost host = new ServiceHost(typeof(Service1), uri); // 要点一:定义元数据发布方式,此处 通过在服务所在的URL后加“?wsdl”的方式公布WSDL,可直接通过HTTP访问得到。 System.ServiceModel.Description.ServiceMetadataBehavior behavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); //此处没有定义mex终结点,必须设置HttpGetEnabled为true,否则客户端无法访问服务 behavior.HttpGetEnabled = true; host.Description.Behaviors.Add(behavior); // 要点二:WebHttpBinding ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1), new WebHttpBinding(), string.Empty); // 要点三: endpoint.EndpointBehaviors.Add(new WebHttpBehavior()); //设置wcf支持ajax调用,仅适用于WebHttpBinding //System.ServiceModel.Description.WebScriptEnablingBehavior' is only intended for use with WebHttpBinding or similar bindings. //endpoint.Behaviors.Add(new WebScriptEnablingBehavior()); host.Opened += (s, e) => { Log4Servcie.Instance.Info("WCF服务启动成功"); }; host.Open(); } catch (Exception ex) { Log4Servcie.Instance.Info("WCF服务启动失败"); Log4Servcie.Instance.Error(ex); } }
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"); }
static void Main(string[] args) { //Create a URI instance to guessService as the base address Uri baseAddress = new Uri("http://localhost:8000/Service"); //create a new ServiceHost instance to host the service ServiceHost selfHost = new ServiceHost(typeof(guessService), baseAddress); try { //add a service endpoint with contract and binding selfHost.AddServiceEndpoint(typeof(myInterface), new WSHttpBinding(), "guessService"); //add metadata for platform-independent access System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); //enable the metadata smb.HttpGetEnabled = true; //add here selfHost.Description.Behaviors.Add(smb); //start the service and waiting for request selfHost.Open(); Console.WriteLine("Running on port 8000, ready to take requests"); Console.WriteLine("Call SecretNumber(int lower, int upper) to generate a Secret Number"); Console.WriteLine("Call CheckNumber(int userNum, int SecretNum) to guess the secret number"); Console.WriteLine("Press <Enter>.\n to quit"); Console.ReadLine(); //close the ServiceHostBase to shutdown service selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An Exception occured: {0}", ce.Message); selfHost.Abort(); } }
public void LoopPrincipal() { try { // Inicia Filas de comunicação entre as threads cqMsgRecebidas = new System.Collections.Concurrent.ConcurrentQueue <MensagemDispositivo>(); cqMsgEnvio = new System.Collections.Concurrent.ConcurrentQueue <MensagemDispositivo>(); // Guarda status atual dos dispositivos conectados cdStatusDispositivos = new System.Collections.Concurrent.ConcurrentDictionary <string, string>(); // Ativa thread a parte para processar as requisições recebidas threadRecebimento = new Thread(LoopProcessamentoRequisicoesRecebidas); threadRecebimento.Start(); #region Porta Serial - Comunicação com a rede de sensores // Xbee conectado ao servidor portaXbeeServidor = new SerialPort(); ConfiguraPortaSerial(portaXbeeServidor); // Ativa porta portaXbeeServidor.Open(); #endregion // Inicia WebService // Recebe as requisições do gerenciador para envio aos dispositivos Uri objUri = new Uri(_UriServidor); using (ServiceHost Host = new ServiceHost(this.GetType(), objUri)) { #region configura o WebService // Habilita HTTP BasicHttpBinding bndng = new BasicHttpBinding(); bndng.MaxReceivedMessageSize = 10485760; bndng.ReceiveTimeout = new TimeSpan(0, 0, 10, 0, 0); System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.HttpGetUrl = objUri; Host.Description.Behaviors.Find <System.ServiceModel.Description.ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; Host.AddServiceEndpoint(typeof(IwsrvHomeOn), bndng, _UriServidor); Host.Description.Behaviors.Add(smb); // Ativa Service Host (Servidor WebService) Host.Open(); #endregion // Faz solicitação do status de todos os dispositivos conectados portaXbeeServidor.Write(MensagemDispositivo.StatusTodosDipositivos(Service._configuradorGeral.IdServidor)); portaXbeeServidor.BaseStream.Flush(); System.Threading.Thread.Sleep(3000); try { #region LOOP da Thread Principal while (Service._bAtivo) { try { int iSleep = 200; MensagemDispositivo objMsg; // Processa mensagem de envio if (cqMsgEnvio.TryDequeue(out objMsg)) { try { string sTextoEnvio = objMsg.TextoEnvio(); portaXbeeServidor.Write(sTextoEnvio); portaXbeeServidor.BaseStream.Flush(); iSleep = 1000; // Grava trace controlTrace.Insere(Biblioteca.Modelo.TraceComunicacao.ProcedenciaTrace.HomeOn, objMsg._Header.ID_Receiver, objMsg._Command.ID_Dispositivo, sTextoEnvio); } catch (Exception exc) { controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro ao escrever mensagem na porta serial.", exc); } } System.Threading.Thread.Sleep(iSleep); } catch (Exception exc) { controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro no Loop Principal do Serviço.", exc); System.Threading.Thread.Sleep(1000 * 30); } } #endregion } finally { // Fecha Webservice if (Host != null && Host.State != CommunicationState.Closed && Host.State != CommunicationState.Closing) { Host.Close(); } } } } catch (Exception exc) { controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, string.Format("Erro ao inicializar o serviço (LoopPrincipal). Detalhes:\r\n{0}", exc.Message), exc); return; } finally { // Fecha conexão serial if (portaXbeeServidor != null) { if (portaXbeeServidor.IsOpen) { portaXbeeServidor.Close(); } portaXbeeServidor.Dispose(); } portaXbeeServidor = null; // Espera thread de Recebimento terminar Service._bAtivo = false; while (threadRecebimento.IsAlive) { System.Threading.Thread.Sleep(500); } } }
static void Main(string[] args) { setupLoggers(); Log cOut = Logger.Instance.getLog(LoggerDefine.OUT_CONSOLE); // Create a WSHttpBinding instance WSHttpBinding binding = new WSHttpBinding(); binding.Security.Mode = SecurityMode.None; binding.Namespace = "http://abc4trust-uprove/Service1"; string baseAddress = "http://127.0.0.1:8080/abc4trust-webservice/"; if (args.Length > 0) { try { int port = int.Parse(args[0]); cOut.write("Starting UProve WebService on port: " + port); } catch (Exception ex) { cOut.write("Exception while parsing port number from args: " + ex.Message); DebugUtils.DebugPrint(ex.StackTrace.ToString()); } baseAddress = "http://127.0.0.1:" + args[0] + "/abc4trust-webservice/"; } try { FlatWsdlServiceHost host = new FlatWsdlServiceHost(typeof(Service1)); // Check to see if the service host already has a ServiceMetadataBehavior System.ServiceModel.Description.ServiceMetadataBehavior smb = host.Description.Behaviors.Find <ServiceMetadataBehavior>(); System.ServiceModel.Description.ServiceDebugBehavior sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>(); // If not, add one if (smb == null) { smb = new ServiceMetadataBehavior(); } if (sdb == null) { sdb = new ServiceDebugBehavior(); } sdb.IncludeExceptionDetailInFaults = true; smb.HttpGetEnabled = true; smb.HttpGetUrl = new Uri(baseAddress + "wsdl"); cOut.write("Fetch WSDL using .NET on Windows at: " + smb.HttpGetUrl.ToString()); host.Description.Behaviors.Add(smb); // add time profile logger if needed. if (ParseConfigManager.SetupTimeProfiles()) { WcfProfileLogger pExt = new WcfProfileLogger(); host.Description.Behaviors.Add(pExt); } // Add a service endpoint using the created binding ServiceEndpoint endp = host.AddServiceEndpoint(typeof(IService1), binding, baseAddress); endp.Behaviors.Add(new FlatWsdl()); host.Open(); cOut.write("UProve WebService listening on {0} . . .", baseAddress); cOut.write("Press Enter to exit"); Console.ReadLine(); host.Close(); } catch (Exception ex) { cOut.write("Exception while running UProve WebService: " + ex.Message); DebugUtils.DebugPrint(ex.StackTrace.ToString()); } }