Cấp bậc tác giả:

DOTNET

Tạo người dùng mới

Được viết bởi QuangIT ngày 20/09/2012 lúc 03:24 PM
Việc tạo người dùng mới tưởng chừng như đơn giản, nhưng đối với bảo mật thì việc tạo người dùng cần phải mã hóa để không thể truy cập được.
  • 0
  • 10079

Tạo người dùng mới

Việc tạo người dùng mới tưởng chừng như đơn giản, nhưng đối với bảo mật thì việc tạo người dùng cần phải mã hóa để không thể truy cập được.

Trong bài viết này, Tôi sẽ hướng dẫn cách sử dụng việc gene code cùng mã hóa và sử dụng insert, update, delete, select trong 1 form. Thêm control Gridview, xử lý trên control Gridview.

Dựa vào bảng(Table) NguoiDung có sẵn trong ví dụ "xây dựng ứng dụng đăng nhập"


Tên bài viết: Tạo người dùng mới

Tác giả: Quang IT

Cấp độ bài viết: Chưa đánh giá

Tóm tắt:


Xây dựng Form CreateNewUser.aspx

<div class="hrm_header_placeholder">Quản lý người dùng</div>

<div style="padding: 10px">

<asp:HiddenField ID="H_CatalogId" Value="0" runat="server" />

<asp:Panel ID="PanelAdd" Width="100%" GroupingText="Cập nhật thông tin"  runat="server">

<table border="0" width="100%" cellpadding="0" cellspacing="0">

    <tr><td colspan="4" height="10"></td></tr>

    <tr>

        <td width="20"></td>

        <td width="110" class="hrm_title_blue"></td>

        <td width="7" class="hrm_title_blue"></td>      

        <td><asp:Label ID="lblStatus" ForeColor="Red" runat="server" Text=""></asp:Label></td>

    </tr>

    <tr><td colspan="4" height="4"></td></tr> 

    <tr>

        <td width="20"></td>

        <td width="110" class="hrm_title_blue">Họ và tên</td>

        <td width="7" class="hrm_title_blue">:</td>      

        <td>

            <asp:TextBox ID="txtHoTen" CssClass="hrm_textbox" Width="400px" MaxLength="100" runat="server"></asp:TextBox>

            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" SetFocusOnError="True" ControlToValidate="txtHoTen" Display="Dynamic" ErrorMessage=" (*)"></asp:RequiredFieldValidator>

        </td>

    </tr>

    <tr><td colspan="4" height="4"></td></tr> 

    <tr>

        <td width="20"></td>

        <td width="110" class="hrm_title_blue">Tên truy cập</td>

        <td width="7" class="hrm_title_blue">:</td>      

        <td>

            <asp:TextBox ID="txtTenTruyCap" CssClass="hrm_textbox" Width="400px" MaxLength="100" runat="server"></asp:TextBox>

            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" SetFocusOnError="True" ControlToValidate="txtTenTruyCap" Display="Dynamic" ErrorMessage=" (*)"></asp:RequiredFieldValidator>

        </td>

    </tr>

    <tr><td colspan="4" height="4"></td></tr> 

    <tr>

        <td width="20"></td>

        <td width="110" class="hrm_title_blue">Mật khẩu</td>

        <td width="7" class="hrm_title_blue">:</td>      

        <td>

            <asp:TextBox ID="txtMatKhau" CssClass="hrm_textbox" Width="400px" TextMode="Password" MaxLength="100" runat="server"></asp:TextBox>

            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" SetFocusOnError="True" ControlToValidate="txtMatKhau" Display="Dynamic" ErrorMessage=" (*)"></asp:RequiredFieldValidator>

        </td>

    </tr>      

    <tr><td colspan="4" height="4"></td></tr>  

    <tr>

        <td width="20"></td>

        <td width="110" class="hrm_title_blue"></td>

        <td width="7" class="hrm_title_blue"></td>      

        <td>

            <asp:ImageButton ID="cmdSave" ImageUrl="~/Images/save.jpg" runat="server" onclick="cmdSave_Click" />

            <asp:ImageButton ID="cmdReset" CausesValidation="false" ImageUrl="~/Images/huy.jpg" runat="server" onclick="cmdReset_Click" />

        </td>

    </tr>

    <tr><td colspan="4" height="8"></td></tr>  

</table>  

</asp:Panel>

<asp:Panel ID="PanelList" Width="100%" Height="355" GroupingText="Danh sách"  runat="server">

<table border="0" width="100%" cellpadding="0" cellspacing="0">  

    <tr>

        <td width="20"></td>

        <td style="padding-right:15px">

            <asp:Panel ID="PanelGrid" Width="100%" runat="server"> 

            <br />                              

            <asp:GridView ID="gridCatalog" runat="server" DataKeyNames="Id" Width="100%" BackColor="White"

                OnRowCommand = "gridCatalog_RowCommand"

                OnRowDataBound = "gridCatalog_RowDataBound"

                EmptyDataText="<br><center>Không tồn tại dữ liệu</center><br>"

                BorderColor="#CCCCCC" AutoGenerateColumns="false" BorderStyle="Solid" BorderWidth="1px" CellPadding="3">

                <Columns>

                    <asp:BoundField DataField="id" Visible="false" HeaderText="id"></asp:BoundField>               

                    <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="7%">

                        <ItemTemplate>  

                            <asp:LinkButton ID="cmdSelect" runat="server" CssClass="command_button" CausesValidation="false" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("id") %>'>Select</asp:LinkButton>                         

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="7%">

                        <ItemTemplate>                              

                            <asp:LinkButton ID="cmdDelete" runat="server" CssClass="command_button" CausesValidation="false" runat="server" Text="Delete" CommandName="Delete" CommandArgument='<%# Eval("id") %>'>Delete</asp:LinkButton>                         

                        </ItemTemplate>

                    </asp:TemplateField>                                  

                    <asp:BoundField DataField="TenTruyCap" ItemStyle-Width="20%" HeaderText="Tên truy cập"></asp:BoundField>

                    <asp:BoundField DataField="HoTen" HeaderText="Họ tên"></asp:BoundField>

                    <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Ngày tạo" ItemStyle-Width="150">

                        <ItemTemplate>

                            <asp:Label ID="Label1" runat="server" Text='<%# Convert.ToDateTime(Eval("NgayCapNhat")).ToString("dd/MM/yyyy")%>'></asp:Label>                              

                        </ItemTemplate>

                    </asp:TemplateField>                   

                </Columns>                

                <RowStyle ForeColor="#000066" />

                <SelectedRowStyle BackColor="#dedfdf" Font-Bold="True" ForeColor="Gray" />

                <HeaderStyle BackColor="#006699" Font-Bold="True" HorizontalAlign="Left" ForeColor="White" />             

            </asp:GridView>

            </asp:Panel>

        </td>

    </tr>  

    <tr><td colspan="2" height="10">&nbsp;</td></tr>  

</table>  

Giao diện sẽ như sau:

Tiếp tục xử lý các sự kiện. Trong CreateNewUser.cs, ta làm như sau:

protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

//truy cập khi trang được load

            Bind_Data();

        }

    }



protected void Bind_Data()

    {

        try

        {

//Sử dụng TList để lấy danh sách người dùng hiện có trên database. GetAll - lấy tất cả

            TList<NguoiDung> Tlist_NguoiDung = DataRepository.NguoiDungProvider.GetAll();

            gridCatalog.DataSource = Tlist_NguoiDung;

            gridCatalog.DataBind();

        }

        catch (Exception)

        {

        }

    }


/// <summary>

    /// onclick: Save

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void cmdSave_Click(object sender, ImageClickEventArgs e)

    {

        try

        {

//Gán chuỗi

            string TenTruyCap = Common.StandardString(txtTenTruyCap.Text);

//Kiểm tra Id tồn tại chưa

            if (H_CatalogId.Value.Length == 0 && DataRepository.NguoiDungProvider.GetByTenTruyCap(TenTruyCap) != null)

            {

                lblStatus.Text = "Tên truy cập đã tồn tại, xin vui lòng chọn tên khác!";

                return;

            }

//Truy cập vào bảng NguoiDung

//Gán các trường dữ liệu trên form vào entities

            NguoiDung entNguoiDung = new NguoiDung();

            entNguoiDung.Id = Convert.ToInt32(H_CatalogId.Value);

            entNguoiDung.HoTen = Common.StandardString(txtHoTen.Text);

            string MatKhau = Common.StandardString(txtMatKhau.Text);

            string MaTruyCap = TenTruyCap + MatKhau;

            entNguoiDung.TenTruyCap = TenTruyCap;

            entNguoiDung.MaTruyCap = Common.EncryptMD5(MaTruyCap);

            entNguoiDung.MatKhau = Common.EncryptMD5(MatKhau);

            entNguoiDung.NgayCapNhat = Common.GetServerDateTime();


            bool updateStatus = false;

            try

            {

                if (entNguoiDung.Id == 0)

                {

                    entNguoiDung.Id = 0;

                    updateStatus = DataRepository.NguoiDungProvider.Insert(entNguoiDung);

                }

                else

                {

                    entNguoiDung.EntityState = EntityState.Changed;

                    updateStatus = DataRepository.NguoiDungProvider.Update(entNguoiDung);

                }

                if (!updateStatus)

                {

                    WebMessage.Show("Cập nhật Người dùng không thành công");

                }

                else

                {

//Thực hiện reset hoặc gọi onclick reset tùy.

                    H_CatalogId.Value = "0";

                    txtHoTen.Text = "";

                    txtMatKhau.Text = "";

                    txtTenTruyCap.Text = "";

                    Bind_Data();

                }

            }

            catch (Exception)

            {

                WebMessage.Show("Cập nhật Người dùng không thành công");

            }

        }

        catch (Exception)

        {

            WebMessage.Show("Cập nhật Người dùng không thành công");

        }

    }


protected void cmdReset_Click(object sender, ImageClickEventArgs e)

    {

        H_CatalogId.Value = "0";

        txtHoTen.Text = "";

        txtMatKhau.Text = "";

        txtTenTruyCap.Text = "";

        lblStatus.Text = "";

    }


//Hiệu ứng trên grid

protected void gridCatalog_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.backgroundColor='WhiteSmoke';";

            e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='White';";


            LinkButton l = (LinkButton)e.Row.FindControl("cmdDelete");

            l.Attributes.Add("onclick", "javascript:return " + "confirm('Bạn chắc chắn muốn xóa thông tin này?');");

        }

    }


//Sự kiện trên grid

protected void gridCatalog_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "Delete")

        {

            try

            {

                int IdNguoiDung = Convert.ToInt32(e.CommandArgument.ToString());

                bool deleteStatus = DataRepository.NguoiDungProvider.Delete(IdNguoiDung);

                if (!deleteStatus)

                {

                    WebMessage.Show("Xóa Người dùng không thành công");

                }

                else

                {

                    Bind_Data();

                    H_CatalogId.Value = "0";

                    txtHoTen.Text = "";

                    txtMatKhau.Text = "";

                    txtTenTruyCap.Text = "";

                }

            }

            catch (Exception)

            {

                WebMessage.Show("Xóa Người dùng không thành công");

                return;

            }

        }

        if (e.CommandName == "Select")

        {

            try

            {

                int IdNguoiDung = Convert.ToInt32(e.CommandArgument.ToString());

                NguoiDung entNguoiDung = DataRepository.NguoiDungProvider.GetById(IdNguoiDung);

                if (entNguoiDung != null)

                {

                    H_CatalogId.Value = entNguoiDung.Id.ToString();

                    txtHoTen.Text = entNguoiDung.HoTen;

                    txtTenTruyCap.Text = entNguoiDung.TenTruyCap;

                }

            }

            catch (Exception)

            {

                return;

            }

        }

    }


Nguồn bài viết: Dngaz.com

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML