How and why implement ixmlserializable Interface

Source: Internet
Author: User

Msdn note:

Provides custom formatting for XML serialization and deserialization.

There are two reasons to implement this interface.The first is to control how your object is serialized or deserialized by the xmlserializer. for example, you can chunk data into bytes instead of buffering large data sets, and also avoid the inflation that occurs when the data is encoded using base64 encoding. to control the serialization, implement the readxmland writexml methods to control the xmlreader and xmlwriter classes used to read and write the XML. for an example of this, see How to: Chunk serialized data.

The second reason is to be able to control the schema. to enable this, you must apply the xmlschemaproviderattribute to the serializable type, and specify the name of the static member that returns the schema. see thexmlschemaproviderattribute for an example.

A class that implements the interface must have a parameterless constructor. This is a requirement of the xmlserializerclass.

[Webmethod]
[System. Web. Services. Protocols. soapdocumentmethodattribute (parameterstyle = Soapparameterstyle. Bare)] Public Songstream downloadsong (downloadauthorization authorization, String Filepath ){ // Turn off response buffering. System. Web. httpcontext. Current. response. Buffer = False ; // Return a song. Songstream Song = New Songstream (filepath ); Return Song ;}
// The following class is defined in the server machine.
[Xmlschemaprovider ( "  Myschema  " )]  Public   Class  Songstream: ixmlserializable {  Private   Const   String NS = "  Http://demos.Contoso.com/webservices  "  ;  Private   String  Filepath;  Public  Songstream (){} Public Songstream ( String  Filepath ){  This . Filepath = Filepath ;}  //  This is the method named by the xmlschemaproviderattribute applied to the type.      Public   Static  Xmlqualifiedname myschema (xmlschemaset XS ){  //  This method is called by the Framework to get the schema for this type.  // We return an existing schema from disk.  Xmlserializer schemaserializer = New Xmlserializer ( Typeof  (XMLSCHEMA ));  String Xsdpath = Null  ;  //  Note: Replace the string with your own path. Xsdpath = system. Web. httpcontext. Current. server. mappath ( "  Songstream. XSD  " ); XMLSCHEMA s = (XMLSCHEMA) schemaserializer. deserialize (  New Xmltextreader (xsdpath ), Null  ); Xs. xmlresolver = New  Xmlurlresolver (); Xs. Add (s );  Return   New Xmlqualifiedname ( "  Songstream  "  , NS );}  Void Ixmlserializable. writexml (system. xml. xmlwriter writer ){  //  This is the chunking code.  //  ASP. NET buffering must be turned off for this to work.        Int Buffersize = 4096  ;  Char [] Songbytes = New   Char  [Buffersize]; filestream infile = File. Open ( This . Filepath, filemode. Open, fileaccess. Read );  Long Length = Infile. length;  //  Write the file name. Writer. writeelementstring ( "  Filename  " , NS, path. getfilenamewithoutextension ( This  . Filepath ));  //  Write the size. Writer. writeelementstring ( " Size  "  , NS, length. tostring ());  //  Write the song bytes. Writer. writestartelement ( "  Song  "  , NS); streamreader SR = New Streamreader (infile, True  );  Int Readlen = Sr. Read (songbytes, 0 , Buffersize );  While (Readlen> 0  ) {Writer. writestartelement (  "  Chunk  "  , NS); writer. writechars (songbytes,  0  , Readlen); writer. writeendelement (); writer. Flush (); readlen = Sr. Read (songbytes, 0 , Buffersize);} writer. writeendelement (); infile. Close ();} system. xml. schema. XMLSCHEMA ixmlserializable. getschema (){  Throw   New  System. notimplementedexception ();}  Void  Ixmlserializable. readxml (system. xml. xmlreader reader ){  Throw   New  System. notimplementedexception ();}} 
 Public   Class  Songfile: ixmlserializable { Public   Static   Event  Progressmade onprogress;  Public  Songfile (){}  Private   Const   String NS = "  Http://demos.teched2004.com/webservices  "  ;  Public   Static   String Musicpath;  Private   String  Filepath;  Private   Double  Size;  Void  Ixmlserializable. readxml (system. xml. xmlreader reader) {reader. readstartelement (  "  Downloadsongresult  "  , NS); readfilename (Reader); readsongsize (Reader); readandsavesong (Reader); reader. readendelement ();} Void  Readfilename (xmlreader reader ){  String Filename = reader. readelementstring ( "  Filename  "  , NS );  This . Filepath = Path. Combine (musicpath, path. changeextension (filename,  "  . MP3  "  ));}  Void Readsongsize (xmlreader reader ){  This . Size = convert. todouble (reader. readelementstring ( "  Size  "  , NS ));}  Void  Readandsavesong (xmlreader reader) {filestream OUTFILE = File. Open (  This  . Filepath, filemode. Create, fileaccess. Write );  String  Songbase64; Byte  [] Songbytes; reader. readstartelement (  "  Song  "  , NS );  Double Totalread = 0  ;  While ( True  ){  If (Reader. isstartelement ( "  Chunk "  , NS) {songbase64 = Reader. readelementstring (); totalread + = Songbase64.length; songbytes = Convert. frombase64string (songbase64); OUTFILE. Write (songbytes,  0  , Songbytes. Length); OUTFILE. Flush ();  If (Onprogress! = Null  ) {Onprogress ( 100 * (Totalread/ Size ));}}  Else  {  Break  ;}} OUTFILE. Close (); reader. readendelement ();} [permissionset (securityaction. Demand, name = "  Fulltrust  "  )]  Public   Void Play () {system. Diagnostics. process. Start (  This  . Filepath);} system. xml. schema. XMLSCHEMA ixmlserializable. getschema (){  Throw   New  System. notimplementedexception ();}  Public   Void  Writexml (xmlwriter writer ){  Throw   New  System. notimplementedexception ();}} 
To implement server-side Chunking
    1. On the server machine, the web method must turn off ASP. NET buffering and return a type that implementsIxmlserializable.

    2. The type that implementsIxmlserializableChunks the data inWritexmlMethod.

To implement client-side Processing
    1. Alter the web method on the client proxy to return the type that implementsIxmlserializable. You can useSchemaimporterextensionTo do this automatically, but this is not shown here.

    2. ImplementReadxmlMethod to read the chunked data stream and write the bytes to disk. This implementation also raises progress events that can be used by a graphic control, such as a progress bar.

see also: http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly

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.