Wednesday, December 31, 2008

DBObject

I made some changes so I could display code on the site. Thanks to This guy


below is a basic working starting point for the DBObject. It does one very important thing. It can fill it's self out from a DataReader.


///
/// This is the baseclass for DB Object created by Chris Richards
///

[Serializable]
public class DBObject
{
//Holds all the properties in the object
protected Hashtable _properties = new Hashtable();

private string _select_query;
private PropertyInfo[] _obj_proterties;

///
/// An Array of all the properities for this object
///

private PropertyInfo[] _propteries_
{
get
{
if (_obj_proterties == null)
{
_obj_proterties = this.GetType().GetProperties();
}
return _obj_proterties;
}
}


///
/// Gets the SELECT ... FROM query for this object
///

protected string SelectQuery
{
get
{
if (_select_query == string.Empty || _select_query == null)
{
//Generate the Select Query
_select_query = "SELECT";
//Get Information about the object
object[] obj_attributes = this.GetType().GetCustomAttributes(false);

//Now Set all the select columns
foreach (PropertyInfo properity in this._propteries_)
{
object[] attributes = properity.GetCustomAttributes(false);
foreach (object attribute in attributes)
{
if (attribute is DBColumn)
{
_select_query += " " + ((DBColumn)attribute).Column + ",";
}
}
}

//Remove the last Comma
_select_query = _select_query.Substring(0, _select_query.Length - 1);

//Get the Table Name for this Object
foreach (object attr in obj_attributes)
{
if (attr is DBTable)
{
//Add the Table to our List
_select_query += " FROM " + ((DBTable)attr).Table;
}
}
}

return _select_query;
}
}



protected DBObject() { }

///
/// This will populate the object from the reader.
/// It will not advance the reader.
///

protected void FromReader(MySqlDataReader reader)
{
//Look for all the properities
foreach (PropertyInfo properity in this._propteries_)
{
if (properity.CanWrite)
{
object[] attributes = properity.GetCustomAttributes(false);
foreach (object attribute in attributes)
{
if (attribute is DBColumn)
{
try
{
properity.SetValue(this, reader[((DBColumn)attribute).Column], null);
}
catch (IndexOutOfRangeException)
{
//Just Skip it
}
catch (Exception ex)
{
//ErrorLog.Log(-1, this.GetType().Name + " reader Error", ex.Message);
string junk = ex.Message;
}
}
}
}
else
{
ErrorLog.Log(-1, "Can't Write " + this.GetType().Name + "'s Properity", "Properity: " + properity.Name);
}
}
}
}

No comments: