WCF bearer service

Source: Internet
Author: User
Document directory
  • WCF bearer service
The WCF bearer service WinForm carries the service code of the WCF server.

Service Interface:

Namespace WCFService

{

[ServiceContract]

Public interface IServiceWindow

{

[OperationContract (IsOneWay = false)]

String GetCurrentTime ();

}

}

Service implementation:

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Runtime. Serialization;

Using System. ServiceModel;

Using System. Text;

Namespace WCFService

{

Public class ServiceWindow: IServiceWindow

{

# Region IServiceWindow Member

Public string GetCurrentTime ()

{

Return string. Format ("Window Server Time: {0}", DateTime. Now. ToString ());

}

# Endregion

}

}

Configuration

<? Xml version = "1.0" encoding = "UTF-8"?>

<Configuration>

<System. serviceModel>

<Services>

<Service behaviorConfiguration = "WCFService. ServiceWindowBehavior"

Name = "WCFService. ServiceWindow">

<Host>

<BaseAddresses>

<Add baseAddress = "http: /localhost: 8000/ServiceWindow/"/>

</BaseAddresses>

</Host>

<Endpoint address = "/Address1"

Binding = "basicHttpBinding"

Contract = "WCFService. IServiceWindow"/>

<Endpoint address = "mex"

Binding = "mexHttpBinding"

Contract = "IMetadataExchange"/>

</Service>

</Services>

<Behaviors>

<ServiceBehaviors>

<Behavior name = "WCFService. ServiceWindowBehavior">

<ServiceMetadata httpGetEnabled = "true"/>

<ServiceDebug includeExceptionDetailInFaults = "false"/>

</Behavior>

</ServiceBehaviors>

</Behaviors>

</System. serviceModel>

</Configuration>

Startup code

Public void Start ()

{

ServiceHost host = new ServiceHost (typeof (ServiceWindow ));

Host. Open ();

}

Private void btnStart_Click (object sender, EventArgs e)

{

Start ();

}

How the client calls

1. Start the service form

2. Add service reference on the client

Call Code

ServiceWindow. ServiceWindowClient myHost3 = new WCFTest. ServiceWindow. ServiceWindowClient ();

Console. WriteLine (myHost3.GetCurrentTime ());

Result:

IIS hosts the service code of the WCF (Omitted) server. Configure the startup code. How does the client call the code Console to host the service code of the WCF server?

1. Service Interface

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Runtime. Serialization;

Using System. ServiceModel;

Using System. Text;

Namespace ConsoleService

{

[ServiceContract]

Public interface IServiceConsole

{

[OperationContract (IsOneWay = false)]

String GetCurrentTime ();

}

}

2. Service implementation

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Runtime. Serialization;

Using System. ServiceModel;

Using System. Text;

Namespace ConsoleService

{

Public class ServiceConsole: IServiceConsole

{

# Region IServiceWindow Member

Public string GetCurrentTime ()

{

// Leleservice. ServiceConsole

Return string. Format ("Console Server Time: {0}", DateTime. Now. ToString ());

}

# Endregion

}

}

Configuration

<? Xml version = "1.0" encoding = "UTF-8"?>

<Configuration>

<System. serviceModel>

<Services>

<Service behaviorConfiguration = "ConsoleService. ServiceConsoleBehavior"

Name = "ConsoleService. ServiceConsole">

<Host>

<BaseAddresses>

<Add baseAddress = "http: /localhost: 9000/ServiceConsole/"/>

</BaseAddresses>

</Host>

<Endpoint address = "/Address2"

Binding = "basicHttpBinding"

Contract = "ConsoleService. IServiceConsole"/>

<Endpoint address = "mex"

Binding = "mexHttpBinding"

Contract = "IMetadataExchange"/>

</Service>

</Services>

<Behaviors>

<ServiceBehaviors>

<Behavior name = "ConsoleService. ServiceConsoleBehavior">

<ServiceMetadata httpGetEnabled = "true"/>

<ServiceDebug includeExceptionDetailInFaults = "false"/>

</Behavior>

</ServiceBehaviors>

</Behaviors>

</System. serviceModel>

</Configuration>

Startup code

Static void Main (string [] args)

{

ServiceHost myHost = new ServiceHost (typeof (ServiceConsole ));

MyHost. Open ();

Console. Read ();

MyHost. Close ();

}

The client adds a service reference and calls the code ServiceConsole. serviceConsoleClient consoleClinet = new WCFTest. serviceConsole. serviceConsoleClient (); Console. writeLine (consoleClinet. getCurrentTime (); Console. read (); Windows Service carries the WCF Server Service Code

1. Service Interface

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Runtime. Serialization;

Using System. ServiceModel;

Using System. Text;

Namespace WindowsService

{

[ServiceContract]

Interface IServiceTest

{

[OperationContract (IsOneWay = false)]

String GetCurrentTime ();

}

}

2. Service implementation

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Runtime. Serialization;

Using System. ServiceModel;

Using System. Text;

Namespace WindowsService

{

Class ServiceTest: IServiceTest

{

# Region IServiceWindowService Member

Public string GetCurrentTime ()

{

Console. WriteLine ("Receive call {0}", DateTime. Now );

Return string. Format ("Console Server Time: {0}", DateTime. Now. ToString ());

}

# Endregion

}

}

ServiceBase class inheritance to implement Windows Service Code

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Diagnostics;

Using System. Linq;

Using System. ServiceProcess;

Using System. Text;

Using System. ServiceModel;

Namespace WindowsService

{

Public partial class ServiceTestWindowService: ServiceBase

{

Private ServiceHost serviceHost = null;

Public ServiceTestWindowService ()

{

InitializeComponent ();

}

Protected override void OnStart (string [] args)

{

If (serviceHost! = Null)

{

ServiceHost. Close ();

}

ServiceHost = new ServiceHost (typeof (ServiceTest ));

ServiceHost. Open ();

}

Protected override void OnStop ()

{

If (serviceHost! = Null)

{

ServiceHost. Close ();

ServiceHost = null;

}

}

}

}

Install services using the Installer inheritance class

Using System;

Using System. Collections;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Configuration. Install;

Using System. Linq;

Using System. ServiceProcess;

Namespace WindowsService

{

[RunInstaller (true)]

Public partial class Installer1: Installer

{

Private ServiceProcessInstaller process;

Private ServiceInstaller service;

Public Installer1 ()

{

InitializeComponent ();

Process = new ServiceProcessInstaller ();

Process. Account = ServiceAccount. LocalSystem;

Service = new ServiceInstaller ();

Service. ServiceName = "WCFWindowsServiceSample ";

Installers. Add (process );

Installers. Add (service );

}

}

}

Configuration code

<? Xml version = "1.0" encoding = "UTF-8"?>

<Configuration>

<System. serviceModel>

<Services>

<Service name = "WindowsService. ServiceTest" behaviorConfiguration = "leleservice. ServiceConsoleBehavior">

<Host>

<BaseAddresses>

<Add baseAddress = "http: // localhost: 9002/WindowService/ServiceTest"/>

</BaseAddresses>

</Host>

<! -- This endpoint is exposed at the base address provided by host: http: // localhost: 8000/ServiceModelSamples/service -->

<Endpoint address = ""

Binding = "wsHttpBinding"

Contract = "WindowsService. IServiceTest"/>

<! -- The mex endpoint is explosed at http: // localhost: 8000/ServiceModelSamples/service/mex -->

<Endpoint address = "mex"

Binding = "mexHttpBinding"

Contract = "IMetadataExchange"/>

</Service>

</Services>

<Behaviors>

<ServiceBehaviors>

<Behavior name = "ConsoleService. ServiceConsoleBehavior">

<ServiceMetadata httpGetEnabled = "true"/>

<ServiceDebug includeExceptionDetailInFaults = "false"/>

</Behavior>

</ServiceBehaviors>

</Behaviors>

</System. serviceModel>

</Configuration>

Installation and startup Interface

1. command line installation

InstallUtil program name

Installutil program name/u

2. Start the service

Client

How to call ServiceWindowService. ServiceTestClient testClient = new WCFTest. ServiceWindowService. ServiceTestClient ();

Console. WriteLine (testClient. GetCurrentTime (); Use

L additional instructions:

ServiceHost is not necessarily implemented in OnStart of windows service. OnStart

The following example demonstrates this implementation.

L implement ServiceHost in Service

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. ServiceModel;

Using System. ServiceModel. Description;

Using System. Xml;

Using TPRIBPM. Base. Tools;

Namespace TPRIBPM. Foundation. PWService

{

Public class WCFService

{

Private ServiceHost host;

Private Uri serverUrl;

Private TPRIBPM. Foundation. PWDB. PWDBDataContext dataContext;

PowerService pwser;

// Http: // localhost: 7654/PWDB/

Public WCFService (Uri serverUrl)

{

Try

{

String connectionString = MyConfig. getConnection ("myconstring ");

If (! String. IsNullOrEmpty (connectionString ))

{

DataContext = new TPRIBPM. Foundation. PWDB. PWDBDataContext (connectionString );

}

Else

{

DataContext = new TPRIBPM. Foundation. PWDB. PWDBDataContext ();

}

DataContext. SubmitChanges ();

MyLog. writeInfo ("database Connection succeeded:" + dataContext. Connection. ConnectionString );

This. serverUrl = serverUrl;

Pwser = new PowerService (dataContext );

Host = new ServiceHost (pwser, serverUrl );

Host. Closed + = new EventHandler (host_Closed );

Host. Opened + = new EventHandler (host_Opened );

Host. UnknownMessageReceived + = new EventHandler <UnknownMessageReceivedEventArgs> (host_UnknownMessageReceived );

Host. Faulted + = new EventHandler (host_Faulted );

ServiceMetadataBehavior behavior = new ServiceMetadataBehavior ();

Behavior. HttpGetEnabled = true;

Host. Description. Behaviors. Add (behavior );

System. ServiceModel. BasicHttpBinding bh = new BasicHttpBinding ();

XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas ();

Quotas. MaxStringContentLength = 7000000;

Bh. ReaderQuotas = quotas;

Bh. maxcompute edmessagesize = 7000000;

Host. AddServiceEndpoint (typeof (IPowerService), bh, "PW /");

}

Catch (System. Exception ex)

{

MyLog. writeError (ex. Message );

Throw new MyException (ex. Message );

}

}

Void host_Faulted (object sender, EventArgs e)

{

MyLog. writeError ("WCF-Faulted ");

}

Void host_UnknownMessageReceived (object sender, UnknownMessageReceivedEventArgs e)

{

MyLog. writeError ("WCF-UnknownMessageReceived ");

}

Void host_Opened (object sender, EventArgs e)

{

MyLog. writeInfo ("WCF Service started, url:" + host. BaseAddresses [0]. AbsoluteUri. ToString ());

}

Void host_Closed (object sender, EventArgs e)

{

MyLog. writeInfo ("the WCF Service has stopped ");

}

Public int? Open ()

{

Try

{

If (host. State = CommunicationState. Created)

{

Host. Open ();

Return null;

}

Return 1;

}

Catch (System. Exception ex)

{

MyLog. writeError (ex. Message );

Throw new MyException (ex. Message );

}

}

Public int? Close ()

{

If (host. State = CommunicationState. Opened)

{

Host. Close ();

Return null;

}

Else

{

Return 1;

}

}

}

}

LWindowsImplementation class that calls serverhost in the service class

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Diagnostics;

Using System. Linq;

Using System. ServiceProcess;

Using System. Text;

Using System. ServiceModel;

Using System. Configuration;

Using TPRIBPM. Foundation. PWService;

Using TPRIBPM. Base. Tools;

Namespace TPRIBPM. Foundation. WinServicePWServer

{

/*************************************** ********************************

* Module: Windows Service package of permission Service

* Author: hbb0b0@163.com

* Create Date: 2009/7/27

* Summary:

**************************************** *******************************/

Public partial class TPRIBPMPWService: ServiceBase

{

/// <Summary>

/// PW WCFService

/// </Summary>

Private WCFService wcfser;

Public TPRIBPMPWService ()

{

InitializeComponent ();

}

/// <Summary>

/// Start

/// </Summary>

/// <Param name = "args"> </param>

Protected override void OnStart (string [] args)

{

String urlAddress = ConfigurationManager. receivettings ["wcfserviceurl"];

Wcfser = new TPRIBPM. Foundation. PWService. WCFService (new Uri (urlAddress ));

Int? V = wcfser. open ();

If (v = null)

{

MyDebug. write ("service started ");

}

}

/// <Summary>

/// Close

/// </Summary>

Protected override void OnStop ()

{

Close ();

}

/// <Summary>

/// Close Method

/// </Summary>

Void close ()

{

If (wcfser! = Null)

{

Int? V = wcfser. close ();

If (v = null)

{

MyDebug. write ("Service stopped ");

}

}

}

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.