A discussion on the combination of polymorphism and Web services

Source: Internet
Author: User
Tags add foreach format define header net string version
Web|web Service

This article reviews the concept of polymorphism and demonstrates XML Web services. The most important thing is that this article will teach you how to combine polymorphism with Web services.

   First, Introduction

You may know polymorphism, and perhaps you know Web services. But what about the polymorphism across Web services? This article reviews the concept of polymorphism and demonstrates XML Web services. The most important thing is that this article will teach you how to combine polymorphism with Web services.

   Second, polymorphism

Readers familiar with object-oriented programming (OOP) should be familiar with polymorphism, but not everyone is familiar with object-oriented programming. If you are the previous reader, you can skip to the "XML Web Services" section. If you are the latter, please continue reading.

Before the advent of object-oriented programming languages, if you want to print different types of data, you need to write multiple methods, such as Printinteger (int i), printstring (string s), and printfloat (float f). That is, you have to differentiate behavior and data types by naming them, because the OOP language appears as a C and does not allow you to write with the same name, even if they have different parameter types.

C + + came to implement the method overload. Therefore, you can write multiple methods, such as Printinteger (int i), printstring (string s), and printfloat (float f), and the compiler will automatically invoke the specific print method. Method overloading is supported by a technique called name mangling, in which the compiler replaces the original method name by combining the original method name with its parameters to produce a unique internal name. So, when you call print (1), the compiler may rename the Print method internally with a prefix that originates from the parameter type, so that print (1) may become i_print (1).

Method overloading is only one case of polymorphism. Name reorganization is a mechanism that supports method overloading. More generally, polymorphism is associated with inheritance. What is inheritance? Inheritance is a new class (called a subclass) that gets its own partial definition from an inherited class (called a parent class or superclass) while adding some new information of its own. If you overload the method in the same class, the data type must be different. If you overload the method under inheritance, the subclass can be exactly the same as the parent, and the name reformer generates the same reorganization name.

For example, suppose a superclass defines a print (int i) method and a subclass that inherits from it also defines a print (int i) method. When you have an instance of a subclass, use polymorphism to call Child.print (int), and when you produce an instance of a parent class, use polymorphism to call Parent.print (int). This is inherited polymorphism: the same name and signature but the class is different.

Inheritance polymorphism is achieved by using a different mechanism related to name reorganization. The compiler places the method in a place called a virtual method table (which is actually an array of methods). Each method has an index in the VMT, so when print (int) is invoked, the compiler is routed to the VMT to find the Print method and the intrinsic index of the class. This allows the compiler to invoke the correct method implementation. The compiler is responsible for managing all VMT indexes and class offsets.

In short, polymorphism allows you to define many methods with very similar names, where the names are often intuitively easy to remember. The OOP compiler will automatically understand which method to invoke based on the caller class. One of the great benefits of polymorphism is that you no longer have to write the following code (only descriptive language is used here):

If type of arg is integer then
Printinteger (ARG)
Else if type of arg is string then
Printstring (ARG)
Else if type of args is float then
Printfloat (ARG)


Now, with the OOP language, the above expression takes only one sentence:

Print (ARG)


The compiler's polymorphic mechanism calculates which version of the print method should be called by generating a method index (which is actually equivalent to the conditional statement above).

To understand the authoritative description of the working mechanism within OOP from a language perspective, refer to Bjarne Stroustrup's "the C + + programming Language" (isbn:0201700735) (Addison Wesley). Note that many OOP languages use mechanisms that are very similar to C + +.

   third, XML Web services

If you have an understanding of XML Web services and its applications, you should have no difficulty in understanding the techniques and motivations of XML Web services and skip to the next section, "Support polymorphism with Web services."

Distributed applications have become increasingly common over the past 10 years or so. Like many other types of engineering, the software industry undergoes a period of invention and standardization. XML Web Services is a standard based on HTTP and XML open protocols, not just Microsoft, but Microsoft does provide the basis. NET architecture and the implementation of XML Web services for its characteristics.

The basic idea is to add a webserviceattribute to the class that describes the Web service through your code, plus WebMethodAttribute attributes to the Web methods in the class or to the methods that allow consumers to invoke them. Microsoft's implementation technology is the use of reflection and code generation technology to generate proxy types and proxy code, which makes it easy to invoke distributed services and methods. In addition to generating proxy code,. NET architecture and Visual Studio also contain a wizard to proxy Web services and Web methods for you.

To create a Web service, run Visual Studio. NET, and then select File-new-project (This is the selected project type "Visual Basic Projects") and select "ASP.net Web in the template list from the New Project dialog box" Service. "

To run the sample Web service and Web method, remove the method provided by the Engineering Template Wizard HelloWorld the previous annotation section, and then run the scenario. To learn more about the generation and application of XML Web services, you can refer to the previous "VB today" column, especially the "building distributed Apps?" Use XML Web Service, not Remoting (mostly) (December 2004).

  Iv. adding polymorphic support for proxy classes based on XML generation

Now, turn your attention to the purpose of this article.

When you define parameters for a Web method and return parameters, a utility called the Network Service Discovery Language (WSDL) activates another tool called SPROXY. SPROXY uses reflection and CodeDom techniques to tick a definition for the type declared in your Web method, and then generate a proxy class for the composite type. For example, if you have a class called person, when the consumer uses the Web service, SPROXY will generate a person class for you. The advantage is that Web service producers do not have to send their proprietary code to consumers because consumers want to use their code. SPROXY did a job for them. By using proxy code, the commercial private business rules are protected while still achieving the purpose of selling-allowing customers access to the features provided by these rules.

The following code describes a person class and a generated person proxy.

Listing 1. The person class behind the Web service

public class Person
{
private string name;
Public person () {}

Public person (string name)
{
THIS.name = name;
}

public string Name
{
get{return name;
set{name = value;}
}

public string Getuppername ()
{
return name. ToUpper ();
}

public string Uppername
{
get{return Getuppername ();}
set{}
}
}

Listing 2. Proxy version of the person class generated by SPROXY

public class Person
{
<remarks/>
public string Name;
}

As you can see, none of the versions contain any private information. Web services do not automatically judge or require you to add your own technical protection-keeping private business rules is only a by-product, because the proxy class that the consumer gets is a structure that does not contain any methods.

Probably what SPROXY can do is reflect the type of Web method and convert the public properties into a common domain. This is sufficient for sending and receiving data between customers and servers via Web services.

In addition, strongly typed collections are converted to strongly typed arrays. For example, one from System.Collections.CollectionBase (for strongly typed collections, see the Visual Basic. NET power Coding, which I wrote) (Addison Wesley Company published) a derived Personcollection collection will be represented as an array person or person (). Paradox here: What if the person class is an abstract class and the purpose of creating the Personcollection collection is to include any derived classes such as employee or customer? Without some special help, the XML Web service will generate a person proxy class without knowing anything about employee or customer (see listing 3 below). This technically means that if you return a employees array to meet the person collection, the consumer program will still be compiled successfully but will crash at run time. Listing 3. Set personcollection and class person, Employee, and customer definitions

Using System;
Using System.Reflection;
Using System.Diagnostics;
Using System.Xml.Serialization;

Namespace Businesscollections
{
[Serializable ()]
public class PersonCollection:System.Collections.CollectionBase
{
public static personcollection CreateNew ()
{
personcollection persons = new Personcollection ();
Persons. ADD (New person ("Paul"));
Persons. ADD (New Customer ("David", "Cadyville"));
Persons. ADD (New Employee ("Kathy", 50000M));
return persons;
}

Public Person This[int Index]
{
get{return (person) List[index];
set{List[index] = value;}
}

public int Add (person value)
{
return List.add (value);
}

Public personcollection Select (type type)
{
personcollection persons = new Personcollection ();
foreach (person p in List)
{
if (P.gettype (). Equals (Type))
Persons. ADD (P);
}
return persons;
}

public void Dump ()
{
foreach (person on this)
{
Debug.WriteLine (String. Format (' Type: {0} ', person. GetType (). FullName));
Propertyinfo[] Properties = person. GetType (). GetProperties ();
foreach (PropertyInfo p in properties)
{
Try
{
Debug.WriteLine (String. Format ("Name: {0}, Value: {1}", P.name, p.getvalue (person, null));
}
Catch
{
Debug.WriteLine (String. Format ("Name: {0}, Value: {1}", P.name, "Unknown"));
}
}
}
}
}

public class Person
{
private string name;
Public person () {}

Public person (string name)
{
THIS.name = name;
}

public string Name
{
get{return name;
set{name = value;}
}

public string Getuppername ()
{
return name. ToUpper ();
}

public string Uppername
{
get{return Getuppername ();}
set{}
}
}

public class Employee:person
{
private decimal salary;
Public Employee (): Base () {}
Public Employee (string name): base (name) {}

Public Employee (string name, decimal salary): Base (name)
{
This.salary = salary;
}

Public decimal Salary
{
get{return salary;}
set{salary = value;}
}
}

public class Customer:person
{
private string City;
Public Customer (): Base () {}
Public Customer (string name): base (name) {}
Public Customer (string name, String city): Base (name)
{
this.city = City;
}

public string City
{
get{return city;
set{city = value;}
}
}

}

The focus of listing 3 is that employee and customer are derived from person but the Web service only understands the person collection. Also, for demonstration purposes, Personcollection creates instances of person, employee, and customer in the static method Personcollection.createnew.

If you want to write a Web method that returns an instance of a personcollection called Getperson (parameter list 4), SPROXY will only generate one delegate class person and the return type becomes person ().

Listing 4: Returns the WebMethod of a Personcollection instance:

[WebMethod]

Public Personcollection getpeople ()
{
return Personcollection.createnew ();
}

If listing 4 is all that you provide to consumers, though, their code compiles successfully, but when the person array returned from the Web method is initialized, the poor consumer will encounter a run-time error thrown soapexception. Finally, because you define other classes that are derived from person, you should also try to make these types available to your Web service consumer.

Now that you know everything about the problem, it's easy to change it. Use the XmlInclude attribute defined in System.Xml.Serialization to specify additional types-consumers also need to generate proxy classes for them. Add the XmlInclude attribute to the header of the class itself, initialize it with a type object--These types of objects are used for each additional type that requires a proxy. Listing 5 shows the header of the class for the Web service (which contains the Getpeople method) definition:

Listing 5: Make sure that the subtype is defined on the consumer side of the Web service by using the XmlInclude property

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Diagnostics;
Using System.Web;
Using System.Web.Services;
Using Businesscollections;
Using System.Xml.Serialization;

Namespace Service
{
<summary>
Summary description for Service1.
</summary>

[XmlInclude (typeof (Customer)),

XmlInclude (typeof (Person)), XmlInclude (typeof (Employee))]
public class Service1:System.Web.Services.WebService
{
Public Service1 ()
{
Codegen:this call are required by the ASP.net Web service
Designer
InitializeComponent ();
}

[Component Designer generated code]
WEB SERVICE EXAMPLE
The HelloWorld () example service returns the string
Hello World
To builds, uncomment the following lines then save and build
The project
To test this Web service, press F5

[WebMethod ()]

Public Personcollection getpeople ()
{
return Personcollection.createnew ();
}
}
}

In order to test network services and network methods, a console program can be generated. Select Project-Add Web Reference, and then add the network services above. Declare an instance of person (), and then activate the Web method.

   v. Summary

This paper introduces the problem of polymorphism of XML Web service environment. You can learn that proxy types do not contain methods and do not have to produce subtypes for Web service consumers-if you are careless it can easily break inheritance relationships.

If you include subtype parameters in your Web method, SPROXY will generate those types for the consumer. Otherwise, the XmlInclude property instructs the XML Web service tool to generate an extra type.

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.