简易封装的 Winform 数据库服务器配置界面

小菜最近的项目接近完工了,发现有个小功能不是很满意,所以回过头优化一下、封装一下


项目源码下载
 其实就一个很笨的小功能,估计很多高手不屑看,
没关系,就当做自己日常积累吧。
结合App.Config 配置文件,设置数据库连接字符串。



上图是一个VS2008 创建的类库项目,包括了所有的类和引用的dll.  

DESEncrypt加密/解密类,取自李天平老师的DBUtility
ContractedBlock.gif ExpandedBlockStart.gif DESEncrypt.cs
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
    
/// DES加密/解密类。
    
/// </summary>

    public class DESEncrypt
ExpandedBlockStart.gifContractedBlock.gif    
{
        
public DESEncrypt()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
        }


ContractedSubBlock.gifExpandedSubBlockStart.gif        
========加密========#region ========加密========

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="Text"></param>
        
/// <returns></returns>

        public static string Encrypt(string Text)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return Encrypt(Text, "litianping");
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 加密数据 
        
/// </summary> 
        
/// <param name="Text"></param> 
        
/// <param name="sKey"></param> 
        
/// <returns></returns> 

        public static string Encrypt(string Text, string sKey)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            
byte[] inputByteArray;
            inputByteArray 
= Encoding.Default.GetBytes(Text);
            des.Key 
= ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            des.IV 
= ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            CryptoStream cs 
= new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 
0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret 
= new StringBuilder();
            
foreach (byte b in ms.ToArray())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ret.AppendFormat(
"{0:X2}", b);
            }

            
return ret.ToString();
        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
========解密========#region ========解密========


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="Text"></param>
        
/// <returns></returns>

        public static string Decrypt(string Text)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return Decrypt(Text, "litianping");
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 解密数据 
        
/// </summary> 
        
/// <param name="Text"></param> 
        
/// <param name="sKey"></param> 
        
/// <returns></returns> 

        public static string Decrypt(string Text, string sKey)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            
int len;
            len 
= Text.Length / 2;
            
byte[] inputByteArray = new byte[len];
            
int x, i;
            
for (x = 0; x < len; x++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                i 
= Convert.ToInt32(Text.Substring(x * 22), 16);
                inputByteArray[x] 
= (byte)i;
            }

            des.Key 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            des.IV 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            CryptoStream cs 
= new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 
0, inputByteArray.Length);
            cs.FlushFinalBlock();
            
return Encoding.Default.GetString(ms.ToArray());
        }


        
#endregion

    }


ConfigurationOperator 程序配置文件(.config)修改类,取自周公http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx

ContractedBlock.gif ExpandedBlockStart.gif ConfigurationOperator.cs
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary> 
    
/// 说明:本类主要负责对程序配置文件(.config)进行修改的类, 
    
/// 可以对网站和应用程序的配置文件进行修改 
    
/// 作者:周公 
    
/// 日期:2008-08-23 
    
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx 
    
/// </summary> 

    public class ConfigurationOperator
ExpandedBlockStart.gifContractedBlock.gif    
{
        
private Configuration config;
        
private string configPath;
        
private ConfigType configType;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 对应的配置文件 
        
/// </summary> 

        public Configuration Configuration
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get return config; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set { config = value; }
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 构造函数 
        
/// </summary> 
        
/// <param name="configType">.config文件的类型,只能是网站配置文件或者应用程序配置文件</param> 

        public ConfigurationOperator(ConfigType configType)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.configType = configType;
            
if (configType == ConfigType.ExeConfig)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                configPath 
= Application.ExecutablePath;
                
//AppDomain.CurrentDomain.BaseDirectory; 
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//configPath = HttpContext.Current.Request.ApplicationPath; 
            }

            Initialize();
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 构造函数 
        
/// </summary> 
        
/// <param name="path">.config文件的位置</param> 
        
/// <param name="type">.config文件的类型,只能是网站配置文件或者应用程序配置文件</param> 

        public ConfigurationOperator(string configPath, ConfigType configType)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.configPath = configPath;
            
this.configType = configType;
            Initialize();
        }

        
//实例化configuration,根据配置文件类型的不同,分别采取了不同的实例化方法 
        private void Initialize()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//如果是WinForm应用程序的配置文件 
            if (configType == ConfigType.ExeConfig)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                config 
= System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
            }

            
else//WebForm的配置文件 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                
//config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath); 
            }

        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 添加应用程序配置节点,如果已经存在此节点,则会修改该节点的值 
        
/// </summary> 
        
/// <param name="key">节点名称</param> 
        
/// <param name="value">节点值</param> 

        public void AddAppSetting(string key, string value)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            AppSettingsSection appSetting 
= (AppSettingsSection)config.GetSection("appSettings");
            
if (appSetting.Settings[key] == null)//如果不存在此节点,则添加 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                appSetting.Settings.Add(key, value);
            }

            
else//如果存在此节点,则修改 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                ModifyAppSetting(key, value);
            }

        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 添加数据库连接字符串节点,如果已经存在此节点,则会修改该节点的值 
        
/// </summary> 
        
/// <param name="key">节点名称</param> 
        
/// <param name="value">节点值</param> 

        public void AddConnectionString(string key, string connectionString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ConnectionStringsSection connectionSetting 
= (ConnectionStringsSection)config.GetSection("connectionStrings");
            
if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                ConnectionStringSettings connectionStringSettings 
= new ConnectionStringSettings(key, connectionString);
                connectionSetting.ConnectionStrings.Add(connectionStringSettings);
            }

            
else//如果存在此节点,则修改 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                ModifyConnectionString(key, connectionString);
            }

        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 修改应用程序配置节点,如果不存在此节点,则会添加此节点及对应的值 
        
/// </summary> 
        
/// <param name="key">节点名称</param> 
        
/// <param name="value">节点值</param> 

        public void ModifyAppSetting(string key, string newValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            AppSettingsSection appSetting 
= (AppSettingsSection)config.GetSection("appSettings");
            
if (appSetting.Settings[key] != null)//如果存在此节点,则修改 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                appSetting.Settings[key].Value 
= newValue;
            }

            
else//如果不存在此节点,则添加 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                AddAppSetting(key, newValue);
            }

        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 修改数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值 
        
/// </summary> 
        
/// <param name="key">节点名称</param> 
        
/// <param name="value">节点值</param> 

        public void ModifyConnectionString(string key, string connectionString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ConnectionStringsSection connectionSetting 
= (ConnectionStringsSection)config.GetSection("connectionStrings");
            
if (connectionSetting.ConnectionStrings[key] != null)//如果存在此节点,则修改 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                connectionSetting.ConnectionStrings[key].ConnectionString 
= connectionString;
            }

            
else//如果不存在此节点,则添加 
ExpandedSubBlockStart.gifContractedSubBlock.gif
            {
                AddConnectionString(key, connectionString);
            }

        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// 保存所作的修改 
        
/// </summary> 

        public void Save()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            config.Save();
        }

    }

程序配置文件类型 枚举
ContractedBlock.gif ExpandedBlockStart.gif ConfigType.cs
    public enum ConfigType
ExpandedBlockStart.gifContractedBlock.gif    
{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// asp.net网站的config文件 
        
/// </summary> 

        WebConfig = 1,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary> 
        
/// Windows应用程序的config文件 
        
/// </summary> 

        ExeConfig = 2

    }

SQL数据库服务器配置界面类
ContractedBlock.gif ExpandedBlockStart.gif SvrConf.cs
ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
    
/// SQL数据库服务器配置界面
    
/// </summary>

    internal partial class SvrConf : Office2007Form
ExpandedBlockStart.gifContractedBlock.gif    
{
        
ContractedSubBlock.gifExpandedSubBlockStart.gif        
值域成员#region 值域成员

        
delegate void BindList(DataTable dt);
        
delegate void Mydelegate(bool a);
        
delegate void LoadValue(string value);
        
delegate void AddValue(object value);
        
delegate void Thisdelegate();
        Thread thread;
        

        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
加载实例#region 加载实例

        
public SvrConf()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            InitializeComponent();
        }


        
private void SvrConf_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ReadConfig();
            StartTread();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 开启线程
        
/// </summary>

        private void StartTread()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            BeginTask();
            ShowText(
"正在加载服务器列表,请稍等");
            
//开启线程
            thread = new Thread(new ThreadStart(LoadSqlServerList));
            thread.Start();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 加载服务器列表
        
/// </summary>

        private void LoadSqlServerList()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            FillList();
            EndTask();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 填充服务器列表
        
/// </summary>

        private void FillList()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//获取本地网络的所有服务器
            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            DataTable dt 
= instance.GetDataSources();

            
foreach (DataRow row in dt.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ShowText(
"正在加载服务器:" + row["ServerName"].ToString());
                AddServer(row[
"ServerName"]);
            }

            ShowText(
"服务器加载完毕");
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 读取数据库配置信息
        
/// </summary>

        private void ReadConfig()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (string.IsNullOrEmpty(
                ConfigurationManager.AppSettings[
"ConnectionString"]))
                
return;

            
string[] strConfig = ConfigurationManager.AppSettings["ConnectionString"].Split(';');
            txtServer.Text 
= strConfig[0].Replace("server=""").Trim();
            txtDataBase.Text 
= strConfig[1].Replace("database=""").Trim();
            txtUid.Text 
= strConfig[2].Replace("uid=""").Trim();
            txtPwd.Text 
= strConfig[3].Replace("pwd=""").Trim();

            chkEncrypt.Checked 
= ConntionConfig.IsEncrypt();
        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
选择服务#region 选择服务

        
private void lstServer_SelectedIndexChanged(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (lstServer.SelectedIndex < 0return;

            txtServer.Text 
= lstServer.SelectedItem.ToString().Trim();

        }


        
#endregion

         
ContractedSubBlock.gifExpandedSubBlockStart.gif        
测试连接#region 测试连接

        
private void commandRefurbish_Executed(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
           TestConntion();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 测试数据库连接,并且提示信息
        
/// </summary>
        
/// <returns>是否连接成功</returns>

        private bool TestConntion()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (ConntionConfig.TestConntion(CreateConnectionString()))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ShowText(
"测试连接成功");

                
return true;
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ShowText(
"测试连接失败");
                  
                
return false;
            }

        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
关闭窗口#region 关闭窗口

        
private void commandCancel_Executed(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            CloseForm();
        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
保存设置#region 保存设置

        
private void commandSave_Executed(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (!CheckInputEmpty()) return;

            
//BeginTask();

            
//写入配置文件
            WriteConfig();

            
//EndTask();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 检查是否输入完整
        
/// </summary>
        
/// <returns></returns>

        private bool CheckInputEmpty()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (txtServer.Text == "")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ShowText(
"服务器名称不能为空!请重新输入!");
                
return false;
            }


            
if (txtDataBase.Text == "")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ShowText(
"数据库名称不能为空!请重新输入!");
                
return false;
            }


            
if (txtUid.Text == "")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                ShowText(
"用户名不能为空!请重新输入!");
                
return false;
            }


            
return true;
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 写入配置信息
        
/// </summary>

        private void WriteConfig()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ShowText(
"正在写入配置文件!请稍等.");

            ConfigurationOperator co 
= 
                
new ConfigurationOperator(Application.StartupPath +
                
"\\" + Application.ProductName + ".exe",
                ConfigType.ExeConfig);

            
string connectionString = CreateConnectionString();

            
//检查是否需要加密
            if (chkEncrypt.Checked)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
string strConn = DESEncrypt.Encrypt(connectionString);
                co.AddAppSetting(
"ConStringEncrypt""TRUE");
                co.AddAppSetting(
"ConnectionString", strConn);
                ConfigurationManager.AppSettings[
"ConStringEncrypt"= "TRUE";
                ConfigurationManager.AppSettings[
"ConnectionString"= connectionString;

            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                co.AddAppSetting(
"ConStringEncrypt""FALSE");
                co.AddAppSetting(
"ConnectionString", connectionString);
                ConfigurationManager.AppSettings[
"ConStringEncrypt"= "FALSE";
                ConfigurationManager.AppSettings[
"ConnectionString"= connectionString;
            }


            co.Save();
//保存写入结果 

            ShowText(
"成功写入配置文件");
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 创建数据库连接字符串
        
/// </summary>

        private string CreateConnectionString()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string connectionString  = "server=" + txtServer.Text.Trim() +
                
";database=" + txtDataBase.Text.Trim() +
                
";uid=" + txtUid.Text.Trim() +
                
";pwd=" + txtPwd.Text.Trim();

            
return connectionString;
        }


        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
委托方法#region 委托方法

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 显示进度条信息
        
/// </summary>
        
/// <param name="text">显示的信息</param>

        private void ShowText(string text)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (this.bar1.InvokeRequired)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                LoadValue d 
= new LoadValue(ShowText);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
this.Invoke(d, new object[] { text });
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                proWait.Text 
= text;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 开始任务
        
/// </summary>

        private void BeginTask()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (this.bar1.InvokeRequired)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Thisdelegate d 
= new Thisdelegate(BeginTask);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
this.Invoke(d, new object[] {});
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
this.Enabled = false;
                proWait.ProgressType 
= eProgressItemType.Marquee;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 结束任务
        
/// </summary>

        private void EndTask()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (this.bar1.InvokeRequired)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Thisdelegate d 
= new Thisdelegate(EndTask);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
this.Invoke(d, new object[] { });
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
this.Enabled = true;
                proWait.ProgressType 
= eProgressItemType.Standard;
                thread.Abort();
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 添加服务器
        
/// </summary>
        
/// <param name="item"></param>

        private void AddServer(object item)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (this.lstServer.InvokeRequired)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                AddValue d 
= new AddValue(AddServer);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
this.Invoke(d, new object[] { item });
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                lstServer.Items.Add(item);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 关闭窗口
        
/// </summary>

        private void CloseForm()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (this.InvokeRequired)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Thisdelegate d 
= new Thisdelegate(CloseForm);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
this.Invoke(d, new object[] { });
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
this.Close();
                
this.Dispose();
            }

        }


        
#endregion


    }

SQL数据库服务器配置静态类
ContractedBlock.gif ExpandedBlockStart.gif ConntionConfig.cs
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
    
/// SQL数据库服务器配置静态类
    
/// </summary>

    public class ConntionConfig
ExpandedBlockStart.gifContractedBlock.gif    
{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 检查配置信息
        
/// </summary>
        
/// <returns>完整有效返回true,无效则启动配置界面</returns>

        public static bool CheckConntionConfig()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (CheckedConnection())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return true;
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
               
return CheckedConfig();
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 验证配置信息
        
/// </summary>

        private static bool CheckedConfig()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            MessageBoxEx.Show(
"数据库服务器无法连接,请重新配置。",
                   
"系统提示",
                   MessageBoxButtons.OK,
                   MessageBoxIcon.Warning);

            SvrConf svrConf 
= new SvrConf();
            svrConf.ShowDialog();

            
if (MessageBoxEx.Show("是否现在进入系统?""询问",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) 
== DialogResult.Yes)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return CheckConntionConfig();
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return false;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 验证配置信息的数据库连接
        
/// </summary>

        private static bool CheckedConnection()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string connectionString = ConString();
            
return !string.IsNullOrEmpty(connectionString) &&
                   TestConntion(connectionString);
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 测试与服务器数据库是否成功连接
        
/// </summary>
        
/// <param name="connectionString">数据库连接字符串</param>
        
/// <returns></returns>

        public static bool TestConntion(string connectionString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
using (SqlConnection conn = new SqlConnection(connectionString))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
if (conn.State == ConnectionState.Open)
                        conn.Close();
                    conn.Open();
                    
return true;
                }

                
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
return false;
                }

                
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    conn.Close();
                    conn.Dispose();
                }

            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 数据库连接字符串
        
/// </summary>
        
/// <returns></returns>

        public static string ConString()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (IsEncrypt())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
//解密后的数据库连接字符串
                    ConfigurationManager.AppSettings["ConnectionString"=
                        DESEncrypt.Decrypt(ConfigurationManager.AppSettings[
"ConnectionString"]);

                    
return ConfigurationManager.AppSettings["ConnectionString"];
                }

                
catch 
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
//解密不成功,返回空字符串
                    ConfigurationManager.AppSettings["ConnectionString"= string.Empty;
                    
return string.Empty;
                }

            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//无须解密的数据库连接字符串
                return ConfigurationManager.AppSettings["ConnectionString"];
            }

           
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 验证是否已加密
        
/// </summary>
        
/// <returns></returns>

        internal static bool IsEncrypt()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
switch (ConfigurationManager.AppSettings["ConStringEncrypt"])
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
case "1":
                
case "TRUE":
                
case "true":
                    
return true;
                
default:
                    
return false;
            }

        }

    }


客户端项目

在客户端Main函数用一条语句
调用ConntionConfig.CheckConntionConfig()

客户端程序不需要事先创建App.Config 文件
在第一次配置成功后,会创建相应的App.Config 文件,如果有自定义的key,可以往上加。

 

ContractedBlock.gif ExpandedBlockStart.gif Program
   static class Program
ExpandedBlockStart.gifContractedBlock.gif    
{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Application.SetCompatibleTextRenderingDefault(
false);

            
//验证配置文件的数据库连接字符串。
            if (!ConntionConfig.CheckConntionConfig())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Application.Exit();
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Application.EnableVisualStyles();
                Application.Run(
new Form1());
            }

        }

    }
第一次运行,或者数据库连接字符串无效时,将出现提示窗口

加载网内服务器

测试数据库连接

保存配置信息

关闭配置窗口的提示

自动产生的 Config 文件
 
ContractedBlock.gif ExpandedBlockStart.gif App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    
<appSettings>
        
<add key="ConStringEncrypt" value="TRUE" />
        
<add key="ConnectionString" value="2DBF1D39417917371156099F05C74F796EBEADAB30F8AEAC9E71AD03EDD4F047D0DC82E4D78623A405C9AF2241225F4D" />
    
</appSettings>
</configuration>

转载于:https://www.cnblogs.com/a7373773/archive/2009/07/30/1535141.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值