XML-Reflection-Inheritance Part 2
Prerequisites
Part of Topic – Creating a Single Table Database Object Storage
Lecture – XML-Reflection-Inheritance
next Lecture: Lecture – XML-Reflection-Inheritance Part 3
Summary
Topics Covered in this Video;
-Recap of Part 1
-XML Representation of SamplePropertiesInherited
-btnGet_Click
-getPropertyFromXml
-XDocument
-System.Xml.Linq
-try – catch
-lblValue
-Breakpoint
-PropertyInfo
Video
Reference Materials
Code for XMLPropertyObject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Xml.Linq;
namespace DatabaseSample1.App_Code
{
interface IXmlPropertyObject<T>
{
string asXML();
string getPropertyFromXml();
}
public class XmlPropertyObject
{
public string Name { get; set; }
public string Description { get; set; }
public string asXML()
{
string s = String.Empty;
string fc = className();
while (fc.Contains("."))
{
fc = fc.Substring(fc.IndexOf(".") + 1);
}
s += "<" + fc + ">\n";
foreach (var property in this.GetType().GetProperties())
{
s += " <" + property.Name + ">";
s += property.GetValue(this);
s += "</" + property.Name + ">";
s += "\n";
}
s += "</" + fc + ">";
return s;
}
private string className()
{
string fc = this.GetType().ToString();
while (fc.Contains("."))
{
fc = fc.Substring(fc.IndexOf(".") + 1);
}
return fc;
}
public string getPropertyFromXml(string property, string xml)
{
XDocument doc = XDocument.Parse(xml);
// Gets the value fom XML
try {return doc.Root.Element(property).Value; }
catch {return String.Empty; }
}
public void setPropertyFromXml(string property, string xml)
{
string value = getPropertyFromXml(property, xml);
setProperty(property, value);
}
public void setProperty(string name, string value)
{
PropertyInfo pi = this.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (null != pi && pi.CanWrite)
{
pi.SetValue(this, value, null);
}
}
}
public class SamplePropertiesInherited : XmlPropertyObject
{
public string Content { get; set;}
}
}
Code for Interface
protected void btnGet_Click(object sender, EventArgs e)
{
SamplePropertiesInherited s = new SamplePropertiesInherited();
// lblValue.Text = s.getPropertyFromXml(tbProperty.Text, tbResults.Text);
s.setPropertyFromXml(tbProperty.Text, tbResults.Text);
lblValue.Text = s.Name;
}