您的位置:首页 > 编程语言 > C#

C#登录窗口一些小技巧应用,防御性编程以及加密

2019-04-11 10:24 399 查看

 实例:

[code]private void LoginBtn_Click(object sender, EventArgs e)
{
//判断用户名和密码输入情况
if (UserName.Text.Length <= 0)
{
MessageBox.Show("用户名为空,请输入用户名!");
return;
}
if (txtPassword.Text.Length <= 0)
{
MessageBox.Show("密码不能为空!");
return;
}

try
{
//string conn = dbconfig.readxml();方法一
string conn = configxml.xmlconn.readxml();
//使用xml读取配置进行数据库连接替代20151023--(使用app.config默认配置程序连接数据库配置)

//string conn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
//使用db.config就是上面这个方法来写,使用ConfigurationManager但要先引用System.configuration;方法二
Helpers.SqlHelper db = new Helpers.SqlHelper(conn);
DataTable dt = db.ExecuteDataTable("select Id,username,password,ErrorTimes,sign_time from T_users where username = @userName", new SqlParameter("@username", UserName.Text));

//防御性编程,判断过滤条件
if (dt.Rows.Count <= 0)
{
MessageBox.Show("输入的用户名不存在或密码错误,请重新输入!");
return;
}

if (dt.Rows.Count > 1)
{
MessageBox.Show("用户名重复!");
return;
}
//读取行记录
DataRow row = dt.Rows[0];
//显性转换类型
string dbpassword = (string)row["password"];
long Id = (long)row["Id"];
int ErrorTimes = (int)row["ErrorTimes"];
DateTime dbtime = (DateTime)row["sign_time"];

//用Timespan函数计算间隔时间差
DateTime TxtTime = DateTime.Parse(DateTime.Now.ToString());
TimeSpan timespan = TxtTime - dbtime;

if (ErrorTimes >= 5)
{
if (timespan.TotalMinutes > 5) //如果超过5分钟即解除锁定
{
db.ExecuteNonQuery("update T_users set ErrorTimes = 0 where Id = @Id", new SqlParameter("@Id", Id));
}
else
{
MessageBox.Show("因密码输错次数过多,该账号已经被禁止登录,请与管理员进行联系或稍候再试!");
}
}
else
{
if (dbpassword != Encrypt.GetMD5_32(txtPassword.Text))
{
{
db.ExecuteNonQuery("update T_users set ErrorTimes = ErrorTimes+1,sign_time = '" + DateTime.Now + "' where Id = @Id", new SqlParameter("@ID", Id));
MessageBox.Show("密码错误,请重新输入!");
txtPassword.Clear();//输入错误自动清空输入框
return;
}
}
else
{
db.ExecuteNonQuery("update T_users set ErrorTimes = 0 where Id = @Id", new SqlParameter("@Id", Id));
GlobalInfo.LoginUser = UserName.Text.ToString();
MISMain d = new MISMain();
d.Show();
this.Hide();
}
}
}

catch
{
ServerConfig sc = new ServerConfig();
sc.Show();
}
}

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: