Blue Theme Orange Theme Green Theme Red Theme
 
ASP.NET Web Hosting – Click Here
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » Add and handle connection strings in an application configuration file: Part I

Add and handle connection strings in an application configuration file: Part I

There are two ways to save data and parameters. In this case we save application parameters like information entered by the user during the installation process.

Author Rank:
Technologies: .NET 1.0/1.1, ASP.NET 1.0, XML,Visual C# .NET
Total downloads :
Total page views :  5800
Rating :
 2/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



Introduction:

There are two ways to save data and parameters. The first is, let us say, the old way. In this case we save application parameters like information entered by the user during the installation process for e.g. or some indications about further parameters that a given application uses to interact with his external environment such as other applications in an intranet context. All this is done using the registry keys or/and (*. INI) files. These were main objects used to restore application's parameters when developing solutions in a previous context. And of Corse, there were some problems that a not negligent number of developers encountered in this context.

Nowadays, there is a new way to do that with a very simple manner. I mean, the application parameters can be saved in a separate file witch is called the configuration file. This last one is an xml format file that contains elements ordered as logical data structure that set and get information about the application configuration, each element is wrapped in two tags, one at the beginning and one at the end. After all configuration parameters have been set, they are inscribed in a configuration file that can be found in the same directory and the same name as the application but with a different extension witch is (*.exe.config). It looks like this .

This is a sample that illustrates how such file form can be:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" >

            <section name="AppConfig.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" requirePermission="false" />

        </sectionGroup>

    </configSections>

  <connectionStrings>

    <add name ="oConnection"  connectionString= "Data Source = STANDARD;Initial Catalog = Essai; Integrated Security = true " />

  </connectionStrings>

  <appSettings>

    <add key="Phone" value="21418198"/>

  </appSettings>

    <applicationSettings>

        <AppConfig.Properties.Settings>

            <setting name="Phone" serializeAs="String">

                <value>123456789</value>

            </setting>

        </AppConfig.Properties.Settings>

    </applicationSettings>

</configuration>

If your application does not have one, then Adding a configuration file into your application is a joke, you simply follow those steps:

  • Open a new project
  • Select a File settings in the items dialog box as bellow:

  • Build the project by clicking build project or click execute
  • Browse to the application directory. The configuration file is located there
  • Open it with your IDE or any other XML editor , the result will be as mentioned bellow:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <
configSections
>
    </
configSections
>
    <
connectionStrings
/>
</
configuration>


Add connection strings to a given project:

This configuration element is used to save parameters of several connections used by the application during the run time and it can be added, removed or cleared using those elements mentioned in the table bellow:

 

Element Description
"add" Adds a connection string as a name/value pair to the collection of connection strings.
"clear" Removes all references to inherited connection strings, allowing only the connection strings that are added by the current add element.
"remove" Removes a reference to an inherited connection string from the collection of connections strings.


Each connection string is specified using a dual attributes, the first one is the name and the second one is the connection string. Of Corse, there are multiple methods used to add connection strings.

Add connection string using the Project properties menu item from the project menu:

  • Open the project menu and click on the project properties: 



Figure 1

The followed window will be opened:



Figure 2

  • Add connection name and set the type as connection string, the scope will be changed automatically to Application. Click on the "Value" corresponding cell and a small button will appear.
  • Click it to open the connection properties dialog box



Figure 3

  • Configure your connection as you like
  • Save the settings by right clicking the first tab and choosing save file



Figure 4

Add the connection string into the application configuration file directly:

The configuration file is located at the same directory as the application one with ".exe.config" as extension and as icon.

  • Open it and add directly whatever your want in terms of connection strings, the "intellisense" will help you to do that.





After adding a couple of connections strings the configuration file looks like bellow:

<?xml version=
"1.0" encoding="utf-8" ?>
   <configuration>
     <
configSections
>
     </
configSections
>
       <
connectionStrings
>
         <
add name="Connection1" connectionString="Data Source = STANDARD;Initial Catalog = Northwind; Integrated Security = true
"/>
         <add name="Connection2" connectionString="Provider = Microsoft.Jet.OLEDB.4.0;Data Source = C:\Test.mdb" />
       </connectionStrings>
           </configuration
>

In this case, two connections string are added. The first one connects the application to the Northwind SQL Server 2005 database, and the second connects it to an Access database called Test in the drive directory C:\.

Add a connection string programmatically:

To add a new connection string programmatically, do as follow:

  • 1. Add this method to your code.

    private void AddNewConnectionString()

    {

        /* This code provides access to configuration files using OpenMappedExeConfiguration,method. You can use the OpenExeConfiguration method instead. For further informatons,consult the MSDN, it gives you more inforamtions about config files access methods*/

        ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();

        oConfigFile.ExeConfigFilename = Application.StartupPath + "\\AppConfig.exe.config[1]";

        Configuration oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile,ConfigurationUserLevel. None);           

        //Define a connection string settings incuding the name and the connection string

        ConnectionStringSettings oConnectionSettings = new ConnectionStringSettings("oConnection", "DataSource=STANDARD;Initial Catalog=Northwind; Integrated Security=true");           

        //Adding the connection string to the oConfiguration object

        oConfiguration.ConnectionStrings.ConnectionStrings.Add(oConnectionSettings);           

        //Save the new connection string settings

        oConfiguration.Save(ConfigurationSaveMode.Full);

        MessageBox.Show(string.Format("Connection {0} is added",oConnectionSettings.Name));           

        //Restart the application to be sure that connection is restored in the config file

        Application.Restart();

    }

  • Call the method at the run time and open the configuration file. The result will be:

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

      <configSections>

      </configSections>

      <connectionStrings>

        <add name="oConnection"

         connectionString="Data Source=STANDARD; Initial Catalog=Northwind; Integrated Security=true" />

      </connectionStrings>

             </configuration> 

Retrieve the connection string parameters for use purposes

Information about connection strings can be retrieved from the configuration file programmatically. Just add this method to the code:

private
static void RetrieveInfo()

{

    /* This code provides access to configuration files using OpenMappedExeConfiguration,method. You can use the OpenExeConfiguration method instead. For further informatons, consult the MSDN, it gives you more inforamtions about config files access methods*/

    ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();

    oConfigFile.ExeConfigFilename = Application.StartupPath + \\AppConfig.exe.config;

    Configuration oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile, ConfigurationUserLevel.None);

    //Define the name of the connection

    string oName = oConfiguration.ConnectionStrings.ConnectionStrings["oConnection"].Name;

    //Define the connection string of the connection

    string oConnectionString = oConfiguration.ConnectionStrings.ConnectionStrings["oConnection"].ConnectionString;

    //Show the parameters

    MessageBox.Show(string.Format("The connection name is :", oName));

    MessageBox.Show(string.Format("The connection connection string :", oConnectionString));
}

Part II


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved