Essentials for using custom classes in WebService)

Source: Internet
Author: User

Http://hi.baidu.com/cjhong_520/item/d7d1d595e4c048d91b49dfa9

A recent project used WebService to call the business layer class. At the beginning, it encountered a little trouble. After two days of summarization and practice, finally, we can summarize the handling methods for many common cases.
I don't know how to deal with it. It may be too basic, so I don't think it is a problem. I did not find any related posts in my blog.
To be honest, I have not actually developed any projects involving WebService before. At most, I would like to look at msdn and write a little bit.ProgramAt that time, no problem was found, because the passed parameters and return values are basic data types, so I did not find the problem mentioned in this article-using custom classes.
The so-called custom class does not know whether it is clearly expressed. Here it refers to the model-layer entity class in petshop.
For exampleCode:
Using system;
Using system. collections;
Using system. Collections. Generic;
Using system. text;

Namespace Model
{
[Serializable]
Public class student
{
Private string stuname;

Public student ()
{}

Public String stuname
{< br> get {return this. stuname ;}< br> set {This. stuname = value ;}< BR >}

the content transmitted by WebService must be serializable, whether it is a parameter or a return value. The entity class student defined above indicates [serializable] before the class definition to indicate serializable. However, when an entity class set is involved, if ilist is used for representation, an error occurs, because ilist cannot be serialized. In this case, we can use system. collections. objectmodel. collection to indicate a collection of object classes. Two possible entity classes and entity classes are provided here. The following describes various processing methods:
1. The object class set is passed as object.
in this case, we must use the entity class in WebService to pass the object [] corresponding to the object class set, and the essentials parameter type in WebService is arraylist.

for example, the essentials in WebService are:
[xmlinclude (typeof (student)]
[webmethod]
Public String hellostus (arraylist stulist)
{< br> BLL. class1 CLS = new BLL. class1 ();
return Cls. getname (stulist);
}

do not miss the line [xmlinclude (typeof (student, otherwise, the entity class in WebService will not be referenced in the presentation layer.
at this time, add web references to the presentation layer. The calling code in the presentation layer is as follows: (refer to the button#click () essentials in the demo)
/** //


// you must use the entity class in WebService to pass the object class set as object, the parameter type in WebService is arraylist, and provides a public class to convert the set to object []
///

///
//
private void button#click (Object sender, eventargs e)
{< br> string STR = "";

Localhost. Student stuinfo1 = new localhost. Student ();
Stuinfo1.stuname = "lxinxuan ";
Localhost. Student stuinfo2 = new localhost. Student ();
Stuinfo2.stuname = "www.cnblogs.com/lxinxuan ";

Ilist <localhost. Student> stulist = new list <localhost. Student> ();
Stulist. Add (stuinfo1 );
Stulist. Add (stuinfo2 );

Object [] array = This. converttoarray <localhost. Student> (stulist); // This is a generic essentials for converting a set to objec [].
STR = Ser. hellostus (array); // pass object []. The returned value is the value of stuname.

MessageBox. Show (STR );
}
// This is a generic essentials for converting a set to objec []
Private object [] converttoarray <t> (ilist <t> tlist)
{
Object [] array = new object [tlist. Count];
Int I = 0;
Foreach (t in tlist)
{
Array [I] = T;
I ++;
}
Return array;
}

2. Pass a single object class and use the entity class in WebService
In this case, it can be seen as a special case of Case 1-an array with only one element.
Of course, in this case, we can use the entity class in WebService.
First look at the code in WebService:
[Xmlinclude (typeof (student)]
[Webmethod]
Public String hellostu (student stuinfo)
{
Return stuinfo. stuname;
}

You must also add this line of code [xmlinclude (typeof (student)].
Then the call code is:
/** // <Summary>
/// Transfer a single object class using the entity class in WebService
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void button2_click (Object sender, eventargs E)
{
String STR = "";
Localhost. Student stuinfo1 = new localhost. Student (); // note that the entity class in WebService is called here, instead of the entity class in model. Otherwise, an error occurs.
Stuinfo1.stuname = "lxinxuan ";
STR = Ser. hellostu (stuinfo1); // transmits the entity class in WebService
MessageBox. Show (STR );
}

3. Transfer collection composed of object classes. This is similar to Case 1, but the transfer type is different. For more information, see.
In this case, you must modify the code of reference. CS, but each update must be modified again, and each class must be modified, which is troublesome! I don't know which of the following tips I have come up with, but I can modify the reference. the CS Code has already demonstrated the spirit of research and encouraged me.

give the necessary code in WebService:
[webmethod]
Public String hellostusbylist (collection stulist) // here the parameter type is collection
{< br> BLL. class1 CLS = new BLL. class1 ();
return Cls. getname (stulist);
}

the essentials parameter is collection. After WebService is added, reference. the corresponding essentials parameter in CS is changed to student [], array !! WebService and array are really close to each other... Change the parameter type of the essentials hellostusbylist in reference. CS to collection , as shown below.
presentation layer call code:
/** //


// transmits a collection composed of entity classes by modifying the reference. CS code, but it must be modified again after each WebService update, and each class must be modified, trouble
//

//
//
private void button3_click (Object sender, eventargs e)
{< br> string STR = "";

Localhost. Student stuinfo1 = new localhost. Student ();
Stuinfo1.stuname = "lxinxuan ";
Localhost. Student stuinfo2 = new localhost. Student ();
Stuinfo2.stuname = "www.cnblogs.com/lxinxuan ";

Collection <localhost. Student> stulist = new collection <localhost. Student> ();
Stulist. Add (stuinfo1 );
Stulist. Add (stuinfo2 );

STR = Ser. hellostusbylist (stulist); // by default, the main parameter of hellostusbylist is student []. You can manually change it to collection.

MessageBox. Show (STR );
}

4. serialize an object class set to a string in XML format, and then deserialize it into a collection in WebService <> (Note: it cannot be ilist <> ), and then pass it to the business layer object.
[Modification: Boyou proposed that binary serialization can be used. Indeed, XML serialization and binary serialization are both possible here, But XML serialization is used only for convenience of tracking information during debugging. It is not listed here. Thank you! "invalid code"]
[Webmethod]
Public String hellostusbycollection (string sxml)
{
Bll. class1 CLS = new BLL. class1 ();
Collection <student> stulist = Cls. deserializercollection <student> (sxml, typeof (collection <student>); // deserialize to collection first
Return Cls. getname (stulist );
} The code for deserializercollection is as follows:
/** // <Summary>
///
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "sxml"> </param>
/// <Param name = "type"> </param>
/// <Returns> </returns>
Public Collection <t> deserializercollection <t> (string sxml, type)
{
Xmlreader reader = xmlreader. Create (New stringreader (sxml ));
System. xml. serialization. xmlserializer serializer = new system. xml. serialization. xmlserializer (type );

Object OBJ = serializer. deserialize (Reader );
Return (collection <t>) OBJ;
}

The calling code for the presentation layer is as follows:/** // <Summary>
/// Serialize the object class set to string, deserialize it to collection in WebService, and pass it to the business layer object.
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void button4_click (Object sender, eventargs E)
{
String STR = "";

Student stuinfo1 = new student ();
Stuinfo1.stuname = "lxinxuan ";
Student stuinfo2 = new student ();
Stuinfo2.stuname = "www.cnblogs.com/lxinxuan ";

Collection <student> stulist = new collection <student> ();
Stulist. Add (stuinfo1 );
Stulist. Add (stuinfo2 );

string stustring = this. serializer (stulist); // serialize the string to the XML file format first
STR = Ser. hellostusbycollection (stustring);
MessageBox. show (STR);
}the code for serialize is as follows:
/** //


// The object class set is serialized as a string
///

// /
//
//
Public String serializer (T objtoxml)
{< br> system. io. stringwriter writer = new system. io. stringwriter ();
system. XML. serialization. xmlserializer serializer = new system. XML. serialization. xmlserializer (objtoxml. getType ();
serializer. serialize (writer, objtoxml);
return writer. getstringbuilder (). tostring ();
}

5. This is a special case in case 4. serialize and pass an object class. If the essentials are similar, you will not write it. For details, refer to the Demo code.
This is probably the case. Passing dataset is the most traditional and best way ~

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.