Wcf4.0 advanced series-Chapter 1 code control configuration and Communication (Part 2)

Source: Internet
Author: User
ArticleDirectory
    • Connect to a service by programming
    • Use clientbase abstract class
    • Send messages to services by programming
Preface the WCF client can connect to the service through a proxy object. If the service administrator disables service metadata publishing or for performance reasons Code Create a channelfactory object to connect to the service and communicate with the service. You can even extend the clientbase sampling class to interact with the service. When using the two methods, there is a premise that service developers can provide components that contain service contracts. If this premise does not exist, you can use the WCF client to access the service as long as you have a document describing the SOAP message received by the Service and the response message sent by the service; you can send messages directly to the service through channels. Connect to a service as a client through programming Program When running and connecting to the service, the client's WCF runtime creates a basic architecture similar to the server's WCF runtime. If you connect to the service through a proxy object, there is actually 1. the client uses the binding element specified in the configuration file to create a binding object and create an endpoint using the endpoint definition during the WCF running process. 2. Create a channelfactory object using these objects during client WCF running. 3. The client uses this object to instantiate the channel stack and connect to the URI specified by the endpoint during the WCF runtime. 4. When a client program calls a service operation through a proxy object, the server sends these requests to the service through the channel stack during the WCF operation. 5. After the response message leaves the service, the response message is sent back to the client's WCF runtime through the channel stack. 6. Then, the proxy object transmits the Response Message to the client program. You can create a client proxy class for the service by using the svcutil utility or the add service reference wizard. For security reasons, the administrator can disable the WCF Service to publish service metadata externally. However, WCF Service developers can distribute components that contain service contracts. You can use these components to dynamically create channel stacks. This implementation method also has performance advantages. For example, you may have discovered that the agent classes generated by using the svcutil utility or adding a service wizard are not optimized as necessary. The automatically generated agent classes are lengthy because they cannot be assumed to implement the technology used by the Service, in addition, this lengthy code affects performance. If you know that the service is generated using WCF, you can save the trouble of creating a proxy object and directly construct a channelfactory object for the client from the component that contains the service contract. This is what we need to do in the following exercises.

Use the channelfactory object to connect to the productsservice Service 1. in Visual Studio, disable the shoppingcartservice solution, and open the path in * \ solutions \ WCF \ step. by. step \ chapter11 \ productsservice solution 2 under the productsservice folder. in the solution, use the following steps for iproductservice under the productsservicelibrary project. add a link to the CS File

    • Right-click the productsclient project, point to add, and click the existing entry
    • In the add existing entry dialog box, browse the productsservice \ productsservicelibrary folder and select the iproductsservice. CS file.
    • Click the drop-down arrow on the Add button and click "Add as Link"
This feature allows you to reference the same Source code File instead of creating a copy. This avoids version issues. You can edit the source file in any project that references the source file. The iproductservice. CS file contains the service contract definition of the productsservice service. If you do not want to share source code with the service contract, you can edit the file as a single component and then distribute the component to the developer who builds the client program. 3. In the solution browser window, open the program. CS file under the productsclient project. The main method of this file contains the basic framework of the client program, but the current Code does not include the function of connecting to the service. Add the following reference to the file using system. servicemodel. Security; 4. In the try section of the main method, add the following declaration.

Ws2007httpbinding httpbinding = new ws2007httpbinding (securitymode. Message );

Wshttpsecurity httpsec = httpbinding. Security; httpsec. Message. algorithmsuite = securityalgorithmsuite. basic128; httpsec. Message. clientcredentialtype = Alibaba. Windows; ws2007httpbinding class implements standard quota binding. Productsservicehost publishes the HTTP endpoint, whose URI is http: // localhost: 8010/productsservice/service. SVC. If you check the app. config file of productsservicehost, you will see that the binding configuration of the current service uses message security, and configured 128-bit message encryption and Windows integrated verification. The preceding Code sets the Security attribute bound to ws2007httpbinding corresponding to the endpoint used by the client program. 5. Add the following declaration to the try segment of the main method.

Endpointaddress address = new endpointaddress ("http: // localhost: 8010/productsservice/service. SVC"); The endpointaddress object encapsulates the address that the client program uses to communicate with the service. 6. Add the following declaration to the try segment of the main method.

Products. iproductsservicev2 channel = channelfactory <products. iproductsservicev2>. createchannel (httpbinding, address );

Create a channel by accessing the static method createchannel of the channelfactory class. The first parameter of this method specifies the channel binding, and the second parameter specifies the channel connection address. This method returns the reference of the created channel. The channel has a type corresponding to the service contract, And this type determines the method that the channel exposes to the client program. In this example, the channel is assigned a variable type of products. iproductsservicev2. Do you still remember that iproductsservicev2 is an interface that is implemented in productsservicecontract. CS. You can create a channel based on any interface marked as servicecontract. 7. Now you can call the service method through the channel. In the try segment, add the following code

Console. writeline ("Test 1: List all bicycle frames ");

List <string> productnumbers = channel. listmatchingproducts ("frame"); foreach (string productnumber in productnumbers) {console. writeline ("number: {0}", productnumber);} the code above is slightly different from the code used to call the service in chapter 6. In the code above, the returned value for calling a service method is a list <string> object instead of the character array returned by the proxy object in chapter 6. 8. Close the connection with the service, and set the channel object to null to release related resources.

Channel = NULL;

9. The complete main method code is as follows:
Static void main (string [] ARGs) {console. writeline ("Please enter when the service is running. "); console. readline (); try {ws2007httpbinding ws2007httpbinding = new ws2007httpbinding (securitymode. message); ws2007httpbinding. security. mode = securitymode. message; ws2007httpbinding. security. message. clientcredentialtype = messagecredentialtype. windows; endpointaddress address = new endpointaddress ("http: // localhost: 8010/productsservice/service. SVC "); products. iproductsservicev2 channel = channelfactory <products. iproductsservicev2>. createchannel (ws2007httpbinding, address); console. writeline ("Test 1: List all bycycle frames"); List <string> productnumebrs = channel. listmatchedproducts ("frame"); foreach (string productnumber in productnumebrs) console. writeline ("number: {0}", productnumber); console. writeline (); Channel = NULL;} catch (exception ex) {console. writeline (ex. innerexception. message);} console. writeline ("Please enter to finish. "); console. readline ();}

10. Generate a project and exit Visual Studio.

Before you run the client program, you need to change a security configuration of your computer: You need to add your current user account to the warehousestaff group. This is because the productsservice service only allows members of this group to access the listmatchingproducts operation.

Configure security and test the client program 1. Open the Windows Start Menu, right-click the computer, and choose manage. 2. in the computer management console, expand local users and group nodes under the System Tool node, and then click User folder 3. on the right panel, right-click your current user name and click Properties 4. in the Properties dialog box, click the member label and then click Add 5. in the select group dialog box, enter warehousestaff and click OK. in the Properties dialog box, click OK. close the Computer Management Console 8. log out of windows and log on to the system again. start Visual Studio and enable productsservice solution 10 again. start the solution in non-adaptive mode. In the product service host program window, click Start. Then, in the console window of the client, press Enter. The client program connects to the service, requests the bicycle frame list, and then displays the result as shown in Figure 11. Press enter in the console window of the client to close the client program. In the product Host Program window, click the stop button and close the window. Please note that the product service host window will pause for a certain period of time to respond to the stop button. This is because the Host Program must wait to ensure that the client program has closed the connection before closing the connection and releasing various network resources. After the client program is set to null in the channel object, the. NET Framework Garbage Collector releases the resources used by the channel object before the client program is disconnected.

in the previous section, you used the clientcredentials attribute of the proxy class to specify the creden。 sent to the service. If you need to provide creden that are not your current Windows identity, the implementation method in the previous exercise cannot meet your needs. At this time, you can define a class that extends system. servicemodel. clientbase abstract class, and then connect to the service using this class. The clientbase class works with the client's channelfactory infrastructure through a series of constructors. This class also needs to implement the interface that defines the service contract. You can use the channel attribute distribution method of the base class to call the method connected to the service interface through the channel. The following code shows a specific example:

Class productsserviceproxy: clientbase <products. iproductsservicev2>, products. iproductsservicev2 {public productsserviceproxy (binding, endpointaddress Address): Base (binding, address) {} public list <string> listmatchingproducts (string match) {return base. channel. listmatchingproducts (MATCH);} public products. productdata getproduct (string productnumber) {return base. channel. getproduct (productnumber);} public int currentstocklevel (string productnumber) {return base. channel. currentstocklevel (productnumber);} public bool changestocklevel (string productnumber, short newstocklevel, string shelf, int bin) {return base. channel. changestocklevel (productnumber, newstocklevel, shelf, BIN );}}

You can instantiate the class and call its method like using a proxy object. The clientbase class provides the clientcredentials attribute. You can specify a specific credential for this attribute and transmit the credential to the service using the following code:

Productsserviceproxy channel = new productsserviceproxy (httpbinding, address); channel. clientcredentials. windows. clientcredential. username = "Fred"; channel. clientcredentials. windows. clientcredential. password = "pa $ w0rd"; channel. clientcredentials. windows. clientcredential. domain = "your PC ";

You can check the code generated using the svcutil utility. You can see that the code generated using the svcutil tool also transmits creden。 to the Service in the preceding way.

The clientbase class also has an advantage. It provides the close method to explicitly terminate the communication channel and immediately release the corresponding resources on the client without waiting for the. NET Framework Garbage Collector to execute these tasks.

One of the main purposes of sending messages to a service through programming is to provide an interoperability platform. You can build a WCF client program to communicate with other non-WCF technologies, such as services implemented by Java. In this case, if the administrator of the service host Program disables Publishing Service metadata, service developers cannot provide you with a C # code or. NET Framework component that contains the service contract. However, if you have a document describing the SOAP message accepted by the Service and the response message sent by the service, you can also use the WCF client to access the service; you can send messages directly to the service through channels. The channel is a very underlying but flexible implementation method. This method allows you to further understand how the client's WCF runtime converts method calls to the channel into soap messages. This is what we need to do in the following exercises.

send messages and process response messages on the client. 1. Disable the productsservice solution in Visual Studio. Open the simpleproductsservice solution in the * \ solutions \ WCF \ step. By. Step \ chapter11 \ simpleproductsservice folder. 2. Open the isimpleproductsservice. CS file under the productsservicelibrary project. Then find the isimpleproductsservice interface, which should be as follows: [servicecontract (namespace = "http://adventure-works.com/2011/07/19", name = "simpleproductsservice")] public interface isimpleproductsservice {[operationcontract (name = "listproducts")] list listproducts ();} the service contract defines only one operation: listproducts. Note the namespace and name of the service. WCF uses the service contract namespace and name in combination with the operation name to define a published SOAP message or activity. In this example, the service will accept and process the following active soap messages: http://adventure-works.com/2011/05/20/productsservice/listproducts. In addition, note that the return value of this method is list . Therefore, the service returns a SOAP message containing the serialized string list. 3. Open the programm. CS file under the productsclient project. The main method creates a default basichttpbinding object and an endpointaddress object. The endpoint URI is http: // localhost: 8010/simpleproductsservice/service. SVC. In the header of the file, add the following using statement using system. serviermodel. channles; 4. In the try segment, add the following statement

Endpointaddress address = new endpointaddress ("Http: // localhost: 8010/simpleproductsservice/service. SVC ");

Ichannelfactory <irequestchannel> factory = httpbinding. buildchannelfactory <irequestchannel> (); factory. open ();

The first line of the statement creates a channelfactory object for the client. The client uses this object to create a channel for sending and receiving messages. This channel uses the specified binding. The open method instantiate the channel factory, and then the channel factory creates the channel stack.

A channel implements its specified interface that supports message mode. One channel can be an input channel or an output channel. The input and output channels form a duplex channel. A specific form of the output channel is the request channel, and the corresponding input channel is the response channel. These interfaces are considered as specific representations of various channels. Whether these representations can be used as transmission channels depends on service factors. Service factors include the transmission channel type and its attribute value. If a TCP transmission channel uses the cache transmission mode, the TCP channel cannot be used as a response channel; in this case, it can only be used as a bidirectional duplex channel. The HTTP protocol uses the sending/receiving mode by default. The HTTP transmission channel forms a request channel on the client side and a corresponding channel form on the server side. The next step is to create a client channel stack that uses the channel factory and connects to the Service Listening address. 5. Add the following statement to create a channel

Irequestchannel channel = factory. createchannel (Address );

Channel. open ();

6. Now you can send messages and receive responses through the channel stack. You can create a message by using the createmessage method of the static method of the message class. When creating a message, you must make a careful version and request action.

Message request = message. createmessage (messageversion. soap11, "http://adventure-works.com/2010/06/29/SimpleProductsService/ListProducts ");

The SOAP message transmission specification has undergone many changes since its release. Different bindings in WCF support different version specifications. Basichttpbinding binding supports soap1.1 message transmission specifications. Messageversion. soap11, the first parameter of the createmessage method, indicates that the method will format the message according to soap1.1 specifications. If you use ws2007httpbinding to bind a message, you will use soap1.2 to format the message. The second parameter of createmessage consists of the Service namespace, service name, and operation corresponding to the service.

The createmessage method is an overload method. You can also use other methods to reload the data of the message body. If service operations require parameters or service configurations to generate soap error messages. When the request/response mode is used, the method for actually sending messages is the channel request method. In the next step, you will use this method to send messages. 7. Add the following statement to send the message reply = channel. Request (request); console. writeline (reply );

The request method will block the current thread until the service response message is received. The Response Message is returned to the client as the return value of the Request Method. After the application receives the response message, the client displays the message content directly on the console-without any conversion.

After receiving the response message, you can continue to send other requests to the service, but in our practice, the client will open a connection from the server. 8. Add the following statement

Request. Close ();

Reply. Close (); Channel. Close (); factory. Close ();

The message, channel, and channel factories all use resources. Therefore, when you stop using them, you need to disable them to release the resources they use.

9. Generate a solution and run it in the adjusted mode. In the product service host window, click Start to start the service. Press enter in the console of the client program. The client program sends a listmatchingproduct request to the service. The response message of the service contains a list of products. Then, the console displays the SOAP message that contains the product list: <S: envelope xmlns: S = "http://schemas.xmlsoap.org/soap/envelope/">
<S: Header/>
<S: Body>
<Listproductsresponse xmlns = "http://adventure-works.com/2010/06/29">
<Listproductsresult
Xmlns: A = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"
Xmlns: I = "http://www.w3.org/2001/XMLSchema-instance">
<A: String> AR-5381 </a: String>
<A: String> BA-8327 </a: String>
...
<A: String> VE-C304-S </a: String>
<A: String> WB-H098 </a: String>
</Listproductsresult>
</Listproductsresponse>
</S: Body>
</S: envelope> 10. Press enter in the console window to close the client program. In the product Host Program window, click "Stop" and close the window.

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.