Step by step in WCF (2)

Source: Internet
Author: User

Step 2:

Which type of WCF Host Program is better? The main hosting hosts include IIS, console programs, WPF, Windows Forms, NT Service, Windows Services, and COM +. IIS is easy to deploy and can be deployed just like web services, but only HTML protocol is supported, and the host process is started when the customer requests. The console is easy to host and generally used for simple WCF programming. The Windows Forms host can provide a UI for managing host status, making operations more intuitive. Generally, enterprise WCF hosts use Windows Services or COM +. Windows Services can run on the background for a long time and support all binding protocols, but the installation and deployment are relatively complex. COM +, as the host, we can use some features of COM +, such as object pool.
For enterprise development, if IIS or Windows Services are selected, you can consider COM + as the host when performing performance requirements. For individuals, it is relatively simple to develop IIS and console programs and convenient to configure.

Here we practice a wcf host: was (net. TCP) in IIS, self-written WPF Program (HTTP or net. TCP), and Windows Service (net. Pipe)

 

Was (net. TCP) in IIS)

1. Make sure that the Windows Process activation service has been installed in Windows Components.

2. Open IIS. For the productsservice service that has been released to IIS in step 1, click "Advanced Settings" and set "HTTP, net. TCP" in "enabled protocol ".

3. Add an endpoint node to the app. config. Of the productsclient project.

<Client>
<Endpoint address = "http: // localhost/productsservice. SVC"
Binding = "basichttpbinding" bindingconfiguration = "basichttpbinding_iproductsservice"
Contract = "productsservice. iproductsservice" name = "basichttpbinding_iproductsservice"/>

<Endpointaddress = "net. TCP: // localhost/productsservice. SVC"
Binding = "nettcpbinding" Contract = "productsservice. iproductsservice"
Name = "nettcpbinding_iproductsservice"/>
</Client>

In IIS, was (net. TCP) can send messages to the WCF Service.

 

WPF Program (HTTP or net. TCP)

1. Create the class library productsservicelibrary and introduce nbuilder. dll. Add tblproduct. CS, tblproductinventory. CS, iproductsservice. CS, and productsservice. CS respectively.

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;

Namespace productsservicelibrary
{
/// <Summary>
/// Summary of tblproduct
/// </Summary>
Public class tblproduct
{
Public tblproduct ()
{
//
// Todo: add the constructor logic here
//
}

Public int productid;

Public string name;

Public String productnumber;

/// <Summary>
/// 0 = the product is purchased. 1 = the product is produced internally.
/// </Summary>
Public bool makeflag;

/// <Summary>
// 0 = the product cannot be sold. 1 = the product can be sold.
/// </Summary>
Public bool finishedgoodsflag;

Public String color;

//// Minimum inventory.
Public int safetystocklevel;

/// <Summary>
/// Trigger the inventory level of the purchase order or work order.
/// </Summary>
Public int reorderpoint;

/// <Summary>
/// Standard cost of the product.
/// </Summary>
Public decimal standardcost;

/// <Summary>
/// Sales price.
/// </Summary>
Public decimal listprice;

/// <Summary>
/// Product specifications.
/// </Summary>
Public String size;

/// <Summary>
/// Measurement unit of the size column.
/// </Summary>
Public String sizeunitmeasurecode;

/// <Summary>
/// Measurement unit of the weight column.
/// </Summary>
Public String weightunitmeasurecode;

/// <Summary>
/// Product weight.
/// </Summary>
Public decimal weight;

/// <Summary>
/// Number of days required for product production.
/// </Summary>
Public int daystomanufacture;

/// <Summary>
/// R = Flat M = mountain T = Travel s = Standard
/// </Summary>
Public String productline;

/// <Summary>
/// H = high M = medium L = low
/// </Summary>
Public string class;

/// <Summary>
// W = Women's M = Men's u = General
/// </Summary>
Public String style;

/// <Summary>
/// Subcategory of the product. The foreign key that points to productsubcategory. productsubcategoryid.
/// </Summary>
Public int productsubcategoryid;

/// <Summary>
/// The product model to which the product belongs. The foreign key that points to productmodel. productmodelid.
/// </Summary>
Public int productmodelid;

/// <Summary>
/// Date on which the product starts to be sold.
/// </Summary>
Public datetime sellstartdate;

/// <Summary>
/// Date on which the product is discontinued.
/// </Summary>
Public datetime sellenddate;

/// <Summary>
/// Date of product suspension.
/// </Summary>
Public datetime discontinueddate;

/// <Summary>
/// The last update date and time of the row.
/// </Summary>
Public datetime modifieddate;
}
}

 

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;

Namespace productsservicelibrary
{
/// <Summary>
/// Summary of productinventory
/// </Summary>
Public class tblproductinventory
{
Public tblproductinventory ()
{
//
// Todo: add the constructor logic here
//
}

/// <Summary>
/// Product ID. The foreign key that points to product. productid.
/// </Summary>
Public int productid;

/// <Summary>
/// Inventory position ID. The foreign key pointing to location. locationid.
/// </Summary>
Public int locationid;

/// <Summary>
/// Storage space in the inventory location.
/// </Summary>
Public String shelf;

/// <Summary>
/// Storage container on the shelf in the inventory position.
/// </Summary>
Public int bin;

/// <Summary>
/// Number of products in the inventory position.
/// </Summary>
Public int quantity;

/// <Summary>
/// The last update date and time of the row.
/// </Summary>
Public datetime modifieddate;
}
}

 

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. runtime. serialization;
Using system. servicemodel;
Using system. text;

Namespace productsservicelibrary
{
// Note: You can use the "RENAME" command on the "refactoring" menu to change the Interface Name "iservice" in the Code and configuration file at the same time ".
[Servicecontract]
Public interface iproductsservice
{

// Get the product number of every product
[Operationcontract]
List <string> listproducts ();
// Get the details of a single product
[Operationcontract]
Productdata getproduct (string productnumber );
// Get the current stock level for a product
[Operationcontract]
Int currentstocklevel (string productnumber );
// Change the stock level for a product
[Operationcontract]
Bool changestocklevel (string productnumber, short newstocklevel, string shelf, int bin );
}
}

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. runtime. serialization;
Using system. servicemodel;
Using system. text;
Using fizzware. nbuilder;
// Note: You can use the "RENAME" command on the "refactoring" menu to change the class name "service" in the code, service, and configuration file at the same time ".
Namespace productsservicelibrary
{
[Datacontract]
Public class productdata
{
[Datamember]
Public string name;
[Datamember]
Public String productnumber;
[Datamember]
Public String color;
[Datamember]
Public decimal listprice;
}

Public class productsserviceimpl: iproductsservice
{
Static ilist <tblproduct> PS = builder <tblproduct>. createlistofsize (50). Build ();
Static ilist <tblproductinventory> Pis = builder <tblproductinventory>. createlistofsize (50). Build ();

Public list <string> listproducts ()
{
VaR P = ps. Select (item => item. productnumber). tolist ();

Return P;
}

Public productdata getproduct (string productnumber)
{

Productdata = NULL;
Tblproduct matchingproduct = ps. First (item => string. Compare (item. productnumber, productnumber) = 0 );

Productdata = new productdata ()
{
Name = matchingproduct. Name,
Productnumber = matchingproduct. productnumber,
Color = matchingproduct. color,
Listprice = matchingproduct. listprice
};

Return productdata;
}

Public int currentstocklevel (string productnumber)
{
Int stocklevel = 0;


// Calculate the sum of all quantities for the specified product
Stocklevel = (from Pi in Pis
Join P in PS
On pi. productid equals P. productid
Where string. Compare (P. productnumber, productnumber) = 0
Select (INT) PI. Quantity). sum ();

Return stocklevel;
}

Public bool changestocklevel (string productnumber, short newstocklevel, string shelf, int bin)
{
// Var Pr = builder <tblproduct>. createlistofsize (50). Build ();
// Var pri = builder <tblproductinventory>. createlistofsize (50). Build ();
Int productid = (from P in PS
Where string. Compare (P. productnumber, productnumber) = 0
Select P. productid). First ();
// Find the productinventory object that matches the parameters passed
// In to the operation
Tblproductinventory productinventory = PIs. First (
Pi => string. Compare (PI. shelf, shelf) = 0 &&
Pi. bin = bin & Pi. productid = productid );
// Update the stock level for the productinventory object
Productinventory. Quantity + = newstocklevel;
// Save the change back to the database

Return true;
}
}
}

 

2. Create a WPF Application Project productsservicehost and add a reference to the productsservicelibrary class library.

Mainwindow front-end:

<Grid>
<Button Height = "23" horizontalalignment = "Left" margin = "51,60, 0, 0 "name =" start "verticalignment =" TOP "width =" 75 "Click =" start_click "> Start </button>
<Button Height = "23" horizontalalignment = "right" margin = "0, 60, 56, 0 "name =" stop "verticalignment =" TOP "width =" 75 "isenabled =" false "Click =" stop_click "> stop </button>
<Label Height = "23" horizontalalignment = "Left" margin = "43,0, 0,111" name = "label1" verticalalignment = "bottom" width = "88"> service status: </label>
<Textbox isreadonly = "true" margin = "133,0, 59,107" name = "status" text = "Service stopped" Height = "26" verticalalignment = "bottom"> </textbox>
</GRID>

 

Mainwindow Background:

Servicehost productsservicehost = NULL;
Private void start_click (Object sender, routedeventargs E)
{
Try
{
Productsservicehost = new servicehost (typeof (productsserviceimpl ));
Productsservicehost. open ();
Stop. isenabled = true;
Start. isenabled = false;
Status. Text = "Service Running ";
}
Catch (exception ex)
{
Handleexception (Ex );
}
}

Private void handleexception (exception ex)
{
MessageBox. Show (ex. Message );
}

Private void stop_click (Object sender, routedeventargs E)
{
Try
{
Productsservicehost. Close ();
Stop. isenabled = false;
Start. isenabled = true;
Status. Text = "Service stopped ";
}
Catch (exception ex)
{
Handleexception (Ex );
}

}

3. App. config

<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<System. servicemodel>
<Services>
<Service name = "productsservicelibrary. productsserviceimpl">

<Endpoint address = "net. TCP: // localhost: 8080/tcpservice"
Binding = "nettcpbinding"
Bindingconfiguration = "" name = "nettcpbinding_iproductsservice"
Contract = "productsservicelibrary. iproductsservice"/>

<Endpoint address = "http: /localhost: 8000/productsservice/service. SVC"
Binding = "basichttpbinding" name = "basichttpbinding_iproductsservice"
Contract = "productsservicelibrary. iproductsservice"/>

</Service>
</Services>
<Behaviors>

</Behaviors>
</System. servicemodel>
</Configuration>

 

Note that two endpoints are set here, and the system starts the WCF Service for these two addresses. The client can select any address to introduce the service.

<Client>
<Endpoint address = "net. TCP: // localhost: 8080/tcpservice"
Binding = "nettcpbinding" Contract = "productsservice. iproductsservice"
Name = "nettcpbinding_iproductsservice"/>

<Endpoint address = "http: /localhost: 8000/productsservice/service. SVC"
Binding = "basichttpbinding"
Bindingconfiguration = "basichttpbinding_iproductsservice"
Contract = "productsservice. iproductsservice"
Name = "basichttpbinding_iproductsservice"/>

</Client>

 

For Windows Services as hosts

1. Create a Windows Service Project windowsproductsservice, add the productsservicelibrary class library reference, and rename service1.cs to servicehostcontroller. CS.

Public partial class servicehostcontroller: servicebase
{
Private servicehost productsservicehost;
Public servicehostcontroller ()
{
Initializecomponent ();
// The name of the service that appears in the Registry
This. servicename = "productsservice ";
// Allow an administrator to stop (and restart) the service
This. canstop = true;
// Report start and stop events to the Windows Event Log
This. autolog = true;
}

Protected override void onstart (string [] ARGs)
{
Productsservicehost = new servicehost (typeof (productsserviceimpl ));
Netnamedpipebinding binding = new netnamedpipebinding ();
Productsservicehost. addserviceendpoint (typeof (iproductsservice ),
Binding, "net. Pipe: // localhost/productsservicepipe ");
Productsservicehost. open ();
}

Protected override void onstop ()
{
Productsservicehost. Close ();
}

 

2. In servicehostcontroller. CS [design], right-click to add and install. Click serviceinstaller1, modify its attribute servicename to servicehostcontroller, and click serviceprocessinstaller1 to modify the account

Is LocalSystem. Generate a project.

3. Use the Administrator permission to open the Visual Studio command prompt. Switch to the debug folder of the windowsproductsservice project and run installutil windowsproductsservice.exe. Windows service installation is complete

4. Add an endpoint in the previous productsclient client configuration file.

<Endpoint address = "net. Pipe: // localhost/productsservicepipe"
Binding = "netnamedpipebinding"
Contract = "productsservice. iproductsservice"
Name = "netnamedpipebinding_iproductsservice"/>

OK. I'm glad to hear that.

 

TIPS: If you want to uninstall Windows Services, you can run installutil/u windowsproductsservice.exe

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.