C# Developers' Journal (original) (raw)
12:46p
people, i've no words. .NET it's capable of solving every task my limited brain is capable of formulating.
the problem is as follows. i wrote a simple ODBC source C# class with just two parameter — source name and driver name. but OLEDB needs additional parameters, like Server, Database for SQLServer... even worse, this list of parameters is different for different drivers. where can i find it? that's right, in the registry. so as you understand, every ODBCSource descendant should have a property returning a string with these parameters — typical polymorphism, isn't it?
but the trick is that depending on the Driver name string, type of constructor has to be determined. it's a pain in the ass to write explicit code that would check values one at a time (all right, driver name contains “SQL Server”; here's you SQLServerODBCSource object! :o) programmer is a big guy and wants to write implementation that will work forever and ever no matter how much specific ODBCSource descendants will be created later on. intrigued, huh?
attention! visual basic, delphi and c++ people should stop reading not or they can get a heart attack. the only language that i know in which such on-the-fly implementation can be implemented is perl...
// create a hash table for Signature - Type pairs Hashtable mapTypes = new Hashtable(); // and now iterate through all types declared in the assembly foreach(Type type in typeof(ODBCSource).Assembly.GetExportedTypes()) { // well, well, let's see if this type inherits ODBCSource if(!type.IsSubclassOf(typeof(ODBCSource))) continue; // if it does, fetch static Signature field for this class // and push it into the hashtable mapTypes[type.GetProperty("Signature").GetValue(null,null)] = type; }
then all you have to do is iterate through the list of ODBC sources and call appropriate constructors (Type.GetConstructor
and ConstructorInfo.Invoke
). i don't even know, and even don't care, how much classes are inherited from base class — i'd be damned, full transparency...
never wrote bullshit like “i did in in five minutes”, but i swear the whole thing took me max 5 minutes, figuring out what i want took 3 of them...
shit, that's unbeleivably amazing...