Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Programming Best Practices » 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 :
Page Views : 10352
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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 also holds:

MCPD enteprise solutions developement 3.5 certification and MCTS distibuted application developement 2.0

 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.