maandag 28 september 2009

Even more external data in testclasses

Now I created a base class for testing purposes:

It contains the next code:

private
static
DataTable ReadXls(string filename, string sheet) {


using (OleDbConnection con = new
OleDbConnection(String.Format(CultureInfo.InvariantCulture, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1\"", filename))) {

con.Open();


try

{


using (DataSet myDataSet = new
DataSet())

{

myDataSet.Locale = CultureInfo.InvariantCulture;


using (OleDbDataAdapter myCommand = new
OleDbDataAdapter(String.Format(CultureInfo.InvariantCulture, " SELECT * FROM [{0}$]", sheet), con))

{

myCommand.Fill(myDataSet);

}

con.Close();


return myDataSet.Tables[0];

}

}


catch

{


throw;

}


finally

{

con.Close();

}

}

}

It opens an excel sheet and reads data from it. Every sheet is a database table and the columns should have a caption to address it in the code.


DataTable tabel = ReadXls(Bestand, typeof(T).Name);


foreach (DataRow dr in tabel.Rows)

{

T obj = (T)typeof(T).GetConstructor(new
Type[] { }).Invoke(new
object[] { });


foreach (DataColumn dc in tabel.Columns)

{


string s = dr[dc.ColumnName].ToString();


PropertyInfo pi = obj.GetType().GetProperty(dc.ColumnName);


if (s == "NULL" || string.IsNullOrEmpty(s) ) s = null;

obj.SetValue(dc.ColumnName, s);

                ...

The code above is not complete, I wish you good luck to complete it.

Geen opmerkingen: