C # A simple WCF example

Source: Internet
Author: User

 

I learned about WCF from Silverlight. Well, it is really a bit difficult for me to learn about it, but it is not called. Here we will try to implement the most basic and simple WCF example at 1.1, this does not involve endpoint, binding, element, asynchronous call, serialization, or other concepts that are hard to understand, simply follow the default settings and use the simplest code to display the most basic applications of WCF.

Step 1: Create an empty solution, create a WCF Service Application Project (use the default name) to simulate the server, and create a console application project (name changed to consoleapp) to simulate the client.

 

Step 2: briefly analyze the wcfservice1 project. The project content is as follows:

In a word, this project simulates the server. The service1.svc file encapsulates the service reference provided to the client. The service1.svc. CS file contains the specific implementation of service reference. But here, because the main content in the service1.svc. CS file-service1 class is inherited from the iservice1.cs file's iservice1 interface, the first part of the play is half the content to the iservice1.cs file.

First, check the iservice1.cs file,It can be seen from the name that this is an interface file, which defines some interfaces and the interface declares some methods. I added two classes public class student1, public class student2, and a method public student1 student1class () for testing. The Code is as follows:

View code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. runtime. serialization;
5 using system. servicemodel;
6 using system. servicemodel. Web;
7 using system. text;
8
9 namespace wcfservice1
10 {
11 // Note: You can use the "RENAME" command on the "refactoring" menu to change the Interface Name "iservice1" in the Code and configuration file at the same time ".
12[Servicecontract]
13 public interface iservice1
14 {
15
16[Operationcontract]
17 string getdata (INT value );
18
19 [operationcontract]
20 compositetype getdatausingdatacontract (compositetype composite );
21
22 [operationcontract]
23 student1 student1class ();
24
25 // todo: add your service operation here
26}
27
28 [datacontract]
29 public class student1
30 {
31 string STR = "from iservice1's student1 ";
32
33 [datamember]
34 Public String STR {set {STR = value;} get {return STR ;}}
35}
36
37 [datacontract]
38 public class student2
39 {
40 string STR = "from iservice2's student1 ";
41
42 [datamember]
43 Public String STR {set {STR = value;} get {return STR ;}}
44}
45
46 // use the data conventions described in the following example to add a composite type to a service operation.
47 [datacontract]
48 public class compositetype
49 {
50 bool boolvalue = true;
51 string stringvalue = "hello ";
52
53 [datamember]
54 public bool boolvalue
55 {
56 get {return boolvalue ;}
57 set {boolvalue = value ;}
58}
59
60 [datamember]
61 Public String stringvalue
62 {
63 get {return stringvalue ;}
64 set {stringvalue = value ;}
65}
66}
67}

The above code should pay attention to the following aspects:

1,Service Contract

The iservice1 interface is prefixed[Servicecontract]This means to declare this interface (including the class that inherits this interface) as a service contract. The service contract is for the client, that is, this interface is exposed to the client, this interface is available to clients. But the visible interface does not express the methods declared in the visible interface. This is two different things (The reason is very simple, even if the interface is visible, but some of the methods are visible and some are invisible. If you want to declare the method as visible to the client, you must add[Operationcontract],This is also called a service contract. Conclusion: There are two types of service contracts. [servicecontract] declares interfaces and classes that are visible to the client. [operationcontract] is the methods in the specific declaration class that are visible to the client.

2. Data contract

The class compositetype that comes with the interface and our custom class student1 and student2 are added before[Datacontract]This class is declared as a data contract, so that the client can use this class to define variables. The class mentioned here is slightly different from the specific content referred to in the above class. The above class is biased towards calling methods in the class, classes here tend to be used to define variables as a type (such as int string. The class is visible to the client, but the fields and variables in the class are not necessarily (the principle is the same as described above). To expose the fields and variables on the client, add[Datamember].However, you cannot add [datamember] to a method (such as a constructor) because the function can only be declared as a service contract (with [operationcontract]). the service contract can only be declared under [servicecontract. Summary: There are two types of data contracts. [datacontract] declares classes or structures, and [datamember] declares specific fields or attributes in a class or structure (recommended attributes) visible to customers.

 

Let's take a look at the service. SVC. CS file.We can see that it only defines a class service1 that inherits the iservice1 interface. The main content is the method declared in the iservice1 interface. The Code is as follows:

View code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. runtime. serialization;
5 using system. servicemodel;
6 using system. servicemodel. Web;
7 using system. text;
8
9 namespace wcfservice1
10 {
11 // Note: You can use the "RENAME" command on the "refactoring" menu to change the class name "service1" in the code, SVC, and configuration file at the same time ".
12
13 public class service1: iservice1
14 {
15 Public String getdata (INT value)
16 {
17 return string. Format ("You entered: {0}", value );
18}
19
20 public compositetype getdatausingdatacontract (compositetype composite)
21 {
22 if (composite = NULL)
23 {
24 throw new argumentnullexception ("composite ");
25}
26 if (Composite. boolvalue)
27 {
28 composite. stringvalue + = "suffix ";
29}
30 return composite;
31}
32
33 public student1 student1class ()
34 {
35 return NULL;
36}
37
38
39}
40
41}

No [servicecontract] or [operationcontract] Declaration is added before the classes or implementation methods defined in the class, because the interface inherited by the class has been declared, therefore, the class does not need to declare [servicecontract], and the method to implement the interface does not need to add [operationcontract].

Maybe you have a problem, that is, do you want to add your own method lines in this class? The answer is yes, but it does not make sense. Because the method in this class is used for the client as the server (which can be considered as this), we need to add [operationcontract] before the declared method. but only the methods in the class with the [servicecontract] attribute can be like that, because the class inherits an interface with the [servicecontract] attribute, therefore, this class does not need to be added with the [servicecontract] attribute (already available). In a word, it is unnecessary in the class that inherits the interface that implements the service contract. Add your own method. Add it to the interface first.

Of course, if you do not need an interface (you do not need an interface, but use an interface to be more object-oriented) and directly define a service contract in the class, simply copy the [servicecontract] and [operationcontract] in the interface.

 

Step 3: analyze the eagleapp Project

 

In a word, the thing in the red box is called service reference, that is, the client, that is, it can call the methods and custom types provided by the server. The method is as follows:

Right-click the leleapp project and choose add service reference (use the default name). A box is displayed:

Click "discovery" on the right to retrieve the current service and display it on the left, and display the address as well. Click the triangle on the left of the Service found in the service on the left. It is opened at the first level. It is service1 class, And iservice1 inherited by service1 class! On the right is the method that the Service provides to the client for calling!

Open the program. CS file in consoleapp. The code in it is very simple. Define a student1 variable, and then obtain a property value and output it.

View code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. runtime. serialization;
6
7 namespace leleapp
8 {
9 class Program
10 {
11 static void main (string [] ARGs)
12 {
13 // defines the Communication Pipeline client, which is used to call the method provided by the server.
14 servicereference1.service1client client = new servicereference1.service1client ();
15 client. student1class ();
16
17
18 // The class provided by the server to the client
19 servicereference1.student1 Stu = new servicereference1.student1 ();
20 console. writeline (STU. Str );
21 console. readkey ();
22
23
24}
25}
26}

 

Servicereference1 (actually a namespace) is the name of the service reference just added. When servicereference1 (Sometimes, if the type you want is not displayed, right-click the wcfservice1 project and choose "regenerate". Then, right-click servicereference1 of the consoleapp project and choose "Update Service reference". This is easy to forget, this is the case for every modification made to the server.). The figure is as follows:

It also defines a communication pipeline. This is probably to encapsulate the methods that can be referenced by the client provided by the server into a class, through which the methods can be called, for details, see the code.

Finally, press F5 to run. Is there any problem? No output? This is normal. If you want to see the output result, You can first assign a value to the STR attribute (STU. Str = "123 ";). Hey, that's all done.

 

There are two other problems:

1. Two Classes of student1 and student2 are customized in the iservice1 interface. Why does the smart sensing after servicereference1. only the student1 type is input, but not the student2 type? Because there is a public student1 student1class () method in the iservice1 interface, the return value of this method is of the studnet1 type, which is the difference .... This is the type you want to use on the server. In addition to the [datacontract] Declaration, there is also a service contract (method) that returns this type. I don't know why .. Answer

2. The STR attribute in student1 has a get {return STR;} method, while the STR field has a default value. Why is it in program. after a student1 class variable is defined in CS, is it blank when getting the value of the STR attribute and outputting it? That is to say, the default value of the property is lost! Why? I don't know. Please find the answer...

Later, some netizens suggested that the serialization may be the cause. Well, it should be the reason. after learning the specific principles, I will analyze them again...

 

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.