Friday, August 31, 2012

Connection String From Web.config in Class file (Three Tire Architecture)

Here I will explain How to retrieve Connection String from Web.config in Class.cs file when using Three Tire Architecture or More Tires. Here in 3 tire...
  • UI Validation (ASP.Net)            //ASP.Net web application
  • BLL (Business Logic Layer)     //Windows - Class Library project
  • DAL (Data Access Layer)         //Windows - Class Library project
 Here we had TWO ways to get connection string from we.config file.

  • In 1st method we can get connection string in web.config file from
    <connectionStrings/> tag i.e.,
     
    <connectionStrings> 
    <add name="constring"
         connectionString="server=(local)\SQLEXPRESS; 
         database=sampleDB; 
         user id=sa; 
         pwd=*********;" />
     </connectionStrings> 
     
    and now we need to add reference
     
    System.Configuration.dll
     
    and the connection string can be written as shown below
     
    private string constring = 
           ConfigurationManager.ConnectionStrings["constring"].ToString();
  • In 2nd method write the connection string as shown below<configuration> 
    <appSettings>
    <add key="constring" 
    value="server=(local)\SQLEXPRESS;
    database=sampleDB;
    user id=sa;
    pwd=*********;"/>    
    </appSettings>
    </configuration> 

    and Now in the DataAccessLayer i.e, in the class file write as shown below.
    Before that you need to add  

    using System.Configuration;

    and now

    private string constring = 
            ConfigurationSettings.AppSettings["constring"].ToString();
     
For ThreeTite architecture Click HERE

No comments:

Post a Comment