Reading Database Connection Strings from an ASP.NET Web.Config file
Recently I was asked by one of our Visual COBOL users how to retrieve a Database connection string for use in an ASP.NET WebForm application. I thought it would be good to put together a small sample and share it on the community site.
In many presentations I have done, I have emphasized that Visual COBOL is a .NET language. That means that techniques to do things in .NET can be used in Visual COBOL as well. This is what makes any .NET language powerful. .NET comes with many categories of classes built in that you can use to speed up development. Take advantage of .NET classes with Visual COBOL just like any other .NET language!
The sample I have put together really is very straightforward and makes use of some recommended classes and code on Microsoft’s MSDN site.
The sample depends on an example connectionString element entry in a Web.Config file. This connectionString element consists of the name of the connectionString, the connectionString itself, and the providerName for the Database you will be using. This example uses SQL Server.
Catalog=MyDataBase;Persist Security Info=True;User
The connectionStrings element is a direct child of the <configuration> element in Web.Config and a peer of the system.web element.
Also, you may not want to store userid and password information. If you do, it should be encrypted. See the following MSDN article on How to Encrypt Connection Strings.
To read the Connection string from Web.Config, you will need the following .NET namespaces. Optionally you can import these namespaces in the Web Application project settings:
You use the following code in your server side code and modify to your needs.
Note: the “~/” is .NET root web operator that gives you the root path of the currently executing web application.
In the sample code it is used to retrieve the Web.Config configuration of the currently running Web Application.
The connection strings collection can then be retrieved from that object. The .NET Configuration and ConnectionStrings classes can also be used to Save or Store database connection strings in the Web.Config file.
declare config as type System.Configuration.Configuration.
set config to type WebConfigurationManager::OpenWebConfiguration("~/")
declare connStringSettings as type System.Configuration.ConnectionStringSettings
if config::ConnectionStrings::ConnectionStrings::Count > 0
set connStringSettings to config::ConnectionStrings::ConnectionStrings["MyDBConnection"]
if connStringSettings not = null
declare conn as type SqlConnection = new SqlConnection(connStringSettings::ConnectionString)
move "No ConnectionSTring" to errMessage
If the requested ConnectionString does not exist in the Web.Config file, no object is returned from the ConnectionStrings collection. It is always a good idea to test for Null when attempting to retrieve the value.