Tuesday, May 19, 2009

Using extenstion method with user define class.

we can convert fields and properties of any class as xml data using extension methods in c# 3.5.
to convert fields and properties as xml data we can use custom logic or we can use XmlSerializer to convert whole object as xml file.
here is the implementation of Toxml and SerilizeToXml method on user defined class Automobile.

Put this class and extension methods calss in App_Code folder as (Automobile.cs)

using System;
using System.Linq;
using System.Xml.Linq;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
///
/// Summary description for Automibile
///

public class Automobile
{
#region Fields
public string Name;
public DateTime LaunchDate;
public int Average;
public string[] ments;
#endregion
#region Properties
public int GetAverage
{
get
{
return Average;
}
set
{
Average = value;
}
}
#endregion
}
public static class AutomobileExtensions
{
#region Automobile Extension methods
public static string ToXml(this Automobile entity)
{
Type t = entity.GetType();
PropertyInfo[] pInfo = t.GetProperties();
FieldInfo[] fInfo = t.GetFields();
var fs = from f in fInfo
select new { Name = f.Name, value = f.GetValue(entity) };
var ps = from p in pInfo
select new { Name = p.Name, value = p.GetValue(entity, null) };
var str = new XElement(t.Name, from n in fs.Union(ps)
select new XElement(n.Name, n.value));
return str.ToString();
}
public static string SerilizeToXml(this Automobile entity)
{
XmlSerializer xmlSerilizer = new XmlSerializer(entity.GetType());
StringWriter strWriter = new StringWriter();
xmlSerilizer.Serialize(strWriter, entity);
return strWriter.ToString();
}
#endregion
}



Calling extension methods.


protected void Page_Load(object sender, EventArgs e)
{
Automobile Honda = new Automobile();
Honda.Name = "Delux";
Honda.LaunchDate = DateTime.Now;
Honda.Average = 60;
Honda.ments = new string[] { "H", "A" };
Response.Write("<br/>");
Response.Write("<b>ToXml</b>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write(Server.HtmlEncode(Honda.ToXml()));
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("<b>SerilizeToXml</b>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write(Server.HtmlEncode(Honda.SerilizeToXml()));
}


Thanks.

No comments:

Post a Comment

Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author