第一步:新建一个文件夹为SystemMgr,并为数据库T_Operator添加两个字段RealName,nvarchar(50),不允许为空,IsLocked bit 不允许为空。在Operator.cs中添加字段,代码如下:
public string RealName { get; set; } public bool IsLocked { get; set; }
并修改OperatorDAL.cs中的相关代码。
在SystemMgr下新建一个窗体,OperatorListUI.xaml.代码如下:
<Window x:Class="HRMSys.UI.SystemMgr.OperatorListUI"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="操作员管理" Height="300" Width="500" Loaded="Window_Loaded" >
<Grid>
<DockPanel>
<ToolBar Height="30" DockPanel.Dock="Top">
<Button Name="btnAdd" Click="btnAdd_Click">
<Image Source="../images/add.ico"></Image>
</Button>
<Button Name="btnDelete" Click="btnDelete_Click">
<Image Source="../images/delete.ico"></Image>
</Button>
<Button Name="btnEdit" Click="btnEdit_Click">
<Image Source="../images/edit.ico"></Image>
</Button>
</ToolBar>
<DataGrid DockPanel.Dock="Top" Name="gridOperators" IsReadOnly="True" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="用户名" Width="100" Binding="{Binding UserName}"></DataGridTextColumn>
<DataGridTextColumn Header="真实姓名" Width="100" Binding="{Binding RealName}"></DataGridTextColumn>
<DataGridCheckBoxColumn Header="是否被绑定" Width="100" Binding="{Binding IsLocked}"> </DataGridCheckBoxColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Grid>
</Window>
OperatorListUI.XAML.cs的代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using HRMSys.DAL; using HRMSys.Model; namespace HRMSys.UI.SystemMgr { /// <summary> /// OperatorListUI.xaml 的交互逻辑 /// </summary> public partial class OperatorListUI : Window { public OperatorListUI() { InitializeComponent(); } private void btnAdd_Click(object sender, RoutedEventArgs e) { OperatorEditUI editUI = new OperatorEditUI(); editUI.IsInsert = true; if (editUI.ShowDialog() == true) { LoadData(); } } private void LoadData() { OperatorDAL dal = new OperatorDAL(); gridOperators.ItemsSource = dal.ListAll(); } private void btnDelete_Click(object sender, RoutedEventArgs e) { Operator op = (Operator)gridOperators.SelectedItem; if (op == null) { MessageBox.Show("没有选中任何行"); return; } if (MessageBox.Show("确定要删除" + op.UserName + "吗?", "提醒", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { OperatorDAL dal = new OperatorDAL(); dal.DeleteById(op.Id); LoadData(); } } private void btnEdit_Click(object sender, RoutedEventArgs e) { Operator op = (Operator)gridOperators.SelectedItem; if (op == null) { MessageBox.Show("没有选中任何行"); return; } OperatorEditUI editUI = new OperatorEditUI(); editUI.IsInsert =false; editUI.EditingId = op.Id; if (editUI.ShowDialog() == true) { LoadData(); } } private void Window_Loaded(object sender, RoutedEventArgs e) { LoadData(); } } }
在新建一个窗体OperatorEditUI.xaml.设计如下:
代码如下:
<Window x:Class="HRMSys.UI.SystemMgr.OperatorEditUI" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="管理员编辑和修改" Height="300" Width="300" Loaded="Window_Loaded"> <Grid> <TextBlock Height="23" HorizontalAlignment="Left" Margin="34,29,0,0" Name="textBlock1" Text="用户名" VerticalAlignment="Top" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="34,58,0,0" Name="textBlock2" Text="真实姓名" VerticalAlignment="Top" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="34,95,0,0" Name="textBlock3" Text="初始密码" VerticalAlignment="Top" Width="66" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="123,23,0,0" Name="txtUserName" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="123,56,0,0" Name="txtRealName" VerticalAlignment="Top" Width="120" /> <PasswordBox Height="23" HorizontalAlignment="Left" Margin="123,95,0,0" Name="pwdPassword" VerticalAlignment="Top" Width="120" /> <Button Content="保存" Height="23" HorizontalAlignment="Left" Margin="46,143,0,0" Name="btnSave" VerticalAlignment="Top" Width="75" Click="btnSave_Click" /> <Button Content="取消" Height="23" HorizontalAlignment="Left" Margin="168,143,0,0" Name="btnCancel" VerticalAlignment="Top" Width="75" Click="btnCancel_Click" /> </Grid> </Window>
OperatorEditUI.XAML.cs代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using HRMSys.DAL; using HRMSys.Model; namespace HRMSys.UI.SystemMgr { /// <summary> /// OperatorEditUI.xaml 的交互逻辑 /// </summary> public partial class OperatorEditUI : Window { public OperatorEditUI() { InitializeComponent(); } public bool IsInsert{get;set;} public Guid EditingId { get; set;} private void btnSave_Click(object sender, RoutedEventArgs e) { if (IsInsert) { Operator op = new Operator(); op.UserName = txtUserName.Text; op.RealName = txtRealName.Text; op.Password = new MD5().GetMD5(pwdPassword.Password + new MD5().GetPasswordSalt()); new OperatorDAL().Insert(op); DialogResult = true; } else { string pwd = pwdPassword.Password; if (pwd.Length <= 0)//如果编辑的时候密码为空则保留现有密码不动 { new OperatorDAL().Update(EditingId,txtUserName.Text,txtRealName.Text); } else//若密码不为空,则将密码重置为用户设置的值 { // string pwdMd5 = new MD5().GetMD5(pwd + "love@beijing"); string pwdMd5 = new MD5().GetMD5(pwd +new MD5().GetPasswordSalt()); new OperatorDAL().Update(EditingId, txtUserName.Text, txtRealName.Text, pwdMd5); } DialogResult = true; } } private void btnCancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; } private void Window_Loaded(object sender, RoutedEventArgs e) { if (IsInsert) { } else { OperatorDAL dal = new OperatorDAL(); Operator op=dal.GetById(EditingId); txtRealName.Text = op.RealName; txtUserName.Text = op.UserName; } } } }
将MD5加盐的“盐”的字符串放到App.config中,代码如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="dbLoginConnStr" connectionString="Data Source=.; Initial Catalog=HRMSYSDB; User ID=hrmsa ;Password=love@beijing"/> </connectionStrings> <appSettings> <add key="passwordSalt" value="love@beijing"/></appSettings> </configuration>
LoginWindow.xaml的设计和代码如下,以及.cs的代码。
<Window x:Class="HRMSys.UI.LoginWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="LoginWindow" Height="200" Width="300" WindowStartupLocation="CenterScreen" ResizeMode="NoResize"> <Grid> <TextBlock Height="23" HorizontalAlignment="Left" Margin="20,22,0,0" Name="textBlock1" Text="用户名" VerticalAlignment="Top" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="20,57,0,0" Name="textBlock2" Text="密码" VerticalAlignment="Top" Width="58" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="87,17,0,0" Name="txtUserName" VerticalAlignment="Top" Width="120" /> <PasswordBox Height="23" HorizontalAlignment="Left" Margin="89,53,0,0" Name="pwbPassword" VerticalAlignment="Top" Width="120" /> <Button Content="登录" Height="23" HorizontalAlignment="Left" Margin="36,102,0,0" Name="btnLogin" VerticalAlignment="Top" Width="75" Click="btnLogin_Click" /> <Button Content="取消" Height="23" HorizontalAlignment="Left" Margin="163,102,0,0" Name="btnCancel" VerticalAlignment="Top" Width="75" Click="btnCancel_Click" /> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using HRMSys.DAL; using HRMSys.Model; namespace HRMSys.UI { /// <summary> /// LoginWindow.xaml 的交互逻辑 /// </summary> public partial class LoginWindow : Window { public LoginWindow() { InitializeComponent(); } private void btnLogin_Click(object sender, RoutedEventArgs e) { string username = txtUserName.Text; string pwd = pwbPassword.Password; Operator op=new OperatorDAL().GetByUserName(username); if (op == null) { MessageBox.Show("用户名或者密码错误!"); } else { string dbMD5 = op.Password;//数据库中存储的密码值。 //string mymd5 = new MD5().GetMD5(pwd+"love@beijing"); string mymd5 = new MD5().GetMD5(pwd +new MD5().GetPasswordSalt()); if (dbMD5 == mymd5) { DialogResult = true; MessageBox.Show("登录成功!"); } else { MessageBox.Show("用户名或者密码错误!"); } } } private void btnCancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; } } }
MainWindow的Xaml和.cs代码如下:
<Window x:Class="HRMSys.UI.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="人力资源管理系统" Height="350" Width="525" WindowState="Maximized" Loaded="Window_Loaded"> <Grid> <Menu> <MenuItem Header="系统" Height="30" DockPanel.Dock="Top"> <MenuItem Name="miOperatorMgr" Header="操作员管理" Click="miOperatorMgr_Click"></MenuItem> </MenuItem> <MenuItem Name="MD5" Header="MD5加密" Click="MD5_Click"></MenuItem> </Menu> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using HRMSys.DAL; using HRMSys.Model; using HRMSys.UI.SystemMgr; namespace HRMSys.UI//UI层需要添加对DAL和Model的引用。引用-->右击添加引用-->项目 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void miOperatorMgr_Click(object sender, RoutedEventArgs e) { //写一个固定用户进行测试 //string str = "123"; //string md5 = new MD5().GetMD5(str+"love@beijing"); //Operator op = new Operator();//注意1.App.config要放在UI层中。 //op.UserName = "王五";//2.DAL层通过ConfigurationManager可以读取主项目中的配置文件中得信息。 //op.Password = md5;//引用关系:DAL引用Model,UI引用DAL和Model //OperatorDAL dal = new OperatorDAL(); //dal.Insert(op); OperatorListUI ListUI = new OperatorListUI(); ListUI.ShowDialog(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MD5_Click(object sender, RoutedEventArgs e) { string str = new MD5().GetMD5("123456"); MessageBox.Show(str); } private void Window_Loaded(object sender, RoutedEventArgs e) { LoginWindow win = new LoginWindow(); if (win.ShowDialog() != true) { // 退出程序 Application.Current.Shutdown(); } } } }
HRMSys.DAL中的MD5.cs的完整代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.Configuration; namespace HRMSys.DAL { public class MD5 { public string GetMD5(string strSource) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] bytValue, bytHash; bytValue = System.Text.Encoding.UTF8.GetBytes(strSource); bytHash = md5.ComputeHash(bytValue); md5.Clear(); string sTemp=""; for(int i=0;i<bytHash.Length;i++) { sTemp+=bytHash[i].ToString("X").PadLeft(2,'0'); } return sTemp.ToLower(); } public string GetPasswordSalt() { string salt = ConfigurationManager.AppSettings["passwordSalt"]; return salt; } } }
OperatorDAL.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HRMSys.Model; using System.Data.SqlClient; using System.Data; namespace HRMSys.DAL { public class OperatorDAL {//在SQL语句中bit用0,1表示,但是在.NET中用bool表示 public void Insert(Operator op) //需要HRMSys.DAL添加对HRMSys.Model的引用,引用-->右击添加引用-->项目 { SqlHelper.ExecuteNonQuery(@"insert into T_Operator (Id,UserName,Password,IsDeleted,RealName,IsLocked) values(newid(), @UserName,@Password,0,@RealName,0)", new SqlParameter("@UserName", op.UserName), new SqlParameter("@Password", op.Password),new SqlParameter("@RealName",op.RealName)); } //封装一个ToOperator的方法 public Operator ToOperator(DataRow row) { Operator op = new Operator(); op.Id=(Guid)row["Id"]; op.UserName=(string)row["UserName"]; op.Password=(string)row["Password"]; op.IsDeleted=(bool)row["IsDeleted"]; op.RealName=(string)row["RealName"]; op.IsLocked=(bool)row["IsLocked"]; return op; } public Operator GetByUserName(string userName) { DataTable table = SqlHelper.ExecuteDataTable("select * from T_Operator where UserName=@userName and IsDeleted=0", new SqlParameter("@UserName", userName)); if (table.Rows.Count <= 0) { return null; } else if (table.Rows.Count > 1) { throw new Exception("存在同名用户!"); } else { DataRow row = table.Rows[0]; return ToOperator(row); } } //软删除 public void DeleteById(Guid id) { SqlHelper.ExecuteNonQuery(@"Update T_Operator Set IsDeleted=1 where Id=@id", new SqlParameter("@id", id)); } //显示所有 public Operator[] ListAll() { DataTable dt = SqlHelper.ExecuteDataTable("Select * from T_Operator where IsDeleted=0"); Operator[] operators = new Operator[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count;i++ ) { operators[i] = ToOperator(dt.Rows[i]); } return operators; } public Operator GetById(Guid id) { DataTable table = SqlHelper.ExecuteDataTable("select * from T_Operator where Id=@Id", new SqlParameter("@Id", id)); if (table.Rows.Count <= 0) { return null; } else if (table.Rows.Count > 1) { throw new Exception("存在重复ID用户!"); } else { DataRow row = table.Rows[0]; return ToOperator(row); } } //更新 public void Update(Guid id ,string userName,string realName) { SqlHelper.ExecuteNonQuery(@"Update T_Operator Set UserName=@UserName,RealName=@RealName where Id=@id", new SqlParameter("@UserName", userName), new SqlParameter("@RealName", realName), new SqlParameter("@id", id)); } public void Update(Guid id,string userName, string realName,string pwd) { SqlHelper.ExecuteNonQuery(@"Update T_Operator Set UserName=@UserName,RealName=@RealName,Password=@Password where Id=@id", new SqlParameter("@UserName", userName), new SqlParameter("@RealName", realName), new SqlParameter("@id", id), new SqlParameter("@Password", pwd)); } } }
SQLHelper.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data.SqlClient; using System.Data; namespace HRMSys.DAL { static class SqlHelper //只在DAL层调用,所以设置为static { //每个实例都需要查看是否修改连接字符串 private static string connStr = ConfigurationManager.ConnectionStrings["dbLoginConnStr"].ConnectionString; //封装方法的原则是:把不变的放到方法里,变化的方法参数中 public static int ExecuteNonQuery(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; return cmd.ExecuteNonQuery(); } } } public static void ExecuteNonQuery(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); cmd.ExecuteNonQuery(); } } } public static object ExecuteScalar(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; return cmd.ExecuteScalar(); } } } public static DataSet ExecuteDataSet(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dataset = new DataSet(); adapter.Fill(dataset); return dataset; } } } public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); return ds.Tables[0]; } } } public static object FromDbValue(object value) { if (value == DBNull.Value) { return null; } else { return value; } } public static object ToDbValue(object value)//private是类内部的方法,现在需要变成公用的,所以修改private为public { if (value == null) { return DBNull.Value; } else { return value; } } } }