Friday 18 January 2013

dynamic changer the connetion string in webconfic


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;
using System.Reflection;


namespace Barcodes
{
    public partial class frmConnectionSetup : Form
    {
        public frmConnectionSetup()
        {
            InitializeComponent();
        }

        private void frmConnectionSetup_Load(object sender, EventArgs e)
        {

        }

        private void btnOK_Click(object sender, EventArgs e)
        {

            try
            {
                if (ValidData() == true)
                {

                    StringBuilder Con = new StringBuilder("server=");
                    Con.Append(txtServerName.Text);
                    Con.Append(";database=");
                    Con.Append(txtDatabase.Text);
                    Con.Append(";uid=");
                    Con.Append(txtUsername.Text);
                    Con.Append(";pwd=");
                    Con.Append(txtPassword.Text);

                    string strCon = Con.ToString();
                    // updateConfigFile(strCon);
                    WriteConnection("ConnectionString", strCon);
                    SqlConnection Db = new SqlConnection();


                    ConfigurationManager.RefreshSection("connectionStrings");
                    Db.ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
                    MessageBox.Show("Connection changed successfully!", "Ken Cloud", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch
            {

            }
        }

        public void updateConfigFile(string con)
        {

            XmlDocument XmlDoc = new XmlDocument();
            try
            {

                XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                foreach (XmlElement xElement in XmlDoc.DocumentElement)
                {
                    if (xElement.Name == "connectionStrings")
                    {
                        foreach (XmlNode node in xElement.ChildNodes)
                        {
                            if (node.Attributes[0].Value.Equals("ConnectionString"))
                            {
                                node.Attributes[1].Value = con;
                            }

                            // xElement.FirstChild.Attributes[1].Value = con;
                        }
                    }
                }

                //   ConfigurationManager.ConnectionStrings.Remove(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                //System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                ConfigurationManager.RefreshSection("connectionStrings");
                string[] pathSplit = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Split('\\');
                //path = path.Substring(0, path.Length - path.StartsWith("bin").ToString().Length - 4);
                string path = "";
                foreach (string item in pathSplit)
                {
                    if (item.ToLower() != "bin")
                        path += item + "\\";
                    else break;
                }
                path += "App.config";
                XmlDoc.Load(path);//("App.config");

            }
            catch (Exception ex)
            {
            }
        }
        # region Validate Method
        private bool ValidData()
        {
            if (txtServerName.Text == "")
            {
                MessageBox.Show("Server name can't be blank.", "KenCloud", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                txtServerName.Focus();
                return false;
            }


            if (txtDatabase.Text == "")
            {
                MessageBox.Show("Database name can't be blank.", "KenCloud", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                txtDatabase.Focus();
                return false;
            }
            if (txtUsername.Text == "")
            {
                MessageBox.Show("User name can't be blank.", "KenCloud", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                txtUsername.Focus();
                return false;
            }
            if (txtPassword.Text == "")
            {
                MessageBox.Show("Password can't be blank.", "KenCloud", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                txtPassword.Focus();
                return false;
            }

            return true;
        }
        # endregion

        #region For Write connection

        public static void WriteConnection(string key, string value)
        {
            // load config document for current assembly
            XmlDocument doc = loadConfigDocument();

            // retrieve appSettings node
            XmlNode node = doc.SelectSingleNode("//appSettings");

            if (node == null)
                throw new InvalidOperationException("appSettings section not found in config file.");

            try
            {
                // select the 'add' element that contains the key
                XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

                if (elem != null)
                {
                    // add value for key
                    elem.SetAttribute("value", value);
                }
                else
                {
                    // key was not found so create the 'add' element
                    // and set it's key/value attributes
                    elem = doc.CreateElement("add");
                    elem.SetAttribute("key", key);
                    elem.SetAttribute("value", value);
                    node.AppendChild(elem);
                }

                string[] pathSplit = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Split('\\');
              
                string path = "";
                foreach (string item in pathSplit)
                {
                    if (item.ToLower() != "bin")
                        path += item + "\\";
                    else break;
                }
                path += "App.config";
                doc.Save(path);// (getConfigFilePath());
            }
            catch
            {
                throw;
            }
        }
        #endregion
        #region For Remove Previous Connection string
        public static void RemoveSetting(string key)
        {
            // load config document for current assembly
            XmlDocument doc = loadConfigDocument();

            // retrieve appSettings node
            XmlNode node = doc.SelectSingleNode("//appSettings");

            try
            {
                if (node == null)
                    throw new InvalidOperationException("appSettings section not found in config file.");
                else
                {
                    // remove 'add' element with coresponding key
                    node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
                    doc.Save(getConfigFilePath());
                }
            }
            catch (NullReferenceException e)
            {
                throw new Exception(string.Format("The key {0} does not exist.", key), e);
            }
        }
        #endregion
        #region made the Appconfig file into XML Format
        private static XmlDocument loadConfigDocument()
        {
            XmlDocument doc = null;
            try
            {
                doc = new XmlDocument();
                doc.Load(getConfigFilePath());
                return doc;
            }
            catch (System.IO.FileNotFoundException e)
            {
                throw new Exception("No configuration file found.", e);
            }
        }
        #endregion
        #region Find the Path of The COnfiguration File
        private static string getConfigFilePath()
        {
            return Assembly.GetExecutingAssembly().Location + ".config";
        }

        #endregion


    }

}



No comments:

Post a Comment