• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ServiceModel.ServiceHost类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.ServiceModel.ServiceHost的典型用法代码示例。如果您正苦于以下问题:C# ServiceHost类的具体用法?C# ServiceHost怎么用?C# ServiceHost使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ServiceHost类属于System.ServiceModel命名空间,在下文中一共展示了ServiceHost类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ShouldSetShieldingWithNonIncludeExceptionDetailInFaults

 public void ShouldSetShieldingWithNonIncludeExceptionDetailInFaults()
 {
     // create a mock service and its endpoint.
     Uri serviceUri = new Uri("http://tests:30003");
     ServiceHost host = new ServiceHost(typeof(MockService), serviceUri);
     host.AddServiceEndpoint(typeof(IMockService), new WSHttpBinding(), serviceUri);
     host.Open();
     try
     {
         // check that we have no ErrorHandler loaded into each channel that
         // has IncludeExceptionDetailInFaults turned off.
         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
         {
             Assert.AreEqual(0, dispatcher.ErrorHandlers.Count);
             Assert.IsFalse(dispatcher.IncludeExceptionDetailInFaults);
         }
         ExceptionShieldingBehavior behavior = new ExceptionShieldingBehavior();
         behavior.ApplyDispatchBehavior(null, host);
         // check that the ExceptionShieldingErrorHandler was assigned to each channel
         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
         {
             Assert.AreEqual(1, dispatcher.ErrorHandlers.Count);
             Assert.IsTrue(dispatcher.ErrorHandlers[0].GetType().IsAssignableFrom(typeof(ExceptionShieldingErrorHandler)));
         }
     }
     finally
     {
         if (host.State == CommunicationState.Opened)
         {
             host.Close();
         }
     }
 }
开发者ID:jmeckley,项目名称:Enterprise-Library-5.0,代码行数:33,代码来源:ExceptionShieldingBehaviorFixture.cs


示例2: Start

        public void Start()
        {
            _source = new CancellationTokenSource();
            var token = _source.Token;
            _listenerTask = new Task(() =>
            {
                BusListener.MessageReceivedEvent += (s, e) => Console.WriteLine("Received message at " + e.Endpoint + " of type " + e.MessageType);
                BusListener.MessageSentEvent += (s, e) => Console.WriteLine("Sent message " + e.MessageType);
                BusListener.BusStartedEvent += (s, e) => Console.WriteLine("Bus started " + e.Endpoint);
                BusListener.MessageExceptionEvent += (s, e) => Console.WriteLine("Exception with message " + e.Endpoint + " for type " + e.MessageType + " with value " + e.Exception);
                using (var host = new ServiceHost(_listener, new[] { new Uri("net.tcp://localhost:5050") }))
                {

                    host.AddServiceEndpoint(typeof(IBusListener), new NetTcpBinding(), "NServiceBus.Diagnostics");

                    host.Opened += (s, e) => Console.WriteLine("Listening for events...");
                    host.Closed += (s, e) => Console.WriteLine("Closed listening for events...");

                    host.Open();

                    while (!token.IsCancellationRequested) { }

                    host.Close();
                }
            }, token);

            _listenerTask.Start();
            _listenerTask.Wait(10000);

        }
开发者ID:nishanperera,项目名称:NServiceBus.MessageRouting,代码行数:30,代码来源:Listener.cs


示例3: CacheHostEngine

        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="cacheHostInformationPoller">The cache host information poller.</param>
        /// <param name="memCache">The mem cache to use for storing objects.</param>
        /// <param name="clientToCacheServiceHost">The client to cache service host.</param>
        /// <param name="cacheManagerClient">The cache manager client.</param>
        public CacheHostEngine(IRunnable cacheHostInformationPoller, MemCache memCache, ServiceHost clientToCacheServiceHost)
        {
            // Sanitize
            if (cacheHostInformationPoller == null)
            {
                throw new ArgumentNullException("cacheHostInformationPoller");
            }
            if (memCache == null)
            {
                throw new ArgumentNullException("memCache");
            }
            if (clientToCacheServiceHost == null)
            {
                throw new ArgumentNullException("clientToCacheServiceHost");
            }

            // Set the cache host information poller
            _cacheHostInformationPoller = cacheHostInformationPoller;

            // Set the mem cache container instance
            MemCacheContainer.Instance = memCache;

            // Initialize the service hosts
            _clientToCacheServiceHost = clientToCacheServiceHost;
        }
开发者ID:nategreenwood,项目名称:dache,代码行数:32,代码来源:CacheHostEngine.cs


示例4: Main

	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 ();
	}
开发者ID:alesliehughes,项目名称:olive,代码行数:34,代码来源:samplesvc10.cs


示例5: ProbeInitialServices

		private void ProbeInitialServices(ServiceHost serviceHost)
		{
			var probe = new DiscoveryClient(UdpDiscoveryEndpoint ?? new UdpDiscoveryEndpoint());
			probe.FindProgressChanged += (_, args) => RegisterService(serviceHost, args.EndpointDiscoveryMetadata);
			probe.FindCompleted += (_, args) => probe.Close();
			probe.FindAsync(ProbeCriteria ?? new FindCriteria());
		}
开发者ID:ramonsmits,项目名称:Castle.Facilities.Wcf,代码行数:7,代码来源:AdHocServiceCatalogDiscovery.cs


示例6: RegisterAsServer

 public static ITestRunner RegisterAsServer(ITestOutput output, Options options)
 {
     var host = new ServiceHost(output);
     int i;
     for (i = 0; i < 50; i += 10) {
         try {
             host.AddServiceEndpoint(typeof(ITestOutput), BindingFactory(), "http://localhost:" + (StartPort + i) + "/");
             break;
         } catch (AddressAlreadyInUseException) {
         }
     }
     host.Open();
     var start = DateTime.Now;
     Exception final = null;
     var res = new ChannelFactory<ITestRunner>(BindingFactory(), "http://localhost:" + (StartPort + i + 1) + "/").CreateChannel();
     while (DateTime.Now - start < TimeSpan.FromSeconds(5)) {
         try {
             res.Ping();
             return res;
         } catch (Exception e) {
             final = e;
         }
     }
     throw final;
 }
开发者ID:SimonRichards,项目名称:msUnit,代码行数:25,代码来源:ConnectionFactory.cs


示例7: Main

        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();
            }
        }
开发者ID:danielglyde,项目名称:WCFStringManipulator,代码行数:34,代码来源:Program.cs


示例8: Main

        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();
            }
        }
开发者ID:zabidin901,项目名称:ReplayAttackWCFProtoType,代码行数:28,代码来源:Program.cs


示例9: Bootstrapper

        public Bootstrapper()
        {
            Naru.Core.UnhandledExceptionHandler.InstallDomainUnhandledException();
            Naru.TPL.UnhandledExceptionHandler.InstallTaskUnobservedException();

            IContainer container = null;

            var builder = new ContainerBuilder();

            builder.RegisterModule(new Log4NetModule
                                            {
                                                SectionName = "CommonLogging.Nitrogen.Server"
                                            });

            builder.RegisterModule(new AgathaServerModule
                                   {
                                       ContainerFactory = () => container,
                                       HandlerAssembly = typeof(AssemblyHook).Assembly,
                                       RequestResponseAssembly = typeof(Common.AssemblyHook).Assembly
                                   });

            container = builder.Build();

            Console.WriteLine("EndPoint - {0}", END_POINT);

            var baseAddress = new Uri(END_POINT);
            Host = new ServiceHost(typeof(WcfRequestProcessor), baseAddress);
            Host.Open();
        }
开发者ID:ganesum,项目名称:Nitrogen,代码行数:29,代码来源:Bootstrapper.cs


示例10: button1_Click

 private void button1_Click(object sender, EventArgs e)
 {
     if (serverIsOn)
     {
         labelStatus.Text = "Turning off...";
         labelStatus.Update();
         host.Close();
         labelStatus.Text = "Server is Off";
         button1.Text = "Turn on Server";
         listView1.Visible = false;
         labelPos2.Visible = false;
         Server.saveDatabaseToFile();
         t.Stop();
     }
     else
     {
         labelStatus.Text = "Turning on...";
         labelStatus.Update();
         host = new ServiceHost(typeof(Server));
         host.Open();
         labelStatus.Text = "Server is On";
         button1.Text = "Turn off Server";
         listView1.Visible = true;
         labelPos2.Visible = true;
         Invalidate();
         t.Start();
     }
     serverIsOn = !serverIsOn;
 }
开发者ID:stefanopf,项目名称:Middleware,代码行数:29,代码来源:ServerForm.cs


示例11: StartService

        internal static void StartService()
        {
            //Consider putting the baseAddress in the configuration system
            //and getting it here with AppSettings
            Uri baseAddress = new Uri( "http://localhost:8080/FileService" );
            //Instantiate new ServiceHost 
            myServiceHost = new ServiceHost( typeof( PracticalWcf.FileService ), baseAddress );
            

            //The following for programatic addition
            //WSHttpBinding wsBinding = new WSHttpBinding();
            //wsBinding.MessageEncoding = WSMessageEncoding.Mtom;
            //myServiceHost.AddServiceEndpoint(
            //    typeof( MtomSvc.IMtomSample ),
            //    wsBinding,
            //    baseAddress );

            //the following for programatic addition of Basic Profile 1.1
            //BasicHttpBinding binding = new BasicHttpBinding();
            //myServiceHost.AddServiceEndpoint(
            //    typeof( MyService,
            //    binding,
            //    baseAddress);


            //Open myServiceHost
            myServiceHost.Open();
        }
开发者ID:ssickles,项目名称:archive,代码行数:28,代码来源:Program.cs


示例12: Main

        static void Main(string[] args)
        {
            ServiceHost host = null;

            Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
            ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");

            foreach (ServiceElement el in svcmod.Services.Services)
            {
                Type type = Type.GetType(el.Name+",JJY.WCF.Service");
                if(type == null)
                {
                    Console.WriteLine(string.Format("服务{0}实例化失败"), el.Name);
                }
                host = new ServiceHost(type);
                //host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
                try
                {
                    host.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("服务{0}启动失败", el.Name));
                    Console.WriteLine(string.Format("错误内容:{0}", ex.ToString()));
                }
                Console.WriteLine(string.Format("{0}已经启动",el.Name));
            }
            Console.ReadLine();
        }
开发者ID:tianma8778,项目名称:WCFCommunication,代码行数:29,代码来源:Program.cs


示例13: Main

        static void Main(string[] args)
        {
            try
            {
                ServiceHost host = new ServiceHost(typeof(RESTService));
                host.Open();

                if (host.State == CommunicationState.Opened)
                {
                    Console.WriteLine("The service is available:");
                    foreach (var address in host.BaseAddresses)
                    {
                        Console.WriteLine(address);
                    }
                    Console.WriteLine();
                }
                else
                {
                    throw new System.Exception("The service is not in a state OPENED.");
                }
            }
            catch (System.Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey(true);
        }
开发者ID:ZyshchykMaksim,项目名称:WCF.REST,代码行数:28,代码来源:Program.cs


示例14: Main

        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();
            }
        }
开发者ID:MartinaMagnusson,项目名称:WCF,代码行数:29,代码来源:Program.cs


示例15: RegisterService

		private void RegisterService(ServiceHost serviceHost, EndpointDiscoveryMetadata endpoint)
		{
			if (FilterService(serviceHost, endpoint) == false)
			{
				serviceCatalog.RegisterService(endpoint);
			}
		}
开发者ID:castleproject,项目名称:Windsor,代码行数:7,代码来源:AdHocServiceCatalogDiscovery.cs


示例16: Main

        // Host the service within this EXE console application.
        public static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service");

            // Create a ServiceHost for the CalculatorService type and provide the base address.
            using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
            {
                // Create a custom binding containing two binding elements
                ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement();
                reliableSession.Ordered = true;

                HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
                httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
                httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

                CustomBinding binding = new CustomBinding(reliableSession, httpTransport);

                // Add an endpoint using that binding
                serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, "");
              
                // Open the ServiceHost to create listeners and start listening for messages.
                serviceHost.Open();

                // The service can now be accessed.
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
            }
        }
开发者ID:spzenk,项目名称:sfdocsamples,代码行数:31,代码来源:service.cs


示例17: StartServiceHost

 static void StartServiceHost()
 {
     _svcHost = new ServiceHost(_worldSvr);
     _svcHost.Faulted += new EventHandler(svcHost_Faulted);
     _svcHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(svcHost_UnknownMessageReceived);
     _svcHost.Open();
 }
开发者ID:natedahl32,项目名称:EqEmulator-net,代码行数:7,代码来源:Program.cs


示例18: ConfigureServiceHost

		protected void ConfigureServiceHost(ServiceHost serviceHost, IWcfServiceModel serviceModel, ComponentModel model)
		{
			serviceHost.Description.Behaviors.Add(
				new WindsorDependencyInjectionServiceBehavior(kernel, model)
				);

			var burden = new WcfBurden(kernel);
			var contracts = new HashSet<ContractDescription>();
			Dictionary<IWcfEndpoint, ServiceEndpoint> endpoints = null;

			if (serviceModel != null && serviceModel.Endpoints.Count > 0)
			{
				endpoints = new Dictionary<IWcfEndpoint, ServiceEndpoint>();
				var builder = new ServiceEndpointBuilder(this, serviceHost);

				foreach (var endpoint in serviceModel.Endpoints)
				{
					endpoints.Add(endpoint, builder.AddServiceEndpoint(endpoint));
				}
			}

			var extensions = new ServiceHostExtensions(serviceHost, kernel)
				.Install(burden, new WcfServiceExtensions());

			if (serviceModel != null)
			{
				extensions.Install(serviceModel.Extensions, burden);
			}

			extensions.Install(burden, new WcfEndpointExtensions(WcfExtensionScope.Services));

			if (endpoints != null)
			{
				foreach (var endpoint in endpoints)
				{
					var addContract = contracts.Add(endpoint.Value.Contract);
					new ServiceEndpointExtensions(endpoint.Value, addContract, kernel)
						.Install(endpoint.Key.Extensions, burden);
				}
			}

			if (serviceHost is IWcfServiceHost)
			{
				var wcfServiceHost = (IWcfServiceHost)serviceHost;

				wcfServiceHost.EndpointCreated += (_, e) =>
				{
					var addContract = contracts.Add(e.Endpoint.Contract);
					var endpointExtensions = new ServiceEndpointExtensions(e.Endpoint, addContract, kernel)
						.Install(burden, new WcfEndpointExtensions(WcfExtensionScope.Services));

					if (serviceModel != null)
					{
						endpointExtensions.Install(serviceModel.Extensions, burden);
					}
				};
			}

			serviceHost.Extensions.Add(new WcfBurdenExtension<ServiceHostBase>(burden));
		}
开发者ID:codereflection,项目名称:Castle.Facilities.Wcf,代码行数:60,代码来源:AbstractServiceHostBuilder.cs


示例19: Main

        public static void Main(string[] args)
        {
            if (System.Environment.UserInteractive)
            {
                string parameter = string.Concat(args);

                try
                {
                    ServiceHost serviceHost = new ServiceHost(typeof(InfoProviderService));

                    serviceHost.Open();
                    LogManager.Instance.WriteInfo("InfoProvider Server Starting...........");

                }
                catch (Exception ex)
                {
                    LogManager.Instance.WriteError(ex.Message);
                }
            }
            else
            {

                ServiceBase.Run(new Program());

            }

        }
开发者ID:ddotan,项目名称:InfoProvider.ASPMVC.WCF,代码行数:27,代码来源:Program.cs


示例20: Main

        public static void Main()
        {
            var baseAddress = new Uri("http://localhost:3370/");

            // Create the ServiceHost.
            using (var host = new ServiceHost(typeof(Service), baseAddress))
            {
                // Enable metadata publishing.
                //var smb = new ServiceMetadataBehavior
                //{
                //    HttpGetEnabled = true,
                //    MetadataExporter = {PolicyVersion = PolicyVersion.Policy15}
                //};

                //host.Description.Behaviors.Add(smb);

                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                host.Close();
            }
        }
开发者ID:symoneig,项目名称:Messenger,代码行数:25,代码来源:Program.cs



注:本文中的System.ServiceModel.ServiceHost类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ServiceModel.ServiceModelDictionary类代码示例发布时间:2022-05-26
下一篇:
C# ServiceModel.OperationContextScope类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap