Lập trình Web – Bài tập / Đề thi – Quản lý thư viện

Lập trình Web – Bài tập / Đề thi – Quản lý thư viện
ASP.NET MVC4 và ADO.NET và KnockoutJs

Bài viết này của tôi nằm trong series ‘các bài tập tham khảo’. Series này chia sẻ một số cách tiếp cận, hiện thực mức căn bản nhất, tóm tắt nhất các bài tập, bài tập lớn ngành Khoa học máy tính, trường ĐH Mở Tp.HCM.

Lập trình web – một môn học chuyên sâu hướng mạng máy tính, nhưng lại được nhiều sự quan tâm của hướng ngành khác. Và điển hình là tôi đã và đang theo hướng cơ sở dữ liệu, đã đăng ký môn này dưới hình thức là môn tự chọn. Môn học này cung cấp kiến thức và kỹ năng phát triển ứng dụng web. Hiện thực trên 2 công nghệ phổ biến hiện nay là ASP.NET Web form và PHP.

Tôi hy vọng bài viết này sẽ hữu ích với các bạn sinh viên IT đang quan tâm đến web.

1.     Giới thiệu

Bài viết này tôi xin trình diễn thực thi một bài tập lập trình web đơn thuần. Thực ra thì đây cũng là đề thi thực hành thực tế môn lập trình web năm 2010 .
a. Yêu cầu :
Xin tóm tắt đề như sau :
Cho csdl : ThuVien. mdb

clip_image002[6]

Xây dựng ứng dụng ASP.NET với nhu yếu sau :
Trang chủ quản lý thư viện :

clip_image004[6]

Xem list fan hâm mộ : hiển thị thông tin fan hâm mộ

clip_image006[6]

Cập nhật thông tin fan hâm mộ : sau khi chọn fan hâm mộ, form dưới sẽ hiển thị và cho chỉnh sửa thông tin fan hâm mộ. Đồng ý sẽ lưu lại, hủy bỏ sẽ xóa trắng form .

clip_image008[6]

b. Các kiến thức và kỹ năng sử dụng :
ASP.NET MVC4 : C #, Razer View Engine
ADO.NET
KnockoutJs, jQuery

2.     Thiết kế chương trình

Tóm lại, đề bài nhu yếu thực thi thao tác đọc, hiển thị và update tài liệu .
Hoạt động, tài liệu đã có sẵn, nên sau đây sẽ là kiến trúc :

Xem thêm  Ứng dụng công nghệ thông tin vào thư viện góp phần xây dựng, bảo tồn và phát triển văn hóa dân gian

clip_image009[6] 

Vậy chương trình theo kiến trúc MVC và sẽ có Rich-client .

3.     Lập trình

Việc tiên phong là chép cơ sở tài liệu vào project .
a. Model
Tôi sẽ triển khai đủ theo nhu yếu đề bài nên tôi cũng sẽ chỉ tạo ra Mã Sản Phẩm vừa đủ dùng. Vì vậy sẽ không cần chăm sóc đến bảng MuonSach .
DiaChi và DocGia quan hệ 1-1 nên tôi sẽ chọn Model :

    public class Author
    {
        public short authorId { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public DateTime birthDate { get; set; }

        public string addressNumber { get; set; }
        public string streetName { get; set; }
        public string district { get; set; }
        public string phoneNumber { get; set; }
    }

b. Data Access
Làm trách nhiệm thao tác với Database, phân phối năng lực CRUD lên Mã Sản Phẩm cho controller. Để ship hàng cho 2 trang nhiệm vụ theo đề bài thì ở đây tôi chỉ triển khai 2 hàm Read và Update :

        public List GetListOfAuthors() 
        {
            OleDbConnection dataConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _databasePath + ";Persist Security Info=True");
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select Ma, HoLot, Ten, NgaySinh, SoNha, Duong, Quan, DienThoai from DocGia, DiaChi where Ma = MaDG", dataConnection);
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            return dataTable.AsEnumerable().Select(row =>
                new Author
                {
                    authorId = row.Field("Ma"),
                    firstName = row.Field("HoLot"),
                    lastName = row.Field("Ten"),
                    birthDate = row.Field("NgaySinh"),
                    addressNumber = row.Field("SoNha"),
                    streetName = row.Field("Duong"),
                    district = row.Field("Quan"),
                    phoneNumber = row.Field("DienThoai")
                }).ToList();
        }

        public void UpdateAuthor(Author author)
        {
            OleDbConnection dataConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _databasePath + ";Persist Security Info=True");
            OleDbCommand commandToUpdateAuthor = new OleDbCommand(@"update DocGia set HoLot=?, Ten=?, Ngaysinh=? where Ma=? ", dataConnection);

            //các tham số của command trong oledb phải giữ đúng thứ tự như trong command đã khai báo. khác với sqlcommand 
            commandToUpdateAuthor.Parameters.AddWithValue("@firstName", author.firstName);
            commandToUpdateAuthor.Parameters.AddWithValue("@lastName", author.lastName);
            commandToUpdateAuthor.Parameters.AddWithValue("@birthDate", author.birthDate);
            commandToUpdateAuthor.Parameters.AddWithValue("@authorId", author.authorId);

            OleDbCommand commandToUpdateAddress = new OleDbCommand(@"update DiaChi set SoNha=?, Duong=?, Quan=?, DienThoai=? where MaDG=? ", dataConnection);

            //các tham số của command trong oledb không có định danh rõ ràng nên cần giữ đúng thứ tự như trong command đã khai báo. khác với sqlcommand 
            commandToUpdateAddress.Parameters.AddWithValue("@addressNumber", author.addressNumber);
            commandToUpdateAddress.Parameters.AddWithValue("@streetName", author.streetName);
            commandToUpdateAddress.Parameters.AddWithValue("@district", author.district);
            commandToUpdateAddress.Parameters.AddWithValue("@phoneNumber", author.phoneNumber);
            commandToUpdateAddress.Parameters.AddWithValue("@authorId", author.authorId);

            using (dataConnection)
            {
                dataConnection.Open();
                commandToUpdateAuthor.ExecuteNonQuery();
                commandToUpdateAddress.ExecuteNonQuery();
            }
}

Thông thường, ở lớp này chỉ cần sử dụng Entity Framework. Nhưng hiện tại, Entity Framework chỉ tương hỗ chính thức cho cơ sở tài liệu SQL Server. N-Hibernate đã có tương hỗ nhưng lại khá cồng kềnh. Vì vậy, sử dụng ADO.NET để liên kết và truy xuất csdl Access cũng không hẳn quan điểm tồi .

Xem thêm  Những câu hỏi gây ấn tượng với nhà tuyển dụng | Tinh tế

 

c. Controller
Theo nhu yếu đề bài sẽ cần tối thiểu 3 action cho 3 trang. Để tiện quản lý, tôi phân nhóm như sau :
HomeController : sẽ chứa action gọi đến trang chủ
BusinessController : sẽ chứa những action đến 2 trang nhiệm vụ
Với mục tiêu là kiến thiết xây dựng rich-client, tôi tạo thêm 1 DataServiceController làm trách nhiệm cung ứng cho client những API thao tác lên tài liệu. Nó sẽ gọi đến những hàm của lớp Data Access và chuyển những đối tượng người tiêu dùng thành JSON. Cũng vì hàng loạt những phương pháp thao tác với tài liệu trải qua DataServiceController nên Các kích hoạt trang chủ, nhiệm vụ chỉ làm một trách nhiệm duy nhất là trả về View

d. View
Tôi sẽ tập trung chuyên sâu vào 2 trang nhiệm vụ. Cấu trúc như sau :

clip_image010[6]

  Knockout Model:

2 trang không độc lạ quá về nhiệm vụ nên hoàn toàn có thể sử dụng cùng Model
AuthorModel. js

var AuthorModel = function (author) {
    var self = this;
    if (!author) {
        self.authorId = ko.observable("");
        self.firstName = ko.observable("");
        self.lastName = ko.observable("");
        self.addressNumber = ko.observable("");
        self.streetName = ko.observable("");
        self.district = ko.observable("");
        self.phoneNumber = ko.observable("");
        self.birthDate = ko.observable("");
    }
    else {
        self.authorId = ko.observable(author.authorId);
        self.firstName = ko.observable(author.firstName);
        self.lastName = ko.observable(author.lastName);
        self.addressNumber = ko.observable(author.addressNumber);
        self.streetName = ko.observable(author.streetName);
        self.district = ko.observable(author.district);
        self.phoneNumber = ko.observable(author.phoneNumber);

        //cần chuyển định dạng json date sang chuỗi dd/mm/yyyy
        var birthDateObj = new Date(parseInt(author.birthDate.substr(6)));
        var curr_date = birthDateObj.getDate();
        var curr_month = birthDateObj.getMonth() + 1; //getMonth() == 0 tức là tháng 1
        var curr_year = birthDateObj.getFullYear();
        self.birthDate = ko.observable(curr_date + "/" + curr_month + "/" + curr_year);
    }

    self.fullName = ko.computed(function () {
        return self.firstName() + " " + self.lastName();
    });

    //lấy dữ liệu
    self.getData = function () {
        return {
            authorId: self.authorId(),
            firstName: self.firstName(),
            lastName: self.lastName(),
            birthDate: self.birthDate(),
            addressNumber: self.addressNumber(),
            streetName: self.streetName(),
            district: self.district(),
            phoneNumber: self.phoneNumber()
        };
    };

    //sao chép
    self.copyFrom = function (authorModel) {
        self.authorId(authorModel.authorId());
        self.firstName(authorModel.firstName());
        self.lastName(authorModel.lastName());
        self.birthDate(authorModel.birthDate());
        self.addressNumber(authorModel.addressNumber());
        self.streetName(authorModel.streetName());
        self.district(authorModel.district());
        self.phoneNumber(authorModel.phoneNumber());
    };
};

  Knockout ViewModel:

ViewAuthorsViewModel. js

var AuthorsViewModel = function () {
    var self = this;
    self.listOfAuthors = ko.observableArray([]);

    self.initData = function () {
        $.getJSON("/DataService/GetJsonListOfAuthors", function (data) {

            //thêm dữ liệu vào danh sách độc giả
            $.each(data, function (key, value) {
                self.listOfAuthors.push(new AuthorModel(value));
            });

            //sắp xếp độc giả trong danh sách theo chiều tăng dần của mã độc giả
            self.listOfAuthors.sort(function (left, right) {
                if (left.authorId() == right.authorId())
                    return 0;
                else if (left.authorId() < right.authorId())
                    return -1;
                else
                    return 1;
            });
        });
    };
}

EditAuthorViewModel. js

var EditAuthorViewModel = function () {
    var self = this;
    self.listOfAuthors = ko.observableArray([]);

    self.initData = function () {
        $.getJSON("/DataService/GetJsonListOfAuthors", function (data) {

            //thêm dữ liệu vào danh sách độc giả
            $.each(data, function (key, value) {
                self.listOfAuthors.push(new AuthorModel(value));
            });
        });
    };

    self.selectingAuthor = ko.observable();

    self.editingAuthor = ko.observable(new AuthorModel());

    //chọn độc giả để chỉnh sửa
    self.editAuthor = function () {
        self.editingAuthor().copyFrom(self.selectingAuthor());
    };

    //cập nhật độc giả
    self.updateData = function() {
        $.post("/DataService/UpdateAuthor",
            self.editingAuthor().getData(),
            function (data) {
                if (data.completed == true) {
                    //sau khi thêm thành công trên server, cập nhật toàn bộ các biến không được tham chiếu
                    var length = self.listOfAuthors().length;
                    for (var i = 0; i < length; i++)
                    {
                        if (self.listOfAuthors()[i].authorId() == self.editingAuthor().authorId()) {
                            self.listOfAuthors()[i].copyFrom(self.editingAuthor());
                            break;
                        }
                    }
                } else {
                    alert(data.message);
                }
            }
        );
    };

    //xóa trạng thái chọn
    self.clearEditData = function () {
        self.editingAuthor(new AuthorModel());
    };
}

  Knockout View:

Xem thêm  [Fanmade] Âm Dương Sư - thức thần Sesshoumaru hướng dẫn bỏ túi | Tin tức có ích về game mới nhất từ Bem2

ViewAuthors. cshtml

Mục lục bài viết

Xem danh sách độc giả


<< Trở về trang chủ
Họ lót Tên Số Nhà Đường Quận Điện thoại

EditAuthor. cshtml

Danh sách độc giả



Mã ĐG:
Họ Lót:
Tên:
Ngày Sinh:
Số Nhà:
Đường:
Quận:
Điện thoại:
<< Trở về trang chủ

  Code behind:

ViewAuthors. js

$(function () {
    $(document).ready(function () {
        
        var viewAuthorsViewModel = new ViewAuthorsViewModel();
        viewAuthorsViewModel.initData();
        ko.applyBindings(viewAuthorsViewModel);
    });
});

EditAuthor. js

$(function () {
    $(document).ready(function () {
        
        var editAuthorViewModel = new EditAuthorViewModel();
        editAuthorViewModel.initData();
        ko.applyBindings(editAuthorViewModel);
    });
});

4.     CSS cho đẹp nữa là hoàn tất 😛

5.     Tài nguyên

Link tải về CSDL thuvien.mdb : http://www.mediafire.com/?6623sij71cjd1cv

Bài viết đến đây là hết. Cám ơn những bạn đã chăm sóc. Rất vui nhận được góp ý của những bạn

Chia sẻ:

  • Thêm

Thích bài này:

Thích

Đang tải ...

Rate this post

Bài viết liên quan

Để lại ý kiến của bạn:

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *