I'd like to refactor some code that runs in a console app. The App updates an external database, and it was recently updated to support either MySQL or SQL Server. So now there are two nearly identical methods with a lot of duplicate code in them, because one has a method signature that uses MySqlConnection and MySqlCommand (etc) and the other uses SqlConnection and SqlCommand (etc).
The code is essentially identical, other than the obvious differences in the ADO objects.
What I'd like to do is something like the following. I've seen several posts here on SO (for e.g. How do I use reflection to call a generic method? ) as well as other sites that show how to set this up with a dynamic type, which is great, except that none of the examples do anything more than write foo.GetType() in the generic method to prove that the dynamic type is correct.
So, how do you call a method on that dynamic type? Of course, when I tried to set this up, trying to call the Open() method on the sqlConnection parameter doesn't compile.
Here's sort of what I'm trying to accomplish:
private static void TransferXmlData(ExportManifest m_settings, XmlNodeList xmlNodeList)
{
if (m_Settings.ServerType.ToLower() == "mysql")
{
using (MySqlConnection mySqlConnection = new MySqlConnection(m_Settings.TargetData.ConnectionString))
{
MySqlCommand mySqlCommand =
new MySqlCommand(Program.GetCommandTextTemplate(m_settings), mySqlConnection);
PrepareSqlCommand(mySqlConnection, mySqlCommand, m_settings)
}
}
else
{
using (SqlConnection sqlConnection =
new SqlConnection(m_Settings.TargetData.ConnectionString))
{
SqlCommand sqlCommand =
new SqlCommand(Program.GetCommandTextTemplate(m_settings), sqlConnection);
PrepareSqlCommand(sqlConnection, sqlCommand, m_settings)
}
}
}
private static void PrepareSqlCommand<T>(T sqlConnection, T sqlCommand, ExportManifest m_settings)
{
// Potentially a lot of code here that looks just like the
// code in the else block, Except that it uses the
// MySqlConnection objects instead of SqlConnection
// Do some stuff
sqlConnection.Open(); // obviously doesn't work
}
Thanks in advance!