Running (zssure): WCF learns to control WinForm host Program main interface control through event binding

Source: Internet
Author: User

Background:

WCF services need to be hosted into the appropriate running process, and there are four common types of hosts, namely, console programs, WinForm programs, IIS, and Windows services. Before learning old a blog and "WCF Comprehensive analysis" most commonly used is the console homestay, recently due to project requirements, need to call WCF services in the WinForm program, this blog post through a simple example to demonstrate the WCF in WinForm homestay. It also focuses on how to control the host UI control using event binding.

Preface

has been sticking to the C + + position, not very cold for new languages and technologies (such as Python, Java ee, Bigdata, AI). Self-thought "principle" are all figured out, is nothing more than the syntax slightly different, integrated API order of magnitude different, want to status quo. -In the final analysis, this is a kind of mental laziness and cowardice, especially when you switch from student context to working context and feel worried. the time slices that the brain can assign to each task are getting shorter, but unable to switch to multi-cpu/multi-core mode, and ' old and frail ', ' memory ' brain capacity is less, Khan σ (° °| | |) ︴ AH.
at the end of the rope, we seek change . Start writing a technology blog, transfer existing knowledge to other media to compensate for the growing lack of memory, explore new technologies, and improve your skills to compensate for this old CPU efficiency.
Book to the story, before the development of the network-type, distributed applications, mostly stay in C/s level. So in the Internet + era is already outdated, so through work and interest, began to dabble in WCF and Java EE, suddenly feel good tall, interesting, but WCF (or Java EE) are the previous technical system of the synthesizer, learning curve and its steep, Chew the book for half a month but always feel stuffy, not bright, but also need to add strength, make unremitting efforts.
The following is a simple record of the first learning of WCF experience, the text will give a WCF instance, the application scenario of instance simulation is:

Two WinForm terminal A and B,a host a WCF service, B calls the service to send a directive message to a, and display in a interface (in fact, similar to QQ chat)

The structure is as follows:


Introduction to WCF:

Microsoft from. NET3.0 began introducing the WPF, WCF, and WF three modules.

wpf,windows Presentation Foundation is the same display subsystem used by Microsoft for Windows, consisting of a display engine and a managed code framework. Windows Presentation Foundation unifies the way Windows creates, displays, and operates documents, media, and user interfaces (UIS), enabling developers and designers to create better visuals, different user experiences.
wcf,windows Communication Foundation is a distributed communication programming framework provided by Microsoft for the construction of service-oriented applications. Using this framework, developers can build enterprise-class, connected application solutions that are cross-platform, secure, reliable, and support transactional processing.
The wf,windows Workflow Foundation is a universal programming framework that can be used to create interactive programs that need to respond to signals from external entities. The basic feature of an interactive program is that it pauses an unknown length of time during execution to wait for input.

This blog is mainly used in the above three new features of the WCF, that is, the distributed communication framework. Windows Communication FOUNDATION,WCF is a framework that Microsoft has developed to build a unified programming model for service-oriented applications. WCF is a run-time environment and a set of APIs for creating new systems that deliver messages between services and clients.
WCF is message-based, and anything can be treated as a unified message in the programming model. Messages are passed between endpoints. An endpoint (endpoints) is where a message is sent or received (or sent and received). With WCF, you can send data from one service endpoint to another in an asynchronous message. Messages can be of a variety, simple to the XML format of a character or a word, complex to the binary data stream.

As a result of just dabble, blog post not too much to introduce the details of WCF, I did not understand thoroughly understand. be interested in exploring the blog or column of the Great god of WCF . From a beginner's immature point of view,

"Humble opinion 1": WCF is a framework, in the simplest context, as long as you are at both ends (server and client) to make a contract (contract), through the WCF binding can be called to each other, regardless of whether the two are in the same process, whether in the same host, whether on the same platform, WCF technology makes the cross-process, Cross-platform can be silent.

"Humble opinion 2": Let's just say that WCF greatly reduces the programmer's work on the underlying interaction by focusing on the logic of the business layer. It greatly reduces the difficulty of program deployment and makes the application more universal.

WCF Homestay:

Explain directly with examples, the smallest unit that manipulates the system to run and allocate resources is the process. However, in the WCF development process, the contract (contract, or convention), Service (contract implementation) are often published in the form of libraries, so in practical applications to use WCF services, the corresponding WCF libraries need to be hosted into the executable environment, there are four common ways- console programs, WinForm programs, IIS, and Windows Service. Here according to the previous use of the scene, using the WinForm program hosted WCF services, and give specific examples, other ways to refer to the old a blog .

WINFROM4HOSTWCFSERVICE:WCF Contract:

From a programmatic point of view, the contract (contracts) is the unified standard for service development in the WCF framework, which is a number of interfaces.
"Note": This is not accurate enough, strictly speaking ServiceContract is a bunch of interfaces, and in the interface of the relevant constraints, configuration requires other contract, such as the interface of the specific functions need to use OperationContract, The specific parameters of the function need to be datacontract, exceptions and errors in the function body need to be faultcontract, in addition to the messagecontract used in the specific interaction process.

For the sake of simplicity, consider the contract to be the relevant rule for constraining interfaces. For the sake of simplicity, it is envisaged that the services provided by the server are "receiving messages sent by the WinForm client and displaying them in a message window directly in the main server window using the MessageBox." It is important to note here that the WCF contract class established here is a traditional C # class library in which the main UI interface is actively triggered by triggering a popup message after receiving a request from a client. This is going to involve the C # rule that only the main UI thread that creates the control can operate on the WinForm project. So how do we make it work? After searching for some data, it is found that the usual event bindings can be used in the contract service class of WCF. The specific code is as follows:
"– Service Contract class –"

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;namespace WCF.WcfContract{[ServiceContract(Name="WcfNotify")]public interface INotify2WinForm{[OperationContract]void Notify2WinForm(string message);}}


"– Service Contract Implementation class –"

using System;using System.Collections.Generic;using System.Linq;using System.Text;using WCF.WcfContract;using System.ServiceModel;namespace WCF.WcfService{public delegate void DisplayMessage(string mes);[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]public class NotifyService:INotify2WinForm{public DisplayMessage displayMessage;public void Notify2WinForm(string message){if (!string.IsNullOrWhiteSpace(message)){if (null != displayMessage)displayMessage(message);}}}}


"Note 1": when establishing contract and service specific implementation classes, you need to add System.ServiceModel references in your project
"NOTE 2": ServiceContract You must add the Instancecontextmode=instancecontextmode.single setting or the WCF service will not start properly

WCF Homestay:

Boarding is the creation of an executable environment, and then invoking the WCF Service class library, the DLL dynamic library. Here we are building a Windows Forms application, the WinForm program. There are only two buttons in the program interface to start and close the WCF service. The interface looks like this:

Here the code is used to implement the WCF service, and the implementation code is as follows:

NotifyService wcfService = new NotifyService();wcfService.displayMessage = this.DisplayMessage;host = new ServiceHost(wcfService);WSHttpBinding httpBinding = new WSHttpBinding(SecurityMode.None);host.AddServiceEndpoint(typeof(INotify2WinForm), httpBinding, "http://localhost:8900");NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None);host.AddServiceEndpoint(typeof(INotify2WinForm), tcpBinding, "net.tcp://localhost:1700/");host.Open();


WCF client:

For demonstration convenience, you did not use SvcUtil.exe to add a WCF service and add a reference to the service contract project directly in the client project. The channel invocation WCF service is then created directly in the main program using coding, with the following code:

EndpointAddress edpHttp = new EndpointAddress("http://localhost:8900/");EndpointAddress edpTcp = new EndpointAddress("net.tcp://localhost:1700/");WSHttpBinding httpBinding = new WSHttpBinding(SecurityMode.None);ChannelFactory<INotify2WinForm> factory = new ChannelFactory<INotify2WinForm>(httpBinding);INotify2WinForm channel = factory.CreateChannel(edpHttp);channel.Notify2WinForm("WinForm4WCFTest-zssure");((IClientChannel)channel).Close();
Summarize:

The actual test results are as follows: Start the WCF Host program WINFORM4HOSTWCF, click the Start WCF button, and start the client winformclient4wcftest. When you enter any string in the window, such as Zssure test WCF 2015/04/04, when you click the TESTWCF button, you see the WINFORM4HOSTWCF interface pop-up message window that displays zssure test WCF 2015/04/04. The concrete result diagram is as follows:


"Zssure":

Many other errors occur during this presentation, such as when the client clicks TESTWCF again when the WINFORM4HOSTWCF window is not closed, and the interface is stuck ; If the MessageBox window is not closed for a long time, a timeout response error window pops up . This shows that the WCF framework of its underlying mechanism is very cumbersome, although easy to use but to open a stable, suitable for specific scenarios of the application needs to have a wealth of practical experience, and continue to work hard, there is time to analyze the two errors in detail. Please look forward to ...

"Source Download":

"GitHub": source code Download "Note": The recent attack on GitHub, upload may be delayed, please wait patiently ...
"CSDN": source code Download




[Email protected]
Date: 2015-04-04

Running (zssure): WCF learns to control WinForm host Program main interface control through event binding

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.