5,426,531 members and growing! (15,880 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Serialization Version 2.0 - Part 1

By evmshankar

Serialization techniques convert objects into binary, Simple Object Access Protocol (SOAP),
C# 2.0, C#, Windows, .NET, .NET 2.0VS2005, Visual Studio, Dev

Posted: 24 Jan 2007
Updated: 24 Jan 2007
Views: 4,955
Bookmarked: 0 times
Announcements



Search    
Advanced Search
Sitemap
3 votes for this Article.
Popularity: 0.48 Rating: 1.00 out of 5
3 votes, 100.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
0 votes, 0.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Objective: Validating an Object with Xml Schema

Steps to follow:

1. Serialize that object to xml document

2. Validate that Xml document with Xml Schema using XmlValidator class.

Background

Serialization:

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is de-serialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred.

The .NET Framework features two serializing technologies:

· Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the Clipboard. You can serialize an object to a stream, to a disk, to memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.

· XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is likewise an open standard, which makes it an attractive choice.

Using the code

Example on Xml Serialization

VALIDATING XML THROUGH SCHEMA

//ValidateXml method Validates an Xml content with related Schema.

private static bool ValidateXml(string XmlizedString)

{

XmlTextReader schemaTextReader = null;

XmlSchemaCollection schemaCollection = null;

XmlValidatingReader validationReader = null;

//Adding Schemas to SchemaCollection

string schemaPath1 = ConfigurationSettings.AppSettings["SchemaPath1"];

string schemaPath2 = ConfigurationSettings.AppSettings["SchemaPath2"];

schemaTextReader = new XmlTextReader(schemaPath1);

schemaCollection = new XmlSchemaCollection();

schemaCollection.Add(null, schemaTextReader);

schemaTextReader = new XmlTextReader(schemaPath2);

schemaCollection.Add(null, schemaTextReader);

// XML validator object

validationReader = new XmlValidatingReader(XmlizedString,

XmlNodeType.Document, null);

validationReader.Schemas.Add(schemaCollection);

// Add validation event handler

validationReader.ValidationType = ValidationType.Schema;

validationReader.ValidationEventHandler +=

new ValidationEventHandler(reader_ValidationEventHandler);

// Validate XML data

while (validationReader.Read()) ;

validationReader.Close();

// Raise exception, if XML validation fails

if (ErrorsCount > 0)

{

throw Exception(ErrorMessage);

}

else

{

return true;

}

return false;

}

//Method will be invoked when Validation Event invoked.

public static void reader_ValidationEventHandler(object sender, ValidationEventArgs args)

{

ErrorMessage = ErrorMessage + args.Message.ToString() + "\r\n";

ErrorsCount++;

}

//Method to convert given object to Xml String

public static string SerializeToXML(object responseObject)

{

//DefaultNamespace of XSD

//We have to Namespace compulsory, if XSD using any namespace.

XmlSerializer xmlObj = new XmlSerializer(responseObject.GetType(), "namespace");

String XmlizedString = null;

MemoryStream memoryStream = new MemoryStream();

XmlTextWriter XmlObjWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

XmlObjWriter.Formatting = Formatting.Indented;

xmlObj.Serialize(XmlObjWriter, responseObject);

memoryStream = (MemoryStream)XmlObjWriter.BaseStream;

UTF8Encoding encoding = new UTF8Encoding();

XmlizedString = encoding.GetString(memoryStream.ToArray());

XmlObjWriter.Close();

XmlizedString = XmlizedString.Substring(1);

return XmlizedString;

}

Note : If you have any Complex Type elements, declare elements for complextypes. Otherwise, it will throw an error that element is not declared, even it was declared as complex type in XSD.

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml;

using System.Xml.Serialization;

using System.IO;

namespace Serialization

{

[Serializable] //use Serializable for serializing a class

public class Employee

{

public string Empno;

public string EmpName;

public long Salary;

public Employee()

{

Empno = String.Empty;

EmpName = String.Empty;

Salary = 0;

}

public Employee(string empno, string ename, long sal)

{

Empno = empno;

EmpName = ename;

Salary = sal;

}

}

class Program

{

static void Main(string[] args)

{

Employee emp=new Employee("1234","Scott",25000);

//Serialization process

XmlSerializer xmlObj = new XmlSerializer(emp.GetType(),"www.employee.com");

String XmlizedString = null;

MemoryStream memoryStream = new MemoryStream();

XmlTextWriter XmlObjWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

XmlObjWriter.Formatting = Formatting.Indented;

xmlObj.Serialize(XmlObjWriter, emp);

memoryStream = (MemoryStream)XmlObjWriter.BaseStream;

UTF8Encoding encoding = new UTF8Encoding();

XmlizedString = encoding.GetString(memoryStream.ToArray());

XmlObjWriter.Close();

XmlizedString = XmlizedString.Substring(1);

//storing into File

FileStream fs = new FileStream("d:\\Emp.xml", FileMode.OpenOrCreate,FileAccess.Write);

StreamWriter w = new StreamWriter(fs);

w.WriteLine(XmlizedString);

w.Flush();

fs.Close();

Console.WriteLine(XmlizedString);

Console.ReadLine();

//deserialization

Employee e = new Employee();

XmlSerializer xmlDeserialize = new XmlSerializer(e.GetType(),"www.employee.com");

FileStream fr=new FileStream("d:\\Emp.xml", FileMode.Open,FileAccess.Read);

e = (Employee) xmlDeserialize.Deserialize(fr);

fr.Close();

Console.WriteLine(e.Empno + " : " + e.EmpName + ":" + e.Salary);

Console.ReadLine();

}

} }

Useful Links :-

http://www.4guysfromrolla.com/webtech/012302-1.shtml

http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=236

http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.xmlserializer.aspx
http://aspalliance.com/983_Introducing_Serialization_in_NET#Page2

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

evmshankar



Occupation: Web Developer
Location: India India

Other popular C# Programming articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
  (Refresh) 
Subject  Author Date 
-- There are no messages in this forum --

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Jan 2007
Editor:
Copyright 2007 by evmshankar
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project