1. 程式人生 > >使用c#完成一個聊天工具的學習過程 2

使用c#完成一個聊天工具的學習過程 2

整改之前的程式碼,選擇mvc模式。

<Window x:Class="ChatTools.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ChatTools"
        mc:Ignorable="d"
        Title="聊天工具" Height="450" Width="700">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="127*"/>
            <ColumnDefinition Width="220*"/>
        </Grid.ColumnDefinitions>
        <Label Content="賬號 :" HorizontalAlignment="Left" Margin="91,231,0,0" VerticalAlignment="Top"/>
        <Label Content="密碼 :" HorizontalAlignment="Left" Margin="91,292,0,0" VerticalAlignment="Top"/>
        <Button Content="登入" HorizontalAlignment="Left" Margin="242,360,0,0" VerticalAlignment="Top" Width="197" Click="Button_Click" Height="26" Grid.ColumnSpan="2"/>
        <TextBox Name="user" Height="26" VerticalContentAlignment="Center" Margin="185,231,0,0" Width="300" Grid.ColumnSpan="2" AutomationProperties.Name="user" VerticalAlignment="Top" HorizontalAlignment="Left"/>
        <PasswordBox Name="passwd" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="26" Margin="185,292,0,0" VerticalAlignment="Top" Width="300" Grid.ColumnSpan="2" AutomationProperties.Name="passwd"/>
        <Image Height="199" Source="image/750.jpg" Grid.ColumnSpan="2" UseLayoutRounding="False" VerticalAlignment="Top" Stretch="UniformToFill" />
        <CheckBox Grid.ColumnSpan="2" Content="記住密碼" HorizontalAlignment="Left" Margin="200,340,0,0" VerticalAlignment="Top"/>
        <CheckBox Content="自動登入" HorizontalAlignment="Left" Margin="130.4,340,0,0" VerticalAlignment="Top" Grid.Column="1"/>
        <Label Content="" Name ="failed" HorizontalAlignment="Left" Margin="185,266,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Width="155"/>
        <Button Content="註冊賬號" Grid.Column="1" HorizontalAlignment="Left" Margin="289.4,237,0,0" VerticalAlignment="Top" Width="75"/>
        <Button Content="忘記密碼?" Grid.Column="1" HorizontalAlignment="Left" Margin="289.4,292,0,0" VerticalAlignment="Top" Width="75"/>

    </Grid>

</Window>
using ChatTools.publicFile;
using ChatTools.models;
using ChatTools.views;
using ChatTools.service;
#region systemusing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 MySql.Data.MySqlClient;
#endregion

namespace ChatTools
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        #region 使用者登入
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //是否查詢到對應記錄 0使用者不存在 1密碼錯誤 2訪問成功
            int flag = 0;
            Console.WriteLine("使用者" + user.Text + "請求登入");

            //宣告user物件
            User u1 = new User();
            u1.setUid(int.Parse(user.Text));
            u1.setUpasswd(passwd.Password);

            LoginService login = new LoginService();
            flag = login.Login(u1);

             if (flag == 0)
            {
                user.Text = "";
                passwd.Password = "";
                failed.Content = "賬號不存在";
            }

            else if (flag == 1)
            {
                passwd.Password = "";
                failed.Content = "密碼錯誤,請重新輸入!";
                Console.WriteLine("使用者" + user.Text + "登入失敗");
            }
            else if (flag == 2)
            {
                Index index1 = new Index();
                index1.Show();
                this.Close();
                Console.WriteLine("使用者" + user.Text + "登入成功");
            }
            else
            {
                Console.WriteLine("使用者" + user.Text + "登入失敗");
            }
            
        }

        #endregion

    }
}

登入服務實現

using ChatTools.models;
using ChatTools.publicFile;
using ChatTools.views;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatTools.service
{
    class LoginService
    {
        public int Login(User user)
        {
            //是否查詢到對應記錄
            int flag = 0;

            //當賬號和密碼都不為空
            if (user.getUid() != 0 && user.getUpasswd() != "")
            {
                string sql = "select * from userinfo"; //sql語句

                //資料庫連線物件
                MySqlConnection objConn = DBConn.GetConn();
                //開啟資料庫連線
                objConn.Open();
                //資料庫操作變數
                MySqlCommand sc = objConn.CreateCommand();
                //傳入sql語句
                sc.CommandText = sql;
                //執行查詢、得到結果集
                MySqlDataReader myDR = sc.ExecuteReader();

                while (myDR.Read()) //迴圈讀取結果集,+1
                {
                    //登入成功
                    if (myDR["uid"].ToString() == user.getUid().ToString() && myDR["upasswd"].ToString() == user.getUpasswd())
                    {
                        //把使用者名稱值賦給User物件
                        user.setUname(myDR["uname"].ToString());
                        flag = 2;

                    }
                    //密碼錯誤
                    if (myDR["uid"].ToString() == user.getUid().ToString() && myDR["upasswd"].ToString() != user.getUpasswd())
                    {
                        flag = 1;
                    }
                }
            }
            else
            {
                flag = 0;
            }
     
            return flag;
        }
    }
}

 資料庫操作類

using MySql.Data.MySqlClient;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatTools.publicFile
{
    class DBConn
    {
        #region  定義連線變數
        public static String strConnRead = "Password=#qwer1234#;User ID=root;Initial Catalog=myqq;Data Source=127.0.0.1;Pooling=true;Connection Lifetime=300";
        public static String strConnEdit = "Password=#qwer1234#;User ID=root;Initial Catalog=myqq;Data Source=127.0.0.1;Pooling=true;Connection Lifetime=300";

        public static String strMySql = "127.0.0.1";

        public static string getStrConn(){
            return strConnRead;
        }
        public static string GetSqlServer()
        {
            return strMySql;
        }

        #endregion

        #region 構造和解構函式
        //建構函式,初始化物件

        public DBConn()
        {
        }

        /// 解構函式,釋放物件資源
        ~DBConn()
        {
            //objConn.Dispose();

        }

        #endregion

        #region 獲取一個數據連線物件

        public static MySqlConnection GetConn()
        {
            MySqlConnection objConn;
            objConn = new MySqlConnection(strConnRead);
            return objConn;
        }
        #endregion

    }

    
}

 model層

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ChatTools.models
{
    class User
    {
        private int uid;         //賬號
        private string uname;    //使用者名稱
        private String upasswd;  //密碼

        #region getter and setter
        public int getUid()
        {
            return this.uid;
        }

        public string getUname()
        {
            return this.uname;
        }

        public string getUpasswd()
        {
            return this.upasswd;
        }

        public void setUid(int uid)
        {
            this.uid = uid;
        }

        public void setUname(string uname)
        {
           this.uname = uname;
        }

        public void setUpasswd(string upasswd)
        {
            this.upasswd = upasswd;
        }

        #endregion

        public string toString()
        {
            return this.uid + this.uname + this.upasswd;
        }

        #region
        public void sendHostInfoToServer()
        {
            string hostIp;
            string hostName;
            string dateTime;  
            try
            {
                hostName = Dns.GetHostName(); //得到主機名
                IPHostEntry IpEntry = Dns.GetHostEntry(hostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //從IP地址列表中篩選出IPv4型別的IP地址
                    //AddressFamily.InterNetwork表示此IP為IPv4,
                    //AddressFamily.InterNetworkV6表示此地址為IPv6型別
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        hostIp = IpEntry.AddressList[i].ToString();
                    }
                }
                dateTime = DateTime.Now.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("獲取本機IP出錯:" + ex.Message);
            }
        }

        #endregion
    }
}