小菜最近的项目接近完工了,发现有个小功能不是很满意,所以回过头优化一下、封装一下
项目源码下载
其实就一个很笨的小功能,估计很多高手不屑看,
没关系,就当做自己日常积累吧。
结合App.Config 配置文件,设置数据库连接字符串。
上图是一个VS2008 创建的类库项目,包括了所有的类和引用的dll.
DESEncrypt加密/解密类,取自李天平老师的DBUtility
ConfigurationOperator 程序配置文件(.config)修改类,取自周公http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
项目源码下载
其实就一个很笨的小功能,估计很多高手不屑看,
没关系,就当做自己日常积累吧。
结合App.Config 配置文件,设置数据库连接字符串。
上图是一个VS2008 创建的类库项目,包括了所有的类和引用的dll.
DESEncrypt加密/解密类,取自李天平老师的DBUtility
DESEncrypt.cs
/**//// <summary>
/// DES加密/解密类。
/// </summary>
public class DESEncrypt
{
public DESEncrypt()
{
}
========加密========#region ========加密========
/**//// <summary>
/// 加密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Encrypt(string Text)
{
return Encrypt(Text, "litianping");
}
/**//// <summary>
/// 加密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
des.Key = ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
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())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
#endregion
========解密========#region ========解密========
/**//// <summary>
/// 解密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Decrypt(string Text)
{
return Decrypt(Text, "litianping");
}
/**//// <summary>
/// 解密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
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
}
/**//// <summary>
/// DES加密/解密类。
/// </summary>
public class DESEncrypt
{
public DESEncrypt()
{
}
========加密========#region ========加密========
/**//// <summary>
/// 加密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Encrypt(string Text)
{
return Encrypt(Text, "litianping");
}
/**//// <summary>
/// 加密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
des.Key = ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
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())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
#endregion
========解密========#region ========解密========
/**//// <summary>
/// 解密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Decrypt(string Text)
{
return Decrypt(Text, "litianping");
}
/**//// <summary>
/// 解密数据
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
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
ConfigurationOperator.cs
/**//// <summary>
/// 说明:本类主要负责对程序配置文件(.config)进行修改的类,
/// 可以对网站和应用程序的配置文件进行修改
/// 作者:周公
/// 日期:2008-08-23
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
/// </summary>
public class ConfigurationOperator
{
private Configuration config;
private string configPath;
private ConfigType configType;
/**//// <summary>
/// 对应的配置文件
/// </summary>
public Configuration Configuration
{
get { return config; }
set { config = value; }
}
/**//// <summary>
/// 构造函数
/// </summary>
/// <param name="configType">.config文件的类型,只能是网站配置文件或者应用程序配置文件</param>
public ConfigurationOperator(ConfigType configType)
{
this.configType = configType;
if (configType == ConfigType.ExeConfig)
{
configPath = Application.ExecutablePath;
//AppDomain.CurrentDomain.BaseDirectory;
}
else
{
//configPath = HttpContext.Current.Request.ApplicationPath;
}
Initialize();
}
/**//// <summary>
/// 构造函数
/// </summary>
/// <param name="path">.config文件的位置</param>
/// <param name="type">.config文件的类型,只能是网站配置文件或者应用程序配置文件</param>
public ConfigurationOperator(string configPath, ConfigType configType)
{
this.configPath = configPath;
this.configType = configType;
Initialize();
}
//实例化configuration,根据配置文件类型的不同,分别采取了不同的实例化方法
private void Initialize()
{
//如果是WinForm应用程序的配置文件
if (configType == ConfigType.ExeConfig)
{
config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
}
else//WebForm的配置文件
{
//config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);
}
}
/**//// <summary>
/// 添加应用程序配置节点,如果已经存在此节点,则会修改该节点的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void AddAppSetting(string key, string value)
{
AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
if (appSetting.Settings[key] == null)//如果不存在此节点,则添加
{
appSetting.Settings.Add(key, value);
}
else//如果存在此节点,则修改
{
ModifyAppSetting(key, value);
}
}
/**//// <summary>
/// 添加数据库连接字符串节点,如果已经存在此节点,则会修改该节点的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void AddConnectionString(string key, string connectionString)
{
ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加
{
ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
connectionSetting.ConnectionStrings.Add(connectionStringSettings);
}
else//如果存在此节点,则修改
{
ModifyConnectionString(key, connectionString);
}
}
/**//// <summary>
/// 修改应用程序配置节点,如果不存在此节点,则会添加此节点及对应的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void ModifyAppSetting(string key, string newValue)
{
AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
if (appSetting.Settings[key] != null)//如果存在此节点,则修改
{
appSetting.Settings[key].Value = newValue;
}
else//如果不存在此节点,则添加
{
AddAppSetting(key, newValue);
}
}
/**//// <summary>
/// 修改数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void ModifyConnectionString(string key, string connectionString)
{
ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
if (connectionSetting.ConnectionStrings[key] != null)//如果存在此节点,则修改
{
connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
}
else//如果不存在此节点,则添加
{
AddConnectionString(key, connectionString);
}
}
/**//// <summary>
/// 保存所作的修改
/// </summary>
public void Save()
{
config.Save();
}
}
/**//// <summary>
/// 说明:本类主要负责对程序配置文件(.config)进行修改的类,
/// 可以对网站和应用程序的配置文件进行修改
/// 作者:周公
/// 日期:2008-08-23
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
/// </summary>
public class ConfigurationOperator
{
private Configuration config;
private string configPath;
private ConfigType configType;
/**//// <summary>
/// 对应的配置文件
/// </summary>
public Configuration Configuration
{
get { return config; }
set { config = value; }
}
/**//// <summary>
/// 构造函数
/// </summary>
/// <param name="configType">.config文件的类型,只能是网站配置文件或者应用程序配置文件</param>
public ConfigurationOperator(ConfigType configType)
{
this.configType = configType;
if (configType == ConfigType.ExeConfig)
{
configPath = Application.ExecutablePath;
//AppDomain.CurrentDomain.BaseDirectory;
}
else
{
//configPath = HttpContext.Current.Request.ApplicationPath;
}
Initialize();
}
/**//// <summary>
/// 构造函数
/// </summary>
/// <param name="path">.config文件的位置</param>
/// <param name="type">.config文件的类型,只能是网站配置文件或者应用程序配置文件</param>
public ConfigurationOperator(string configPath, ConfigType configType)
{
this.configPath = configPath;
this.configType = configType;
Initialize();
}
//实例化configuration,根据配置文件类型的不同,分别采取了不同的实例化方法
private void Initialize()
{
//如果是WinForm应用程序的配置文件
if (configType == ConfigType.ExeConfig)
{
config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
}
else//WebForm的配置文件
{
//config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);
}
}
/**//// <summary>
/// 添加应用程序配置节点,如果已经存在此节点,则会修改该节点的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void AddAppSetting(string key, string value)
{
AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
if (appSetting.Settings[key] == null)//如果不存在此节点,则添加
{
appSetting.Settings.Add(key, value);
}
else//如果存在此节点,则修改
{
ModifyAppSetting(key, value);
}
}
/**//// <summary>
/// 添加数据库连接字符串节点,如果已经存在此节点,则会修改该节点的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void AddConnectionString(string key, string connectionString)
{
ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加
{
ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
connectionSetting.ConnectionStrings.Add(connectionStringSettings);
}
else//如果存在此节点,则修改
{
ModifyConnectionString(key, connectionString);
}
}
/**//// <summary>
/// 修改应用程序配置节点,如果不存在此节点,则会添加此节点及对应的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void ModifyAppSetting(string key, string newValue)
{
AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
if (appSetting.Settings[key] != null)//如果存在此节点,则修改
{
appSetting.Settings[key].Value = newValue;
}
else//如果不存在此节点,则添加
{
AddAppSetting(key, newValue);
}
}
/**//// <summary>
/// 修改数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public void ModifyConnectionString(string key, string connectionString)
{
ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
if (connectionSetting.ConnectionStrings[key] != null)//如果存在此节点,则修改
{
connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
}
else//如果不存在此节点,则添加
{
AddConnectionString(key, connectionString);
}
}
/**//// <summary>
/// 保存所作的修改
/// </summary>
public void Save()
{
config.Save();
}
}
程序配置文件类型 枚举
ConfigType.cs
public enum ConfigType
{
/**//// <summary>
/// asp.net网站的config文件
/// </summary>
WebConfig = 1,
/**//// <summary>
/// Windows应用程序的config文件
/// </summary>
ExeConfig = 2
}
public enum ConfigType
{
/**//// <summary>
/// asp.net网站的config文件
/// </summary>
WebConfig = 1,
/**//// <summary>
/// Windows应用程序的config文件
/// </summary>
ExeConfig = 2
}
SQL数据库服务器配置界面类
SvrConf.cs
/**//// <summary>
/// SQL数据库服务器配置界面
/// </summary>
internal partial class SvrConf : Office2007Form
{
值域成员#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
加载实例#region 加载实例
public SvrConf()
{
InitializeComponent();
}
private void SvrConf_Load(object sender, EventArgs e)
{
ReadConfig();
StartTread();
}
/**//// <summary>
/// 开启线程
/// </summary>
private void StartTread()
{
BeginTask();
ShowText("正在加载服务器列表,请稍等");
//开启线程
thread = new Thread(new ThreadStart(LoadSqlServerList));
thread.Start();
}
/**//// <summary>
/// 加载服务器列表
/// </summary>
private void LoadSqlServerList()
{
FillList();
EndTask();
}
/**//// <summary>
/// 填充服务器列表
/// </summary>
private void FillList()
{
//获取本地网络的所有服务器
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
DataTable dt = instance.GetDataSources();
foreach (DataRow row in dt.Rows)
{
ShowText("正在加载服务器:" + row["ServerName"].ToString());
AddServer(row["ServerName"]);
}
ShowText("服务器加载完毕");
}
/**//// <summary>
/// 读取数据库配置信息
/// </summary>
private void ReadConfig()
{
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
选择服务#region 选择服务
private void lstServer_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstServer.SelectedIndex < 0) return;
txtServer.Text = lstServer.SelectedItem.ToString().Trim();
}
#endregion
测试连接#region 测试连接
private void commandRefurbish_Executed(object sender, EventArgs e)
{
TestConntion();
}
/**//// <summary>
/// 测试数据库连接,并且提示信息
/// </summary>
/// <returns>是否连接成功</returns>
private bool TestConntion()
{
if (ConntionConfig.TestConntion(CreateConnectionString()))
{
ShowText("测试连接成功");
return true;
}
else
{
ShowText("测试连接失败");
return false;
}
}
#endregion
关闭窗口#region 关闭窗口
private void commandCancel_Executed(object sender, EventArgs e)
{
CloseForm();
}
#endregion
保存设置#region 保存设置
private void commandSave_Executed(object sender, EventArgs e)
{
if (!CheckInputEmpty()) return;
//BeginTask();
//写入配置文件
WriteConfig();
//EndTask();
}
/**//// <summary>
/// 检查是否输入完整
/// </summary>
/// <returns></returns>
private bool CheckInputEmpty()
{
if (txtServer.Text == "")
{
ShowText("服务器名称不能为空!请重新输入!");
return false;
}
if (txtDataBase.Text == "")
{
ShowText("数据库名称不能为空!请重新输入!");
return false;
}
if (txtUid.Text == "")
{
ShowText("用户名不能为空!请重新输入!");
return false;
}
return true;
}
/**//// <summary>
/// 写入配置信息
/// </summary>
private void WriteConfig()
{
ShowText("正在写入配置文件!请稍等.");
ConfigurationOperator co =
new ConfigurationOperator(Application.StartupPath +
"\\" + Application.ProductName + ".exe",
ConfigType.ExeConfig);
string connectionString = CreateConnectionString();
//检查是否需要加密
if (chkEncrypt.Checked)
{
string strConn = DESEncrypt.Encrypt(connectionString);
co.AddAppSetting("ConStringEncrypt", "TRUE");
co.AddAppSetting("ConnectionString", strConn);
ConfigurationManager.AppSettings["ConStringEncrypt"] = "TRUE";
ConfigurationManager.AppSettings["ConnectionString"] = connectionString;
}
else
{
co.AddAppSetting("ConStringEncrypt", "FALSE");
co.AddAppSetting("ConnectionString", connectionString);
ConfigurationManager.AppSettings["ConStringEncrypt"] = "FALSE";
ConfigurationManager.AppSettings["ConnectionString"] = connectionString;
}
co.Save();//保存写入结果
ShowText("成功写入配置文件");
}
/**//// <summary>
/// 创建数据库连接字符串
/// </summary>
private string CreateConnectionString()
{
string connectionString = "server=" + txtServer.Text.Trim() +
";database=" + txtDataBase.Text.Trim() +
";uid=" + txtUid.Text.Trim() +
";pwd=" + txtPwd.Text.Trim();
return connectionString;
}
#endregion
委托方法#region 委托方法
/**//// <summary>
/// 显示进度条信息
/// </summary>
/// <param name="text">显示的信息</param>
private void ShowText(string text)
{
if (this.bar1.InvokeRequired)
{
LoadValue d = new LoadValue(ShowText);
this.Invoke(d, new object[] { text });
}
else
{
proWait.Text = text;
}
}
/**//// <summary>
/// 开始任务
/// </summary>
private void BeginTask()
{
if (this.bar1.InvokeRequired)
{
Thisdelegate d = new Thisdelegate(BeginTask);
this.Invoke(d, new object[] {});
}
else
{
this.Enabled = false;
proWait.ProgressType = eProgressItemType.Marquee;
}
}
/**//// <summary>
/// 结束任务
/// </summary>
private void EndTask()
{
if (this.bar1.InvokeRequired)
{
Thisdelegate d = new Thisdelegate(EndTask);
this.Invoke(d, new object[] { });
}
else
{
this.Enabled = true;
proWait.ProgressType = eProgressItemType.Standard;
thread.Abort();
}
}
/**//// <summary>
/// 添加服务器
/// </summary>
/// <param name="item"></param>
private void AddServer(object item)
{
if (this.lstServer.InvokeRequired)
{
AddValue d = new AddValue(AddServer);
this.Invoke(d, new object[] { item });
}
else
{
lstServer.Items.Add(item);
}
}
/**//// <summary>
/// 关闭窗口
/// </summary>
private void CloseForm()
{
if (this.InvokeRequired)
{
Thisdelegate d = new Thisdelegate(CloseForm);
this.Invoke(d, new object[] { });
}
else
{
this.Close();
this.Dispose();
}
}
#endregion
}
/**//// <summary>
/// SQL数据库服务器配置界面
/// </summary>
internal partial class SvrConf : Office2007Form
{
值域成员#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
加载实例#region 加载实例
public SvrConf()
{
InitializeComponent();
}
private void SvrConf_Load(object sender, EventArgs e)
{
ReadConfig();
StartTread();
}
/**//// <summary>
/// 开启线程
/// </summary>
private void StartTread()
{
BeginTask();
ShowText("正在加载服务器列表,请稍等");
//开启线程
thread = new Thread(new ThreadStart(LoadSqlServerList));
thread.Start();
}
/**//// <summary>
/// 加载服务器列表
/// </summary>
private void LoadSqlServerList()
{
FillList();
EndTask();
}
/**//// <summary>
/// 填充服务器列表
/// </summary>
private void FillList()
{
//获取本地网络的所有服务器
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
DataTable dt = instance.GetDataSources();
foreach (DataRow row in dt.Rows)
{
ShowText("正在加载服务器:" + row["ServerName"].ToString());
AddServer(row["ServerName"]);
}
ShowText("服务器加载完毕");
}
/**//// <summary>
/// 读取数据库配置信息
/// </summary>
private void ReadConfig()
{
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
选择服务#region 选择服务
private void lstServer_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstServer.SelectedIndex < 0) return;
txtServer.Text = lstServer.SelectedItem.ToString().Trim();
}
#endregion
测试连接#region 测试连接
private void commandRefurbish_Executed(object sender, EventArgs e)
{
TestConntion();
}
/**//// <summary>
/// 测试数据库连接,并且提示信息
/// </summary>
/// <returns>是否连接成功</returns>
private bool TestConntion()
{
if (ConntionConfig.TestConntion(CreateConnectionString()))
{
ShowText("测试连接成功");
return true;
}
else
{
ShowText("测试连接失败");
return false;
}
}
#endregion
关闭窗口#region 关闭窗口
private void commandCancel_Executed(object sender, EventArgs e)
{
CloseForm();
}
#endregion
保存设置#region 保存设置
private void commandSave_Executed(object sender, EventArgs e)
{
if (!CheckInputEmpty()) return;
//BeginTask();
//写入配置文件
WriteConfig();
//EndTask();
}
/**//// <summary>
/// 检查是否输入完整
/// </summary>
/// <returns></returns>
private bool CheckInputEmpty()
{
if (txtServer.Text == "")
{
ShowText("服务器名称不能为空!请重新输入!");
return false;
}
if (txtDataBase.Text == "")
{
ShowText("数据库名称不能为空!请重新输入!");
return false;
}
if (txtUid.Text == "")
{
ShowText("用户名不能为空!请重新输入!");
return false;
}
return true;
}
/**//// <summary>
/// 写入配置信息
/// </summary>
private void WriteConfig()
{
ShowText("正在写入配置文件!请稍等.");
ConfigurationOperator co =
new ConfigurationOperator(Application.StartupPath +
"\\" + Application.ProductName + ".exe",
ConfigType.ExeConfig);
string connectionString = CreateConnectionString();
//检查是否需要加密
if (chkEncrypt.Checked)
{
string strConn = DESEncrypt.Encrypt(connectionString);
co.AddAppSetting("ConStringEncrypt", "TRUE");
co.AddAppSetting("ConnectionString", strConn);
ConfigurationManager.AppSettings["ConStringEncrypt"] = "TRUE";
ConfigurationManager.AppSettings["ConnectionString"] = connectionString;
}
else
{
co.AddAppSetting("ConStringEncrypt", "FALSE");
co.AddAppSetting("ConnectionString", connectionString);
ConfigurationManager.AppSettings["ConStringEncrypt"] = "FALSE";
ConfigurationManager.AppSettings["ConnectionString"] = connectionString;
}
co.Save();//保存写入结果
ShowText("成功写入配置文件");
}
/**//// <summary>
/// 创建数据库连接字符串
/// </summary>
private string CreateConnectionString()
{
string connectionString = "server=" + txtServer.Text.Trim() +
";database=" + txtDataBase.Text.Trim() +
";uid=" + txtUid.Text.Trim() +
";pwd=" + txtPwd.Text.Trim();
return connectionString;
}
#endregion
委托方法#region 委托方法
/**//// <summary>
/// 显示进度条信息
/// </summary>
/// <param name="text">显示的信息</param>
private void ShowText(string text)
{
if (this.bar1.InvokeRequired)
{
LoadValue d = new LoadValue(ShowText);
this.Invoke(d, new object[] { text });
}
else
{
proWait.Text = text;
}
}
/**//// <summary>
/// 开始任务
/// </summary>
private void BeginTask()
{
if (this.bar1.InvokeRequired)
{
Thisdelegate d = new Thisdelegate(BeginTask);
this.Invoke(d, new object[] {});
}
else
{
this.Enabled = false;
proWait.ProgressType = eProgressItemType.Marquee;
}
}
/**//// <summary>
/// 结束任务
/// </summary>
private void EndTask()
{
if (this.bar1.InvokeRequired)
{
Thisdelegate d = new Thisdelegate(EndTask);
this.Invoke(d, new object[] { });
}
else
{
this.Enabled = true;
proWait.ProgressType = eProgressItemType.Standard;
thread.Abort();
}
}
/**//// <summary>
/// 添加服务器
/// </summary>
/// <param name="item"></param>
private void AddServer(object item)
{
if (this.lstServer.InvokeRequired)
{
AddValue d = new AddValue(AddServer);
this.Invoke(d, new object[] { item });
}
else
{
lstServer.Items.Add(item);
}
}
/**//// <summary>
/// 关闭窗口
/// </summary>
private void CloseForm()
{
if (this.InvokeRequired)
{
Thisdelegate d = new Thisdelegate(CloseForm);
this.Invoke(d, new object[] { });
}
else
{
this.Close();
this.Dispose();
}
}
#endregion
}
SQL数据库服务器配置静态类
ConntionConfig.cs
/**//// <summary>
/// SQL数据库服务器配置静态类
/// </summary>
public class ConntionConfig
{
/**//// <summary>
/// 检查配置信息
/// </summary>
/// <returns>完整有效返回true,无效则启动配置界面</returns>
public static bool CheckConntionConfig()
{
if (CheckedConnection())
{
return true;
}
else
{
return CheckedConfig();
}
}
/**//// <summary>
/// 验证配置信息
/// </summary>
private static bool CheckedConfig()
{
MessageBoxEx.Show("数据库服务器无法连接,请重新配置。",
"系统提示",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
SvrConf svrConf = new SvrConf();
svrConf.ShowDialog();
if (MessageBoxEx.Show("是否现在进入系统?", "询问",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
return CheckConntionConfig();
}
else
{
return false;
}
}
/**//// <summary>
/// 验证配置信息的数据库连接
/// </summary>
private static bool CheckedConnection()
{
string connectionString = ConString();
return !string.IsNullOrEmpty(connectionString) &&
TestConntion(connectionString);
}
/**//// <summary>
/// 测试与服务器数据库是否成功连接
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <returns></returns>
public static bool TestConntion(string connectionString)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
return true;
}
catch
{
return false;
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
/**//// <summary>
/// 数据库连接字符串
/// </summary>
/// <returns></returns>
public static string ConString()
{
if (IsEncrypt())
{
try
{
//解密后的数据库连接字符串
ConfigurationManager.AppSettings["ConnectionString"] =
DESEncrypt.Decrypt(ConfigurationManager.AppSettings["ConnectionString"]);
return ConfigurationManager.AppSettings["ConnectionString"];
}
catch
{
//解密不成功,返回空字符串
ConfigurationManager.AppSettings["ConnectionString"] = string.Empty;
return string.Empty;
}
}
else
{
//无须解密的数据库连接字符串
return ConfigurationManager.AppSettings["ConnectionString"];
}
}
/**//// <summary>
/// 验证是否已加密
/// </summary>
/// <returns></returns>
internal static bool IsEncrypt()
{
switch (ConfigurationManager.AppSettings["ConStringEncrypt"])
{
case "1":
case "TRUE":
case "true":
return true;
default:
return false;
}
}
}
/**//// <summary>
/// SQL数据库服务器配置静态类
/// </summary>
public class ConntionConfig
{
/**//// <summary>
/// 检查配置信息
/// </summary>
/// <returns>完整有效返回true,无效则启动配置界面</returns>
public static bool CheckConntionConfig()
{
if (CheckedConnection())
{
return true;
}
else
{
return CheckedConfig();
}
}
/**//// <summary>
/// 验证配置信息
/// </summary>
private static bool CheckedConfig()
{
MessageBoxEx.Show("数据库服务器无法连接,请重新配置。",
"系统提示",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
SvrConf svrConf = new SvrConf();
svrConf.ShowDialog();
if (MessageBoxEx.Show("是否现在进入系统?", "询问",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
return CheckConntionConfig();
}
else
{
return false;
}
}
/**//// <summary>
/// 验证配置信息的数据库连接
/// </summary>
private static bool CheckedConnection()
{
string connectionString = ConString();
return !string.IsNullOrEmpty(connectionString) &&
TestConntion(connectionString);
}
/**//// <summary>
/// 测试与服务器数据库是否成功连接
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <returns></returns>
public static bool TestConntion(string connectionString)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
return true;
}
catch
{
return false;
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
/**//// <summary>
/// 数据库连接字符串
/// </summary>
/// <returns></returns>
public static string ConString()
{
if (IsEncrypt())
{
try
{
//解密后的数据库连接字符串
ConfigurationManager.AppSettings["ConnectionString"] =
DESEncrypt.Decrypt(ConfigurationManager.AppSettings["ConnectionString"]);
return ConfigurationManager.AppSettings["ConnectionString"];
}
catch
{
//解密不成功,返回空字符串
ConfigurationManager.AppSettings["ConnectionString"] = string.Empty;
return string.Empty;
}
}
else
{
//无须解密的数据库连接字符串
return ConfigurationManager.AppSettings["ConnectionString"];
}
}
/**//// <summary>
/// 验证是否已加密
/// </summary>
/// <returns></returns>
internal static bool IsEncrypt()
{
switch (ConfigurationManager.AppSettings["ConStringEncrypt"])
{
case "1":
case "TRUE":
case "true":
return true;
default:
return false;
}
}
}
客户端项目
在客户端Main函数用一条语句
调用ConntionConfig.CheckConntionConfig()
客户端程序不需要事先创建App.Config 文件
在第一次配置成功后,会创建相应的App.Config 文件,如果有自定义的key,可以往上加。
Program
static class Program
{
/**//// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
//验证配置文件的数据库连接字符串。
if (!ConntionConfig.CheckConntionConfig())
{
Application.Exit();
}
else
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
第一次运行,或者数据库连接字符串无效时,将出现提示窗口
static class Program
{
/**//// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
//验证配置文件的数据库连接字符串。
if (!ConntionConfig.CheckConntionConfig())
{
Application.Exit();
}
else
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
加载网内服务器
测试数据库连接
保存配置信息
关闭配置窗口的提示
自动产生的 Config 文件
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConStringEncrypt" value="TRUE" />
<add key="ConnectionString" value="2DBF1D39417917371156099F05C74F796EBEADAB30F8AEAC9E71AD03EDD4F047D0DC82E4D78623A405C9AF2241225F4D" />
</appSettings>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConStringEncrypt" value="TRUE" />
<add key="ConnectionString" value="2DBF1D39417917371156099F05C74F796EBEADAB30F8AEAC9E71AD03EDD4F047D0DC82E4D78623A405C9AF2241225F4D" />
</appSettings>
</configuration>