Connection String Editor

When writing database-related applications, scripts or tools, one almost always needs a connection string as a command-line argument or some setting to be read out of a configuration file. However, you may also want to provide the possibility to prompt a power user for a connection string or edit a default one before proceeding with connecting to the database. Other times, if the connection fails with a given connection string then you may want to provide the user with opportunity to tweak the connection string and re-try before giving up. Below is a small IronPython script that shows how you can prompt the user for a connection string using a built-in connection string editor (modal dialog box) from the Microsoft .NET Framework:

import clr, sys clr.AddReference('System.Design') from System.Web.UI.Design import ConnectionStringEditor from System.ComponentModel import ITypeDescriptorContext

class TypeDescriptorContext(ITypeDescriptorContext): def get_Instance(self): return None Instance = property(get_Instance)

def main(args): value = args and args[0] or None context = TypeDescriptorContext editor = ConnectionStringEditor print editor.EditValue(context, None, value)

if __name__ == '__main__': main(sys.argv[1:])

The Microsoft .NET Framework contains an abstraction for type editors (see ), which are typically used in design-time environments to enhance or even simplify the display and editing UI for values of a particular type or nature. The Microsoft .NET Framework already contains a number of type editor implementations, most of which reside in the  assembly. The script above uses one such type editor, namely, designed for editing string properties of classes that represent a database connection string. Some type editors cannot be used outside the context of a complex design-time environment (such as Microsoft Visual Studio) without providing a number of host services, but  is fairly independent. All it requires is an implementation of  that is passed as the first parameter to. Even then, the  implementation only need provide an implementation of the   property and which can simply return a null reference:

class TypeDescriptorContext(ITypeDescriptorContext): def get_Instance(self): return None Instance = property(get_Instance)

The second parameter to  can be   and the third is the existing value (connection string) to load into the editor. That's it! Once  is called, it will display a simple modal dialog box where the user can specify the new connection string and which becomes the return value of.

Back to Contents.