Custom class passed by webservice

Source: Internet
Author: User

Original article: http://hi.baidu.com/h520/blog/item/70303697cb8d476755fb961f.html

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 just looked at msdn and wrote some small programs. I didn't find any problems at the time, because the passed parameters and returned values are both basic data types, we 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 example, the following code:
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
        {
            get { return this.stuName; }
            set { this.stuName = value; }
        }
    }
}

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 <Student> is used for representation, an error occurs, because IList cannot be serialized. In this case, we can use System. collections. objectModel. collection <Student> to indicate a Collection of object classes. Two possible entity classes and entity classes are provided here. The following describes the 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 of WebService are:
[XmlInclude(typeof(Student))]
        [WebMethod]
        public string HelloStus(ArrayList stuList)
        {
            BLL.Class1 cls = new BLL.Class1();
            return cls.GetName(stuList);
        }

Do not omit the [XmlInclude (typeof (Student)] line. Otherwise, the entity class in WebService will not be referenced in the presentation layer.
At this time, add a web reference in the presentation layer. The calling code in the presentation layer is as follows: (refer to the button#click () essentials in the Demo)
/** // <Summary>
/// 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 for converting a set into Object [].
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void button#click (object sender, EventArgs e)
{
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 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.

The following code is provided first:
[WebMethod]
Public string HelloStusByList (Collection <Student> stuList) // The parameter type here is Collection
{
BLL. Class1 cls = new BLL. Class1 ();
Return cls. GetName (stuList );
}

The essentials parameter is Collection. After webservice is added, the essentials parameter in Reference. 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 <localhost. student>, as shown below.
Presentation Layer call code:
/** // <Summary>
/// Transfer the Collection composed of object classes by modifying the code of Reference. cs. However, each time WebService is updated, it must be modified again and each class must be modified, which is troublesome.
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void button3_Click (object sender, EventArgs e)
{
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 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 <Collection <Student> (stuList); // serialize the data to a string in xml file format.
Str = ser. HelloStusByCollection (stuString );
MessageBox. Show (str );
} The code for Serialize is as follows:
/** // <Summary>
/// The object class set is serialized as a string
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "objToXml"> </param>
/// <Returns> </returns>
Public string Serializer <T> (T objToXml)
{
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 ~

 

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 just looked at msdn and wrote some small programs. I didn't find any problems at the time, because the passed parameters and returned values are both basic data types, we 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 example, the following code:
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
        {
            get { return this.stuName; }
            set { this.stuName = value; }
        }
    }
}

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 <Student> is used for representation, an error occurs, because IList cannot be serialized. In this case, we can use System. collections. objectModel. collection <Student> to indicate a Collection of object classes. Two possible entity classes and entity classes are provided here. The following describes the 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 of WebService are:
[XmlInclude(typeof(Student))]
        [WebMethod]
        public string HelloStus(ArrayList stuList)
        {
            BLL.Class1 cls = new BLL.Class1();
            return cls.GetName(stuList);
        }

Do not omit the [XmlInclude (typeof (Student)] line. Otherwise, the entity class in WebService will not be referenced in the presentation layer.
At this time, add a web reference in the presentation layer. The calling code in the presentation layer is as follows: (refer to the button#click () essentials in the Demo)
/** // <Summary>
/// 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 for converting a set into Object [].
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void button#click (object sender, EventArgs e)
{
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 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.

The following code is provided first:
[WebMethod]
Public string HelloStusByList (Collection <Student> stuList) // The parameter type here is Collection
{
BLL. Class1 cls = new BLL. Class1 ();
Return cls. GetName (stuList );
}

The essentials parameter is Collection. After webservice is added, the essentials parameter in Reference. 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 <localhost. student>, as shown below.
Presentation Layer call code:
/** // <Summary>
/// Transfer the Collection composed of object classes by modifying the code of Reference. cs. However, each time WebService is updated, it must be modified again and each class must be modified, which is troublesome.
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void button3_Click (object sender, EventArgs e)
{
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 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 <Collection <Student> (stuList); // serialize the data to a string in xml file format.
Str = ser. HelloStusByCollection (stuString );
MessageBox. Show (str );
} The code for Serialize is as follows:
/** // <Summary>
/// The object class set is serialized as a string
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "objToXml"> </param>
/// <Returns> </returns>
Public string Serializer <T> (T objToXml)
{
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.