C # create a WebService series (non-original)

Source: Internet
Author: User
Tags stock prices

In this article, I will introduce some basic knowledge about web service and how to use C # to create a web service. Through the article, we will also have a general understanding of WSDL, UDDI and the Future Web service.

In its. NET strategy, Microsoft publicized the Web service it promoted. Currently, Web services are in full swing, and various new technologies are emerging. The development of Web Services is building a bright future in the Internet age. In this article, I will introduce some basic knowledge about web service and how to use C # to create a web service. Through the article, we will also have a general understanding of WSDL, UDDI and the Future Web service.

  Why do we need web services?

In the past, distributed application logic used distributed object models by using basic structures such as DCOM, CORBA, and RMI, developers can still have the rich resources and accuracy provided by using local models, and can place services in remote systems.

Why do we have to worry about the web when we already have a favorite middleware platform (RMI, Jini, CORBA, DCOM, and so on? Middleware does provide powerful service implementation means, but these systems share a common defect that they cannot be extended to the Internet: they require that the service clients and the services provided by the system must be closely coupled, that is, a similar basic structure is required. However, such a system is often very fragile: if the execution mechanism at one end changes, the other end will crash. For example, if the interface of the server application changes, the client will crash. To expand to the Internet, we need a loosely coupled basic structure to solve this problem. In this case, the birth of Web Service is ushered in.

  What is Web service?

Web Service is a new Web application branch. It is a self-contained, self-describing, and modular application that can be released, located, and called through the Web. Web services can execute any function from simple requests to complex business processing. After deployment, other Web service applications can discover and call the services deployed by the application.

Web Service is an application that uses Web network technology and component-based development. Standard Internet protocols, such as Hypertext Transfer Protocol (HTTP) and XML, can be used to visually display functions on the Internet and enterprise intranets. Component-based object models such as DCOM, RMI, and IIOP have become popular for a long time. However, these models depend on a specific object model protocol. Web service extends these models so that they can communicate with Simple Object Access Protocol (SOAP) and XML to eradicate the obstacles brought by specific object model protocols. WebService can be considered as component programming on the web. (See 1)

Web Services basically use Hypertext Transfer Protocol (HTTP) and soap to make commercial data available online. It exposes commercial objects (such as COM objects and Java Beans) to soap calls over HTTP and performs remote function calls. Therefore, Web service users can call methods on the Web through soap and HTTP on remote objects.

Figure 1

Soap call is a kind of call that can cause the execution of Web Service component programs on location B. Then, the execution result of the program is returned to the user at location a in the form of an XML document.

In Figure 1, how do users in location a know the situations of users in location B? This involves a general standard. Service Description Language (SDL), Soap contract language (SCL), and network accessible Specification Language (nassl) all are XML language for this purpose. However, IBM and Microsoft recently agreed to use the Web Service Description Language (WSDL) as the standard for Web Services.

The structure of web service components is revealed through the Web Service Description Language.

  Tasks

The best way to learn about Web Services is to manually create an instance. We are all familiar with the stock quote service. NASDAQ and Dow Jones are famous examples. They all provide an interface to enter the company code and get the latest stock price. In this article, we try to design the same function.

  Tools for creating Web Services

In this article, we use the Ms. NET Framework SDK to implement this program.

A good integrated development environment (IDE) for creating web services is Visual Studio. NET. However, you can easily create a web service file using any text editor (Notepad, WordPad, Visual Studio 6.0 ).

Also, you must be familiar with the following concepts:

Basic knowledge of the Net Platform

C # basic knowledge

Basic knowledge of object-oriented concepts

  Create a Web Service

Next, we will use C # to create a web service named "securitywebservice. A Web service file will contain an extension in the form of. asmx. (Just like the file extension of Asp.net is. aspx)

<% @ WebService Language = "C #" class = "securitywebservice" %>

This statement tells the compiler that the program will run in Web service mode and the name of the C # class. At the same time, we want to access the Web Service namespace. Also, it is best to add a reference to the system namespace.

Using system; using system. Web. Services;

The securitywebservice class should inherit the functions of the web service class. Therefore, we added the following line of code:

Public class securitywebservice: WebService

Now we use our object-oriented skills to compile a C # class. C # classes are very similar to C ++ and Java classes. If you have C ++ and Java basics, this is just a piece of cake.

The Web Service under. Net can set some basic data types. Therefore, if we return data types such as "int", "float", or "string", It can automatically convert them into standard XML output. Unfortunately, in most cases, we need a type of dataset of the same entity. Here is an example. Our securitywebservice stock quote service requires the user to enter a company code, and then it will give the company's full name and the current stock price. Therefore, we need three pieces of information about a company:

Company Code (Data Type: string)
Company full name (Data Type: string)
Stock price (Data Type: Double)

We need to split up the data of a single stock quote. There are many ways to do this. Here we use the best enumerated data type. We use structs in C #, which is the same as structs in C ++. The Code is as follows:

Public struct securityinfo
{
Public String code;
Public String companyName;
Public double price;
}

Now we have completed all the modules required to establish the web service. Therefore, all the code is as follows:

<% @ WebService Language = "C #" class = "securitywebservice" %>

Using system;
Using system. Web. Services;

Public struct securityinfo
{
Public String code;
Public String companyName;
Public double price;
}

Public class securitywebservice: WebService
{
Private securityinfo security;

Public securitywebservice ()
{
Security. Code = "";
Security. companyName = "";
Security. Price = 0;
}

Private void assignvalues (string code)
{
// Use commercial components here
// Method call is used to obtain the required data
// In this program, I add a corresponding string to the corresponding code to facilitate display
// At the same time, I used a random number generator to generate stock prices

Security. Code = code;
Security. companyName = code + "Pty Ltd ";
Random randomnumber = new system. Random ();
Security. Price = double. parse (new system. Random (randomnumber. Next (). nextdouble (). tostring ("##.##"));
}

[Webmethod (description = "This method call will get the company name and the price for a given security code.", enablesession = false)]
Public securityinfo getsecurityinfo (string code)
{
Assignvalues (CODE );
Securityinfo securitydetails = new securityinfo ();
Securitydetails. Code = Security. Code;
Securitydetails. companyName = Security. companyName;
Securitydetails. Price = Security. price;
Return securitydetails;
}
}

 

Remember that this web service can be used in any way over HTTP. We may involve some sensitive commercial data in the code, but we don't want it to fall into the hands of others. The solution is to protect some logical functions so that users can only access some functions used to display data. To achieve this goal, we use the keyword "[web method]". The following is the sample code:

[Webmethod (description = "This...", enablesession = false)]

Public securityinfo getsecurityinfo (string code)

The access type of this function is public. The label "Description" is used to describe the functions of this web service. Because we do not need to store any session data, we set the session status to false.

Private void assignvalues (string code)

This is a function that should be logically protected. Because we do not want our commercial confidential data to be easily obtained on the Web, we set the function access type to private (Note: Here, even if you set the function access type to public, this function cannot be accessed in public because the keyword "[web method]" is not used ).

At this point, we can use the getsecurityinfo (string) function to obtain the latest stock price. For convenience, I added the company name to the company code. Also, the stock price is randomly generated.

Finally, we save the file in a directory controlled by IIS and the file name is "sampleservice. asmx ". The following figure shows the operation result:

Figure 2

The above is a Web page generated by. NET Framework. We didn't create this page (it is automatically generated by the system, so I don't need to write any code to create this page ). This function reduces our workload. Similarly, you can use the pagelets function of Asp.net or modify the webpage file to display the content of the page in different ways.

How to use this web service?

Now we will use this web service. First, we enter some values to obtain the stock sample price.

Figure 3

Press the invoke button to obtain the following XML document:

Figure 4

 

In this way, the Web Service provides users with the information they need. Because it is a document in XML format, we need to write the client to extract this XML document. The client can be of the following types:

1. A web page
2. A console or Windows Application
3. A mobile phone program described in WML language
4. A palm or Win CE Program Applied to PDA

You can directly use the http get method to call this web service. In this way, the first page will not appear, and you do not need to click the invoke button. Specific Method:

Http: // server/webservicename. asmx/functionname? Parameter = parametervalue

The method for calling our Web Service is:

Http: // localhost/work/aspx/sampleservice. asmx/getsecurityinfo? Code = IBM

So far, we have known how to create and use a web service with C #, but the task is not completely completed. We need to know how to find our Web Service on the Internet, and whether our web service can be included in a large search engine. To solve this problem, we need to create a "discovery" file.

  Create a file

Before accessing an existing web service, you must first find and integrate the web service. This process is the Web service discovery process. Through this discovery process, you will know what kind of service this web service can provide for you and how you interact with it. The file is an XML file with the. Disco extension. In practice, you do not have to create a discovery file for each web service. The following is an example of file discovery:

<? XML version = "1.0"?>
<Disco: discovery xmlns: Disco = "http://schemas.xmlsoap.org/disco/">
<SCL: contractref ref = "http: // localhost/work/aspx/sampleservice. asmx? SDL "/>
</Disco: discovery>

First, we name this file "sampleservice. Disco" and save it to the directory of the web service. If we create a web service under the "/work/aspx" directory, we can use more flexible "dynamic discovery. "Dynamic discovery" can automatically detect the "/work/aspx" directory and all *. Disco files in the subdirectory for us, saving us a lot of effort.

<? XML version = "1.0"?>
<Dynamicdiscovery xmlns = "urn: Schemas-dynamicdiscovery: disco.2000-03-17">
</Dynamicdiscovery>

You can find a usable file at http://services3.xmethods.net/dotnet/default.disco.pdf. Through analysis, we can find the required web service. However, you must know the exact URL of the detected file before obtaining the file. Otherwise, you still cannot find the file you want, so you certainly cannot find the Web service you want. Now we need to use a new technology-universal discovery, description, and integration (UDDI) to promote existing Web Services. UDDI is public and Internet-based. This technology is still in its initial stage, so it is constantly evolving. You can get reference on UDDI in http://uddi.microsoft.com.

  Publish this Web Service

Publishing a Web Service is simple. Similar to the Asp.net program, you only need to copy the. asmx file and. disco file to the corresponding directory, so that if everything works properly, this web service can work.

  The future of Web Service

The future of Web Service technology is quite bright. On the road to pushing forward Web Service technology, not only did Microsoft inject a lot of investment, but sun and IBM also expressed great interest. At the same time, there is also a soap toolkit developed for Apache and Java Web on the Internet. However, a lot of work needs to be done before the Web service starts. Especially in China, the Web Service technology started a step later than abroad, so it is necessary to seize the time and meet the challenges.

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.