Click here to Skip to main content
15,885,244 members
Articles / Programming Languages / C# 3.5
Tip/Trick

ConnectionString for Winform and Reportsource from a txt File

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 Jul 2014CPOL1 min read 9.2K   3  
To set the Connectionstring and the other configuration variables in a file and access it dynamically

Introduction

One of the main issues faced by the winform developers at the time of deployment is the issue of changing the connectionstring and the locations pointer variables which are already used inside the application. This tutorial aims at giving an alternative way, i.e., keeping all those types of connectionstring and reportsources, etc. from a text file.

Background

I am developing an application where I use my production system as the SQL server and set all the required locations within the system. Now I need to deploy it to multiple clients who may be using a distributed Server or Network folders for storing images and files. So I decided to make the application read from the text file located in the C drive the parameters and connectionstrings required.

Using the Code

I created public static variables in the Program.CS for all the required parameters and created a class databasePicker for setting the values to these variables from textfile.

So my Program.cs will look like this:

C#
static class Program
    {   public static String ConnStr = "";
        public static String OurReportSource = "";
        public static String OurLogSource = "";
        public static String OurImagelocation = "";
        public static String database = "";
        public static String  Server = "";
        public static String dbUsername = "";
        public static String dbPassword = ""; 
 public static int USERPK;
        public static String UserType;
        public static int LOCTNPK;
        public static String UserName;
        public static String LOCATIONCODE;
        public static String EmpName;
        public static DateTime Datetoday=DateTime.Now ;
 public static Transactions.DatabasePicker databasepcker = null;
        public static int usernampk;
[STAThread] 
/// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            databasepcker = new Transactions.DatabasePicker();
 Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            databasepcker.SetConnctionString();
           Application.Run(new MainForm());        
        }  
}

And in my DatabasePicker class, I had assumed that the textfile with name DBKey will be available on the C drive of client system which have all the required information for the application including connectionstring,reportsource, logfile source, image location, filestorage location, etc.

And if the DBKey does not exist, a filedialog box will be displayed to user and ask him to copy the DB key from any of the network folders or location (USB, CD, etc.).

C#
class DatabasePicker
    {
        private const string FILE_NAME = "C:\\DBkey.txt";

        public void SetConnctionString()
        {
            if (!File.Exists(FILE_NAME))
            {
                DialogResult dialogResult = MessageBox.Show(
                    "Database configuration file not found  Do you want to Reset it ? ", 
                    "Database Key not Found", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();

                    openFileDialog1.InitialDirectory = "c:\\";
                    openFileDialog1.Filter = "Text|*.txt|All|*.*";
                    openFileDialog1.RestoreDirectory = true;

                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            String Sourcefile = openFileDialog1.FileName;
                            File.Copy(Sourcefile, "c:\\DBkey.txt");
                            MessageBox.Show("Data Key Recieved", "Data Key");
                            SetConnctionString();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error: Could not read file from disk. 
                            Original error: " + ex.Message, "Data Key");
                        }
                    }
                }
                else if (dialogResult == DialogResult.No)
                {
                    Application.Exit();
                }                              
            }

            else
            {
                string line;

                // Read the file and display it line by line.
                System.IO.StreamReader file =
                   new System.IO.StreamReader("c:\\DBkey.txt");

                string[] lines = File.ReadAllLines("c:\\DBkey.txt"); //File is in System.IO
                // for Dubai
                string firstLine = lines[1]; //constring
                string secondline = lines[2]; //reportlocation
                string ThirdLine = lines[3]; //log
                string FourthLine = lines[4]; //images
                string fifthline = lines[5]; //servername
                string sixthline = lines[6]; //databasename
                string seventhline = lines[7]; //userid
                string eightline = lines[8];//password               

                           Program.ConnStr = firstLine;
                Program.OurReportSource = secondline;
                Program.OurLogSource = ThirdLine;
                Program.OurImagelocation = FourthLine;
                Program.Server = fifthline;
                Program.database = sixthline;
                Program.dbUsername = seventhline;
                Program.dbPassword = eightline;
            }
        } 

Now the Connectionstring can be called from anywhere using the static variable program ConnStr.

Points of Interest

This method will help in clearing the difficulty caused when the database server or the application server changes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Arab Emirates United Arab Emirates
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --