public InfoService(Platform platform, VLogger logger) { this.platform = platform; this.logger = logger; string homeIdPart = string.Empty; //if (HomeOS.Shared.Globals.HomeId != null) //{ // homeIdPart = "/" + HomeOS.Shared.Globals.HomeId; //} host = new ServiceHost(this, new Uri(HomeOS.Hub.Common.Constants.InfoServiceAddress + homeIdPart)); host.AddServiceEndpoint(typeof(IHomeOSInfo), new WebHttpBinding(), "").Behaviors.Add(new System.ServiceModel.Description.WebHttpBehavior()); var smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); try { host.Open(); } catch (Exception e) { logger.Log("Could not open the service host: " + e.Message + @" Possible issues: 1) are you running the command prompt / Visual Studio in administrator mode? 2) is another instance of Platform running? 3) is a local copy of Gatekeeper running? 4) is another process occupying the InfoServicePort (51430)?"); throw e; } }
protected override void OnContinue() { foreach (MonitorPack monitorPack in packs) { monitorPack.StartPolling(); } if (Properties.Settings.Default.EnableRemoteHost) { if (wcfServiceHost != null) { wcfServiceHost.Close(); } wcfServiceHost = new ServiceHost(typeof(RemoteCollectorHostService), baseAddress); if (Properties.Settings.Default.WcfEnableMetadata) { // Enable metadata publishing. System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; wcfServiceHost.Description.Behaviors.Add(smb); wcfServiceHost.AddServiceEndpoint(typeof(IRemoteCollectorHostService), new BasicHttpBinding(), baseAddress); } wcfServiceHost.Open(); } base.OnContinue(); }
static void Main(string[] args) { Uri uri = new Uri("http://localhost:8080/ServiceModel/Service"); ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), uri); try { serviceHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService"); System.ServiceModel.Description.ServiceMetadataBehavior serviceMetadataBehavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); serviceMetadataBehavior.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); serviceHost.Open(); Console.WriteLine("This service is ready"); Console.WriteLine("Press <Enter> to terminate"); Console.WriteLine(); Console.ReadLine(); serviceHost.Close(); } catch (CommunicationException ex) { Console.WriteLine("Error occured"); serviceHost.Abort(); } }
static void Main(string[] args) { //服务地址 Uri baseAddress = new Uri("net.tcp://127.0.0.1:8081/Robin_Wcf_Formatter"); ServiceHost host = new ServiceHost(typeof(Robin_Wcf_SvcLib.Service1), new Uri[] { baseAddress }); //服务绑定 NetTcpBinding bind = new NetTcpBinding(); host.AddServiceEndpoint(typeof(Robin_Wcf_SvcLib.IService1), bind, ""); if (host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null) { System.ServiceModel.Description.ServiceMetadataBehavior svcMetaBehavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); svcMetaBehavior.HttpGetEnabled = true; svcMetaBehavior.HttpGetUrl = new Uri("http://127.0.0.1:8001/Mex"); host.Description.Behaviors.Add(svcMetaBehavior); } host.Opened+=new EventHandler(delegate(object obj,EventArgs e){ Console.WriteLine("服务已经启动!"); }); foreach (var sep in host.Description.Endpoints) { sep.Behaviors.Add(new RobinLib.OutputMessageBehavior()); foreach (var op in sep.Contract.Operations) { op.Behaviors.Add(new RobinLib.Base64BodyBehavior()); } } host.Open(); Console.Read(); }
public InfoService (Platform platform, VLogger logger) { this.platform = platform; this.logger = logger; string homeIdPart = string.Empty; //if (HomeOS.Shared.Globals.HomeId != null) //{ // homeIdPart = "/" + HomeOS.Shared.Globals.HomeId; //} host = new ServiceHost(this, new Uri(HomeOS.Hub.Common.Constants.InfoServiceAddress + homeIdPart)); host.AddServiceEndpoint(typeof(IHomeOSInfo), new WebHttpBinding(), "").Behaviors.Add(new System.ServiceModel.Description.WebHttpBehavior()); var smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); try { host.Open(); } catch (Exception e) { logger.Log("Could not open the service host: " + e.Message + @" Possible issues: 1) are you running the command prompt / Visual Studio in administrator mode? 2) is another instance of Platform running? 3) is a local copy of Gatekeeper running? 4) is another process occupying the InfoServicePort (51430)?"); throw e; } }
private void _load_soap_host() { Uri _soap_http_url = new Uri( System.Configuration.ConfigurationManager.AppSettings["SOAP_HTTP_Url"]); _soap_service_host = new System.ServiceModel.ServiceHost(wcf_service, _soap_http_url); //Añadimos endopoint soap System.ServiceModel.Description.ServiceEndpoint epoint = _soap_service_host.AddServiceEndpoint(_service_interface, new System.ServiceModel.BasicHttpBinding(), _soap_http_url); //Habilitamos metadata para este endpoint System.ServiceModel.Description.ServiceMetadataBehavior mthttp = _soap_service_host.Description.Behaviors.Find <System.ServiceModel.Description.ServiceMetadataBehavior>(); if (mthttp != null) { mthttp.HttpGetEnabled = true; } else { mthttp = new System.ServiceModel.Description.ServiceMetadataBehavior(); mthttp.HttpGetEnabled = true; _soap_service_host.Description.Behaviors.Add(mthttp); } }
static void Main(string[] args) { //服务地址 Uri baseAddress = new Uri("net.tcp://127.0.0.1:8081/Robin_Wcf_Formatter"); ServiceHost host = new ServiceHost(typeof(Robin_Wcf_SvcLib.Service1), new Uri[] { baseAddress }); //服务绑定 NetTcpBinding bind = new NetTcpBinding(); host.AddServiceEndpoint(typeof(Robin_Wcf_SvcLib.IService1), bind, ""); if (host.Description.Behaviors.Find <System.ServiceModel.Description.ServiceMetadataBehavior>() == null) { System.ServiceModel.Description.ServiceMetadataBehavior svcMetaBehavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); svcMetaBehavior.HttpGetEnabled = true; svcMetaBehavior.HttpGetUrl = new Uri("http://127.0.0.1:8001/Mex"); host.Description.Behaviors.Add(svcMetaBehavior); } host.Opened += new EventHandler(delegate(object obj, EventArgs e){ Console.WriteLine("服务已经启动!"); }); foreach (var sep in host.Description.Endpoints) { sep.Behaviors.Add(new RobinLib.OutputMessageBehavior()); foreach (var op in sep.Contract.Operations) { op.Behaviors.Add(new RobinLib.Base64BodyBehavior()); } } host.Open(); Console.Read(); }
private System.ServiceModel.ServiceHost InitializeSOAPService() { log4net.LogManager.GetLogger("").Info("Configuring Kernel SOAP Service"); List <IPAddress> ips = new List <IPAddress>(); ips.AddRange(Dns.GetHostAddresses(Dns.GetHostName()).Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)); if (ips.Any()) { System.ServiceModel.ServiceHost serviceHost = new System.ServiceModel.ServiceHost(this); foreach (var ip in Enumerable.Repeat(IPAddress.Loopback, 1)) { log4net.LogManager.GetLogger("").Info(string.Format("Adding Endpoint {0}:{1}", ip, 8733)); string stringURI = string.Empty; stringURI = string.Format( "http://{0}:{1}/CoreInterface/", ip, 9997 ); System.Uri uri = new System.Uri(stringURI); System.Uri mexUri = new System.Uri(uri, "mex"); serviceHost.AddServiceEndpoint( typeof(Core.Communication.ICoreService), new System.ServiceModel.WSHttpBinding(), uri ); System.ServiceModel.Description.ServiceMetadataBehavior smb = serviceHost.Description.Behaviors.Find <System.ServiceModel.Description.ServiceMetadataBehavior>(); bool addSMB = smb == null; smb = smb ?? new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.HttpGetUrl = mexUri; smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; if (addSMB) { serviceHost.Description.Behaviors.Add(smb); } serviceHost.AddServiceEndpoint( System.ServiceModel.Description.ServiceMetadataBehavior.MexContractName, System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), mexUri ); } return(serviceHost); } return(null); }
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(); }
public WebFileServer(string directory, string baseUrl, VLogger logger) { this.logger = logger; this.directory = directory; this.host = new ServiceHost(this, new Uri(baseUrl)); this.host.AddServiceEndpoint(typeof(IWebFileServer), new WebHttpBinding(), "").Behaviors.Add(new System.ServiceModel.Description.WebHttpBehavior()); var smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; this.host.Description.Behaviors.Add(smb); this.host.Open(); }
public WebFileServer(string directory, string baseUrl, VLogger logger) { this.logger = logger; this.directory = directory; this.host = new ServiceHost(this, new Uri(baseUrl)); this.host.AddServiceEndpoint(typeof(IWebFileServer), new WebHttpBinding(), "").Behaviors.Add(new System.ServiceModel.Description.WebHttpBehavior()); var smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; this.host.Description.Behaviors.Add(smb); this.host.Open(); }
private void PublicarPorHTTP() { try { //---------------------------------------------- // Esta sección se activa solo para generar el código del cliente // luego la podemos comentar. // svcutil.exe /language:cs /out:RuleManagerProxy.cs /config:app.config http://127.0.0.1:22229/RequestManager #if DEBUG System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetUrl = new Uri("http://127.0.0.1:22229/RequestManager"); smb.HttpGetEnabled = true; _host.Description.Behaviors.Add(smb); #endif // Fin del código para generación usando SVCUTIL.EXE //---------------------------------------------- } catch (Exception er) { log.Error("PublicarPorHTTP()", er); } }
static string iv = null; // "XdTkT85fZ0U="; protected virtual ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { //服务地址 ServiceHost host = new ServiceHost(serviceType, baseAddresses); if (key == null && iv == null) { try { key = Keel.Internal.KeelHackHelper.ReadKeelHack("KeelWCFDataSafe_Key"); iv = Keel.Internal.KeelHackHelper.ReadKeelHack("KeelWCFDataSafe_IV"); } catch (Exception) { key = "JggkieIw7JM="; iv = "XdTkT85fZ0U="; } Console.WriteLine("key" + key); Console.WriteLine("iv" + iv); } host.AddServiceEndpoint(serviceType.GetInterfaces()[0], new KeelDataSafeBinding(key, iv), ""); if (host.Description.Behaviors.Find <System.ServiceModel.Description.ServiceMetadataBehavior>() == null) { System.ServiceModel.Description.ServiceMetadataBehavior svcMetaBehavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); svcMetaBehavior.HttpGetEnabled = true; svcMetaBehavior.HttpGetUrl = new Uri(baseAddresses[0].OriginalString + "?wsdl");// new Uri("http://127.0.0.1:8001/Mex"); host.Description.Behaviors.Add(svcMetaBehavior); } host.Opened += new EventHandler(delegate(object obj, EventArgs e) { Console.WriteLine("服务已经启动!"); }); return(host); }
private void _load_soap_host() { Uri _soap_http_url = new Uri( System.Configuration.ConfigurationManager.AppSettings["SOAP_HTTP_Url"]); _soap_service_host = new System.ServiceModel.ServiceHost(wcf_service, _soap_http_url); //Añadimos endopoint soap System.ServiceModel.Description.ServiceEndpoint epoint = _soap_service_host.AddServiceEndpoint(_service_interface, new System.ServiceModel.BasicHttpBinding(), _soap_http_url); //Habilitamos metadata para este endpoint System.ServiceModel.Description.ServiceMetadataBehavior mthttp = _soap_service_host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>(); if (mthttp != null) { mthttp.HttpGetEnabled = true; } else { mthttp = new System.ServiceModel.Description.ServiceMetadataBehavior(); mthttp.HttpGetEnabled = true; _soap_service_host.Description.Behaviors.Add(mthttp); } }
protected override void OnStart(string[] args) { #region Provide way to attach debugger by Waiting for specified time #if DEBUG //The following code is simply to ease attaching the debugger to the service to debug the startup routine DateTime startTime = DateTime.Now; while ((!Debugger.IsAttached) && ((TimeSpan)DateTime.Now.Subtract(startTime)).TotalSeconds < 20) // Waiting until debugger is attached { RequestAdditionalTime(1000); // Prevents the service from timeout Thread.Sleep(1000); // Gives you time to attach the debugger } // increase as needed to prevent timeouts RequestAdditionalTime(5000); // for Debugging the OnStart method, #endif #endregion InitializeGlobalPerformanceCounters(); concurrencyLevel = Properties.Settings.Default.ParralelThreads; int monitorPacksLoaded = 0; //There are two ways to specify Monitor packs //Old way is by using the MonitorPackPaths array if (Properties.Settings.Default.MonitorPackPaths != null && Properties.Settings.Default.MonitorPackPaths.Count > 0) { foreach (string monitorPackPath in Properties.Settings.Default.MonitorPackPaths) { if (System.IO.File.Exists(monitorPackPath)) { AddAndStartMonitorPack(monitorPackPath); monitorPacksLoaded++; } } } //New way is to list them in an external file if (Properties.Settings.Default.MonitorPackFile != null && Properties.Settings.Default.MonitorPackFile.Length > 0) { string monitorPackFile = Properties.Settings.Default.MonitorPackFile; if (!monitorPackFile.Contains("\\")) { monitorPackFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), monitorPackFile); } if (System.IO.File.Exists(monitorPackFile)) { foreach (string monitorPackPath in System.IO.File.ReadAllLines(monitorPackFile)) { if (System.IO.File.Exists(monitorPackPath)) { AddAndStartMonitorPack(monitorPackPath); monitorPacksLoaded++; } } } } if (monitorPacksLoaded == 0) { EventLog.WriteEntry(Globals.ServiceEventSourceName, "No (valid) monitor pack specified in service config! This service will only operate as a Remote Collector Host (if enabled). To hide this warning please add some MonitorPacks in QuickMonService.exe.config", EventLogEntryType.Warning, 0); } else { EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Started QuickMon Service with {0} monitor pack(s).", packs.Count), EventLogEntryType.Information, 0); } EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Started QuickMon monitoring and alerting service.\r\nService version: {0}\r\nShared components version: {1}\r\nConcurrency level: {2}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), System.Reflection.Assembly.GetAssembly(typeof(MonitorPack)).GetName().Version.ToString(), concurrencyLevel ), EventLogEntryType.Information, 0); if (Properties.Settings.Default.EnableRemoteHost) { if (wcfServiceHost != null) { wcfServiceHost.Close(); } try { if (!HTTPActivationTest.IsHTTPActivationEnabled()) { EventLog.WriteEntry(Globals.ServiceEventSourceName, "WARNING: Server Feature WCF HTTP Activation is not installed! Remote host functionality may not work.", EventLogEntryType.Warning, 0); } } catch (Exception httpActEx) { EventLog.WriteEntry(Globals.ServiceEventSourceName, "Server Feature WCF HTTP Activation Test failed: " + httpActEx.Message, EventLogEntryType.Error, 0); } if (Properties.Settings.Default.WcfRenameLocalHostNameToRealHost) { if (Properties.Settings.Default.WcfServiceURL.Contains("localhost")) { baseAddress = new Uri(Properties.Settings.Default.WcfServiceURL.Replace("localhost", System.Net.Dns.GetHostName())); } } EventLog.WriteEntry(Globals.ServiceEventSourceName, "Starting Remote Agent Host service for : " + baseAddress.OriginalString, EventLogEntryType.Information, 0); wcfServiceHost = new ServiceHost(typeof(CollectorEntryRelay), baseAddress); if (Properties.Settings.Default.WcfEnableMetadata) { // Enable metadata publishing. System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; wcfServiceHost.Description.Behaviors.Add(smb); wcfServiceHost.AddServiceEndpoint(typeof(ICollectorEntryRelay), new BasicHttpBinding(), baseAddress); } wcfServiceHost.Open(); } }
private void StartService(string serverIP, string serverPort, string localPort) { if (!(NetworkingToolkit.ValidateIPAddress(serverIP) && NetworkingToolkit.ValidatePort(serverPort) && NetworkingToolkit.ValidatePort(localPort))) { throw new ArgumentException() { Source = "ListeningForm.StartService(string serverIP, string serverPort, string localPort)" } } ; ////endereço do player Uri baseAddress = new Uri(String.Format("net.tcp://{0}:{1}/PlayerService/{2}", NetworkingToolkit.LocalIPAddress, localPort, Guid.NewGuid())); ////endpoint para onde as mensagens de announcement serão enviadas Uri announcementEndpointAddress = new Uri(String.Format("net.tcp://{0}:{1}/Announcement", serverIP, serverPort)); //criar o host do serviço serviceHost = new ServiceHost(typeof(PlayerService), baseAddress); try { ////Adicionar um endpoint para o serviço //NetTcpBinding tcpBindingService = new NetTcpBinding(); //tcpBindingService.Security.Mode = SecurityMode.None; //Alterar a autenticação para um modelo melhor ////tcpBindingService.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None; //tcpBindingService.MaxReceivedMessageSize = 10000000; //tcpBindingService.MaxBufferSize = 10000000; //tcpBindingService.MaxBufferPoolSize = 10000000; //ServiceEndpoint netTcpEndpoint = serviceHost.AddServiceEndpoint(typeof(IPlayer), tcpBindingService, string.Empty); //Criar um endpoint para o announcement server, que aponta para o DiscoveryProxy NetTcpBinding tcpBindingAnnouncement = new NetTcpBinding(); tcpBindingAnnouncement.Security.Mode = SecurityMode.None; //Alterar a autenticação para um modelo melhor ////http://nerdwords.blogspot.pt/2008/01/wcf-error-socket-connection-was-aborted.html AnnouncementEndpoint announcementEndpoint = new AnnouncementEndpoint(tcpBindingAnnouncement, new EndpointAddress(announcementEndpointAddress)); //Criar um DiscoveryBehaviour e adicionar o endpoint ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint); #if EXPOSE_METADATA //Adicionar um endpoint MEX (Metadata EXchange) por TCP System.ServiceModel.Channels.BindingElement bindingElement = new System.ServiceModel.Channels.TcpTransportBindingElement(); System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding(bindingElement); System.ServiceModel.Description.ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find <System.ServiceModel.Description.ServiceMetadataBehavior>(); if (metadataBehavior == null) { metadataBehavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(metadataBehavior); } serviceHost.AddServiceEndpoint(typeof(System.ServiceModel.Description.IMetadataExchange), binding, "MEX"); #endif //Adicionar o serviceDiscoveryBehavior ao host para poder ser descoberto serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); serviceHost.Open(); Clipboard.SetText(baseAddress.ToString()); } catch (CommunicationException e) { Log(e); } catch (TimeoutException e) { Log(e); } catch (Exception ex) { Log(ex); } } void serviceHost_UnknownMessageReceived(object sender, UnknownMessageReceivedEventArgs e) { Log("Mensagem desconhecida recebida"); Log(e.Message.ToString()); } void serviceHost_RefreshState(object sender, EventArgs e) { this.RefreshState(); }
static void Main(string[] args) { //netsh http add urlacl url=http://+:8080/ user=\Everyone //string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; string baseAddress = "http://localhost:8000/Service"; ServiceHost host = new NewtonsoftJsonServiceHost(typeof(Service), true, new Uri(baseAddress)); Console.WriteLine("Opening the host"); host.Open(); 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}"); SendRequest(baseAddress + "/json/Add?x=15&y=20", "GET", null, null); try { SendRequest(baseAddress + "/json/Throw", "GET", null, null); } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine("Now using the client formatter"); ChannelFactory <ITestService> newFactory = NewtonsoftJsonServiceHost.GetClientFactory <ITestService>(new Uri(baseAddress), null, null /*"anonymous", "anonymous"*/, c => { var ser = c.NewtonsoftSettings().JsonSerializer; ser.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter()); ser.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); }); ITestService newProxy = newFactory.CreateChannel(); Console.WriteLine(newProxy.GetPerson()); Console.WriteLine(newProxy.AddGet(444, 555)); Console.WriteLine(newProxy.EchoPet(new Pet { Color = "gold", Id = 2, Markings = "Collie", Name = "Lassie", BirthDay = DateTime.UtcNow.AddMonths(-4) })); try { newProxy.Throw(1); } catch (FaultException <CommonFault> fault) { Console.WriteLine(fault.Detail.Error); } SendRequest(baseAddress + "/json/GetPerson", "GET", null, null);//once more //Console.WriteLine("Press ENTER to close"); //Console.ReadLine(); host.Close(); Console.WriteLine("Host closed"); Console.WriteLine("Host2 opened"); host = new TestServiceHost(typeof(Service), true, new Uri(baseAddress)); Console.WriteLine("Opening the host2"); host.Open(); SendRequest(baseAddress + "/json/GetPerson", "GET", null, null);//different settings //Console.WriteLine("Press ENTER to close"); //Console.ReadLine(); host.Close(); Console.WriteLine("Host closed"); ServiceHost host2 = new ServiceHost(typeof(Service), new Uri(baseAddress + "/soap")); var ssss = host2.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), "soap"); var serv2 = new System.ServiceModel.Description.ServiceMetadataBehavior() { }; serv2.HttpGetEnabled = true; serv2.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; host2.Description.Behaviors.Add(serv2); var mex = host2.AddServiceEndpoint(System.ServiceModel.Description.ServiceMetadataBehavior.MexContractName, System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); host2.Open(); var result = SendRequest(baseAddress + "/soap?singlewsdl", "GET", null, null, false); result = result.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"wsdl-viewer.xsl\"?>\n"); File.WriteAllText("../../Metadata.xml", result); Console.WriteLine("Press ENTER to close"); Console.ReadLine(); host2.Close(); Console.WriteLine("Host closed"); }
protected override void OnStart(string[] args) { #region Provide way to attach debugger by Waiting for specified time #if DEBUG //The following code is simply to ease attaching the debugger to the service to debug the startup routine DateTime startTime = DateTime.Now; while ((!Debugger.IsAttached) && ((TimeSpan)DateTime.Now.Subtract(startTime)).TotalSeconds < 20) // Waiting until debugger is attached { RequestAdditionalTime(1000); // Prevents the service from timeout Thread.Sleep(1000); // Gives you time to attach the debugger } // increase as needed to prevent timeouts RequestAdditionalTime(5000); // for Debugging the OnStart method, #endif #endregion InitializeGlobalPerformanceCounters(); concurrencyLevel = Properties.Settings.Default.ParralelThreads; int monitorPacksLoaded = 0; string monitorPackFile = ""; //New way is to list them in an external file if (Properties.Settings.Default.MonitorPackFile != null && Properties.Settings.Default.MonitorPackFile.Length > 0) { monitorPackFile = Properties.Settings.Default.MonitorPackFile; if (!monitorPackFile.Contains("\\")) { monitorPackFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), monitorPackFile); } if (System.IO.File.Exists(monitorPackFile)) { foreach (string monitorPackPath in System.IO.File.ReadAllLines(monitorPackFile)) { if (System.IO.File.Exists(monitorPackPath)) { AddAndStartMonitorPack(monitorPackPath); monitorPacksLoaded++; } } } } if (monitorPacksLoaded == 0) { EventLog.WriteEntry(Globals.ServiceEventSourceName, "No (valid) monitor pack specified in service config! This service will only operate as a Remote Agent. To hide this warning please add some MonitorPacks in MonitorPackList.txt (default)", EventLogEntryType.Warning, 0); } else { EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Started QuickMon Service with {0} monitor pack(s).", packs.Count), EventLogEntryType.Information, (int)QuickMonServiceEventIDs.General); } EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Started QuickMon monitoring and alerting service.\r\nService version: {0}\r\nShared components version: {1}\r\nConcurrency level: {2}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), System.Reflection.Assembly.GetAssembly(typeof(MonitorPack)).GetName().Version.ToString(), concurrencyLevel ), EventLogEntryType.Information, (int)QuickMonServiceEventIDs.General); if (Properties.Settings.Default.EnableRemoteHost) { if (wcfServiceHost != null) { wcfServiceHost.Close(); } if (Properties.Settings.Default.WcfRenameLocalHostNameToRealHost) { if (Properties.Settings.Default.WcfServiceURL.Contains("localhost")) { baseAddress = new Uri(Properties.Settings.Default.WcfServiceURL.Replace("localhost", System.Net.Dns.GetHostName())); } } EventLog.WriteEntry(Globals.ServiceEventSourceName, "Starting Remote Collector Host service for : " + baseAddress.OriginalString, EventLogEntryType.Information, (int)QuickMonServiceEventIDs.General); wcfServiceHost = new ServiceHost(typeof(RemoteCollectorHostService), baseAddress); if (Properties.Settings.Default.WcfEnableMetadata) { // Enable metadata publishing. System.ServiceModel.Description.ServiceMetadataBehavior smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; wcfServiceHost.Description.Behaviors.Add(smb); } System.ServiceModel.Description.ServiceEndpoint endpoint = wcfServiceHost.AddServiceEndpoint(typeof(IRemoteCollectorHostService), new BasicHttpBinding(), baseAddress); List <string> blockedCollectorAgentTypes = new List <string>(); if (Properties.Settings.Default.BlockedCollectorAgentTypes != null) { foreach (string s in Properties.Settings.Default.BlockedCollectorAgentTypes) { blockedCollectorAgentTypes.Add(s); } } endpoint.Behaviors.Add( new RemoteCollectorHostServiceInstanceProvider( Properties.Settings.Default.ApplicationMasterKey, Properties.Settings.Default.ApplicationUserNameCacheFilePath, blockedCollectorAgentTypes, monitorPackFile) ); wcfServiceHost.Open(); } }
public ExitCode Run(string[] arguments) { ExceptionReporter reporter = new ExceptionReporter(_console); Options options = new Options(); if (!options.ParseArguments(arguments)) { _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } ISpecificationRunListener mainListener = null; do { List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>(); var timingListener = new TimingRunListener(); listeners.Add(timingListener); if (options.TeamCityIntegration) { mainListener = new TeamCityReporter(_console.WriteLine, timingListener); } else { mainListener = new RunListener(_console, options.Silent, timingListener); } try { if (!String.IsNullOrEmpty(options.HtmlPath)) { if (IsHtmlPathValid(options.HtmlPath)) { listeners.Add(GetHtmlReportListener(options)); } else { _console.WriteLine("Invalid html path:" + options.HtmlPath); _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } } if (!String.IsNullOrEmpty(options.XmlPath)) { if (IsHtmlPathValid(options.XmlPath)) { listeners.Add(GetXmlReportListener(options)); } else { _console.WriteLine("Invalid xml path:" + options.XmlPath); _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } } listeners.Add(mainListener); if (options.AssemblyFiles.Count == 0) { _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } _console.WriteLine("Files Count: {0} Name: {1}", options.AssemblyFiles.Count, options.AssemblyFiles.Count > 0?options.AssemblyFiles[options.AssemblyFiles.Count-1]:"none"); bool runXap = options.AssemblyFiles.Count > 0 && options.AssemblyFiles[options.AssemblyFiles.Count-1].EndsWith(".xap", StringComparison.OrdinalIgnoreCase); if (!options.WcfListen && !runXap) { listeners.Add(new AssemblyLocationAwareListener()); var listener = new AggregateRunListener(listeners); ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions()); List<Assembly> assemblies = new List<Assembly>(); foreach (string assemblyName in options.AssemblyFiles) { if (!File.Exists(assemblyName)) { throw NewException.MissingAssembly(assemblyName); } Assembly assembly = Assembly.LoadFrom(assemblyName); assemblies.Add(assembly); } specificationRunner.RunAssemblies(assemblies); } else { var completionListener = new CompletionListener(); listeners.Add(completionListener); var listener = new AggregateRunListener(listeners); var proxy = new WcfRunnerProxy(listener); ServiceHost host = null; try { host = new ServiceHost(proxy); host.AddServiceEndpoint(typeof(ISpecificationRunListener), new BasicHttpBinding(), new Uri("http://localhost:5931/MSpecListener")); ((System.ServiceModel.Description.ServiceDebugBehavior)host.Description.Behaviors[typeof(System.ServiceModel.Description.ServiceDebugBehavior)]).IncludeExceptionDetailInFaults = true; var smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; host.Description.Behaviors.Add(smb); host.AddServiceEndpoint(typeof(System.ServiceModel.Description.IMetadataExchange), System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:5931/MSpecListener/MEX"); host.Open(); _console.WriteLine("========================================================================="); _console.WriteLine("Waiting for test results via WCF at http://localhost:5931/MSpecListener"); if (runXap) { var xap = options.AssemblyFiles[options.AssemblyFiles.Count-1]; if (!File.Exists(xap)) { throw NewException.MissingAssembly(xap); } var runner = new Wp7DeviceRunner(true); runner.RunXap(xap); } completionListener.WaitForRunCompletion(); System.Threading.Thread.Sleep(1000); } finally { if (host != null && host.State != CommunicationState.Faulted) host.Close(); } } } catch (Exception ex) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); reporter.ReportException(ex); return ExitCode.Error; } } while (options.Loop); if (mainListener != null && mainListener is ISpecificationResultProvider) { var errorProvider = (ISpecificationResultProvider)mainListener; if (errorProvider.FailureOccured) { Console.WriteLine("Generic failure occurred, no idea what this is"); return ExitCode.Failure; } } return ExitCode.Success; }