Thumbnail
Category: Lập trình

Kinh nghiệm ASP.NET + LINQ

Date: August 17, 2020
106 views

1. Cài đặt mô hình 3 lớp

Các bạn tạo 3 project tương ứng với 3 lớp: giao diện, xử lý, dữ liệu. Ở đây mình đặt tên tương ứng là GUI, BLL, DAL.

  • Đầu tiên bạn tạo project DAL, chọn class library nhé.

  • Xóa file trong project và tạo file mới chọn LINQ to SQL Class. Sau đó chọn Server Explorer kết nối và cơ sở dữ liệu ra. Vậy là xong lớp DAL.
  • Tạo thêm project BLL, chọn class library tương tự DAL. File tạo ra bạn đổi tên BLL tương ứng.
  • Nháy chuột phải vào reference để add DAL và System.Data.Linq
  • Using DAL và tạo đối tượng DAL
  • Tạo thêm project GUI, chọn WebForm đừng chọn class library nhé.
  • Using DAL, BLL và tạo đối tượng BLL tương ứng nhé.

Video tạo mô hình ba lớp

Video xử lý thêm, xóa, sửa theo mô hình 3 lớp sử dụng Linq.

2. Linq

2.1 Lấy tất cả


public List<nganh> getAll()
{
  return connect.nganhs.ToList();
}

2.1.1 Lấy theo điều kiện

Lamda


 public List<Sinhvien> thongTinSinhVien_TraVinh()
 {
   return db.Sinhviens.Where(sv => sv.DiaChi == "Trà Vinh").ToList();
 }

Không theo lamda


public List<Sinhvien> thongTinSinhVien_TraVinh()
{
    var data = from sv in db.Sinhviens
               where sv.DiaChi == "Trà Vinh"
               select sv;
    return data.ToList();
}

2.2 Xử lý thêm


public bool AddNganh(String ma_Nganh, String ten_Nganh)
{
  nganh Ng = new nganh();
​
  Ng.maNganh = ma_Nganh;
  Ng.tenNganh = ten_Nganh;
​
  connect.nganhs.InsertOnSubmit(Ng);
​
  try
  {
    connect.SubmitChanges();
    return true;
  }
  catch
  {
    return false;
  }
}


public bool themLoaiSanPham(string maLoai, string tenLoai)
{
  try
  {
    LOAIHANG lh = new LOAIHANG();
    lh.MaLoai = maLoai;
    lh.TenLoai = tenLoai;
    db.LOAIHANGs.InsertOnSubmit(lh);
    db.SubmitChanges();
    return true;
  } catch(Exception ex)
  {
    return false;
  }   
}

2.3 Xử lý tìm kiếm


public nganh get_by_ma(String id)
{
  return connect.nganhs.Where(Ng => Ng.maNganh == id).FirstOrDefault();
}

2.3.1 Like – Tìm kiếm gần đúng


public List<LOAIHANG> timLoaiSanPhamTheoTen(string tuCanTim)
{
  var data = from lh in db.LOAIHANGs
    where lh.TenLoai.Contains(tuCanTim)
    select lh;
  return data.ToList();
}

2.3.1 Like – so sánh ký tự đầu


public List<NHANVIEN> cau_26_tenNV_batDaua_luong_lon_hon_1000000()
{
  var data = from nv in db.NHANVIENs
    where (nv.Ten.StartsWith("a")) && nv.LuongCB > 1000000
    select nv;
  return data.ToList();
}

2.4 Xử lý xóa

Bạn sử dụng hàm tìm kiếm để tìm record cần xóa nhé.


public bool xoa(String id)
{
  nganh Ng = get_by_ma(id);
  connect.nganhs.DeleteOnSubmit(Ng);
  try
  {
    connect.SubmitChanges();
    return true;
  }
  catch
  {
    return false;
  }
}


 public bool xoaLoaiSanPham(string maLoai)
 {
   try
   {
     LOAIHANG lh = db.LOAIHANGs.Single(x => x.MaLoai == maLoai);
     db.LOAIHANGs.DeleteOnSubmit(lh);
     db.SubmitChanges();
     return true;
   }
   catch (Exception ex)
   {
     return false;
   }
 }

2.5 Xử lý sửa

Cũng vậy, bạn sử dụng hàm tìm kiếm để tìm record cần sửa


public bool sua(String maNganh, String tenNganh)
{
  nganh Ng = get_by_ma(maNganh);
  Ng.maNganh = maNganh;
  Ng.tenNganh = tenNganh;
​
  try
  {
    connect.SubmitChanges();
    return true;
  }
  catch
  {
    return false;
  }
} 


public bool suaLoaiSanPham(string maLoai, string tenLoai)
{
  try
  {
    LOAIHANG lh = db.LOAIHANGs.Single(x => x.MaLoai == maLoai);
    lh.TenLoai = tenLoai;
    db.SubmitChanges();
    return true;
  }
  catch (Exception ex)
  {
    return false;
  }
}

2.6 Order By


public List<ketquathuctap> getLast()
{
  return connect.ketquathuctaps.OrderByDescending(pc => pc.maPhieuCham).ToList();
}


public List<NHANVIEN> cau_12_sapGiamDanNhanVienTheoTenHo_TraVinh()
{
  var data = from nv in db.NHANVIENs
    where nv.DiaChi == "Trà Vinh"
    orderby nv.Ho descending, nv.Ten descending
    select nv;
  return data.ToList();
}

2.7 Lấy dữ liệu từ nhiều bảng


// Tạo class mới chứa dữ liệu
public class Diem {
  public string tenNguoiCham {get; set;}
  public double diem {get; set;}
  public string nhanXet { get; set; }
}
​
​
//Tạo mới đối tượng ở phần new ớ
public List<Diem> getAll(string maSV)
{
  var kq =
    from ketquathuctap in connect.ketquathuctaps
    from nguoidung in connect.nguoidungs
    from chitietdiem in connect.chitietdiems
    where ketquathuctap.maPhieuCham == chitietdiem.maPhieuCham
    where ketquathuctap.maNguoiCham == nguoidung.maNguoiDung
    where ketquathuctap.maSV == maSV
    select new Diem
    {
    tenNguoiCham = nguoidung.hoTen,
    diem = chitietdiem.diem,
    nhanXet = chitietdiem.nhanXet
    };
    return kq.ToList();
}

2.8 Nhiều điều kiện where


public ketquathuctap getByMaSVAndNHD(String maSV, String maNHD)
{
  return connect.ketquathuctaps.Where(kq=> (kq.maSV == maSV) && (kq.maNguoiCham == maNHD)).FirstOrDefault();
}

2.9 Limit


public List<thongbao> getAllLimit5()
{
  return connect.thongbaos.OrderByDescending(tb => tb.maThongBao).Take(5).ToList();
}

2.10 Xử lý ngày


//Thêm vào csdl
public bool ThemPhieuCham(String diem, String nhanXet, DateTime ngayCham)
{
  try
  {
    chitietdiem pc = new chitietdiem();
    pc.diem = double.Parse(diem);
    pc.nhanXet = nhanXet;
    pc.ngayCham = ngayCham;
​
    connect.chitietdiems.InsertOnSubmit(pc);
​
    try
    {
      connect.SubmitChanges();
      return true;
    }
    catch
    {
      return false;
    }
  }
  catch
  {
    return false;
  }
}
​
//Lấy ngày ra
public List<ThongTinThucTap> get_TTTT_cho_giang_vien(string maNguoiCham)
{
  var kq =              
    from nguoidung in connect.nguoidungs                
    from thongtinthuctap in connect.thongtinthuctaps
    where thongtinthuctap.maSinhVien == nguoidung.maNguoiDung
    where thongtinthuctap.maGiangVien == maNguoiCham
    select new ThongTinThucTap
    {
    maSV = thongtinthuctap.maSinhVien,
    tenSV = nguoidung.hoTen,
    ngayBatDauThucTap = thongtinthuctap.ngayBatDauThucTap.ToString()
​
    };
    return kq.ToList();
}
​
//Class ThongTinThucTap
public class ThongTinThucTap
{
  public string maSV { get; set; }
  public string tenSV { get; set; }
  public string ngayBatDauThucTap { get; set; }
}
​
//Chỗ in ngày ra
ltr_phancongthuctap.Text += ((DateTime)item.ngayBatDauThucTap).ToString("dd/MM/yyyy") + @" </td>";

2.10.1 Chỉ lấy năm


 public List<ThongTinNhanVien> cau_3_thongTinNhanVien()
 {
   var data = from nv in db.NHANVIENs
     select new ThongTinNhanVien()
   {
     hoTen = nv.Ho + " " + nv.Ten,
     diaChi = nv.DiaChi,
     namSinh = nv.NgaySinh.Value.Year
     };
   return data.ToList();
 }

2.11 Group By


public List<LoaiHang_BaoNhieuSanPham> cau_14_LoaiHang_BaoNhieuSanPham()
{
  var data = from sp in db.SANPHAMs
    group sp by sp.MaLH into sp_n
    select new
  {
    ma = sp_n.Key,
    soLuong = sp_n.Count()
    } into NewTable
    from l in db.LOAIHANGs
    where NewTable.ma == l.MaLoai
    select new LoaiHang_BaoNhieuSanPham
  {
    ten = l.TenLoai,
    soLuong = NewTable.soLuong
    };
  return data.ToList();
}

2.12 Skip


 public List<TTNV_THU3> cau_19_thongtinNV_thu3()
 {
   var data = (from nv in db.NHANVIENs
               select new TTNV_THU3()
               {
                 maNV = nv.MaNV,
                 hoNV = nv.Ho,
                 tenNV = nv.Ten,
                 gioitinhNV = nv.GioiTinh,
                 ngaysinhNV = nv.NgaySinh,
                 diachiNV = nv.DiaChi
                 }).Skip(2);
   return data.ToList();
 }

3. Xử lý trong C# Webform

3.1 Chuyển trang


Response.Redirect("../index.aspx");

3.2 In ra tương tự echo PHP


Response.Write("abc");

3.3 Session


//Đặt session
Session["ma"] = item.maNguoiDung;
Session["user"] = item.loaiUser;
Session["ten"] = "abc";
​
//Xóa session
Session.Remove("user");
Session.Remove("ma");
Response.Redirect("../index.aspx");
​
//kiểm tra giá trị session
if (Session["user"] == null && Session["user"] != "Admin")
{
  Response.Redirect("../index.aspx");
}

3.4 Literal

Dùng để chèn code html vào thêm


ltr_table.Text += @"
                    <tr>
                        <td> " + i + @" </td>
                        <td> " + value.maNganh + @" </td>
                        <td> " + value.tenNganh + @" </td>
                        <td>
                            <div class='d-flex justify-content-center align-content-center'>
                                <a title='Sửa' href = 'sua-nganh.aspx?id_sua=" + value.maNganh + @"'><i class='fas fa-edit'></i></a> 
                                <a style='padding-left:10px; color: red;' title='Xóa' href = 'quan-ly-nganh.aspx?id_xoa=" + value.maNganh + @"'><i class='fas fa-trash-alt'></i></a> 
                            </div>
                        </td>
                        
                    </tr>
                ";
//@ để xuống hàng nó vẫn nhận không bị lỗi

3.5 GET PHP


//Lấy giá trị
string valuee = Request.QueryString["id"];
​
//Đặt đường dẫn
<a title='Sửa' href = 'sua-nganh.aspx?id_sua=" + value.maNganh + @"'><i class='fas fa-edit'></i></a> 

3.6 Viết code xử lý trực tiếp vào giao diện

Sử dụng <% %>


<% Response.Write(Session["ten"].ToString()); %>

3.7 Validate

  • RequiredFieldValidator: Không được để trống
  • ReguilarExpressionValidator: Các ràng buộc khác(email, số điện thoại)

Lưu ý: Cần set các giá trị: 

  • Text
  • ForeColor
  • ControlToValidate (cái cần ràng buộc)
  • ValidationExpresstion (ràng buộc khác thì điền vào đây)


((09|03|07|08|05)+([0-9]{8})\b) //số điện thoại Việt Nam
^\d$ //chỉ nhập số

3.8 Một số lưu ý

  1. Một file webformchir sử dụng 1 form duy nhất. Nếu nhiều hơn sẽ lỗi, bấm button không nhận,…
  2. Các nút xử lý chung với validate thì khi nhập đúng form nút xử lý mới hoạt động. Lỗi khi form thêm có button xử lý đăng xuất. Khắc phục: tạo riêng file xử lý đăng xuất rồi link đến đó, không nên xử lý bằng button.

3.9 Hàm lấy địa chỉ ip máy tính


public static string getIpInternet()
{
  try
  {
    using (System.Net.WebClient client = new System.Net.WebClient())
    {
      string ip = client.DownloadString("http://ipinfo.io/ip");
      ip = ip.Replace("\r", "").Replace("\n", "");
      return ip;
    }
  }
  catch
  {
    return "127.0.0.1";
  }
}

3.10 Hàm lấy tên trình duyệt mở web


public string GetWebBrowserName()
{
  string WebBrowserName = string.Empty;
  try
  {
    WebBrowserName = HttpContext.Current.Request.Browser.Browser;
  }
  catch (Exception ex)
  {
    throw new Exception(ex.Message);
  }
  return WebBrowserName;
}

3.11 Lấy tên máy tính


String hostname = Environment.MachineName;

3.12 Mã hóa password

Code mã hóa:


public string mahoa(string pass)
{
  return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pass.Trim(), "SHA1");
}

Password 123456 đã mã hóa sẽ như thế này:


7C4A8D09CA3762AF61E59520943DC26494F8941B

3.13 Upload hình ảnh

Bạn copy đoạn code sau vào:


bool CheckFileType(string fileName)
{
​
  string ext = Path.GetExtension(fileName);
  switch (ext.ToLower())
  {
    case ".gif":
      return true;
    case ".png":
      return true;
    case ".jpg":
      return true;
    case ".jpeg":
      return true;
    default:
      return false;
  }
}

Ở button bạn cần xử lý:


protected void btnUpload_Click(object sender, EventArgs e)
{
  if (Page.IsValid && FileUpload1.HasFile && CheckFileType(FileUpload1.FileName))
  {
    string fileName = "images/" + DateTime.Now.ToString("ddMMyyyy_hhmmss_tt_") + FileUpload1.FileName;
    string filePath = MapPath(fileName);
    FileUpload1.SaveAs(filePath);
  }
}
  • biến fileName là tên file bạn có thể bỏ vào csdl luôn


protected void btnUpload_Click(object sender, EventArgs e)
{
  if (Page.IsValid && FileUpload1.HasFile && CheckFileType(FileUpload1.FileName))
  {
    string fileName = "images/" + DateTime.Now.ToString("ddMMyyyy_hhmmss_tt_") + FileUpload1.FileName;
    string filePath = MapPath(fileName);
    FileUpload1.SaveAs(filePath);
    //Image1.ImageUrl = fileName;
    SqlCommand cmd = new SqlCommand("insert into tblcauhoi(noidung,goiy,hinhanh) values(N'" + txtnoidung.Text + "',N'" + txtgoiy.Text + "','" + fileName + "')", kn.con);
    kn.con.Open();
    cmd.ExecuteNonQuery();
    kn.con.Close();
    Response.Write("<script>alert('Thanh cong')</script>");
  }
}

3.14 Download file

Tạo một file aspx mới


 protected void Page_Load(object sender, EventArgs e)
 {
   String path = Request.QueryString["path"];
   string filename = "abc.txt";
   Response.ContentType = "application/octet-stream";
   Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
   Response.TransmitFile(Server.MapPath(path));
   Response.End();
 }
  • Dòng 4, sửa thành tên file sẽ lưu về

Đến đây bạn chỉ cần redirect hoặc href đến trang này và truyền thêm biến path vào đường dẫn


Literal1.Text += "<a href='" + "download.aspx?path=" + tb.Rows[i][1] + "' target='blank'>" + abc.txt + "</a> <br/>";

3.15 Xuất Excel


DataTable dt = new DataTable();
String sql = "select file_name from file_upload";
dt = connect.LayBang(sql);
string name_ = "du_lieu"; //Tên file excel mà bạn lưu về máy
​
//Tạo mới bảng để chép vào file excel
​
Table tb = new Table();
​
//Định dạng bảng
​
tb.BorderColor = System.Drawing.Color.FromName("red");
​
tb.CellPadding = 4;
​
tb.GridLines = GridLines.Both;
​
tb.CellSpacing = 0;
​
tb.Width = Unit.Percentage(100);
​
TableCell cell;
​
TableRow row;
​
int from = 0;
​
int to = dt.Rows.Count;
​
int header = 0;
​
for (int i = from; i < to; i++)
​
{
​
  DataRow dr = dt.Rows[i];
​
  if (header == 0)
​
  {
​
    row = new TableRow();
​
    cell = new TableCell();
​
    //so thu tu
​
    cell.Height = 50;
​
    cell.BackColor = System.Drawing.Color.FromName("orange");
​
    cell.Width = 200;
​
    cell.Text = "<b>FileName</b>";
​
    cell.HorizontalAlign = HorizontalAlign.Center;
​
    cell.VerticalAlign = VerticalAlign.Middle;
​
    row.Cells.Add(cell);
​
​
​
    tb.Rows.Add(row);
​
  }
​
  header++;
​
  row = new TableRow();
​
  cell = new TableCell();
​
​
​
  //TenSanPham
​
  cell = new TableCell();
​
  cell.Height = 50;
​
  cell.Text = dr[0].ToString();
​
  cell.HorizontalAlign = HorizontalAlign.Left;
​
  row.Cells.Add(cell);
​
  row.Cells.Add(cell);
​
​
  tb.Rows.Add(row);
​
}
​
​
Response.Clear();
​
Response.Buffer = true;
​
//excel
​
string ex_ = "xls";
​
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + name_ + "." + ex_);
​
//    Context.Response.AddHeader("Content-Length", strpath.Length.ToString());
​
Response.ContentType = "application/vnd.ms-excel";
​
Response.Charset = "UTF-8";
​
Response.ContentEncoding = System.Text.Encoding.Unicode;
​
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
​
this.EnableViewState = false;
​
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
​
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
​
tb.RenderControl(oHtmlTextWriter);
​
Response.Write(oStringWriter.ToString());
​
Response.End();

Xem thêm tại: https://expressmagazine.net/development/

3.16 Import excel


    protected void btnImport_Click(object sender, EventArgs e)
    {
      // CHECK IF A FILE HAS BEEN SELECTED.
      if ((excelUpload.HasFile))
      {
        if (!Convert.IsDBNull(excelUpload.PostedFile) &
            excelUpload.PostedFile.ContentLength > 0)
        {
​
          //FIRST, SAVE THE SELECTED FILE IN THE ROOT DIRECTORY.
          excelUpload.SaveAs(Server.MapPath(".") + "\\excel\\" + excelUpload.FileName);
​
          SqlBulkCopy oSqlBulk = null;
​
          // SET A CONNECTION WITH THE EXCEL FILE.
          string path = Server.MapPath(".") + "\\excel\\" + excelUpload.FileName;
          string Extension = System.IO.Path.GetExtension(excelUpload.PostedFile.FileName);
          string connStr = "";
          if (Extension == ".XLS" || Extension == ".XLSX" || Extension == ".xls" || Extension == ".xlsx")
          {
​
            switch (Extension)
            {
              case ".xls": //Excel 97-03
                connStr = "Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
                break;
​
              case ".xlsx": //Excel 07
                connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
                break;
            }
          }
​
          OleDbConnection myExcelConn = new OleDbConnection(connStr);
          try
          {
            myExcelConn.Open();
            string sql = "SELECT * FROM [Sheet1$]";
            using (OleDbDataAdapter adaptor = new OleDbDataAdapter(sql, myExcelConn))
            {
              DataTable ds = new DataTable();
              adaptor.Fill(ds);
              GridView1.DataSource = ds;
              GridView1.DataBind();
              for (int i = 1; i < ds.Rows.Count; i++)
              {
                string sql2 = "insert into file_upload(file_name) values('" + ds.Rows[i][0] + "')";
                connect.CapnhatCSDL(sql2);
              }
            }
​
            Response.Write("<script>alert('DATA IMPORTED SUCCESSFULLY.')</script>");
          }
          catch (Exception ex)
          {
​
            Response.Write("<script>alert('" + ex.Message + "')</script>");
​
​
          }
          finally
          {
            // CLEAR.
            //oSqlBulk.Close();
            oSqlBulk = null;
            //myExcelConn.Close();
            myExcelConn = null;
          }
        }
      }
 }

Code trên sẽ lưu file vào thư mục excel

  • Dòng 11, 16: chỉ folder lưu
  • Dòng 38 chỉ sheet cần đọc

Lưu ý:

  • Cần chọn file excel đuôi .xlsx thì code trên mới hoạt động, file excel bản cũ 97-2003 đuôi .xls đưa vào không được.

4. Tham khảo

Còn một bài viết về môn học sử dụng công nghệ này. Đó là bài viết Xây dựng phần mềm hướng đối tượng các bạn có thể tham khảo thêm nhé!


Copyright © 2025 All Right Reserved