WCF 4.0 advanced series-Chapter 1 Use callback contract to publish and subscribe to events (Part 2)

Source: Internet
Author: User
ArticleDirectory
    • Notify the client of the result of one-way operation using the callback contract
    • Use callback contract to implement event mechanism
A callback contract is used to notify the client of the results of one-way operations. A callback contract is used to provide a service that notifies the client of one-way operations without returning any information. Program . The example in this section is based on the previous product price change scenario. When the client program calls the changeprice operation of the productsservice service, when the price of the product in the database is updated, the service calls back the client and notifies the client that the price has changed. Exercise: Add a callback contract for the productsservice service and add an operation to call the callback. use Visual Studio to open productsservicev3.sln. The solution is in WCF \ step. by. under the step \ solutions \ chapter16 \ productsservicev3 folder. This Service implements listproducts, getproduct, currentstocklevel and changestocklevelcaozuo. In addition, it also contains a new operation changeprice. The client program can call this operation to change the product price. In addition, the solution contains a WPF program that hosts the service and a client program used to test the produtsservice service. 2. Generate and run the solution. In the products service host window, click Start. After the service is started, press enter in the console window of the client. The client connects to the service, first displaying a list of products, then displaying the details of the product FR-M21S-40, changing the price of the product, and finally displaying the updated price. When the client program ends, close the console window of the client. In the products service host window, click STOP to stop the service, close the Host Program, and return to visual studio3. in the solution window, open the programm. CS file under the productsclient project. View Code . This method creates an instance of the client class and then runs the testproductsservice method of the instance. Use the testproductsservice method to create a proxy object, connect to the productsservice, and then perform the listporucts and getproduct operations. The testproductsservice method also calls the pricechange method to update the price of a specified product. The changeprice operation always blocks the client from calling it before the price of the product is updated in the database. After the product price is updated, this operation returns a Boolean value to the caller to indicate whether the product price is updated. Because this operation takes some time to update the database, you will change it to a one-way operation, and create a callback contract for the productsservice Service, using this callback contract to notify the client of the operation results. This policy allows the client to continue running without waiting for the execution of the pricechange operation to complete. 4. In the solution browser window, open the iproductsservice. CS file under the productsservice service. Add the following callback contract: the callback contract only contains an onpricechanged operation. You will change the changeprice operation in the productsservice service in subsequent steps. The purpose of this operation is to notify the client that the price of the product passed in as a parameter has been changed. Note that this operation is a one-way operation. It only notifies the client and does not return any other response. 5. Modify the servicecontract feature of the iproductsservicev3 interface to reference the callback contract defined in step 2. Because the callbackcontract attribute must be of type, the above Code uses the typeof operation to return the type of the iproductsservicev3callback interface. 6. In the iproductsservicev3 interface, modify the definition of the changeprice operation and mark the operation as one-way operation. One-way operations cannot return values. Therefore, change the return type to void7. open the productsservice. CS file and find the changeprice method. This method uses the new product price to update the adventureworks database. If the update is successful, true is returned. Otherwise, false is returned. Change the return type of this method to void. And modify return false or return true to return. 8. To generate a productservice project, follow these steps to implement a callback contract in the client program, but first you need to generate a proxy class for the client. Exercise: Generate client proxy objects and implement callback Contract 1. use the following steps to generate proxy class 1 for the client program ). open the Visual Studio command line tool and switch to the chapter16 \ productsservicev3 \ productsservice \ bin \ DEBUG directory 2 ). in Visual Studio command line tool, enter the following command svcutil productsservice. dll3 ). run the following command svcutil/namespace :*. productsclient. productsservice *. WSDL *. XSD/out: productsserviceproxy. CS2. make the Visual Studio command line open; then return to Visual Studio. In the productsclient project, Delete the existing productsserviceproxy. CS file, and add the generated productsserviceproxy. CS file to the productsclient project. 3. Edit the program. CS file under the productsclient project. Modify the client class to implement the productsservicecallback and idisposable interfaces. Productsservicecallback is the callback contract interface defined in the proxy object. Therefore, the client class must implement this interface. 4. add the onpricechanged Method 5 after the testproductsservice method in the client column. after the onpricechanged method, add the dispose method 6. in the testproductsservice method, modify the declaration of creating a proxy object: The above code is a common instancecontext object, which references the client object and is passed into the connection object as a parameter. Note that the name of the endpoint used for the connection has changed (ws2007httpbinding_iproductsservicev3 is used now). In the subsequent steps, you will add ws2007httpbinding_iproductsservicev3 endpoint definition to the client configuration file. 7. In the testproductsservice method, find the code snippet that calls the changeprice method of the proxy object in if/else. Because the new changeprice operation is a one-way operation, it does not return any value. Change this code and remove the IF/else process. 8. After the catch code, delete the Declaration to close the proxy object, because the dispose method is used to close the proxy object. 9. In the main method of the programm. CS class, reconstruct the life of the client object, call the testproductsservice method, and wait for the user to press enter to end the program. 10. regenerate the solution. Exercise: configure the WCF Service and client program to use wsdualhttpbinding to bind 1. in the productsservicehost project, use the service configuration editor to edit the app. config2. in the configuration panel, expand the service folder and expand Products. productsserviceimpl service, expand the endpoint folder, right-click the ws2007httpbinding_iproductsservcie endpoint, and click Delete endpoint. In the service configuration editor dialog box, click confirm to delete. 3. On the configuration panel, right-click the endpoint folder and click Create service endpoint. Create a new endpoint according to the following table.
Attribute Value
Name Wsdualhttpendpoint_iproductsservice
Address Http: // localhost: 8010/productsservice/service. SVC
Bind Wsdualhttpbinding
Contract Products. iproductsservicev3
4. save the configuration file and exit the WCF Service configuration editor. in the productsserviceclient project, use the service configuration editor to edit the app. config6. in the configuration panel, expand the client folder, right-click the endpoint folder, and click Create new endpoint to create a new endpoint. Set the new endpoint according to the following table.
Attribute Value
Name Wsdualhttpendpoint_iproductsservice
Address Http: // localhost: 8010/productsservice/service. SVC
Bind Wsdualhttpbinding
contract productsclient. products. iproductsservicev3
Unlike the service host program, you can retain the existing client endpoint on the client. 7. Save the location file and exit the WCF Service configuration editor. 8. Start the project in non-adaptive mode. In the product service host window, click Start. Then, press enter in the console window of the client. The client first displays a list of products, then the TV FR-M21S-40 product details, and then calls the changeprice operation to increase the price of the product by $10. Note that after test 3 starts, the message "callback from service: price of LL mountain frame-sliver, 40 changed to $274.05" will be displayed ". The message is displayed because the service calls the onpricechanged operation. Using the callback contract to implement the event mechanism callback contract allows the service to confirm that the client program has changed the product price, but the client instance that accepts the confirmation message may already know this, because the client initiates the price change operation. Undoubtedly, it is very useful to notify other concurrent client programs that the price has changed. You can use callback to implement an event mechanism. The Service publishes events and provides operations for the client program to subscribe to these events or cancel the subscription. When an event occurs, the Service uses a callback contract to send messages to each client that subscribes to the event. To achieve this, the Service does not hesitate to reference each client instance. In the following contact, you will modify the produtsservice service to activate the client program by subscribing to the operation to pay attention to the price changes of products of interest. The purpose of this operation is to simplify the reference of the cache client instance. When the service calls the onpricechanged operation, these customers but instances will be used. You will also add an unsubscribe operation to enable the client program to cancel the price and upgrade the subscription. Exercise: Add a subscription and a smile subscription to The productsservice service. 1. Open the iproductsservice. CS file under the productsservice project in Visual Studio. 2. Add the renewal time and event to the iproductsservicev3 service contract. The client program will use the subscribetopricechangedevent operation to pay attention to the price changes of the products you are interested in. 3. open productsservice. in the CS file, add the following private variable: The productsserviceimpl class adds the client callback reference of the Service to the list for each client instance that is interested in the product. 4. Add the subscribetopricechangedevent method to obtain the reference of the callback contract corresponding to the client instance that calls the changeprice operation and saves it in the subscription list. If the reference of the callback contract already exists in the list, the reference of the callback contract is not added to the List. 5. Add the specific implementation of the unsubscribetopricechangedevent method. The above method removes the callback reference for the client instance that calls the changeprice operation from the list. 6. Add the following private method to the productsserviceimple class. This method traverses all callback references in all the subscription lists. If a reference is found and the reference is valid (the client instance is still running), this method calls the onpricechanged operation, and pass the corresponding product as a parameter to the onpricechanged operation. If the reference is invalid, the reference is deleted from the subscription list. 7. In the changeprice method, delete the declaration that gets the callback reference corresponding to the client program, and delete the code that calls the onpricechanged method. Instead, create a productdata object to save and modify the details of the product, and then call the raisepricechangeevnet method. When the client program instance changes the price of a product, all client program instances subscribed to the price change time will be notified of the onpricechanged method execution. 8. regenerate the productsservice project exercise: update the WCF client program to subscribe to the price change event 1. regenerate the client proxy class 2. Close the Visual Studio command line tool window and return to Visual Studio. Delete productsserviceproxy from the productsclient project. CS file, and add the new version of productsserviceproxy generated in the previous step. CS file 3. open the programm of the productsclient project. CS file, add the code that calls the subscribetopricechangeevent operation. Whenever the client program instance updates the price of a product, the service will call the onpricechanged method of the client instance. 4. regenerate the productsclient project. Exercise: test the price change event of the productsservice service. 1. In the solution browser window, right-click the productsservicehost project, select adjustment, and click Create new instance. In the productsservice host window, click Start to start the service. 2. In the windows browser, go to the \ WCF \ step. By. Step \ solutions \ chapter16 \ productsservicev3withevents \ productsclient folder. In this folder, there is a command line file named runclients. This command file allows you to run the productsclient program three times at the same time and opens a new window each time. The content of this file is as follows: start bin \ debug \ productsclientstart bin \ debug \ productsclient3. double-click runclients. CMD file, three console windows are displayed, and each window creates a client program instance. In a console window, press enter, wait for the product list to appear, display the details of the FR-M21S-40 product, and then change the price of the product. Confirm the message of the callback operation. Keep the current control window open. 4. In the other two console windows, press Enter. Wait for the product list to display the details of the FR-M21S-40 product and change the product price. Confirm the message of the callback operation. Note that the message for the second callback operation also appears in the first Console window. In addition, the first window also shows the product price updated by the second Console window. 5. In the last Console window, press Enter. Confirm that the client instance has updated the product price and returned a callback message. Then you can find that the first and second console windows also output callback messages. Up to now, three callback messages have been displayed in the first Console window. 6. Press enter in each console window to close the client program. In the productsservice host window, click the stop button to close the service and close the productsservice window. Delivery Model of publishing and subscription Using callback contracts can easily implement the WCF-based publishing and subscription services. You should be aware that the environment you configured in the previous exercise is a well-configured and relatively perfect running environment. If you implement such a system in a large enterprise or internetzhong, you should consider security and stability, in addition, the impact of the selected model on the client program of the WCF Service callback should be considered. Generally, the publishing and subscription systems adopt three common models. You can build a WCF System Based on any model. Each model has its own advantages and disadvantages. Push Model This model is the model you used in the previous exercises in this chapter. In this model, the publisher (WCF Service) sends messages directly to each subscriber (WCF client program) through the operations in the callback contract. The service must have sufficient resources to call back a large number of subscribers at the same time. When the callback operation returns data, the service needs to generate a new thread for each subscriber, or use one-way operation for callback when the callback operation does not return data. The main weakness of this method is security. The callback operation of the service calling client may be blocked by the Client Firewall. Drag Model With this model, the publisher updates unique and trusted third-party service information when an event occurs. Each subscriber periodically queries whether the information of a third-party service has been updated. This model reduces firewall problems, but the requirements for subscribers are more complex. Using this model may also face scalability problems-when a large number of subscribers frequently query third-party services. In addition, if a group subscriber does not frequently query third-party services, the client may miss the event. Man-in-the-middle model
This model is a combination of the previous two models. The publisher updates a unique and trusted third-party service when time occurs. Third-party services are placed in a specific location, such as a network in which customers trust services that do not send events or subscribe to events. The subscriber registers for an event in a third-party service instead of subscribing to the event directly at the original service.

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.