COURSE 70-528 ALL LABS

Published on July 2016 | Categories: Documents | Downloads: 36 | Comments: 0 | Views: 1101
of 296
Download PDF   Embed   Report

Comments

Content

MCPD Web Developer

Course 70-528

LAB 1 - ADO.NET FUNDAMENTALS
FROM LESSON

From Lesson 1 : Connect to Microsoft Access Database: Northwind.mdb (Microsoft Access Sample Database)



Create Win Form Application, recommended as below: File  New  Project

• •
• •

After creating your project, copy file “Northwind.mdb” to “\bin\Debug” folder of your project (ex: D:\Projects\ADO\bin\Debug) Design your Win Form by dragging 3 buttons from Toolbox to Windows Form like below: Write code for 3 buttons by double-clicking each buttons like below: Running Your Application

Page 1 of 296

MCPD Web Developer

Course 70-528

Form1.cs using System; using System.Data; using System.Data.OleDb; using System.Windows.Forms; namespace ADOLab1 { public partial class Form1 : Form { //declare class variable conn for using globaly private OleDbConnection conn = new OleDbConnection(" Provider=Microsoft.Jet.OleDb.4.0;Data Source=Northwind.mdb"); public Form1() { InitializeComponent(); } //code for button : ‘Connect to Access Northwind’ private void btnConnectDB_Click(object sender, EventArgs e) { try { conn.Open(); MessageBox.Show("Connect Access Succesfully"); } catch(Exception ex) { MessageBox.Show("Connect to Access Fail due to Error:" + ex.Message); } }
Page 2 of 296

MCPD Web Developer

Course 70-528

} }

//code for button : ‘Close database’ private void btnViewDB_Click(object sender, EventArgs e) { String strState = "Closed"; if (conn.State == ConnectionState.Open) strState = "Openned"; MessageBox.Show("Current Connection State :" + strState + DataSource :" + conn.DataSource); } //code for button : ‘View Database Information’ private void btnCloseDB_Click(object sender, EventArgs e) { conn.Close(); MessageBox.Show("Database Access Closed!"); }

",

From Lesson 2 : Connect to Microsoft SQL Server Server: Microsoft SQL Server 2005 Database: Northwind • Checking “Microsoft SQL Server 2005”, make sure The SQL Server 2005 is running



Add new Win Form to your projects by right-clicking project name  choose Add  Window Form. Choose template: “Windows Form”. Then click “Add”

Page 3 of 296

MCPD Web Developer

Course 70-528



Design this form just like the form in “From Lesson 1”, code for 3 buttons below

Form2.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab1 { public partial class Form2 : Form { //declare class variable conn for using globaly
Page 4 of 296

MCPD Web Developer

Course 70-528

} }

private SqlConnection conn = new SqlConnection(" server=.;database=Northwind;Integrated Security=True"); public Form2() { InitializeComponent(); } private void btnConnectDB_Click(object sender, EventArgs e) { try { conn.Open(); MessageBox.Show("Connect SQL Server Succesfully"); }catch (Exception ex) { MessageBox.Show("Connect to SQL Server Fail due to Error:" + ex.Message); } } private void btnViewDB_Click(object sender, EventArgs e) { String strState = "Closed"; if (conn.State == ConnectionState.Open) strState = "Openned"; MessageBox.Show("Current Connection State :" + strState + ", DataSource :" + conn.DataSource); } private void btnCloseDB_Click(object sender, EventArgs e) { conn.Close(); MessageBox.Show("Database SQL Server Closed!"); }



Running your application – Set up Startup form by revise start execute function of C# application Main() like bellow

Page 5 of 296

MCPD Web Developer

Course 70-528

From Lesson 3 : Using Command object Database: Use database Northwind sample of MS SQL Server database, Table Employees



Add new Window Form to your project

Form description • User click “Execute Scalar” button: Get the first column of the first row of Employees table, and display message. • User click “Insert” button: Insert Employee with info: a. Title : “Mr.” b. First Name : “Jack” c. Last Name : “Band” (After Insert display message: Insert OK!) • User click “Update” button: Update info of employee where first name = “Jack” and Last Name = “Band” with new info a. First Name : “James” b. Last Name : “Bond” (After Update display message: Update OK!) • User click “Delete” button : Delete employee where first name = “James” , Last Name = “Bond”



(After Insert display message: Delete OK!)

Form3.cs using System; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab1 {
Page 6 of 296

MCPD Web Developer

Course 70-528

public partial class Form3 : Form { private SqlConnection conn = new SqlConnection(" server=SERVER_NAME;database=Northwind;Integrated Security=True"); public Form3() { InitializeComponent(); } private void btnExecuteScalar_Click(object sender, EventArgs e) { conn.Open(); SqlCommand cmd = new SqlCommand("Select * From Employees", conn); MessageBox.Show(cmd.ExecuteScalar().ToString()); conn.Close(); } private void btnInsert_Click(object sender, EventArgs e) { String cmdStr = "Insert Into Employees(Title,FirstName,LastName) Values('Mr.','Jack','Band')"; conn.Open(); SqlCommand cmd = new SqlCommand(cmdStr, conn); if (cmd.ExecuteNonQuery() > 0) MessageBox.Show("Insert OK!"); else MessageBox.Show("Insert Fail !"); conn.Close(); } private void btnUpdate_Click(object sender, EventArgs e) { String cmdStr = "Update Employees Set FirstName='James',LastName='Bond' Where FirstName='Jack' and LastName='Band'"; conn.Open(); SqlCommand cmd = new SqlCommand(cmdStr, conn); if (cmd.ExecuteNonQuery() > 0) MessageBox.Show("Update OK!"); else MessageBox.Show("Update Fail !"); conn.Close(); } private void btnDelete_Click(object sender, EventArgs e) { String cmdStr = "Delete From Employees Where FirstName='James' and LastName='Bond'"; conn.Open(); SqlCommand cmd = new SqlCommand(cmdStr, conn); if (cmd.ExecuteNonQuery() > 0) MessageBox.Show("Delete OK!"); else MessageBox.Show("Delete Fail !"); conn.Close(); } } }

Page 7 of 296

MCPD Web Developer

Course 70-528

From Lesson 4 : Using DataReader object

a. Get single result from data

Form4.cs using System; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab1 { public partial class Form4 : Form { public Form4() { InitializeComponent(); } private void btnGet_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection( "server=.;database=Northwind;Integrated Security=True"); conn.Open(); SqlCommand cmd = new SqlCommand("Select EmployeeID,FirstName,LastName From Employees", conn); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { txtData.Text = txtData.Text + dr["EmployeeID"] + "\t" + dr["FirstName"] + "\t" + dr["LastName"] + Environment.NewLine; } conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); } } } }

Page 8 of 296

MCPD Web Developer

Course 70-528

b. Get multiple Result from Data

Form4.cs using System; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab1 { public partial class Form4 : Form { public Form4() { InitializeComponent(); } private void btnGet_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection(" server=.;database=Northwind;Integrated Security=True"); conn.Open(); SqlCommand cmd = new SqlCommand("Select EmployeeID,FirstName,LastName From Employees;Select CustomerID,CompanyName,ContactName From Customers", conn); SqlDataReader dr = cmd.ExecuteReader(); txtData.Text = "Employee Table" + Environment.NewLine; while (dr.Read()) { txtData.Text += dr["EmployeeID"] + "\t" + dr["FirstName"] + "\t" + dr["LastName"] + Environment.NewLine;
Page 9 of 296

MCPD Web Developer

Course 70-528

} txtData.Text += "________________________________________________________" + Environment.NewLine; txtData.Text += "Customer Table" + Environment.NewLine; dr.NextResult(); while (dr.Read()) { txtData.Text += dr["CustomerID"] + "\t" + dr["CompanyName"] + "\t\t" + dr["ContactName"] + Environment.NewLine; } conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); }

} } }

EXERCISE - REAL WORLD SITUATION
1. Scenario: •
You want to make a form to manage your Customer at Northwind Traders. Database’s availabe in SQL Server 2005 (Northwind). Use Customers Table in Database.

Data defition

Data Sample

2. Requirements
• You must do “Updating Form” and “Inserting Form” in SAME ONE FORM. Every database operations must be done with SqlDataReader, SqlCommand Object.

Page 10 of 296

MCPD Web Developer

Course 70-528

Updated Mode : This is the initial mode when form is firstly loaded

Description: • The purpose of update mode is updating customer’s information When the form is firstly loaded, it will be in “update mode”, the ComboBox CustomerID (cbID) should be filled with all CustomerID in Customers Table. The first customer in the list must be chosen in this first loading-time. The cbID must be read-only. When the user choose another CustomerID from ComboBox, the information of this Customer will be get and fill in others field of the form. Any Customer’s field is blank will be commented with “N/A” line GroupBox’s Text will notify user whether it’s in “insert mode” or “update mode” In “update mode”, button “U” (btnUpdate button) should be disabled

• •
• • •

Page 11 of 296

MCPD Web Developer

Course 70-528



When user click “OK” button, the new information of current chosen Customer will be updated to the database. 2 Fields : CustomerID, CompanyName is required, others are not required (if user left these fields blank, a Null value must be given to database column) • When user click “Delete” button, program must ask user to make sure to delete current Customer. If user has confirmed to delete current chosen customer, the current chosen customer information will be deleted from database. After this delete-action, the customerID list must be refreshed • When user click “N” button (btnNew button), the form will be changed to “insert mode” Inserted Mode: inserting new customer to database

Description: • The purpose of “insert mode” is inserting new customer to database When user change from “update mode” to “insert mode”, the CustomerID ComboBox (cbID) must be disappear, and the textbox CustomerID appear, other Fields must be cleared. When user click “OK” button, the information of New Customer will be inserted to the database. 2 Fields : CustomerID, CompanyName is required, others are not required (if user left these fields blank, a Null value must be given to database column) In “update mode”, button “U” (btnUpdate button) should be disabled When user click “U” button (btnUpdate button), the form will be changed to “update mode”


• • •

Form5_Exercise.cs using System.Data.SqlClient; using System.Windows.Forms;
Page 12 of 296

MCPD Web Developer

Course 70-528

namespace ADOLab1 { public partial class Form5_Exercise : Form { private static readonly string connStr = "server=.;database=Northwind;Integrated Security=True"; private readonly SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd; SqlDataReader dr; bool insertMode; public Form5_exercise() { InitializeComponent(); } private void Form5_exercise_Load(object sender, System.EventArgs e) { GetCustomerIDList(); } public void GetCustomerIDList() { //kiem tra neu list da co du lieu thi phai xoa het di if (cbID.Items.Count > 0) cbID.Items.Clear(); insertMode = false; cbID.Visible = true; txtID.Visible = false; conn.Open(); cmd = new SqlCommand("Select CustomerID From Customers", conn); dr = cmd.ExecuteReader(); while (dr.Read()) { cbID.Items.Add(dr[0]); } conn.Close(); //sort du lieu theo alphabet cbID.Sorted = true; //chon ve muc du lieu dau tien cbID.SelectedIndex = 0; //neu selectedindex van de la 0 thi khi tu trang thai new //back ve trang thai update ,ko goi ham setcustomerinfobyid SetCustomerInfoByID(cbID.SelectedItem.ToString()); btnDelete.Visible = true; GroupBox1.Text = "In Update Customer Mode"; btnNew.Enabled = true; btnUpdate.Enabled = false; } public void ClearData() { txtID.Visible = true; cbID.Visible = false; txtCompanyName.Text = ""; txtContactName.Text = ""; txtContactTitle.Text = ""; txtAddress.Text = ""; txtCity.Text = ""; txtRegion.Text = ""; txtPostalCode.Text = "";
Page 13 of 296

MCPD Web Developer

Course 70-528

txtCountry.Text = ""; txtPhone.Text = ""; txtFax.Text = ""; insertMode = true; btnDelete.Visible = false; GroupBox1.Text = "In New Customer Mode"; btnNew.Enabled = false; btnUpdate.Enabled = true; } public void SetCustomerInfoByID(string id) { conn.Open(); cmd = new SqlCommand("Select * From Customers Where CustomerID='" + id + "'", conn); dr = cmd.ExecuteReader(); while (dr.Read()) { txtCompanyName.Text = dr["CompanyName"].ToString(); //chu y System.DBNull.Value trong DB txtContactName.Text = getDisplayStr(dr["ContactName"].ToString()); txtContactTitle.Text = getDisplayStr(dr["ContactTitle"].ToString()); txtAddress.Text = getDisplayStr(dr["Address"].ToString()); txtCity.Text = getDisplayStr(dr["City"].ToString()); txtRegion.Text = getDisplayStr(dr["Region"].ToString()); txtPostalCode.Text = getDisplayStr(dr["PostalCode"].ToString()); txtCountry.Text = getDisplayStr(dr["Country"].ToString()); txtPhone.Text = getDisplayStr(dr["Phone"].ToString()); txtFax.Text = getDisplayStr(dr["Fax"].ToString()); } conn.Close(); } private static string getDisplayStr(string displayStr) { return ReferenceEquals(displayStr, System.DBNull.Value) ? "N/A" : displayStr; } private void btnNew_Click(object sender, System.EventArgs e) { ClearData(); } private void btnUpdate_Click(object sender, System.EventArgs e) { GetCustomerIDList(); } private void cbID_SelectedIndexChanged(object sender, System.EventArgs e) { SetCustomerInfoByID(cbID.SelectedItem.ToString()); } private void btnOK_Click(object sender, System.EventArgs e) { conn.Open(); string cmdStr; string contactName = getSafeInputString(txtContactName.Text.Trim()); string contactTitle = getSafeInputString(txtContactTitle.Text.Trim()); string address = getSafeInputString(txtAddress.Text.Trim()); string city = getSafeInputString(txtCity.Text.Trim()); string region = getSafeInputString(txtRegion.Text.Trim()); string postalCode = getSafeInputString(txtPostalCode.Text.Trim()); string country = getSafeInputString(txtCountry.Text.Trim()); string phone = getSafeInputString(txtPhone.Text.Trim());
Page 14 of 296

MCPD Web Developer

Course 70-528

string fax = getSafeInputString(txtFax.Text.Trim()); //cho ca 2 truong hop insert va update //kiem tra 2 truong ID va CompanyName phai duoc nhap day du //va truong ID ko duoc phep trung voi nhung ID co san if ((((txtID.Text.Trim() == "" | txtCompanyName.Text.Trim() == "") & insertMode) | (txtCompanyName.Text.Trim() == "" & insertMode == false))) { MessageBox.Show("Customer ID and Company Name can't be left blank!"); conn.Close(); return;

} else if ((cbID.Items.Contains(txtID.Text.Trim()))) { MessageBox.Show("Customer ID already exists ! Please choose another ID !"); conn.Close(); return; } if (insertMode) cmdStr = "Insert Customers Values('" + txtID.Text.Trim() + "','" + txtCompanyName.Text.Trim() + "'," + contactName + "," + contactTitle + "," + address + "," + city + "," + region + "," + postalCode + "," + country + "," + phone + "," + fax + ")"; else cmdStr = "Update Customers Set companyName='" + txtCompanyName.Text.Trim() + "',contactName=" + contactName + ",contactTitle=" + contactTitle + ",address=" + address + ",city=" + city + ",region=" + region + ",postalCode=" + postalCode + ",country=" + country + ",phone=" + phone + ",fax=" + fax + " where CustomerID='" + cbID.SelectedItem + "'"; cmd = new SqlCommand(cmdStr, conn); cmd.ExecuteNonQuery(); if (insertMode) MessageBox.Show("Insert Successful!"); else MessageBox.Show("Update Successful!"); conn.Close(); } private static string getSafeInputString(string str) { return (str == "N/A" || str == "" ? "null" : "'" + str + "'"); } private void btnDelete_Click(object sender, System.EventArgs e) { DialogResult ask = MessageBox.Show("Are you sure to delete this customer?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (ask == DialogResult.Yes) { conn.Open(); cmd = new SqlCommand("Delete from Customers Where CustomerID='" + cbID.SelectedItem + "'", conn); cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("Customer Deleted Successful!"); GetCustomerIDList(); } }

}

Page 15 of 296

MCPD Web Developer

Course 70-528

}

Page 16 of 296

MCPD Web Developer

Course 70-528

LAB 2 - DISCONNECTED ARCHITECTURE
FROM LESSON
From Lesson 1: Get Data from Database (SQL Server) Server: SQL Server 2005 Database: Northwind Table : Employees

btnLoad_Click //code for button “Load Data from SQL Server”(btnLoad) private void btnLoad_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection(" server=.;database=Northwind;Integrated Security=True"); conn.Open(); SqlDataAdapter da =new SqlDataAdapter("Select * From Employees", conn); DataSet ds = new DataSet(); da.Fill(ds, "Employee"); dgEmployee.DataSource = ds.Tables["Employee"]; conn.Close(); } catch(Exception ex) { } }
Page 17 of 296

MCPD Web Developer

Course 70-528

From Lesson 2 : Create data by coding

btnCreate_Click private void btnCreate_Click(object sender, EventArgs e) { String[] valName = { "Sachin", "Avinash", "Rahul" }; DataTable productsTable = new DataTable("Products"); productsTable.Columns.Add("ID", Type.GetType("System.Int32")); productsTable.Columns.Add("Name", Type.GetType("System.String")); productsTable.Columns.Add("Category", Type.GetType("System.Int32")); productsTable.Columns[0].AutoIncrement = true; productsTable.Columns[0].AutoIncrementSeed = 1; productsTable.Columns[0].ReadOnly = true; for (int i = 0; i < 3; i++) { DataRow drRow = productsTable.NewRow(); drRow["Name"] = valName[i]; drRow["Category"] = i + 1; productsTable.Rows.Add(drRow); } DataSet myDS = new DataSet("Product Details"); myDS.Tables.Add(productsTable); dgProduct.DataSource = myDS.Tables["Products"]; }

Page 18 of 296

MCPD Web Developer

Course 70-528

From Lesson 3: Insert/Update/Delete in DataGrid Server: SQL Server 2005 Database: Pubs Table : Authors

Form1.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab2_3 { public partial class Form1 : Form { private SqlDataAdapter da; private SqlConnection conn; private DataSet ds; public Form1() { InitializeComponent(); } //code for form_load event private void Form1_Load(object sender, EventArgs e) { try { conn = new SqlConnection("server=.;database=pubs;Integrated Security=True ");
Page 19 of 296

MCPD Web Developer

Course 70-528

}

} catch(Exception ex) { }

conn.Open(); da = new SqlDataAdapter("Select au_id,au_lname,au_fname,phone,contract From Authors", conn); da.Fill(ds); dgAuthor.DataSource = ds.Tables[0];

} }

//code for button “Save”(btnSave) private void btnSave_Click(object sender, EventArgs e) { SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da); DataSet dsChanged = ds.GetChanges(); da.Update(dsChanged); ds.AcceptChanges(); MessageBox.Show("Database Updated!"); conn.Close(); }

From Lesson 4: Filter Data by using DataView

Form1.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms;

Page 20 of 296

MCPD Web Developer

Course 70-528

namespace ADOLab2_4 { public partial class Form1 : Form { private SqlConnection conn; private SqlDataAdapter da; private DataSet ds; public Form1() { InitializeComponent(); } private void btnAll_Click(object sender, EventArgs e) { try { ds.Clear(); conn = new SqlConnection(" server=SERVER_NAME;database=Northwind;Integrated Security=True"); conn.Open(); da = new SqlDataAdapter("Select CustomerID,CompanyName,ContactName,ContactTitle,City,Country,Phone, Fax From Customers",conn); da.Fill(ds, "Customers"); dgCustomer.DataSource = ds.Tables["Customers"]; conn.Close(); } catch (Exception ex) { } } private void btnFilter_Click(object sender, EventArgs e) { DataView dv = new DataView(ds.Tables["Customers"]); dv.RowFilter = "Country like 'USA'"; dgCustomer.DataSource = dv; } } }

EXERCISE
• 1. Scenario: You want to make to manage the results of University Entry Tester 2. Requirements: Use DataSet, SqlDataAdapter, SqlCommand Object to handle database operations. Database : SQL Server (TUYENSINHDAIHOC) with 1 table : THISINH with following information




Page 21 of 296

MCPD Web Developer

Course 70-528

THI SINH

Page 22 of 296

MCPD Web Developer

Course 70-528

1 2 3

Event Form_Load btnThem_click btnXoa_click

Tasks Load All Tester with Result Information (7 columns: MASO, HOTEN, NGAYSINH, KHOITHI, DIEM1, DIEM2, DIEM3) to datagrid dgThisinh Reset all field in “Chi tiết thí sinh” Area and ready for insert new tester Note: txtMaso is readonly in “Chi tiết thí sinh” area Delete datagriad’s current chosen tester with confirmation :

4 5 6

btnDanhsach_click dgThisinh_click btnChapnhan_click

7 8 9

rbTimTen_CheckedChanged rbTimMaSo_CheckedChanged btnTim_click

Load All Tester with Result Information (7 columns: MASO, HOTEN, NGAYSINH, KHOITHI, DIEM1, DIEM2, DIEM3) to datagrid dgThisinh (similar to Form_Load event) When clicking (choosing) a tester in datagrid, his information will be filled in “Chi tiết thí sinh” area Process for 2 mode : InsertedMode and UpdatedMode • InsertedMode : Insert new Tester to THISINH table • UpdatedMode : Update current chosen tester information After processing, Refresh all tester information from database. Enable txtTimTen, Disable txtTimMaso Disable txtTimTen, Enable txtTimMaso Based on which options enabled (rbTimTen or rbTimMaso), processing the requirements: • Search by name : compare user’s entered name with HOTEN column in THISINH table to find matchs  Display result in Datagrid dgThisinh. • Search by tester code : compare user’s entered code with MASO column in THISINH table to find a match  display result by filling “Chi tiết thí sinh” area.

Form2_exercise.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab2_3 { public partial class Form2_exercise : Form { readonly SqlConnection conn = new SqlConnection("server=.;database=TUYENSINHDAIHOC;Integrated Security=True "); SqlDataAdapter da; DataSet ds; SqlCommand cmd; bool insertMode = true; public Form2_exercise() { InitializeComponent(); } private void Form2_exercise_Load(object sender, EventArgs e) { try
Page 23 of 296

MCPD Web Developer

Course 70-528

{

} catch (Exception ex) { MessageBox.Show("Connect database failed:" + ex.StackTrace); } } public void GetAll() { da = new SqlDataAdapter("SELECT MASO, HOTEN, NGAYSINH, KHOITHI, DIEM1, DIEM2, DIEM3 FROM THISINH", conn); ds = new DataSet(); da.Fill(ds, "THISINH"); dgThisinh.DataSource = ds.Tables["THISINH"]; } public void SetThisinhInfoByMaso(string maso) { da = new SqlDataAdapter("SELECT * FROM THISINH WHERE MASO='" + maso + "'", conn); ds = new DataSet(); da.Fill(ds, "THISINH"); if (ds.Tables["THISINH"].Rows.Count > 0) { DataRow row = ds.Tables["THISINH"].Rows[0]; txtMaso.Text = row["MASO"].ToString(); txtHoten.Text = row["HOTEN"].ToString(); txtNgaysinh.Text = row["NGAYSINH"].ToString(); txtDiachi.Text = row["DIACHI"].ToString(); txtCMND.Text = row["CMND"].ToString(); cbKhoithi.Text = row["KHOITHI"].ToString(); txtMon1.Text = row["DIEM1"].ToString(); txtMon2.Text = row["DIEM2"].ToString(); txtMon3.Text = row["DIEM3"].ToString(); insertMode = false; } else { MessageBox.Show("Không tìm thấy thí sinh có mã số " + maso); } } private void btnThem_Click(object sender, EventArgs e) { txtMaso.ReadOnly = false; insertMode = true; txtMaso.Text = ""; txtHoten.Text = ""; txtNgaysinh.Text = ""; txtDiachi.Text = ""; txtCMND.Text = ""; cbKhoithi.Text = ""; txtMon1.Text = ""; txtMon2.Text = ""; txtMon3.Text = ""; } private void btnChapnhan_Click(object sender, EventArgs e) { try {
Page 24 of 296

conn.Open(); GetAll();

MCPD Web Developer

Course 70-528

if ((txtMaso.Text == "" | txtHoten.Text == "" | txtNgaysinh.Text == "" | txtDiachi.Text == "" | txtCMND.Text == "" | cbKhoithi.Text == "" | txtMon1.Text == "" | txtMon2.Text == "" | txtMon3.Text == "")) { MessageBox.Show("Hãy điền đầy đủ thông tin !"); return; } string cmdStr = ""; if (insertMode) cmdStr = "INSERT INTO THISINH(MASO,HOTEN,NGAYSINH,DIACHI,CMND,KHOITHI,DIEM1,DIEM2,DIEM3) VALUES('" + txtMaso.Text.Trim() + "',N'" + txtHoten.Text + "','" + DateTime.Parse(txtNgaysinh.Text) + "',N'" + txtDiachi.Text + "','" + txtCMND.Text + "','" + cbKhoithi.Text + "'," + txtMon1.Text + "," + txtMon2.Text + "," + txtMon3.Text + ")"; else cmdStr = "UPDATE THISINH SET HOTEN=N'" + txtHoten.Text.Trim() + "',NGAYSINH='" + txtNgaysinh.Text + "',DIACHI=N'" + txtDiachi.Text + "',CMND='" + txtCMND.Text + "',KHOITHI='" + cbKhoithi.Text + "',DIEM1=" + txtMon1.Text + ",DIEM2=" + txtMon2.Text + ",DIEM3=" + txtMon3.Text + " WHERE MASO='" + txtMaso.Text + "'"; cmd = new SqlCommand(cmdStr, conn); cmd.ExecuteNonQuery(); cmd.Dispose(); MessageBox.Show("Thành công"); GetAll(); insertMode = false; } catch (Exception ex) { MessageBox.Show("Có lỗi:" + ex.Message); }

}

private void btnXoa_Click(object sender, EventArgs e) { try { string strMaso = dgThisinh.CurrentRow.Cells[0].Value.ToString(); if ((MessageBox.Show("Bạn có chắc muốn xóa thí sinh có mã số " + strMaso, "Hỏi?", MessageBoxButtons.YesNo) == DialogResult.Yes)) { string cmdStr = "DELETE FROM THISINH WHERE MASO='" + strMaso + "'"; cmd = new SqlCommand(cmdStr, conn); cmd.ExecuteNonQuery(); cmd.Dispose(); MessageBox.Show("Ðã xoá thí sinh có mã số" + strMaso); GetAll(); } } catch (Exception ex) { MessageBox.Show("Có l?i:" + ex.Message); } } private void btnTim_Click(object sender, EventArgs e) {
Page 25 of 296

MCPD Web Developer

Course 70-528

try { if (rbTimTen.Checked) { string cmdStr = "SELECT * FROM THISINH WHERE HOTEN like N'%" + txtTimTen.Text.Trim() + "%'"; da = new SqlDataAdapter(cmdStr, conn); ds = new DataSet(); da.Fill(ds, "THISINH"); if ((ds.Tables["THISINH"].Rows.Count > 0)) { dgThisinh.DataSource = ds.Tables["THISINH"]; da.Dispose(); } else MessageBox.Show("Không tim thấy thí sinh có tên " + txtTimTen.Text); } else if (rbTimMaso.Checked) SetThisinhInfoByMaso(txtTimMaso.Text.Trim()); } catch (Exception ex) { MessageBox.Show("Có lỗi:" + ex.Message); }

} }

} private void btnDanhsach_Click(object sender, EventArgs e) { GetAll(); } private void rbTimTen_CheckedChanged(object sender, EventArgs e) { txtTimTen.ReadOnly = false; txtTimMaso.ReadOnly = true; } private void rbTimMaso_CheckedChanged(object sender, EventArgs e) { txtTimTen.ReadOnly = true; txtTimMaso.ReadOnly = false; } private void dgThisinh_Click(object sender, EventArgs e) { SetThisinhInfoByMaso(dgThisinh.CurrentRow.Cells[0].Value.ToString()); txtMaso.ReadOnly = true; }

Page 26 of 296

MCPD Web Developer

Course 70-528

LAB 3 : STORED PROCEDURES AND TRANSACTIONAL OPERATION
FROM LESSON
From Lesson 1 : Calling GET_ALL_CUSTOMERS Stored Procedure to get all Customers from Customers table of Northwind database



Create Stored procedures

GetAllCustomer CREATE PROCEDURE dbo.GetAllCustomer AS Select * From Customer RETURN Code for button click private void btnGetData_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection("server=.;database=Northwind;Integrated Security=True"); conn.Open(); SqlCommand cmd = new SqlCommand("GetAllCustomer", conn);
Page 27 of 296

MCPD Web Developer

Course 70-528

cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "Customers"); dgCustomer.DataSource = ds.Tables["Customers"]; conn.Close(); } catch(Exception ex) { } }

From Lesson 2 :Using NonQuery Stored Procedures to Insert /Update/ Delete Employee from Employee table of Northwind database :



Calling INSERT_EMPLOYEE Stored Procedure to insert new Employee to Employees table.

INSERT_EMPLOYEE CREATE PROC INSERT_EMPLOYEE ( @ID INT OUT, @TITLE VARCHAR(30), @FIRSTNAME NVARCHAR(10), @LASTNAME NVARCHAR(20) ) AS INSERT INTO EMPLOYEES(TITLE,FIRSTNAME,LASTNAME) VALUES(@TITLE,@FIRSTNAME,@LASTNAME) IF @@ERROR=0 SET @ID = @@IDENTITY



Calling UPDATE_EMPLOYEE Store Procedure to update employee.

UPDATE_EMPLOYEE CREATE PROC UPDATE_EMPLOYEE ( @ID INT , @TITLE VARCHAR(30), @FIRSTNAME NVARCHAR(10), @LASTNAME NVARCHAR(20) ) AS UPDATE EMPLOYEES SET TITLE = @TITLE, FIRSTNAME=@FIRSTNAME, LASTNAME=@LASTNAME WHERE EMPLOYEEID= @ID



Calling DELETE_EMPLOYEE Store Procedure to delete employee.

DELETE_EMPLOYEE CREATE PROC DELETE_EMPLOYEE ( @ID INT ) AS DELETE EMPLOYEES WHERE EMPLOYEEID=@ID

Page 28 of 296

MCPD Web Developer

Course 70-528

1 2 3

Event Button1_Click Button2_Click Button3_Click

Description - Insert new employee to Employee Table - Fill new employee to below Datagrid - Update current employee information - Refresh datagrid below to get updated information - Delete current employee - Clear the datagrid

From2.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab3 { public partial class Form2 : Form { readonly SqlConnection conn = new SqlConnection("server=.;database=Northwind;uid=sa;pwd=sa"); int curEmpID; public Form2() { InitializeComponent(); } public void RefreshDataGrid() { conn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select EmployeeID,Title,FirstName,LastName From Employees Where EmployeeID=" + curEmpID, conn); DataSet ds = new DataSet(); da.Fill(ds, "Employees"); dgEmployee.DataSource = ds.Tables["Employees"];
Page 29 of 296

MCPD Web Developer

Course 70-528

da.Dispose(); conn.Close(); } private void btnInsert_Click(object sender, EventArgs e) { try { conn.Open(); SqlCommand cmd = new SqlCommand("INSERT_EMPLOYEE", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter ID_PARM = new SqlParameter(); ID_PARM.ParameterName = "@ID"; ID_PARM.SqlDbType = SqlDbType.Int; ID_PARM.Direction = ParameterDirection.Output; cmd.Parameters.Add(ID_PARM); cmd.Parameters.Add(new SqlParameter("@TITLE", txtTitle.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@FIRSTNAME", txtFirstName.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@LASTNAME", txtLastName.Text.Trim())); cmd.ExecuteNonQuery(); curEmpID = (int)ID_PARM.Value; MessageBox.Show("New Employee Created : ID = " + ID_PARM.Value); cmd.Dispose(); conn.Close(); RefreshDataGrid(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnUpdate_Click(object sender, EventArgs e) { try { conn.Open(); SqlCommand cmd = new SqlCommand("UPDATE_EMPLOYEE", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID", curEmpID)); cmd.Parameters.Add(new SqlParameter("@TITLE", txtTitle.Text)); cmd.Parameters.Add(new SqlParameter("@FIRSTNAME", txtFirstName.Text)); cmd.Parameters.Add(new SqlParameter("@LASTNAME", txtLastName.Text)); cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("Employee Updated"); RefreshDataGrid(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnDelete_Click(object sender, EventArgs e) { try { conn.Open();
Page 30 of 296

MCPD Web Developer

Course 70-528

} catch (Exception ex) { MessageBox.Show(ex.Message); } } } }

SqlCommand cmd = new SqlCommand("DELETE_EMPLOYEE", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID", curEmpID)); cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("Employee Deleted"); txtTitle.Text = ""; txtFirstName.Text = ""; txtLastName.Text = ""; curEmpID = -1; dgEmployee.DataSource = null;

From Lesson 3 : Using Transaction to update database series Database • Create Database “DIALY” in SQL Server with 2 tables : MIEN, THANHPHO

Forms Description

Page 31 of 296

MCPD Web Developer

Course 70-528

Event Form_Load Button “Execute 2 Commands” Button “Commit Transaction” Button “Rollback Transaction”

Description Load all rows in 2 tables MIEN, THANHPHO to 2 DataGridView in your Project Insert 2 rows : “2,Mien Bac” to table MIEN and “2, Ha Noi” to table THANHPHO Commit transaction Rollback transaction

From3.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab3 { public partial class Form3 : Form { readonly SqlConnection conn = new SqlConnection("server=.;database=Dialy;Integrated Security=True "); SqlTransaction transaction; public Form3() { InitializeComponent(); } public void BindData() { SqlDataAdapter da = new SqlDataAdapter("Select * from Mien", conn); DataTable dt1 = new DataTable("Mien"); da.Fill(dt1); dgMien.DataSource = dt1; DataTable dt2 = new DataTable("Thanhpho"); da = new SqlDataAdapter("Select * From Thanhpho", conn); da.Fill(dt2);
Page 32 of 296

MCPD Web Developer

Course 70-528

} }

dgThanhpho.DataSource = dt2; } private void Form3_Disposed(object sender, EventArgs e) { conn.Close(); } private void Form3_Load(object sender, EventArgs e) { conn.Open(); BindData(); } private void btnExecute_Click(object sender, EventArgs e) { SqlCommand cmd1 = new SqlCommand("Insert Into Mien Values(2,'Mien Bac')", conn); SqlCommand cmd2 = new SqlCommand("Insert Into Thanhpho Values(2,'Ha Noi')", conn); transaction = conn.BeginTransaction(); cmd1.Transaction = transaction; cmd2.Transaction = transaction; cmd1.ExecuteNonQuery(); cmd2.ExecuteNonQuery(); MessageBox.Show("2 commands have been executed succesful - waiting for transaction commit or rollback"); } private void btnCommit_Click(object sender, EventArgs e) { transaction.Commit(); MessageBox.Show("Commit Transaction"); BindData(); } private void btnRollback_Click(object sender, EventArgs e) { transaction.Rollback(); MessageBox.Show("Rollback Transaction"); BindData(); }

EXERCISE
1. Scenario: • An invoice-management form will be made to serve exchanging products

2. Requirement : • Database : SQL Server (database name : INVOICE) with 4 tables : COMPANY, PRODUCT, INVOICE, INVOICE_ITEM with following information:

COMPANY table

Page 33 of 296

MCPD Web Developer

Course 70-528

PRODUCT table

INVOICE table

INVOICE_ITEM table

Testing data for PRODUCT table



Stored Procedure

GET_ALL_PRODUCTS CREATE PROC GET_ALL_PRODUCTS AS SELECT * FROM PRODUCT INSERT_COMPANY CREATE PROC INSERT_COMPANY ( @COMPANY_ID INT OUT, @COMPANY_NAME NVARCHAR(50), @ADDRESS NVARCHAR(100), @BANKID_NUMBER VARCHAR(10), @CONTACT_NAME NVARCHAR(100) )
Page 34 of 296

MCPD Web Developer

Course 70-528

AS BEGIN TRAN INSERT INTO COMPANY (COMPANY_NAME, ADDRESS, BANKID_NUMBER,CONTACT_NAME) VALUES(@COMPANY_NAME,@ADDRESS, @BANKID_NUMBER,@CONTACT_NAME) IF @@ERROR = 0 BEGIN SET @COMPANY_ID = @@IDENTITY COMMIT TRAN END ELSE ROLLBACK TRAN INSERT_INVOICE CREATE PROC INSERT_INVOICE ( @INVOICE_ID INT OUT, @DATE DATETIME, @TOTAL_PRICE FLOAT, @COMPANY_ID INT ) AS BEGIN TRAN INSERT INTO INVOICE ([DATE],TOTAL_PRICE,COMPANY_ID) VALUES(@DATE,@TOTAL_PRICE,@COMPANY_ID) IF @@ERROR = 0 BEGIN SET @INVOICE_ID = @@IDENTITY COMMIT TRAN END ELSE ROLLBACK TRAN INSERT_INVOICE_ITEM CREATE PROC INSERT_INVOICE_ITEM ( @INVOICE_ID INT , @PRODUCT_ID INT, @QUANTITY INT ) AS BEGIN TRAN INSERT INTO INVOICE_ITEM IF @@ERROR = 0 BEGIN COMMIT TRAN END ELSE ROLLBACK TRAN VALUES(@INVOICE_ID,@PRODUCT_ID,@QUANTITY)

Page 35 of 296

MCPD Web Developer

Course 70-528

Description 1 2 Event Form_Load btnChoose_Click dgProduct_DoubleClick btnCreateInvoice_Click Tasks Load all products from PRODUCT table to datagrid dgProduct 1) Add current row from dgProduct to dgProductInvoice 2) Decrease 1 unit of the quantity column in dgProduct, increase 1 unit of the quantity column in dgProductInvoice. 3) Calculate the total price of all chosen products and display 3 steps: 1) Insert new company information to COMPANY table and get back CompanyID 2) Insert new invoice information to INVOICE table and get back InvoiceID 3) Insert each invoice item to INVOICE_ITEM table which CompanyID and InvoiceID

3

From_exercise.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace ADOLab3 { public partial class Form_exercise : Form { private readonly SqlConnection conn = new SqlConnection("server=.;database=INVOICE;uid=sa;pwd=sa");
Page 36 of 296

MCPD Web Developer

Course 70-528

private private private private private private private

SqlDataAdapter da; readonly DataSet ds = new DataSet(); SqlCommand cmd1; SqlCommand cmd2; SqlCommand cmd3; DataTable dt = new DataTable(); SqlTransaction transaction;

public Form_exercise() { InitializeComponent(); } public DataTable CreateProductListInInvoice() { DataTable dtable = new DataTable("ProductInvoice"); dtable.Columns.Add("ProductID", Type.GetType("System.Int32")); dtable.Columns.Add("ProductName", Type.GetType("System.String")); dtable.Columns.Add("Quantity", Type.GetType("System.Int32")); dtable.Columns.Add("Price", Type.GetType("System.Double")); return dtable; } public bool ProductCurrentInInvoice() { bool retVal = false; if (dt.Rows.Count != 0) { foreach (DataRow dr in dt.Rows) { if (dr[0] == dgProduct.CurrentRow.Cells[0].Value) { if (((int)dgProduct.CurrentRow.Cells[2].Value > 0)) { dr[2] = (int)dr[2] + 1; dgProduct.CurrentRow.Cells[2].Value = (int)dgProduct.CurrentRow.Cells[2].Value - 1; double price = Convert.ToDouble(lblTotalPrice.Text) + Convert.ToDouble(dr[3]); lblTotalPrice.Text = price.ToString(); } else MessageBox.Show("Product Out of Store !"); retVal = true; } } } return retVal; } public void ChooseProductToInvoice() { if (!ProductCurrentInInvoice()) { DataRow dr = dt.NewRow(); dr[0] = dgProduct.CurrentRow.Cells[0].Value; dr[1] = dgProduct.CurrentRow.Cells[1].Value; dr[2] = 1; dr[3] = dgProduct.CurrentRow.Cells[3].Value; dt.Rows.Add(dr);
Page 37 of 296

MCPD Web Developer

Course 70-528

dgProductInvoice.DataSource = dt; dgProduct.CurrentRow.Cells[2].Value = (int)dgProduct.CurrentRow.Cells[2].Value - 1; double price = Convert.ToDouble(lblTotalPrice.Text) + Convert.ToDouble(dr[3]); lblTotalPrice.Text = price.ToString(); } } private void Form_Exercise_Load(object sender, EventArgs e) { try { conn.Open(); cmd1 = new SqlCommand("GET_ALL_PRODUCTS", conn); cmd1.CommandType = CommandType.StoredProcedure; da = new SqlDataAdapter(cmd1); da.Fill(ds, "Product"); dgProduct.DataSource = ds.Tables["Product"]; cmd1.Dispose(); conn.Close(); dt = CreateProductListInInvoice(); CreateProductListInInvoice(); } catch (Exception ex) { MessageBox.Show("Error:" + ex.StackTrace); } } private void btnChoose_Click(object sender, EventArgs e) { try { ChooseProductToInvoice(); } catch (Exception ex) { MessageBox.Show("Error:" + ex.StackTrace); } } private void btnCreateInvoice_Click(object sender, EventArgs e) { try { //step 1 : insert to company table if ((txtCompanyName.Text == "" | txtAddress.Text == "" | txtBankID.Text == "" | txtContactName.Text == "")) { MessageBox.Show("Not Enough Information!!!"); return; } conn.Open(); transaction = conn.BeginTransaction(); cmd1 = new SqlCommand("INSERT_COMPANY", conn); cmd1.Transaction = transaction; cmd1.CommandType = CommandType.StoredProcedure; SqlParameter ComID_Parm = new SqlParameter(); ComID_Parm.ParameterName = "@COMPANY_ID";
Page 38 of 296

MCPD Web Developer

Course 70-528

(int)dr[0]));

ComID_Parm.SqlDbType = SqlDbType.Int; ComID_Parm.Direction = ParameterDirection.Output; cmd1.Parameters.Add(ComID_Parm); cmd1.Parameters.Add(new SqlParameter("@COMPANY_NAME", txtCompanyName.Text)); cmd1.Parameters.Add(new SqlParameter("@ADDRESS", txtAddress.Text)); cmd1.Parameters.Add(new SqlParameter("@BANKID_NUMBER", txtBankID.Text)); cmd1.Parameters.Add(new SqlParameter("@CONTACT_NAME", txtContactName.Text)); if ((cmd1.ExecuteNonQuery() <= 0)) { transaction.Rollback(); conn.Close(); return; } //step 2 : insert to invoice table cmd2 = new SqlCommand("INSERT_INVOICE", conn); cmd2.Transaction = transaction; cmd2.CommandType = CommandType.StoredProcedure; SqlParameter InvoiceID_Parm = new SqlParameter(); InvoiceID_Parm.ParameterName = "@INVOICE_ID"; InvoiceID_Parm.SqlDbType = SqlDbType.Int; InvoiceID_Parm.Direction = ParameterDirection.Output; cmd2.Parameters.Add(InvoiceID_Parm); cmd2.Parameters.Add(new SqlParameter("@DATE", DateTime.Now.ToShortDateString())); cmd2.Parameters.Add(new SqlParameter("@TOTAL_PRICE", Convert.ToDouble(lblTotalPrice.Text))); cmd2.Parameters.Add(new SqlParameter("@COMPANY_ID", Convert.ToInt32(ComID_Parm.Value))); if ((cmd2.ExecuteNonQuery() <= 0)) { transaction.Rollback(); conn.Close(); return; } //step 3 : insert to invoice_item table foreach (DataRow dr in dt.Rows) { //cmd3.Dispose() cmd3 = new SqlCommand("INSERT_INVOICE_ITEM", conn); cmd3.Transaction = transaction; cmd3.CommandType = CommandType.StoredProcedure; cmd3.Parameters.Add(new SqlParameter("@INVOICE_ID", (int)InvoiceID_Parm.Value)); cmd3.Parameters.Add(new SqlParameter("@PRODUCT_ID", cmd3.Parameters.Add(new SqlParameter("@QUANTITY", (int)dr[3])); if ((cmd3.ExecuteNonQuery() <= 0)) { transaction.Rollback(); conn.Close(); return; }

} transaction.Commit(); conn.Close(); LoadInvoiceAfterCreated(Convert.ToInt32(ComID_Parm.Value), Convert.ToInt32(InvoiceID_Parm.Value));
Page 39 of 296

MCPD Web Developer

Course 70-528

} public void LoadInvoiceAfterCreated(int comID, int InvoiceID) { conn.Open(); DataTable dtTemp = new DataTable(); da = new SqlDataAdapter("select * from Company where company_ID=" + comID, conn); da.Fill(dtTemp); dgCompany.DataSource = dtTemp; dtTemp = new DataTable(); da = new SqlDataAdapter("select * from Invoice where Invoice_ID=" + InvoiceID, conn); da.Fill(dtTemp); dgInvoice.DataSource = dtTemp; dtTemp = new DataTable(); da = new SqlDataAdapter("select * from Invoice_Item where Invoice_ID=" + InvoiceID, conn); da.Fill(dtTemp); dgInvoiceItem.DataSource = dtTemp; conn.Close(); } } }

} catch (Exception ex) { MessageBox.Show("Error:" + ex.StackTrace); }

Page 40 of 296

MCPD Web Developer

Course 70-528

LAB 4 : WORKING WITH XML IN ADO.NET
FROM LESSON
From Lesson 1: Create XML file and XSD file 1. XML file • Create XML file : Right Click Project Name  Add  New Item : choose XML file and rename “Booklist.xml”

Page 41 of 296

MCPD Web Developer

Course 70-528

<?xml version="1.0" standalone="yes" ?> <Books xmlns="http://tempuri.org/BookList.xsd"> <Book> <BookCode>1861003323</BookCode> <Title>Web Application in .NET</Title> <PublicationDate>2002-07-20</PublicationDate> <FirstName>Archana</FirstName> <LastName>Kamrah</LastName> </Book> <Book> <BookCode>1861003324</BookCode> <Title>Win Application in .NET</Title> <PublicationDate>2002-07-24</PublicationDate> <FirstName>Pooja</FirstName> <LastName>Vaid</LastName> </Book> <Book> <BookCode>1861003325</BookCode> <Title>Data Access in .NET</Title> <PublicationDate>2002-07-01</PublicationDate> <FirstName>Avinash</FirstName> <LastName>Sinha</LastName> </Book> <Book> <BookCode>1861003326</BookCode> <Title>C# Programming</Title> <PublicationDate>2002-02-01</PublicationDate> <FirstName>Abhishek</FirstName> <LastName>Upadhyay</LastName> </Book> <Book> <BookCode>1861003327</BookCode> <Title>VB.NET Programming</Title> <PublicationDate>2002-02-01</PublicationDate> <FirstName>Sreevalli</FirstName> <LastName>Janapati</LastName> </Book> <Book> <BookCode>1861003328</BookCode> <Title>SharePoint Portal Server 2002</Title> <PublicationDate>2002-02-01</PublicationDate> <FirstName>Dilip</FirstName> <LastName>Nedungadi</LastName> </Book> </Books>



View XML file in Grid Format : Right Click in XML file  choose View Data Grid

Page 42 of 296

MCPD Web Developer

Course 70-528

2. XSD file : Choose menu XML  Create Schema




As default, Xsd file created on User Profile / Visual studio project directory Click File/Save As to save xsd file to project directory

From Lesson 2 : Load Xml Data File • Copy 2 file : BookList.xml, BookList.xsd to your Project’s bin/Debug folder

Page 43 of 296

MCPD Web Developer

Course 70-528

private void btnLoadXml_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXmlSchema("BookList.xsd"); ds.ReadXml("BookList.xml"); dgBook.DataSource = ds.Tables[0]; }

From Lesson 3 : Write Xml Data File

Page 44 of 296

MCPD Web Developer

Course 70-528

From1.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace Lab4_FromLesson3 { public partial class Form1 : Form { private SqlConnection conn; private DataSet ds = new DataSet(); private SqlDataAdapter da; public Form1() { InitializeComponent(); } private void btnLoadData_Click(object sender, EventArgs e) { try { ds.Clear(); conn = new SqlConnection("server=.;database=Northwind;Integrated Security=True"); conn.Open(); da = new SqlDataAdapter("Select * From Customers", conn); da.Fill(ds, "Customers"); conn.Close(); dgCustomer.DataSource = ds.Tables["Customers"];
Page 45 of 296

MCPD Web Developer

Course 70-528

}

} catch (Exception ex) { MessageBox.Show(ex.StackTrace); }

} }

private void btnSaveXML_Click(object sender, EventArgs e) { try { if (ds.Tables.Count > 0) { ds.WriteXmlSchema("Customers.xsd"); ds.WriteXml("Customers.xml"); MessageBox.Show("Write File Xml Successfully!"); } else { MessageBox.Show("No Data Available!"); } } catch (Exception ex) { MessageBox.Show(ex.StackTrace); } }

From Lesson 4 : Read & Write using XmlReader ,XmlWriter

Page 46 of 296

MCPD Web Developer

Course 70-528

From1.cs using System; using System.Windows.Forms; using System.Xml; namespace Lab4_FromLesson4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnCreateXML_Click(object sender, EventArgs e) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; XmlWriter writer; writer = XmlWriter.Create("treeModel.xml", settings); writer.WriteStartElement("Root"); writer.WriteStartElement("A"); writer.WriteStartElement("A1");
Page 47 of 296

MCPD Web Developer

Course 70-528

writer.WriteElementString("A11", "This is A11"); writer.WriteElementString("A12", "This is A12"); writer.WriteEndElement(); writer.WriteStartElement("A2"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("B"); writer.WriteElementString("B1", "This is B1"); writer.WriteElementString("B2", "This is B2"); writer.WriteEndElement(); writer.WriteStartElement("C"); writer.WriteStartElement("C1"); writer.WriteStartElement("C111"); writer.WriteElementString("C1111", "This is C1111"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteElementString("D", "This is D"); writer.WriteStartElement("E"); writer.WriteElementString("E1", "This is E1"); writer.WriteEndElement(); writer.WriteEndElement(); writer.Close(); MessageBox.Show("Create Xml file Successful"); } private void btnWriteXML_Click(object sender, EventArgs e) { XmlReader reader; reader = XmlReader.Create("treeModel.xml"); TreeNode a = null; TreeNode b = null; TreeNode parent = null; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: { a = new TreeNode(reader.Name); if (reader.AttributeCount > 0) { reader.MoveToFirstAttribute(); a.Text += " " + reader.Name + "=" + reader.Value; for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToNextAttribute(); a.Text += " " + reader.Name + "=" + reader.Value; } } if (parent == null) { tree.Nodes.Add(a); } else { parent.Nodes.Add(a); }
Page 48 of 296

MCPD Web Developer

Course 70-528

parent = a; } break; case XmlNodeType.EndElement: { parent = parent.Parent; } break; case XmlNodeType.Text: { b = new TreeNode(reader.Value); a.Nodes.Add(b); } break; } } tree.ExpandAll();

} } }

From Lesson 5: Read & Write Xml file by using XmlDocument

Page 49 of 296

MCPD Web Developer

Course 70-528

From2.cs using System; using System.Windows.Forms; using System.Xml; namespace Lab4_FromLesson5 { public partial class Form1 : Form { XmlDataDocument doc = new XmlDataDocument(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { doc.DataSet.ReadXmlSchema("BookList.xsd"); doc.Load("BookList.xml"); dg.DataSource = doc.DataSet.Tables[0]; } private void btnSave_Click(object sender, EventArgs e) { doc.Save("BookList.xml"); MessageBox.Show("Successful"); }

} }

Page 50 of 296

MCPD Web Developer

Course 70-528

EXERCISE
Scenario: • You want to make a form to manage communications between database and xml file

Requirement : • Use DataSet to handle tasks.



Drag 2 Dialogs to form : OpenFileDialog (rename dgOpen), and SaveFileDialog (rename dgSave)



Description:

Page 51 of 296

MCPD Web Developer

Course 70-528

1 2

Event Form_Load trDB_DoubleClick

3

btnLoadXmlFile_click

4

btnSaveXml_click

Tasks Load TreeView including All Databases in SQL Server and all tables in each Database to treeview trDB control When double clicking to node table in treeview, load Current Chosen Table’s Information and bind data to datagrid dg. Change lblTable text to “Load From SQL Server”\\ DBName \\ TableName. Ex : Load From SQL Server \\ Northwind \\ Customers - Show Open File Dialog (Figure 1) - Let user choose a XML file name - Get data from xml file and display in grid - Change lblTable text to “Load from xml file :” + Path to xml file. Ex : Load from xml file : D:\Project\ADONET\Lab5\bin\products.xml - If data in grid is data from Database: o Show Save File Dialog (Figure 2) o Let user choose a file name o Save the table’s information to user’ chosen xml-filname - If data in grid is data from Xml file : just save it back to orginal xml file.

Open File Dialog

Save File Dialog
Page 52 of 296

MCPD Web Developer

Course 70-528

Form_Exercise.cs using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; using System.Xml; public partial class Form_Exercise : Form { private static readonly string connStr = "server=.;uid=sa;pwd=sa;database=NorthWind"; private readonly SqlConnection conn = new SqlConnection(connStr); private SqlDataAdapter da; private DataSet ds; private bool loadDB = false; private string filePath; private XmlDataDocument xmlDoc = new XmlDataDocument(); public Form_Exercise() { InitializeComponent(); } public void LoadAllDatabases() { ds = new DataSet(); TreeNode parentNode; TreeNode[] nodeArr; conn.Open(); SqlCommand cmd = new SqlCommand("sp_databases", conn); da = new SqlDataAdapter(cmd); da.Fill(ds, "Database"); int dbCount = ds.Tables["Database"].Rows.Count; nodeArr = new TreeNode[dbCount];
Page 53 of 296

MCPD Web Developer

Course 70-528

for(int i = 0; i < dbCount; i++) { string dbName = (string)ds.Tables["Database"].Rows[i][0]; TreeNode node = new TreeNode(dbName, LoadAllTables(dbName)); nodeArr[i] = node; } parentNode = new TreeNode("SQL Server", nodeArr); trDB.Nodes.Add(parentNode); da.Dispose(); conn.Close(); } public TreeNode[] LoadAllTables(string dbName) { TreeNode[] nodeArr = null; try { SqlCommand cmd = new SqlCommand("use " + dbName + " exec sp_tables", conn); SqlDataAdapter da2 = new SqlDataAdapter(cmd); DataSet ds2 = new DataSet(); da2.Fill(ds2, "Table"); DataView dv = ds2.Tables["Table"].DefaultView; dv.RowFilter = "TABLE_TYPE='TABLE'"; nodeArr = new TreeNode[dv.Count]; for (int i = 0; i < dv.Count;i++ ) { nodeArr[i] = new TreeNode(dv[i][2].ToString()); } } catch (Exception ex) { MessageBox.Show("Error:" + ex.Message); } return nodeArr; } private void Form_Exercise_Load(object sender, EventArgs e) { LoadAllDatabases(); } private void btnLoadXml_Click(object sender, EventArgs e) { xmlDoc = new XmlDataDocument(); dlgOpen.Filter = "Xml Files(*.xml)|*.xml"; if ((dlgOpen.ShowDialog() == DialogResult.OK)) { filePath = dlgOpen.FileName; xmlDoc.DataSet.ReadXml(filePath); lblTable.Text = "Load From Xml File :" + filePath; if ((xmlDoc.DataSet.Tables.Count > 0)) dg.DataSource = xmlDoc.DataSet.Tables[0]; else MessageBox.Show("NO DATA in file!"); loadDB = false; } } private void btnXmlFile_Click(object sender, EventArgs e) { if (((ds != null))) { if (loadDB)
Page 54 of 296

MCPD Web Developer

Course 70-528

{

} else { }

dlgSave.Filter = "Xml Files(*.xml)|*.xml|Xsd Files(*.xsd)|*.xsd"; dlgSave.InitialDirectory = Application.StartupPath; if ((dlgSave.ShowDialog() == DialogResult.OK)) { if ((ds.Tables.Count > 0)) { string fileXmlPath = dlgSave.FileName; try { ds.WriteXml(fileXmlPath); MessageBox.Show("Write File Successful !"); } catch (Exception ex) { MessageBox.Show("Error :" + ex.Message); } } }

xmlDoc.Save(filePath); MessageBox.Show("Save Successful!"); } else

MessageBox.Show("NO DATA in GRID!"); } private void trDB_DoubleClick(object sender, EventArgs e) { try { if (((trDB.SelectedNode.Parent != null))) { if (((trDB.SelectedNode.Parent.Parent != null))) { if ((ReferenceEquals(trDB.SelectedNode.Parent.Parent.Text, "SQL Server"))) { string strDBName = trDB.SelectedNode.Parent.Text; lblTable.Text = "Load From SQL Server" + " \\\\ " + strDBName + " \\\\ " + trDB.SelectedNode.Text; ds = new DataSet(); da = new SqlDataAdapter("Use " + strDBName + " Select * From [" + trDB.SelectedNode.Text + "]", conn); da.Fill(ds, "table"); dg.DataSource = ds.Tables[0]; } } loadDB = true; } } catch (Exception ex) { MessageBox.Show("Error:" + ex.Message); } } }
Page 55 of 296

MCPD Web Developer

Course 70-528

LAB 1: AN INTRODUCTION TO ASP.NET
FROM LESSON
From Lesson 1: Create Virtual Directory • • Step 1 : Choose Control Panel / Administrative Tools / Internet Information Services (IIS) Manager. Or Start/Run type inetmgr Step 2 : Choose Web Sites , right click default Web Site , choose New / Virtual Directory.



Page 56 of 296

MCPD Web Developer

Course 70-528



Step 3 : Virtual Directory Creation Wizard appears , click Next to Continue.



Step 4 : The next step is enter the name for your virtual directory, example ASPNETLab, from now on your website will have url : http://localhost/ASPNETLab/....... Click Next to continue.

Page 57 of 296

MCPD Web Developer

Course 70-528



Step 5 : Use the “Browse” button to select the directory in which you put your aspnet project. ( here I choose D:\Projects\ASPNETLab). Click Next to continue.



Acceps all default Settings in the dialog and click Next.

Page 58 of 296

MCPD Web Developer

Course 70-528



Click Finish to complete the wizard.

From Lesson 2 : Write Hello World program Creating ASP.NET Web Application using VS 2005 • Open Visual Studio 2005 from Start Menu.



Choose menu File  New  Website

Page 59 of 296

MCPD Web Developer

Course 70-528



“New WebSite” Dialog appears, Choose “ASP.NET Website” template. Choose Location type = HTTP . Then type : http://localhost/ASPNETLab/ASP70528 address box beside

Note : Type the url in the Location which 2 parts : http://localhost/ASPNETLab/ means that you use the virtual directory created above (ASPNETLab physical located in D:\Projects\ASPNETLab\) (if you only use http://localhost the project will store in root path : ex C: \InetPub\wwwroot\). The second part (here is Lab1) is the name of your project (ex : ASP70528)



Double click in page default.aspx  write code in file default.aspx.cs, in the Page_Load event sub.

using System; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write("Hello ASP web 2.0 !"); } }

• •

Run Ignore this message. Just click OK

Page 60 of 296

MCPD Web Developer

Course 70-528

Page with Button • Open default.aspx
• Click Design tab Add a button to Web Form ( drag button from Toolbox to Web Form) Rewrite Page_Load event

• •

using System; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) Response.Write("Hello ASP web 2.0 !"); } }



Run & Notice the difference when having Page.IsPostBack

From Lesson 3: Write Message Box Hello World program



Add new Web Form by right-clicking project name  choose “Add New Item” : then choose Web Form

Page 61 of 296

MCPD Web Developer

Course 70-528

using System; public partial class default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Put client code to initialize the page here Response.Write("<script language=javascript>alert('Hello ASP web 2.0!')</script>"); } } From Lesson 4 : Begging Design Interface with Table with VS.NET • Design a webpage which display manipulation-table for each number entered in Textbox

Page 62 of 296

MCPD Web Developer

Course 70-528



Insert Table to set layout your page, choose menu Layout  InsertTable



In “Insert Table” dialog, choose custom Layout and setup a “1 row-2 columns Table” with border = 1

Page 63 of 296

MCPD Web Developer

Course 70-528



Use 2 labels, 1 Textbox and 1 button to design your page like below : Text “Nhập bảng cửu chương muốn lấy” “Lấy Bảng Cửu Chương” Type Label Textbox Button

ControlID Label1 TextBox1 Button1 Label2

Code for Button1_Click
Page 64 of 296

MCPD Web Developer

Course 70-528

using System; public partial class default3 : System.Web.UI.Page { protected void btnLoad_Click(object sender, EventArgs e) { Label2.Text = ""; int num = Int32.Parse(TextBox1.Text); for(int i = 1; i <=10; i++) { Label2.Text = Label2.Text + num + " x " + i + " = " + num*i; Label2.Text = Label2.Text + "<br>"; }

} }

Page 65 of 296

MCPD Web Developer

Course 70-528

LAB 2: BASIC CONTROLS OF ASP.NET PAGE
Scenario:
• Design a website to manage students information, marks ,subjects in your college

Database

Functions
Student functions : • • • • • Login Register Account Register Subjects View Marks Update Information

Admin functions:


• • •

` Login Add New Student Manage Marks Manage Student Information

Sequence Actions

Page 66 of 296

MCPD Web Developer

Course 70-528

Solutions Login.aspx (admin)

Login.aspx (student)

Page 67 of 296

MCPD Web Developer

Course 70-528

AdminMarks.aspx

AdminNewStudent.aspx

NewStudent.aspx

Page 68 of 296

MCPD Web Developer

Course 70-528

SubjectRegister.aspx



Before submitting subject register (before clicking “Cập nhập” button)



After submitting subject register (After clicking “Cập nhật” button)

Page 69 of 296

MCPD Web Developer

Course 70-528

Web Forms
a) web.config <configuration> <appSettings/> <connectionStrings> <add connectionString="server=SERVER_NAME;database=QLSV;Integrated Security=True" name="connStr"/> </connectionStrings> <system.web> . . .

Page 70 of 296

MCPD Web Developer

Course 70-528

b) Login.aspx

Description Event btnDangnhap_Click Description Check Student / Admin Login: - Admin login successful : Redirect to AdminMarks.aspx - Student login sucessful : Redirect to SubjectRegister.aspx with passing mssv in URL ex: “Lab2_SubjectRegister.aspx?mssv=0611001”

Login.aspx using System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class Login : System.Web.UI.Page { private SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlCommand cmd; protected void btnDangnhap_Click(object sender, EventArgs e) { try { conn.Open(); cmd = new SqlCommand("KT_DANGNHAP", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@TAIKHOAN", txtTaikhoan.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@MATKHAU", txtMatkhau.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@QUANTRI", rbQuantri.Checked)); String mssv = cmd.ExecuteScalar().ToString(); if(mssv != "") if (rbQuantri.Checked) Response.Redirect("AdminMarks.aspx"); else Response.Redirect("SubjectRegister.aspx?mssv=" + mssv);
Page 71 of 296

MCPD Web Developer

Course 70-528

conn.Close(); lblError.Text = "Tài khoản không đúng !"; } catch(Exception ex) { } } }

c) AdminMarks.aspx

Description Event Page_Load lbMonhoc_SelectedIndexChanged ddlMssv_SelectedIndexChanged btnNhapdiem_Click btnCapnhat_Click Description Load all student’s MSSV to Dropdownlist ddlMssv, set choosen to first student in ddlMssv Load all registered subject of current chosen student to ListBox lbMonhoc Load marks of chosen subject to txtDiem if existed Load chosen student’s information Load all registered subject of current chosen student to ListBox lbMonhoc Update Marks to Listbox lbMonhoc Update current student’s information Update current student’s subject-marks

AdminMarks.aspx using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class AdminMasks : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
Page 72 of 296

MCPD Web Developer

Course 70-528

private SqlCommand cmd; private SqlDataReader dr; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { try { conn.Open(); cmd = new SqlCommand("LAY_TATCA_MSSV", conn); dr = cmd.ExecuteReader(); while (dr.Read()) { ddlMssv.Items.Add(new ListItem(dr["MSSV"].ToString(), dr["MSSV"].ToString())); } cmd.Dispose(); dr.Close(); conn.Close(); LayMonhocDaDangky(ddlMssv.SelectedValue); LaySVTheoMSSV(ddlMssv.SelectedValue); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } } private void LaySVTheoMSSV(string mssv) { try { conn.Open(); cmd = new SqlCommand("LAY_SV_THEO_MSSV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", mssv)); dr = cmd.ExecuteReader(); while (dr.Read()) { txtTen.Text = dr["TEN"].ToString(); txtDiachi.Text = dr["DIACHI"].ToString(); if (Convert.ToBoolean(dr["GIOITINH"])) rdoNam.Checked = true; else rdoNu.Checked = true; txtDienthoai.Text = dr["DIENTHOAI"].ToString(); } cmd.Dispose(); dr.Close(); conn.Close(); lblErr.Visible = false; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } private static double LayDiemTuChuoi(string chuoi) {
Page 73 of 296

MCPD Web Developer

Course 70-528

try { int vitri = chuoi.IndexOf("("); String sodau = "-1"; if (vitri > 0) { sodau = chuoi.Substring(vitri + 1, 1); String sosau = chuoi.Substring(vitri + 2, 1); if (sosau == "0") sodau = sodau + sosau; else if (sosau == ".") { sodau = sodau + sosau; String socuoi = chuoi.Substring(vitri + 3, 1); sodau = sodau + socuoi; } } return Convert.ToDouble(sodau);

}

} catch (Exception ex) { Console.WriteLine(ex.StackTrace); } return -1;

private void LayMonhocDaDangky(string mssv) { conn.Open(); //lay cac mon hoc chua dang ky cmd = new SqlCommand("LAY_MONHOC_DANGKY", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", mssv)); dr = cmd.ExecuteReader(); if (!dr.HasRows) { lblMsg2.Visible = true; lbMonhoc.Visible = false; txtDiem.Visible = false; btnNhapdiem.Visible = false; } else { lblMsg2.Visible = false; lbMonhoc.Visible = true; txtDiem.Visible = true; btnNhapdiem.Visible = true; while (dr.Read()) { ListItem li; if (dr["DIEM"] == DBNull.Value) li = new ListItem(dr["TEN"].ToString(), dr["MAMON"].ToString()); else li = new ListItem(dr["TEN"] + "(" + dr["DIEM"] + ");", dr["MAMON"].ToString()); lbMonhoc.Items.Add(li); lbMonhoc.SelectedIndex = 0; double diem = LayDiemTuChuoi(lbMonhoc.SelectedItem.Text); if (diem != -1)
Page 74 of 296

MCPD Web Developer

Course 70-528

}

txtDiem.Text = diem.ToString();

} dr.Close(); cmd.Dispose(); conn.Close(); } protected void btnNhapdiem_Click(object sender, EventArgs e) { double diem; try { diem = Convert.ToDouble(txtDiem.Text.Trim()); } catch (Exception) { diem = -1; } if (diem < 0 || diem > 10) { lblErr.Visible = true; lblErr.Text = "Điểm không hợp lệ!"; } else { diem = LayDiemTuChuoi(lbMonhoc.SelectedItem.Text); if (diem == -1) lbMonhoc.SelectedItem.Text = lbMonhoc.SelectedItem.Text + "(" + txtDiem.Text.Trim() + ");"; else lbMonhoc.SelectedItem.Text = lbMonhoc.SelectedItem.Text.Substring(0, lbMonhoc.SelectedItem.Text.IndexOf("(") + 1) + txtDiem.Text.Trim() + ");"; lblErr.Visible = false; } } protected void ddlMssv_SelectedindexChanged(object sender, EventArgs e) { LayMonhocDaDangky(ddlMssv.SelectedValue); LaySVTheoMSSV(ddlMssv.SelectedValue); } protected void btnCapnhat_Click(object sender, EventArgs e) { try { //cap nhat thong tin sinh vien conn.Open(); cmd = new SqlCommand("CAPNHAT_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", ddlMssv.SelectedValue)); cmd.Parameters.Add(new SqlParameter("@TEN", txtTen.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DIACHI", txtDiachi.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DIENTHOAI", txtDienthoai.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@GIOITINH", rdoNam.Checked)); cmd.ExecuteNonQuery(); cmd.Dispose(); //cap nhat thong tin mon hoc
Page 75 of 296

MCPD Web Developer

Course 70-528

} catch (Exception ex) { Console.WriteLine(ex.StackTrace); }

if (lbMonhoc.Visible) { foreach (ListItem li in lbMonhoc.Items) { double diem = LayDiemTuChuoi(li.Text); if (diem != -1) { cmd = new SqlCommand("NHAP_DIEM", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", ddlMssv.SelectedValue)); cmd.Parameters.Add(new SqlParameter("@MAMON", Convert.ToInt32(li.Value))); cmd.Parameters.Add(new SqlParameter("@DIEM", Convert.ToDouble(diem))); cmd.ExecuteNonQuery(); cmd.Dispose(); } } } conn.Close(); lblErr.Text = "Cập nhật thành công!"; lblErr.Visible = true;

} protected void lbMonHoc_SelectedIndexChanged(object sender, EventArgs e) { try { double diem = LayDiemTuChuoi(lbMonhoc.SelectedItem.Text); if (diem != -1) txtDiem.Text = Convert.ToString(diem); else txtDiem.Text = ""; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } }

Page 76 of 296

MCPD Web Developer

Course 70-528

d) AdminNewStudent.aspx

Description Event btnThem_Click AdminNewStudent.aspx using System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class AdminNewStudent : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlCommand cmd; private bool KiemTraTontaiSV() { bool retVal = false; try { conn.Open(); cmd = new SqlCommand("KT_TONTAI_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); if (cmd.ExecuteScalar() != null) retVal = true; cmd.Dispose(); conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } return retVal; } protected void btnThem_Click(object sender, EventArgs e) { try
Page 77 of 296

Description Insert new student information to database

MCPD Web Developer

Course 70-528

{

} catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } }

if (KiemTraTontaiSV()) Response.Write("<script language=javascript>alert('Sinh viên này đã tồn tại!')</script>"); else { conn.Open(); cmd = new SqlCommand("THEM_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@TEN", txtTen.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DIACHI", txtDiachi.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DIENTHOAI", txtDienthoai.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@GIOITINH", rdoNam.Checked)); cmd.ExecuteNonQuery(); conn.Close(); Response.Write("<script language=javascript>alert('Thêm sinh viên thành công!')</script>"); }

e) NewStudent.aspx

Description Event btnDangky_Click Description Checking student existed , if existed Register new account for student

AdminNewStudent.aspx using System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class NewStudent : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
Page 78 of 296

MCPD Web Developer

Course 70-528

private SqlCommand cmd; protected void btnDangKy_Click(object sender, EventArgs e) { try { if (KiemTraTontaiSV()) if (!KiemTraTontaiDangnhap()) { conn.Open(); cmd = new SqlCommand("THEM_TAIKHOAN_SV", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter idParm = new SqlParameter(); idParm.ParameterName = "@ID"; idParm.SqlDbType = SqlDbType.Int; idParm.Direction = ParameterDirection.Output; cmd.Parameters.Add(idParm); cmd.Parameters.Add(new SqlParameter("@TAIKHOAN", txtTaikhoan.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@MATKHAU", txtMatkhau.Text.Trim())); cmd.ExecuteNonQuery(); cmd.Dispose(); cmd = new SqlCommand("CAPNHAT_TAIKHOAN_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DANGNHAP_ID", Convert.ToInt32(idParm.Value))); cmd.ExecuteNonQuery(); conn.Close(); Response.Write("<script language=javascript>alert('Tài khoản đã được thêm thành công!')</script>"); txtMSSV.Text = ""; txtTaikhoan.Text = ""; txtMatkhau.Text = ""; } else Response.Write("<script language=javascript>alert('Sinh viên này đã có tài khoản đăng nhập!')</script>"); else Response.Write("<script language=javascript>alert('Sinh viên không tồn tại!')</script>"); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } private bool KiemTraTontaiSV() { bool retVal = false; try { conn.Open(); cmd = new SqlCommand("KT_TONTAI_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); if (cmd.ExecuteScalar() != null) retVal = true;
Page 79 of 296

MCPD Web Developer

Course 70-528

cmd.Dispose(); conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } return retVal; } private bool KiemTraTontaiDangnhap() { bool retVal = false; try { conn.Open(); cmd = new SqlCommand("KT_TONTAI_DANGNHAP", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); if ((cmd.ExecuteScalar() != null)) retVal = true; cmd.Dispose(); conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } return retVal; }

} f)

SubjectRegister.aspx

Description Event Page_Load btnCapnhat_Click
Page 80 of 296

Description Receiving mssv in URL, and load all student information to form, load all Registered Subject and Non-Registered Subject of current logged in student Update student information and update student registered/non-registered subjects of

MCPD Web Developer

Course 70-528

current logged in student SubjectRegister.aspx using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class SubjectRegister : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlCommand cmd; private SqlDataReader dr; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) try { string mssv = Request.QueryString["mssv"]; if (mssv != "") { //lay thong tin sv conn.Open(); txtMSSV.Text = Request.QueryString["mssv"]; cmd = new SqlCommand("KT_TONTAI_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", mssv)); dr = cmd.ExecuteReader(); dr.Read(); txtTen.Text = dr["TEN"].ToString(); txtDiachi.Text = dr["DIACHI"].ToString(); if (Convert.ToBoolean(dr["GIOITINH"])) rdoNam.Checked = true; else rdoNu.Checked = true; txtDienthoai.Text = dr["DIENTHOAI"].ToString(); conn.Close(); LayMonhocChuaDangky(mssv); LayMonhocDaDangky(mssv); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } private void LayMonhocChuaDangky(string mssv) { conn.Open(); //lay cac mon hoc chua dang ky cmd = new SqlCommand("LAY_MONHOC_CHUADANGKY", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", mssv)); dr = cmd.ExecuteReader(); while (dr.Read()) { ListItem li = new ListItem(); li.Text = dr["TEN"].ToString();
Page 81 of 296

MCPD Web Developer

Course 70-528

li.Value = dr["ID"].ToString(); cblSubjects.Items.Add(li); } if (cblSubjects.Items.Count == 0) lblMsg.Visible = true; else lblMsg.Visible = false; dr.Close(); cmd.Dispose(); conn.Close(); } private void LayMonhocDaDangky(string mssv) { conn.Open(); //lay cac mon hoc chua dang ky cmd = new SqlCommand("LAY_MONHOC_DANGKY", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", mssv)); dr = cmd.ExecuteReader(); if (!dr.HasRows) lblMsg2.Visible = true; else { lblKetqua.Text = ""; lblMsg2.Visible = false; lblKetqua.Text = lblKetqua.Text + "<table with =100% border = 1><tr><td bgcolor=yellow>Tên môn</td><td bgcolor=yellow>Điểm</td></tr>"; while (dr.Read()) { if (dr["DIEM"] == DBNull.Value) lblKetqua.Text = lblKetqua.Text + "<tr><td>" + dr["TEN"] + "</td>" + "<td>" + "Chưa có điểm" + "</td>"; else lblKetqua.Text = lblKetqua.Text + "<tr><td>" + dr["TEN"] + "</td>" + "<td>" + dr["DIEM"] + "</td>"; } lblKetqua.Text = lblKetqua.Text + "</table>"; } dr.Close(); cmd.Dispose(); conn.Close(); } protected void btnCapnhat_Click(object sender, EventArgs e) { try { //cap nhat thong tin sinh vien conn.Open(); cmd = new SqlCommand("CAPNHAT_SV", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@TEN", txtTen.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DIACHI", txtDiachi.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DIENTHOAI", txtDienthoai.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@GIOITINH", rdoNam.Checked)); cmd.ExecuteNonQuery(); cmd.Dispose(); //them cac mon hoc dang ky foreach (ListItem li in cblSubjects.Items)
Page 82 of 296

MCPD Web Developer

Course 70-528

{

if (li.Selected) { cmd = new SqlCommand("THEM_MONHOC_DANGKY", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MSSV", txtMSSV.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@MAMON", Convert.ToInt32(li.Value))); cmd.ExecuteNonQuery(); cmd.Dispose(); }

} catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } }

} conn.Close(); cblSubjects.Items.Clear(); LayMonhocChuaDangky(txtMSSV.Text.Trim()); LayMonhocDaDangky(txtMSSV.Text.Trim());

Page 83 of 296

MCPD Web Developer

Course 70-528

LAB 3 : VALIDATION CONTROLS AND RICH CONTROLS
FROM LESSON
How to create Validation Controls?
From Lesson 1: RequiredFieldValidator Control

Create a TextBox in the Web Form.(named TextBox1) Create a RequiredFieldValidator in the Web Form with the properties info below: o ErrorMessage: This is required field! o ControlToValidate: TextBox1. Create a Button in the Web Form. Run & Test.

From Lesson 2: CompareValidatorControl

Create 2 TextBox in the Web Form (named TextBox1, TextBox2) Create a CompareValidator in the Web Form with the properties info below : o ControlToValidate : TextBox1 o ControlToCompare: TextBox2. o Error Message: Not Equal ! Create a Button in the Web Form. Run & Test.

Page 84 of 296

MCPD Web Developer

Course 70-528

From Lesson 3: RangeValidatorControl

Create a TextBox in the Web Form (named TextBox1) Create a RangeValidator in the Web Form with the properties info below: o ControlToValidate: TextBox1. o ErrorMessage: Out of Range. o MaximumValue : 100. o MinimumValue : 1. o Type : Integer. Create a buttion in the Web Form. Run & Test. From Lesson 4: RegularExpressionValidatorControl

Create a TextBox in the Web Form (named TextBox1) Create a RegularExpressionValidator in the Web Form with the properties info below: o ControlToValidate : TextBox1. o ValidationExpression : choose Internet E-mail Address (in the Regular Expression Editor Dialog).

o ErrorMessage : Email Format Not Valid ! Create a button in the Web Form. Run & Test.
Page 85 of 296

MCPD Web Developer

Course 70-528

From Lesson 5: CustomValidatorControl (Server Side)

Create a TextBox in the Web Form (named TextBox1) Create a CustomValidator in the Web Form with the properties info below : Error Message : Must be 8 – 10 Characters Length. Double Click the validator and write codes: (Server Validation) protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if (args.Value.Length < 8 || args.Value.Length > 10) args.IsValid = false; else args.IsValid = true; } Create a button in the Web Form. Run & Test. From Lesson 6: CustomValidatorControl (Client Side)

Create a TextBox in the Web Form (named TextBox1) Create a CustomValidator in the Web Form with the properties info below : Error Message : Must be 8 – 10 Characters Length. Create a javascript function in Html View.

Page 86 of 296

MCPD Web Developer

Course 70-528

In Custom Validation Control Property Dialog : set ClientValidationFunction = ValidateLength.

Create a button in the Web Form. Run & Test. From Lesson 7: ValidationSummaryControl

- Create form & validation control for all fields like below : Name (RequiredFieldValidator), Age (Required, Range (0-100)), Email (Required, Format), Marks (Reqired, Custom : 0 <= value <= 10)

Create a ValidationSummary control.
Page 87 of 296

MCPD Web Developer

Course 70-528

Create a button. Run & Test. From Lesson 8: Manage Different Validation Group Design Web Form like below

Source Code using System; public partial class Default2 : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { Label7.Text = "Private Information Received!"; } protected void Button2_Click(object sender, EventArgs e) { Label8.Text = "Bank Information Received!"; } } From Lesson 2: How to use Rich controls? From Lesson 9: AdRotator Control

thanhnien.gif
Page 88 of 296

MCPD Web Developer

Course 70-528

tuoitre.gif Create a xml file, named Ad.xml with the following contents <?xml version="1.0" encoding="utf-8" ?> <Advertisements> <Ad> <ImageUrl>thanhnien.gif</ImageUrl> <NavigateUrl>http://www.thanhnien.com.vn</NavigateUrl> <Keyword>Bao Thanh Nien</Keyword> <Impressions>80</Impressions> </Ad> <Ad> <ImageUrl>tuoitre.gif</ImageUrl> <NavigateUrl>http://www.tuoitre.com.vn</NavigateUrl> <Keyword>Bao Tuoi Tre</Keyword> <Impressions>80</Impressions> </Ad> </Advertisements> Create an AdRotator control, with properties info below: o Advertisements File : browse to the file Ad.xml.

Page 89 of 296

MCPD Web Developer

Course 70-528

Run & Test.

From Lesson 10: Calendar Control Add 3 control to Web Form : a Calendar (named calendar1) control, a label (named label1), a button (named Button1) like below :

Use AutoFormat for Calendar :

Page 90 of 296

MCPD Web Developer

Course 70-528

Double Click to Calendar1 to write code for “Calendar1_SelectionChanged” event like below : protected void Calendar1_SelectionChanged(object sender, EventArgs e) { Label9.Text = "You have chosen : " + Calendar1.SelectedDate; } Run & Test From Lesson 11: FileUpload control Create Web Form with 1 FileUpload control, 1 Button and Image control like below:

Page 91 of 296

MCPD Web Developer

Course 70-528

Source Code: protected void Button1_Click(object sender, EventArgs e) { FileUpload1.SaveAs(Request.PhysicalApplicationPath + "\\" + FileUpload1.FileName); Image1.ImageUrl = FileUpload1.FileName; }

Page 92 of 296

MCPD Web Developer

Course 70-528

EXERCISE
Scenario:
You want to make a website to manage customers relationship of your company (CRM : Customer Relationship Management)

Database

Web Forms
g) web.config <configuration> <appSettings/> <connectionStrings> <add connectionString="server=.;database=CRM;Integrated Security=True" name="connStr"/> </connectionStrings> <system.web> ... h) Login.aspx

Login.aspx source-code using System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class Login : System.Web.UI.Page
Page 93 of 296

MCPD Web Developer

Course 70-528

{

} i) CRM.aspx

private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlCommand cmd; protected void btnDangnhap_Click(object sender, EventArgs e) { try { conn.Open(); cmd = new SqlCommand("CHECK_LOGIN", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@USERNAME", txtUser.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@PASSWORD", txtPassword.Text.Trim())); String id = cmd.ExecuteScalar().ToString(); if (id != "") Response.Redirect("CRM.aspx?id=" + id + "&mode=1"); else Response.Write("<script language=javascript>alert('Login Fail!Invalid Username/Password')</script>"); conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } }

Validator
Page 94 of 296

MCPD Web Developer

Course 70-528

Type RequiredFieldValidator RegularExpressionValidator RegularExpressionValidator RegularExpressionValidator CompareValidator Description Event Page_Load btnUpdate_Click btnInsert_Click Running Mode: Update Mode

Control All (except txtConfirm) txtPhone ([+]\d{2}\d{2}\d{7}) (ex: +84088123123) txtFax ([(]\d{2,3}[)]\d{7}) (ex: (848)8123123) txtEmail (email format) txtConfirm (compare with txtPassword)

Description Updated Mode : Load Current Company’s Information with His Customer’s List Update current-logged in company’s information Insert new company as customer of currentlogged in company

Page 95 of 296

MCPD Web Developer

Course 70-528

Insert Mode

Page 96 of 296

MCPD Web Developer

Course 70-528

CRM.aspx Source code using System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class CRM : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlCommand cmd; private SqlDataReader dr; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) try { String mode = Request.QueryString["mode"]; if (mode == "1") { String comID = Request.QueryString["id"]; btnUpdate.Visible = true; btnInsert.Visible = false; btnAddNew.Visible = true; Label1.Visible = true; Label2.Visible = true; Label3.Visible = true; Label4.Visible = true; txtUsername.Visible = true; txtPassword.Visible = true; txtConfirm.Visible = true; if (comID != "") { conn.Open(); //get company information cmd = new SqlCommand("GET_COMPANY_BY_ID", conn); cmd.CommandType = CommandType.StoredProcedure;
Page 97 of 296

MCPD Web Developer

Course 70-528

cmd.Parameters.Add(new SqlParameter("@COMPANY_ID", Convert.ToInt32(comID))); dr = cmd.ExecuteReader(); while (dr.Read()) { txtCompanyName.Text = dr["CompanyName"].ToString(); txtAddress.Text = dr["Address"].ToString(); txtPhone.Text = dr["Phone"].ToString(); txtFax.Text = dr["Fax"].ToString(); txtEmail.Text = dr["Email"].ToString(); txtDescription.Text = dr["Description"].ToString(); txtUsername.Text = dr["Username"].ToString(); } dr.Close(); cmd.Dispose(); //get customers list cmd = new SqlCommand("GET_COMPANY_LIST_BY_PARENT_ID", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@PARENT_ID", Convert.ToInt32(comID))); dr = cmd.ExecuteReader(); lblCompanyList.Text = lblCompanyList.Text + "<table width=100% border=1> <tr bgcolor=yellow><td>Company Name</td><td>Phone</td><td>Fax</td><td>Email</td><td>Address </td></tr>"; while (dr.Read()) { lblCompanyList.Text = lblCompanyList.Text + "<tr><td><a href='CRM.aspx?id=" + dr["ID"] + "&mode=1'>" + dr["CompanyName"] + "</a></td>" + "<td>" + dr["Phone"] + "</td>" + "<td>" + dr["Fax"] + "</td>" + "<td><a href='mailto:" + dr["Email"] + "'>" + dr["Email"] + "</a></td>" + "<td>" + dr["Address"] + "</td></tr>"; } } lblCompanyList.Text = lblCompanyList.Text + "</table>"; dr.Close(); cmd.Dispose(); conn.Close();

} else {

btnUpdate.Visible = false; btnInsert.Visible = true; btnAddNew.Visible = false; Label1.Visible = false; Label2.Visible = false; Label3.Visible = false; Label4.Visible = false; txtUsername.Visible = false; txtPassword.Visible = false; txtConfirm.Visible = false; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); }

}
Page 98 of 296

MCPD Web Developer

Course 70-528

protected void btnAddNew_Click(object sender, EventArgs e) { Response.Redirect("CRM.aspx?id=" + Request.QueryString["id"] + "&mode=2"); } protected void btnUpdate_Click(object sender, EventArgs e) { try { conn.Open(); cmd = new SqlCommand("UPDATE_COMPANY", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@COMPANYNAME", txtCompanyName.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@ADDRESS", txtAddress.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@PHONE", txtPhone.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@FAX", txtFax.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@EMAIL", txtEmail.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DESCRIPTION", txtDescription.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@USERNAME", txtUsername.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@PASSWORD", txtPassword.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@ID", Convert.ToInt32(Request.QueryString["id"]))); cmd.ExecuteNonQuery(); Response.Write("<script language=javascript>alert('Update Successful')</script>"); conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } protected void btnInsert_Click(object sender, EventArgs e) { try { conn.Open(); cmd = new SqlCommand("INSERT_NEW_CUSTOMER", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@COMPANYNAME", txtCompanyName.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@ADDRESS", txtAddress.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@PHONE", txtPhone.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@FAX", txtFax.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@EMAIL", txtEmail.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@DESCRIPTION", txtDescription.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@PARENT_ID", Convert.ToInt32(Request.QueryString["id"]))); cmd.ExecuteNonQuery(); conn.Close(); Response.Redirect("CRM.aspx?id=" + Request.QueryString["id"] + "&mode=1"); } catch (Exception ex)
Page 99 of 296

MCPD Web Developer

Course 70-528

{ }

Console.WriteLine(ex.StackTrace);

} protected void btnHome_Click(object sender, EventArgs e) { Response.Redirect("CRM.aspx?id=" + Request.QueryString["id"] + "&mode=1"); } }

Page 100 of 296

MCPD Web Developer

Course 70-528

LAB 4 : ASP.NET INTRINSIC OBJECTS
FROM LESSON
1) From Lesson 1 : Using Cookies

using System; using System.Web; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCreateCookie_Click(object sender, EventArgs e) { HttpCookie mycookie = new HttpCookie("mycookie"); mycookie.Value = "Your last visited at " + DateTime.Now.ToString(); mycookie.Expires = DateTime.Now.AddHours(1); Response.Cookies.Add(mycookie); btnCreateCookie.Enabled = false; } protected void btnGetCookie_Click(object sender, EventArgs e) { if (Request.Cookies["mycookie"] == null) lblCookie.Text = "No cookies"; else lblCookie.Text = Request.Cookies["mycookie"].Value; }

}

2) From Lesson 2 : Passing Values between pages (using Session or QueryString)
Page 101 of 296

MCPD Web Developer

Course 70-528

default1.aspx

default2.aspx

default3.apsx





Using Session
default1 .aspx (button Next click) protected void Button1_Click(object sender, EventArgs e) { Session["Num1"] = TextBox1.Text; Response.Redirect("default2.aspx"); } protected void Button1_Click(object sender, EventArgs e) { Session["Num2"] = TextBox1.Text; Response.Redirect("default3.aspx"); } protected void Page_Load(object sender, EventArgs e) { int num1 = Int32.Parse(Session["Num1"].ToString()); int num2 = Int32.Parse(Session["Num2"].ToString()); Label1.Text = num1 + "+" + num2 + "=" + (num1 + num2); }

default2 .aspx (button Next click)

default3 .aspx (Page_Load)

Using QueryString default1 .aspx (button Next click) protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("default2.aspx?num1=" + TextBox1.Text); } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("default3.aspx?num1=" + Request.QueryString["num1"] + "&num2=" + TextBox1.Text); } protected void Page_Load(object sender, EventArgs e) { int num1 = Int32.Parse(Request.QueryString["Num1"].ToString()); int num2 = Int32.Parse(Request.QueryString["Num2"].ToString()); Label1.Text = num1 + "+" + num2 + "=" + (num1 + num2); }

default2 .aspx (button Next click)

default3.aspx (Page_Load)

3) From Lesson 3 : Application object

Page 102 of 296

MCPD Web Developer

Course 70-528

Coding
File Global.asax

Code
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["NumOfUsers"] = 0; } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown int Num = Int32.Parse(Application["NumOfUsers"].ToString()); Application["NumOfUsers"] = Num + 1; } protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) Response.Write("Number of Users :" + Application["NumOfUsers"]); }

default4.aspx (Page_Load)

4) From Lesson4 : get information form PreviousPage class Create 2 Web Form : default.aspx, default2.aspx Add CheckBoxList control to default.aspx form Add Code for default.aspx.cs public partial class default5 : System.Web.UI.Page { public CheckBoxList CBValue { get{return CheckBoxList1;} } } In default2.aspx, switch to Source View and add the PreviousPageType directive <%@ Page Language="C#" AutoEventWireup="true" CodeFile="default2.aspx.cs" Inherits="default2" %> <%@ PreviousPageType VirtualPath="~/default.aspx" %> Code for default2.aspx.cs (Page_Load event) protected void Page_Load(object sender, EventArgs e) { if (PreviousPage != null) { if (PreviousPage.IsCrossPagePostBack) Response.Write("This is a cross-post"); else Response.Write("This is a Server.Transfer"); Response.Write("<br/>You have selected :"); for (int i = 0; i < PreviousPage.CBValue.Items.Count - 1; i++) { if (PreviousPage.CBValue.Items[i].Selected) Response.Write(PreviousPage.CBValue.Items[i].ToString() + " "); } }
Page 103 of 296

MCPD Web Developer

Course 70-528

}

Page 104 of 296

MCPD Web Developer

Course 70-528

EXERCISE

Scenario
Online Company Profile Management website

Database

Web Forms
j) web.config

Page 105 of 296

MCPD Web Developer

Course 70-528

<configuration> <appSettings/> <connectionStrings> <add connectionString=" server=SERVER_NAME;database=CompanyProfile;Integrated Security=True" name="connStr"/> </connectionStrings> <system.web> ... k) List.aspx

Source code using System; using System.Configuration; using System.Data.SqlClient; public partial class List : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack ) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("Select * From Congty", conn); SqlDataReader dr = cmd.ExecuteReader(); int i = 1; Label1.Text = "<table border=1 bordercolor=red><tr bgcolor=orange><td>Số thứ tự</td><td>Công ty</td><td>Lĩnh vực</td></tr>"; while (dr.Read()) { Label1.Text = Label1.Text + "<tr><td>" + i + "</td><td>" + dr["Ten"] + "</td><td>" + dr["Linhvuc"] + "</td>"; i = i + 1; } Label1.Text = Label1.Text + "</table>"; conn.Close(); } } }

Page 106 of 296

MCPD Web Developer

Course 70-528

l)

step1.aspx

Source code using System; public partial class step1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["Tencongty"] != null) txtCongty.Text = Convert.ToString(Session["Tencongty"]); if (Session["Diachi"] != null) txtDiachi.Text = Convert.ToString(Session["Diachi"]); if (Session["Dienthoai"] != null) txtDienthoai.Text = Convert.ToString(Session["Dienthoai"]); if (Session["Linhvuc"] != null) txtLinhvuc.Text = Convert.ToString(Session["Linhvuc"]); if (Session["Sonhanvien"] != null) txtSonhanvien.Text = Convert.ToString(Session["Sonhanvien"]); //neu da co ho ten thi hien thi nut buoc 3 len if (Session["Hoten"] != null) btnBuoc3.Visible = true; } } protected void btnBuoc2_Click(object sender, EventArgs e) { LuuThongtinBuoc1VaoSession(); Response.Redirect("step2.aspx"); } protected void btnBuoc3_Click(object sender, EventArgs e) { LuuThongtinBuoc1VaoSession(); Response.Redirect("step3.aspx"); } private void LuuThongtinBuoc1VaoSession()
Page 107 of 296

MCPD Web Developer

Course 70-528

{

Session["Tencongty"] = txtCongty.Text.Trim(); Session["Diachi"] = txtDiachi.Text.Trim(); Session["Dienthoai"] = txtDienthoai.Text.Trim(); Session["Linhvuc"] = txtLinhvuc.Text.Trim(); Session["Sonhanvien"] = txtSonhanvien.Text.Trim();

} } m) step2.aspx

Source code: Javascript : step2.aspx (source view) <head runat="server"> <title>Untitled Page</title> <script language="javascript"> function Show() { var temp = '<%=Session("Matkhau")%>' if(temp != "") { document.getElementById("txtMatkhau").value = temp; document.getElementById("txtMatkhau2").value = temp; } } </script> </head> step2.aspx.cs using System; public partial class step2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { if(Session["TenDangnhap"] != null) { txtDangnhap.Text = Convert.ToString(Session["TenDangnhap"]); } } }
Page 108 of 296

MCPD Web Developer

Course 70-528

protected void btnBuoc2_Click(object sender, EventArgs e) { LuuThongTinBuoc2VaoSession(); Response.Redirect("step1.aspx"); } protected void btnBuoc3_Click(object sender, EventArgs e) { LuuThongTinBuoc2VaoSession(); Response.Redirect("step3.aspx"); } private void LuuThongTinBuoc2VaoSession() { Session["TenDangnhap"] = txtDangnhap.Text.Trim(); Session["Matkhau"] = txtMatkhau.Text.Trim(); } }

n) step3.aspx

Event btnChapnhan_Click

Description Insert new information into 3 tables in database : Congty, Taikhoan, Nguoidaidien

Source Code: using System; using System.Configuration; using System.Data; using System.Data.SqlClient; public partial class step3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["Danhxung"] != null) txtDanhxung.Text = Convert.ToString(Session["Danhxung"]); if (Session["Hoten"] != null) txtHoten.Text = Convert.ToString(Session["Hoten"]);
Page 109 of 296

MCPD Web Developer

Course 70-528

if (Session["DienthoaiDaidien"] != null) txtDienthoai.Text = Convert.ToString(Session["DienthoaiDaidien"]); if (Session["Mobile"] != null) txtMobile.Text = Convert.ToString(Session["Mobile"]); if (Session["Email"] != null) txtEmail.Text = Convert.ToString(Session["Email"]); } } protected void btnBuoc1_Click(object sender, EventArgs e) { LuuThongTinBuoc3VaoSession(); Response.Redirect("step1.aspx"); } protected void btnBuoc2_Click(object sender, EventArgs e) { LuuThongTinBuoc3VaoSession(); Response.Redirect("step2.aspx"); } protected void btnChapnhan_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); conn.Open(); SqlTransaction transaction = conn.BeginTransaction(); SqlCommand cmd1; SqlCommand cmd2; SqlCommand cmd3; //Buoc 1 : Nhap thong tin vao bang Congty cmd1 = new SqlCommand("THEMCONGTY", conn); cmd1.Transaction = transaction; cmd1.CommandType = CommandType.StoredProcedure; SqlParameter id_parm = new SqlParameter("@ID", SqlDbType.Int); id_parm.Direction = ParameterDirection.Output; cmd1.Parameters.Add(id_parm); SqlParameter ten_parm = new SqlParameter("@TEN", SqlDbType.NVarChar, ten_parm.Value = Convert.ToString(Session["TenCongty"]); cmd1.Parameters.Add(ten_parm); SqlParameter diachi_parm = new SqlParameter("@DIACHI", SqlDbType.NVarChar, 200); diachi_parm.Value = Convert.ToString(Session["Diachi"]); cmd1.Parameters.Add(diachi_parm); SqlParameter dienthoai_parm = new SqlParameter("@DIENTHOAI", SqlDbType.VarChar, 10); dienthoai_parm.Value = Convert.ToString(Session["Dienthoai"]); cmd1.Parameters.Add(dienthoai_parm); SqlParameter linhvuc_parm = new SqlParameter("@LINHVUC", SqlDbType.NText); linhvuc_parm.Value = Convert.ToString(Session["Linhvuc"]); cmd1.Parameters.Add(linhvuc_parm); SqlParameter sonhanvien_parm = new SqlParameter("@SONHANVIEN", SqlDbType.Int); sonhanvien_parm.Value = Convert.ToInt32(Session["Sonhanvien"]); cmd1.Parameters.Add(sonhanvien_parm); if (cmd1.ExecuteNonQuery() <= 0) { transaction.Rollback(); conn.Close();
Page 110 of 296

50);

MCPD Web Developer

Course 70-528

return; } //Buoc 2 : Nhap thong tin vao bang Taikhoan cmd2 = new SqlCommand("THEMTAIKHOAN", conn); cmd2.Transaction = transaction; cmd2.CommandType = CommandType.StoredProcedure; SqlParameter id_parm2 = new SqlParameter("@ID", SqlDbType.Int); id_parm2.Direction = ParameterDirection.Output; cmd2.Parameters.Add(id_parm2); SqlParameter tendangnhap_parm = new SqlParameter("@TENDANGNHAP", SqlDbType.VarChar, 30); tendangnhap_parm.Value = Convert.ToString(Session["TenDangnhap"]); cmd2.Parameters.Add(tendangnhap_parm); SqlParameter matkhau_parm = new SqlParameter("@MATKHAU", SqlDbType.VarChar, 30); matkhau_parm.Value = Convert.ToString(Session["Matkhau"]); cmd2.Parameters.Add(matkhau_parm); if ((cmd2.ExecuteNonQuery() <= 0)) { transaction.Rollback(); conn.Close(); return; } //Buoc 3 : Nhap thong tin vao bang Nguoidaidien cmd3 = new SqlCommand("THEMNGUOIDAIDIEN", conn); cmd3.Transaction = transaction; cmd3.CommandType = CommandType.StoredProcedure; SqlParameter danhxung_parm = new SqlParameter("@DANHXUNG", SqlDbType.NVarChar, 10); danhxung_parm.Value = txtDanhxung.Text.Trim(); cmd3.Parameters.Add(danhxung_parm); SqlParameter hoten_parm = new SqlParameter("@HOTEN", SqlDbType.NVarChar, 50); hoten_parm.Value = txtHoten.Text.Trim(); cmd3.Parameters.Add(hoten_parm); SqlParameter dienthoai2_parm = new SqlParameter("@DIENTHOAI", SqlDbType.VarChar, 10); dienthoai2_parm.Value = txtDienthoai.Text.Trim(); cmd3.Parameters.Add(dienthoai2_parm); SqlParameter mobile_parm = new SqlParameter("@MOBILE", SqlDbType.VarChar, 10); mobile_parm.Value = txtMobile.Text.Trim(); cmd3.Parameters.Add(mobile_parm); SqlParameter email_parm = new SqlParameter("@EMAIL", SqlDbType.VarChar, 30); email_parm.Value = txtEmail.Text.Trim(); cmd3.Parameters.Add(email_parm); SqlParameter congtyid_parm = new SqlParameter("@CONGTYID", SqlDbType.Int); congtyid_parm.Value = id_parm.Value; cmd3.Parameters.Add(congtyid_parm); SqlParameter taikhoanid_parm = new SqlParameter("@TAIKHOANID", SqlDbType.Int); taikhoanid_parm.Value = id_parm2.Value; cmd3.Parameters.Add(taikhoanid_parm); if ((cmd3.ExecuteNonQuery() <= 0)) { transaction.Rollback(); conn.Close(); return;
Page 111 of 296

MCPD Web Developer

Course 70-528

} catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } private void LuuThongTinBuoc3VaoSession() { Session["Danhxung"] = txtDanhxung.Text.Trim() ; Session["Hoten"] = txtHoten.Text.Trim(); Session["DienthoaiDaidien"] = txtDienthoai.Text.Trim(); Session["Mobile"] = txtMobile.Text.Trim(); Session["Email"] = txtEmail.Text.Trim(); }

} transaction.Commit(); conn.Close(); Session.RemoveAll(); Response.Redirect("list.aspx");

}

Page 112 of 296

MCPD Web Developer

Course 70-528

LAB 5 : LIST CONTROLS
FROM LESSON
Note : Using pubs database in SQL Server to test List Controls From Lesson 1 : DropDownList

using System; using System.Data; using System.Data.SqlClient; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { SqlConnection conn = new SqlConnection("server=.;database=pubs;Integrated Security=True"); SqlDataAdapter da = new SqlDataAdapter("Select * From authors", conn); DataSet ds = new DataSet(); da.Fill(ds, "Authors"); conn.Close(); DropDownList1.DataSource = ds.Tables["Authors"]; DropDownList1.DataTextField = "au_lname"; DropDownList1.DataValueField = "au_id"; DropDownList1.DataBind(); } }
Page 113 of 296

MCPD Web Developer

Course 70-528

}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Label1.Text = DropDownList1.SelectedItem.Text; }

ListBox, CheckBoxList, RadioButtonList : Similar to DropDownList From Lesson 2 : GridView

Binding Data and Paging in GridView

GridView Attribute Setting : AllowPaging = True PageSize = 10

Source Code using using using using System; System.Data; System.Data.SqlClient; System.Web.UI.WebControls;

public partial class default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e)
Page 114 of 296

MCPD Web Developer

Course 70-528

{ }

if(!IsPostBack) BindingData();

private void BindingData() { SqlConnection conn = new SqlConnection("server=.;database=pubs;Integrated Security=True"); SqlDataAdapter da = new SqlDataAdapter("Select * From authors", conn); DataSet ds = new DataSet(); da.Fill(ds, "Authors"); conn.Close(); GridView1.DataSource = ds.Tables["Authors"]; GridView1.DataBind(); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; BindingData(); } }

Using Bound Field and Template Field
In SQL Server : Import 1 table “employee” from pubs database to your database. Create new database in SQL Server named “TEST”

Page 115 of 296

MCPD Web Developer

Course 70-528

Import data form table “employee” from “pubs” database to TEST database

Page 116 of 296

MCPD Web Developer

Course 70-528

Page 117 of 296

MCPD Web Developer

Course 70-528

Page 118 of 296

MCPD Web Developer

Course 70-528

Create Web Form like below :

Page 119 of 296

MCPD Web Developer

Course 70-528

Choose “Columns” property of GridView. Add 4 field : 3 Bound Field and 1 Template Field to GridView. Field Properties Settings: o BoundField 1: DataField = emp_id, Header Text = ID o BoundField 2: DataField = fname, Header Text = First Name o BoundField 3: DataField = lname, Header Text = Last Name o TemplateField : Header Text = Delete - Uncheck “Auto-generate fields”

Page 120 of 296

MCPD Web Developer

Course 70-528

Then click OK The GridView will now look like below :

Page 121 of 296

MCPD Web Developer

Course 70-528

Customize Template Field : Right click the GridView and choose like below :

In Edit template mode : Drag a button to “Item Template” area and Set Text Delete for the button

Then right click and choose “End Edit Item Template”

Page 122 of 296

MCPD Web Developer

Course 70-528

The GridView now look like this :

Source code (notice that code must be written for 2 event of GridView : RowCreated and RowCommand) using System; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class Default3 : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection("server=.;database=Test;Integrated Security=True"); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) BindGrid(); } private void BindGrid() { conn.Open();
Page 123 of 296

MCPD Web Developer

Course 70-528

SqlDataAdapter da = new SqlDataAdapter("select * from employee", conn); DataSet ds = new DataSet(); da.Fill(ds, "employee"); GridView1.DataSource = ds.Tables["employee"]; GridView1.DataBind(); conn.Close(); } protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Button editButton = (Button)e.Row.Cells[3].Controls[1]; editButton.CommandArgument = e.Row.RowIndex.ToString(); } } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { try { conn.Open(); int row = Convert.ToInt32(e.CommandArgument); String emp_id = GridView1.Rows[row].Cells[0].Text; String fullname = GridView1.Rows[row].Cells[1].Text + " " + GridView1.Rows[row].Cells[2].Text; SqlCommand cmd = new SqlCommand("Delete From Employee Where emp_id='" + emp_id + "'", conn); cmd.ExecuteNonQuery(); conn.Close(); Response.Write("Successful Deleted Employee :" + fullname); BindGrid(); } catch (Exception ex) { Response.Write(ex.StackTrace); } } } DataList: Data Binding with Item Template 1) Create a DataList (named dlstAuthor) , and a label (named Label1)

Page 124 of 296

MCPD Web Developer

Course 70-528

2) Right click datalist, choose Edit Template / Item Templates.

3) Create a LinkButton for ItemTemplate.(named lbtnAuthor)

Page 125 of 296

MCPD Web Developer

Course 70-528

4) Right click the LinkButton (lbtnAuthor), choose “Edit DataBindings”

Page 126 of 296

MCPD Web Developer

Course 70-528

Then add code to “Custom Binding” field : DataBinder.Eval(Container.DataItem,"au_lname") + " " + DataBinder.Eval(Container.DataItem,"au_fname")

Right click DataList control choose “End Template Editing”

Page 127 of 296

MCPD Web Developer

Course 70-528

The datalist will now look like this :

Source Code
Page 128 of 296

MCPD Web Developer

Course 70-528

using System; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class Default4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) BindingData(); } private void BindingData() { SqlConnection conn = new SqlConnection(" server=.;database=pubs;Integrated Security=True"); SqlDataAdapter da = new SqlDataAdapter("Select * From authors", conn); DataSet ds = new DataSet(); da.Fill(ds, "Authors"); conn.Close(); dlstAuthor.DataSource = ds.Tables["Authors"]; dlstAuthor.DataBind(); } protected void dlstAuthor_ItemCommand(object source, DataListCommandEventArgs e) { dlstAuthor.SelectedIndex = e.Item.ItemIndex; Label1.Text = ((LinkButton) e.Item.FindControl("lbtnAuthor")).Text; } } 5) Run & Test.

Page 129 of 296

MCPD Web Developer

Course 70-528

Page 130 of 296

MCPD Web Developer

Course 70-528

EXERCISE
Create Database In SQL Server create database BANSACH with 2 Table : DANHMUC, SACH.
Table DANHMUC

Table SACH

Page 131 of 296

MCPD Web Developer

Course 70-528

1) web.config <configuration> <appSettings/> <connectionStrings> <add connectionString="server=.;database=BANSACH;Integrated Security=True" name="connStr"/> </connectionStrings> <system.web> ...
Page 132 of 296

MCPD Web Developer

Course 70-528

Create web form
QLDanhmuc.aspx

Ad literal LitID

Running mode

SOURCE CODE
Page 133 of 296

MCPD Web Developer

Course 70-528

(QLDanhmuc.aspx) using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Net.Mime; using System.Web.UI.WebControls; public partial class QLyDanhmuc : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlDataAdapter da; private SqlCommand cmd; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } try { LayListDanhMuc(); Session["CapnhatMode"] = false; } catch (Exception ex) { Response.Write(ex.StackTrace); } } public void LayListDanhMuc() { conn.Open(); da = new SqlDataAdapter("SELECT * FROM DANHMUC", conn); DataSet ds = new DataSet(); da.Fill(ds, "DANHMUC"); dlDanhmuc.DataSource = ds.Tables["DANHMUC"]; dlDanhmuc.DataBind(); conn.Close(); } protected void btnThemmoi_Click1(object sender, EventArgs e) { Session["CapnhatMode"] = false; txtDanhmuc.Text = ""; } protected void btnChapnhan_Click1(object sender, EventArgs e) { try { conn.Open(); if (!Convert.ToBoolean(Session["CapnhatMode"])) cmd = new SqlCommand("INSERT DANHMUC(TEN) VALUES(N'" + txtDanhmuc.Text + "')", conn); else cmd = new SqlCommand("UPDATE DANHMUC SET TEN=N'" + txtDanhmuc.Text + "' WHERE ID=" + litID.Text, conn); cmd.ExecuteNonQuery(); conn.Close(); LayListDanhMuc(); }
Page 134 of 296

MCPD Web Developer

Course 70-528

catch (Exception ex) { Response.Write(ex.StackTrace); } } protected void dlDanhmuc_ItemCommand1(object source, DataListCommandEventArgs e) { try { dlDanhmuc.SelectedIndex = e.Item.ItemIndex; litID.Text = ((Label)e.Item.FindControl("lblID")).Text; Session["CapnhatMode"] = true; txtDanhmuc.Text = ((LinkButton)e.Item.FindControl("lbDanhmuc")).Text; } catch (Exception ex) { Response.Write(ex.StackTrace); } }

}

QLSach.aspx Design Mode

Page 135 of 296

MCPD Web Developer

Course 70-528

Running mode

Source code (QLSach.aspx) using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; public partial class QLSach : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlDataAdapter da; private SqlCommand cmd; private readonly DataSet ds = new DataSet(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { conn.Open(); da = new SqlDataAdapter("SELECT * FROM DANHMUC", conn); da.Fill(ds, "DANHMUC"); dlDanhmuc.DataSource = ds.Tables["DANHMUC"]; dlDanhmuc.DataBind(); ddlDanhmuc.DataSource = ds.Tables["DANHMUC"]; ddlDanhmuc.DataTextField = "TEN"; ddlDanhmuc.DataValueField = "ID"; ddlDanhmuc.DataBind(); conn.Close(); Session["CapnhatSachMode"] = false; } catch (Exception ex) { Response.Write(ex.StackTrace); } } } protected void dlDanhmuc_ItemCommand(object source, DataListCommandEventArgs e) { try { dlDanhmuc.SelectedIndex = e.Item.ItemIndex; litCateID.Text = ((Label)e.Item.FindControl("lblID")).Text; LaySachTheoDanhmuc(litCateID.Text); ModeThemsach(); } catch (Exception ex)
Page 136 of 296

MCPD Web Developer

Course 70-528

{ }

Response.Write(ex.StackTrace);

} protected void btnThemsach_Click(object sender, EventArgs e) { ModeThemsach(); } protected void btnChapnhan_Click(object sender, EventArgs e) { try { String hinh = ""; if (FileUpload1.HasFile) { FileUpload1.SaveAs(Request.PhysicalApplicationPath + "\\" + FileUpload1.FileName); hinh = FileUpload1.FileName; } conn.Open(); string cmdStr; if (!Convert.ToBoolean(Session["CapnhatSachMode"])) cmdStr = "INSERT INTO SACH( TUASACH,TACGIA,NXB,NAMXB,MOTA,DANHMUC_ID,GIA,HINH) VALUES(N'" + txtTuasach.Text.Trim() + "',N'" + txtTacgia.Text.Trim() + "',N'" + txtNXB.Text + "'," + txtNamXB.Text.Trim() + ",N'" + txtMota.Text.Trim() + "'," + ddlDanhmuc.SelectedValue + "," + txtGia.Text.Trim() + ",'" + hinh + "')"; else { if (hinh == "") hinh = litHinh.Text; cmdStr = "UPDATE SACH SET TUASACH=N'" + txtTuasach.Text.Trim() + "'" + ",TACGIA=N'" + txtTacgia.Text.Trim() + "',NXB=N'" + txtNXB.Text.Trim() + "',NAMXB=" + txtNamXB.Text.Trim() + ",MOTA=N'" + txtMota.Text.Trim() + "',DANHMUC_ID=" + ddlDanhmuc.SelectedValue + ",GIA=" + txtGia.Text.Trim() + ",HINH='" + hinh + "' WHERE ID=" + litSachID.Text; cmd = new SqlCommand(cmdStr, conn); } cmd = new SqlCommand(cmdStr, conn); cmd.ExecuteNonQuery(); conn.Close(); LaySachTheoDanhmuc(ddlDanhmuc.SelectedValue); dlDanhmuc.SelectedIndex = ddlDanhmuc.SelectedIndex; //sau khi thuc hien them/capnhat, dua len hinh moi litHinh.Text = hinh; imgSach.ImageUrl = hinh; //sau khi them moi , chuyen trang thai ve dang cap nhat if (!Convert.ToBoolean(Session["CapnhatSachMode"])) { Session["CapnhatSachMode"] = true; dgSach.SelectedIndex = dgSach.Rows.Count - 1; litSachID.Text = dgSach.Rows[dgSach.Rows.Count - 1].Cells[1].Text; } } catch (Exception ex) {
Page 137 of 296

MCPD Web Developer

Course 70-528

}

Response.Write(ex.StackTrace);

}

} public void LaySachTheoDanhmuc(String id) { conn.Open(); da = new SqlDataAdapter("SELECT * FROM SACH WHERE DANHMUC_ID=" + id, conn); da.Fill(ds, "SACH"); dgSach.DataSource = ds.Tables["SACH"]; dgSach.DataBind(); ddlDanhmuc.SelectedValue = id; conn.Close(); } public void ModeThemsach() { Session["CapnhatSachMode"] = false; txtTuasach.Text = ""; txtTacgia.Text = ""; txtNXB.Text = ""; txtNamXB.Text = ""; txtMota.Text = ""; txtGia.Text = ""; imgSach.ImageUrl = ""; dgSach.SelectedIndex = -1; }

Page 138 of 296

MCPD Web Developer

Course 70-528

LAB 6 : ASP 2.0 ADVANCED CONTROLS
FROM LESSON
1) From Lesson 1 : Multi-View control Create Web Form with 1 MultiView control (MultiView1) and 3 View control (View1, View2, View3) and design each View like below:

Source code : 1 event-method for 5 button (Button1, Button2, Button3, Button4, Button5) using System; using System.Web.UI.WebControls;
Page 139 of 296

MCPD Web Developer

Course 70-528

public partial class _default : System.Web.UI.Page { protected void AllButton_Click(object sender, EventArgs e) { string buttonLabel = ((Button)sender).Text; if(buttonLabel=="Next") MultiView1.ActiveViewIndex += 1; else if(buttonLabel=="Previous") MultiView1.ActiveViewIndex -= 1; else if(buttonLabel=="Finish") Label5.Text = "You've registered with Firstname : <b>" + TextBox1.Text + "</b>,LastName :<b>" + TextBox2.Text + "</b>. Your birthday is :<b>" + Calendar1.SelectedDate + "</b>"; else if(buttonLabel=="Finish") MultiView1.ActiveViewIndex = 0; } } 2) From Lesson 2 : Wizard control Create Web Form with Wizard control. Choose “WizardSteps” property to add remove steps to Wizard control

Add “Step 3” to Wizard control

Page 140 of 296

MCPD Web Developer

Course 70-528

Design Step1 like below :

- Design Step2 like below :

Page 141 of 296

MCPD Web Developer

Course 70-528

Design Step3 like below :

Source code for button Finish (Wizard1.FinishButtonClick) using System.Web.UI.WebControls; public partial class default2 : System.Web.UI.Page { protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { Label5.Text = "You've registered with Firstname : <b>" + TextBox1.Text + "</b>,LastName :<b>" + TextBox2.Text + "</b>. Your birthday is :<b>" + Calendar1.SelectedDate + "</b>"; } } 3) From Lesson 3 : ImageMap control Create Web Form with 1 ImageMap control and attach with VietNam’s Map image file like below:

Page 142 of 296

MCPD Web Developer

Course 70-528

Create Hotspot for ImageMap : Right click ImageMap control  choose Properties. Then click “HotSpots” collection to add/remove Hotspots

Page 143 of 296

MCPD Web Developer

Course 70-528

Now add 3 Circle hotspots to your Web Form :

Write code for Image1_Click by double-click ImageMap using System.Web.UI.WebControls; public partial class Default3 : System.Web.UI.Page { protected void ImageMap1_Click(object sender, ImageMapEventArgs e) { Response.Write("Bạn đã chọn :<b>" + e.PostBackValue + "<b>"); } }
Page 144 of 296

MCPD Web Developer

Course 70-528

4) From Lesson 4 : SiteMapPath tracing

Create web.sitemap file (xml file) : Right click Project Name  Add New Item : choose SiteMap template

Page 145 of 296

MCPD Web Developer

Course 70-528

web.sitemap file content : <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="default.aspx" title="Homepage" description="Page 2" > <siteMapNode url="default2.aspx" title="Page 2" description="Page 2"> <siteMapNode url="default4.aspx" title="Page 4" description="Page 4" /> </siteMapNode> <siteMapNode url="default3.aspx" title="Page 3" description="Page 3"> <siteMapNode url="default5.aspx" title="Page 5" description="Page 5" /> </siteMapNode> </siteMapNode> </siteMap> Create Web Form contains SiteMapPath control (tracing website)

5) From Lesson 5 : TreeView control Create new Web Form with TreeView control

Page 146 of 296

MCPD Web Developer

Course 70-528

Then choose “Auto Format” to customize TreeView look and feel

In TreeView property choose “DataSourceID” property  then click “New data source”
Page 147 of 296

MCPD Web Developer

Course 70-528

Then choose SiteMap as main datasource for treeview

The TreeView now :
Page 148 of 296

MCPD Web Developer

Course 70-528

6) From Lesson 6 : Menu control Create new Web Form with Menu control

Page 149 of 296

MCPD Web Developer

Course 70-528

Then choose “Auto Format” to customize Menu look and feel

Page 150 of 296

MCPD Web Developer

Course 70-528

In Menu property choose “DataSourceID” property  then click “New data source”

Then choose SiteMap as main datasource for treeview

Page 151 of 296

MCPD Web Developer

Course 70-528

Web Form will now look like this :

Page 152 of 296

MCPD Web Developer

Course 70-528

EXERCISE
dangky.aspx (using Multi-View control for “Bước 1” and “Bước 2” display)

Page 153 of 296

MCPD Web Developer

Course 70-528

Scenario: Design a website to manage Viet Nam Business Information : Company Profile. Your task design & code 2 page : o Dangky.aspx : help company register their info with our website o Trangchu.aspx : list company profile by category

trangchu.aspx

Page 154 of 296

MCPD Web Developer

Course 70-528

web.config
<configuration> <appSettings/> <connectionStrings> <add connectionString="server=SERVER_NAME;database=Business;Integrated Security=True" name="connStr"/> </connectionStrings> <system.web> ...

dangky.aspx
using using using using using System; System.Configuration; System.Data; System.Data.SqlClient; System.Web.UI.WebControls;

public partial class dangky : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private DataTable dt; public void TaoCayVung() { conn.Open(); SqlCommand cmd = new SqlCommand("GET_ALL_REGION", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); dt = new DataTable("Vung"); da.Fill(dt);
Page 155 of 296

MCPD Web Developer

Course 70-528

conn.Close(); if ((tvVung.Nodes.Count == 0)) { for (int i = 0; i <= dt.Rows.Count - 1; i++) { TreeNode node = new TreeNode(dt.Rows[i]["Name"].ToString(), dt.Rows[i]["ID"].ToString()); if (ReferenceEquals(dt.Rows[i]["ParentID"], DBNull.Value)) tvVung.Nodes.Add(node); else for (int j = 0; j <= tvVung.Nodes.Count - 1; j++) DuyetCayThemLa(tvVung.Nodes[j], dt.Rows[i]["ParentID"].ToString(), node); } } tvVung.ExpandAll(); Panel2.Visible = true; Panel4.Visible = false; } public void DuyetCayThemLa(TreeNode parentNode, string parentID, TreeNode node) { if (parentNode.Value == parentID) { parentNode.ChildNodes.Add(node); return; } else if (parentNode.ChildNodes.Count > 0) for (int i = 0; i <= parentNode.ChildNodes.Count - 1; i++) DuyetCayThemLa(parentNode.ChildNodes[i], parentID, node); } protected void btnChonVung_Click(object sender, EventArgs e) { try { TaoCayVung(); } catch (Exception ex) { Response.Write("Error:" + ex.StackTrace); } } public void TaoCayDanhmuc() { conn.Open(); SqlCommand cmd = new SqlCommand("GET_ALL_CATEGORY", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); dt = new DataTable("Danhmuc"); da.Fill(dt); conn.Close(); if (mnuDanhmuc.Items.Count == 0) for (int i = 0; i <= dt.Rows.Count - 1; i++) { MenuItem item = new MenuItem(dt.Rows[i]["Name"].ToString(), dt.Rows[i]["ID"].ToString()); if (ReferenceEquals(dt.Rows[i]["ParentID"], DBNull.Value)) mnuDanhmuc.Items.Add(item); else
Page 156 of 296

MCPD Web Developer

Course 70-528

} Panel1.Visible = true; Panel3.Visible = false;

for (int j = 0; j <= mnuDanhmuc.Items.Count - 1; j++) DuyetDanhmucThemLa(mnuDanhmuc.Items[j], dt.Rows[i]["ParentID"].ToString(), item);

} public void DuyetDanhmucThemLa(MenuItem parentItem, string parentID, MenuItem item) { if (parentItem.Value == parentID) parentItem.ChildItems.Add(item); else if (parentItem.ChildItems.Count > 0) for (int i = 0; i <= parentItem.ChildItems.Count - 1; i++) DuyetDanhmucThemLa(parentItem.ChildItems[i], parentID, item); } protected void btnChonDanhmuc_Click(object sender, EventArgs e) { try { TaoCayDanhmuc(); } catch (Exception ex) { Response.Write("Error:" + ex.StackTrace); } } protected void btnThemVung_Click(object sender, EventArgs e) { Panel2.Visible = false; Panel4.Visible = true; txtLanhthoMoi.Text = ""; conn.Open(); SqlCommand cmd = new SqlCommand("GET_ALL_REGION", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); dt = new DataTable("Vung"); da.Fill(dt); conn.Close(); ddlLanhtho.DataSource = dt; ddlLanhtho.DataTextField = "Name"; ddlLanhtho.DataValueField = "ID"; ddlLanhtho.DataBind(); } protected void btnThemDanhmuc_Click(object sender, EventArgs e) { Panel1.Visible = false; Panel3.Visible = true; txtDanhmucMoi.Text = ""; conn.Open(); SqlCommand cmd = new SqlCommand("GET_ALL_CATEGORY", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); dt = new DataTable("Danhmuc"); da.Fill(dt); ddlDanhmuc.DataSource = dt; ddlDanhmuc.DataTextField = "Name";
Page 157 of 296

MCPD Web Developer

Course 70-528

ddlDanhmuc.DataValueField = "ID"; ddlDanhmuc.DataBind(); } protected void btnThemDM_Click(object sender, EventArgs e) { conn.Open(); SqlCommand cmd = new SqlCommand("INSERT_CATEGORY", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter id_parm = new SqlParameter("ID_PARM", SqlDbType.Int); id_parm.Direction = ParameterDirection.Output; cmd.Parameters.Add(id_parm); cmd.Parameters.Add(new SqlParameter("NAME_PARM", txtDanhmucMoi.Text.Trim())); cmd.Parameters.Add(new SqlParameter("PARENT_ID_PARM", ddlDanhmuc.SelectedValue)); cmd.ExecuteNonQuery(); conn.Close(); mnuDanhmuc.Items.Clear(); TaoCayDanhmuc(); txtDanhmuc.Text = txtDanhmucMoi.Text.Trim(); lblDanhmucID.Text = id_parm.Value.ToString(); } protected void btnThemLT_Click(object sender, EventArgs e) { conn.Open(); SqlCommand cmd = new SqlCommand("INSERT_REGION", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter id_parm = new SqlParameter("ID_PARM", SqlDbType.Int); id_parm.Direction = ParameterDirection.Output; cmd.Parameters.Add(id_parm); cmd.Parameters.Add(new SqlParameter("NAME_PARM", txtLanhthoMoi.Text.Trim())); cmd.Parameters.Add(new SqlParameter("PARENT_ID_PARM", ddlLanhtho.SelectedValue)); cmd.ExecuteNonQuery(); conn.Close(); tvVung.Nodes.Clear(); TaoCayVung(); txtLanhtho.Text = txtLanhthoMoi.Text; lblLanhthoID.Text = id_parm.Value.ToString(); } protected void mnuDanhmuc_MenuItemClick(object sender, MenuEventArgs e) { txtDanhmuc.Text = mnuDanhmuc.SelectedItem.Text; lblDanhmucID.Text = mnuDanhmuc.SelectedItem.Value; } protected void tvVung_SelectedNodeChanged(object sender, EventArgs e) { txtLanhtho.Text = tvVung.SelectedNode.Text; lblLanhthoID.Text = tvVung.SelectedNode.Value; } protected void AllButtons_Click(object sender, EventArgs e) { switch (((Button)sender).Text)
Page 158 of 296

MCPD Web Developer

Course 70-528

{

case "Bước 1": MultiView1.ActiveViewIndex -= 1; break; case "Bước 2": if (fuLogo.HasFile) Session["fuLogo"] = fuLogo; if (txtMatkhau.Text != "") Session["matkhau"] = txtMatkhau.Text; MultiView1.ActiveViewIndex += 1; break; case "Hoàn tất": conn.Open(); SqlTransaction transaction = conn.BeginTransaction(); SqlCommand cmd1 = new SqlCommand("INSERT_COMPANY", conn); cmd1.CommandType = CommandType.StoredProcedure; cmd1.Transaction = transaction; SqlParameter id_parm = new SqlParameter("ID_PARM", SqlDbType.Int); id_parm.Direction = ParameterDirection.Output; cmd1.Parameters.Add(id_parm); FileUpload logo = (FileUpload)Session["fuLogo"]; cmd1.Parameters.Add(new SqlParameter("@NAME_PARM", txtTenCongty.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@ADDRESS_PARM", txtDiachi.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@REGION_ID_PARM", lblLanhthoID.Text)); cmd1.Parameters.Add(new SqlParameter("@CATEGORY_ID_PARM", lblDanhmucID.Text)); cmd1.Parameters.Add(new SqlParameter("@PHONE_PARM", txtDienthoai.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@FAX_PARM", txtFax.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@EMAIL_PARM", txtEmail.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@WEBSITE_PARM", txtWebsite.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@DESCRIPTION_PARM", txtMota.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@LOGO_PARM", logo.FileName)); cmd1.Parameters.Add(new SqlParameter("@USER_PARM", txtDangnhap.Text.Trim())); cmd1.Parameters.Add(new SqlParameter("@PASS_PARM", Session["matkhau"])); logo.SaveAs(Request.PhysicalApplicationPath + "\\\\" + logo.FileName); if ((cmd1.ExecuteNonQuery() < 1)) { transaction.Rollback(); return; } for (int i = 0; i <= gvHanghoa.Rows.Count - 1; i++) { SqlCommand cmd2 = new SqlCommand("INSERT_PRODUCT", conn); cmd2.CommandType = CommandType.StoredProcedure; cmd2.Parameters.Add(new SqlParameter("@NAME_PARM", gvHanghoa.Rows[i].Cells[0].Text.Trim()));

Page 159 of 296

MCPD Web Developer

Course 70-528

} transaction.Commit(); conn.Close(); Response.Redirect("trangchu.aspx"); break;

cmd2.Parameters.Add(new SqlParameter("@COMPANY_ID_PARM", id_parm.Value)); cmd2.Parameters.Add(new SqlParameter("@DESCRIPTION_PARM", gvHanghoa.Rows[i].Cells[1].Text.Trim())); cmd2.Parameters.Add(new SqlParameter("@IMAGE_PARM", gvHanghoa.Rows[i].Cells[2].Text)); float price = (float)Convert.ToDouble(gvHanghoa.Rows[i].Cells[3].Text); cmd2.Parameters.Add(new SqlParameter("@PRICE_PARM", price)); cmd2.Transaction = transaction; if (cmd2.ExecuteNonQuery() < 1) { transaction.Rollback(); return; }

}

} } protected void btnNhaphang_Click(object sender, EventArgs e) { if (Session["hanghoa"] != null) dt = (DataTable)Session["hanghoa"]; else { dt = new DataTable(); dt.Columns.Add(new DataColumn("Tên")); dt.Columns.Add(new DataColumn("Mô tả")); dt.Columns.Add(new DataColumn("Hình")); dt.Columns.Add(new DataColumn("Giá")); } DataRow dr = dt.NewRow(); dr[0] = txtTenHang.Text.Trim(); dr[1] = txtMotaHang.Text.Trim(); fuHinh.SaveAs(Request.PhysicalApplicationPath + "\\\\" + fuHinh.FileName); dr[2] = fuHinh.FileName; dr[3] = txtGia.Text.Trim(); dt.Rows.Add(dr); Session["hanghoa"] = dt; gvHanghoa.DataSource = dt; gvHanghoa.DataBind(); } protected void btnThemhang_Click(object sender, EventArgs e) { txtTenHang.Text = ""; txtMotaHang.Text = ""; txtGia.Text = ""; }

trangchu.aspx
using using using using using System; System.Configuration; System.Data; System.Data.SqlClient; System.Web.UI.WebControls;

Page 160 of 296

MCPD Web Developer

Course 70-528

public partial class trangchu : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); public void TaoCayDanhmuc() { conn.Open(); SqlCommand cmd = new SqlCommand("GET_ALL_CATEGORY", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable("Danhmuc"); da.Fill(dt); conn.Close(); if (mnuDanhmuc.Items.Count == 0) for (int i = 0; i <= dt.Rows.Count - 1; i++) { MenuItem item = new MenuItem(dt.Rows[i]["Name"].ToString(), dt.Rows[i]["ID"].ToString()); if (ReferenceEquals(dt.Rows[i]["ParentID"], DBNull.Value)) mnuDanhmuc.Items.Add(item); else for (int j = 0; j <= mnuDanhmuc.Items.Count - 1; j++) DuyetDanhmucThemLa(mnuDanhmuc.Items[j], dt.Rows[i]["ParentID"].ToString(), item); } } public void DuyetDanhmucThemLa(MenuItem parentItem, string parentID, MenuItem item) { if (parentItem.Value == parentID) parentItem.ChildItems.Add(item); else if (parentItem.ChildItems.Count > 0) for (int i = 0; i <= parentItem.ChildItems.Count - 1; i++) DuyetDanhmucThemLa(parentItem.ChildItems[i], parentID, item); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) TaoCayDanhmuc(); } protected void mnuDanhmuc_MenuItemClick(object sender, MenuEventArgs e) { Panel2.Visible = true; int category_id = Convert.ToInt32(mnuDanhmuc.SelectedItem.Value); lblDanhmuc.Text = mnuDanhmuc.SelectedItem.Text; conn.Open(); SqlCommand cmd = new SqlCommand("GET_COMPANY_BY_CATEGORY", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@CATEGORY_ID_PARM", category_id)); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); conn.Close(); gvCompany.DataSource = dt; gvCompany.DataBind(); } protected void gvCompany_RowCommand(object sender, GridViewCommandEventArgs e) {
Page 161 of 296

MCPD Web Developer

Course 70-528

Panel1.Visible = true; int row = Convert.ToInt32(e.CommandArgument.ToString()); int company_id = Convert.ToInt32(( (Label)gvCompany.Rows[row].Cells[4].Controls[1]).Text); conn.Open(); SqlCommand cmd = new SqlCommand("GET_COMPANY_BY_ID", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID_PARM", company_id)); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { lblTenCty.Text = dr["Name"].ToString(); lblDiachi.Text = dr["Address"].ToString(); lblVung.Text = dr["RegionName"].ToString(); lblDienthoai.Text = dr["Phone"].ToString(); lblFax.Text = dr["Fax"].ToString(); lblEmail.Text = dr["Email"].ToString(); lblWebsite.Text = dr["Website"].ToString(); lblMota.Text = dr["Description"].ToString(); imgLogo.ImageUrl = dr["Logo"].ToString(); } dr.Close(); cmd.Dispose(); cmd = new SqlCommand("GET_PRODUCT_BY_COMPANY_ID", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@COMPANY_ID_PARM", company_id)); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); dlstProduct.DataSource = dt; dlstProduct.DataBind(); conn.Close(); } protected void gvCompany_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton lbChitiet = (LinkButton)e.Row.Cells[3].Controls[1]; lbChitiet.CommandArgument = e.Row.RowIndex.ToString(); Label lblSTT = (Label)e.Row.Cells[0].Controls[1]; lblSTT.Text = (e.Row.RowIndex + 1).ToString(); } }

}

Page 162 of 296

MCPD Web Developer

Course 70-528

LAB 7 : USER CONTROLS AND CUSTOM CONTROLS
FROM LESSON
1) From Lesson 1: Using User controls Right click web project name. Choose  Add New Item : Choose “Web User Control” template Enter a name : ex LoginUC.ascx In the file LoginUC.ascx ,create the Interface

Write code for Login Button protected void btnLogin_Click(object sender, EventArgs e) { if (txtUsername.Text != "test" || txtPassword.Text != "test") Response.Write("<script language=javascript>alert('Login Fail ! ')</script>"); else Response.Write("<script language=javascript>alert('Login Successful ! ')</script>"); } Drag Login.ascx usercontrol to Web Form1.aspx. Run & test Web Form1.aspx

2) From Lesson 2 : Using Custom controls

a) Inherited Control
Add a “Visual C# / Windows / Web Control Library”
Page 163 of 296

MCPD Web Developer

Course 70-528

Add a class named CountryDropDown.(CountryDropDown.cs) Write the code for CountryDropDown.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [DefaultProperty("Text"), ToolboxData("<{0}:CountryDropDown runat=server></{0}:CountryDropDown>")] public class CountryDropDown : DropDownList { public enum ValueListChoice { CountryCodes = 1, CountryNames = 0 } string _text; ValueListChoice vlc; [Bindable(true), Category("Appearance"), DefaultValue("")] public string Text { get { return _text; } set { _text = value; } } [Bindable(true), Category("Appearance"), DefaultValue("0")] public ValueListChoice ValueList { get { return vlc; } set { vlc = value; LoadItems(); } } private void CountryDropDown_Init(object sender, System.EventArgs e) { LoadItems(); } private void LoadItems() { Items.Clear(); if (vlc == ValueListChoice.CountryNames) { Items.Add("--Country--"); Items.Add("Australia"); Items.Add("Brazil");
Page 164 of 296

MCPD Web Developer

Course 70-528

Items.Add("Canada"); Items.Add("China"); Items.Add("Denmark"); Items.Add("France"); Items.Add("Germany"); Items.Add("India"); Items.Add("United Kingdom"); Items.Add("United States"); Items.Add("Vietnam"); }else if (vlc == ValueListChoice.CountryCodes) { ListItemCollection col = new ListItemCollection(); ListItem nav = new ListItem(); nav.Text = "--Country--"; nav.Value = ""; col.Add(nav); ListItem au = new ListItem(); au.Text = "Australia"; au.Value = "AUS"; col.Add(au); ListItem br = new ListItem(); br.Text = "Brazil"; br.Value = "BRA"; col.Add(br); ListItem ca = new ListItem(); ca.Text = "Canada"; ca.Value = "CAN"; col.Add(ca); ListItem cn = new ListItem(); cn.Text = "China"; cn.Value = "CHN"; col.Add(cn); ListItem dk = new ListItem(); dk.Text = "Denmark"; dk.Value = "DNK"; col.Add(dk); ListItem fr = new ListItem(); fr.Text = "France"; fr.Value = "FRA"; col.Add(fr); ListItem de = new ListItem(); de.Text = "Germany"; de.Value = "DEU"; col.Add(de); ListItem ind = new ListItem(); ind.Text = "India"; ind.Value = "IND"; col.Add(ind); ListItem gb = new ListItem(); gb.Text = "United Kingdom"; gb.Value = "GBR"; col.Add(gb); ListItem us = new ListItem();
Page 165 of 296

MCPD Web Developer

Course 70-528

us.Text = "United States"; us.Value = "USA"; col.Add(us); ListItem vn = new ListItem(); vn.Text = "Vietnam"; vn.Value = "VNM"; col.Add(vn); foreach (ListItem li in col) { Items.Add(li); }

} } }

Build Project. In ASP.NET Project , right click ToolBox , choose “Choose Items…”

Choose “.NET Framework Components”, browse to CountryDropDown.dll file.

Page 166 of 296

MCPD Web Developer

Course 70-528

In toolbox , drag the control to Web Form.

b) Composite Control
Add a “Visual C# / Windows / Web Control Library” project. (named CompositeControl)

Add a class name CompositeControl (CompositeControl.cs) with the code below: using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel;
Page 167 of 296

MCPD Web Developer

Course 70-528

using System.Web.UI; using System.Web.UI.WebControls; namespace MyCompositeControl { public class MyLoginControl : Control, INamingContainer { private readonly TextBox txtUsername = new TextBox(); private readonly TextBox txtPassword = new TextBox(); public string Username { get { EnsureChildControls(); return txtUsername.Text; } set { EnsureChildControls(); txtUsername.Text = value; } } [Category("Info"), Description("Password")] public string Password { get { EnsureChildControls(); return txtPassword.Text; } set { EnsureChildControls(); txtPassword.Text = value; } } protected override void CreateChildControls() { Controls.Add(new LiteralControl("Username ")); Controls.Add(txtUsername); Controls.Add(new LiteralControl("<br>")); Controls.Add(new LiteralControl("Password ")); txtPassword.TextMode = TextBoxMode.Password; Controls.Add(txtPassword); Controls.Add(new LiteralControl("<br>")); } } } Build it. ( CompositeControl.dll) In ASP.NET Project , right click ToolBox , choose “Choose Items” Choose .NET Framework Component, browse to .dll file. In toolbox , drag the control to Web Form.

Add a button to Web Form.(named btnLogin) Write code for the Login button : protected void btnLogin_Click(object sender, EventArgs e)
Page 168 of 296

MCPD Web Developer

Course 70-528

{

if ((MyLoginControl1.Username != "test" | MyLoginControl1.Password != "test")) Response.Write("<script language=javascript>alert('Login Fail ! ')</script>"); else Response.Write("<script language=javascript>alert('Login Successful ! ')</script>"); }

- Run & Test.

Page 169 of 296

MCPD Web Developer

Course 70-528

EXERCISE
BookStore FrontEnd

CODING
Create 2 Interface file in App_Code folder
Page 170 of 296

MCPD Web Developer

Course 70-528

IChitietUC.cs
public interface IChitietUC { void LayChitietSach(int id); } DanhmucUC.ascx

ISachUC.cs
public interface ISachUC { void LaySachTheoDanhmuc(int danhmuc_id); }

using using using using using

System; System.Configuration; System.Data; System.Data.SqlClient; System.Web.UI.WebControls;

public partial class DanhmucUC : System.Web.UI.UserControl { private readonly SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private readonly DataSet ds = new DataSet(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { conn.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM DANHMUC", conn); da.Fill(ds, "DANHMUC"); dlDanhmuc.DataSource = ds.Tables["DANHMUC"]; dlDanhmuc.DataBind(); conn.Close(); } catch (Exception ex) { Response.Write("ERROR:" + ex.StackTrace);
Page 171 of 296

MCPD Web Developer

Course 70-528

}

}

} protected void dlDanhmuc_ItemCommand(object source, DataListCommandEventArgs e) { dlDanhmuc.SelectedIndex = e.Item.ItemIndex; Session["DanhmucID"] = ((Label)e.Item.FindControl("lblID")).Text; Parent.Parent.FindControl("SachUC1").Visible = true; ((ISachUC)Parent.Parent.FindControl("SachUC1")).LaySachTheoDanhmuc((int)Ses sion["DanhmucID"]); Parent.Parent.FindControl("ChitietUC1").Visible = false; } } SachUC.ascx

using using using using

System; System.Configuration; System.Data; System.Data.SqlClient;

Page 172 of 296

MCPD Web Developer

Course 70-528

public partial class SachUC : System.Web.UI.UserControl, ISachUC { private readonly SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private readonly DataSet ds = new DataSet(); void ISachUC.LaySachTheoDanhmuc(int danhmuc_id) { try { conn.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM SACH WHERE DANHMUC_ID=" + danhmuc_id, conn); da.Fill(ds, "SACH"); dlSach.DataSource = ds.Tables["SACH"]; dlSach.DataBind(); conn.Close(); } catch (Exception ex) { Response.Write("ERROR:" + ex.StackTrace); } } }

ChitietUC.ascx

using using using using

System; System.Configuration; System.Data; System.Data.SqlClient;

public partial class ChitietUC : System.Web.UI.UserControl, IChitietUC { private readonly SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); private SqlDataAdapter da; private readonly DataSet ds = new DataSet(); public void LayChitietSach(int id) { try { conn.Open(); da = new SqlDataAdapter("SELECT * FROM SACH WHERE ID=" + id, conn); da.Fill(ds, "Sach"); conn.Close(); imgSach.ImageUrl = "images/" + ds.Tables["Sach"].Rows[0][8];
Page 173 of 296

MCPD Web Developer

Course 70-528

lblTua.Text = ds.Tables["Sach"].Rows[0][1].ToString(); lblTacgia.Text = ds.Tables["Sach"].Rows[0][2].ToString(); lblNXB.Text = ds.Tables["Sach"].Rows[0][3].ToString(); lblNamXB.Text = ds.Tables["Sach"].Rows[0][4].ToString(); lblGia.Text = ds.Tables["Sach"].Rows[0][7].ToString(); lblMota.Text = ds.Tables["Sach"].Rows[0][5].ToString(); } catch (Exception ex) { Response.Write("ERROR:"+ex.StackTrace); } } }

trangchinh.aspx

public partial class trangchinh : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["id"] != "") { SachUC1.Visible = false; ChitietUC1.Visible = true; ChitietUC1.LayChitietSach(Convert.ToInt32(Request.QueryString["id"])); } else { SachUC1.Visible = true; ChitietUC1.Visible = false; } } } }
Page 174 of 296

MCPD Web Developer

Course 70-528

LAB 8 : LOCALIZATION
FROM LESSON
From Lesson 1 : Get All Cultures, view culture currency and date information Create web project. Create a web form interface like below:

using System; using System.Globalization; using System.Threading; using System.Web.UI.WebControls; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { //get default culture lbldefault.Text = Thread.CurrentThread.CurrentCulture.Name + Thread.CurrentThread.CurrentCulture.DisplayName; //get all culture if(ListBox1.Items.Count == 0) { foreach(CultureInfo cul in CultureInfo.GetCultures(CultureTypes.AllCultures)) ListBox1.Items.Add(new ListItem(cul.DisplayName, cul.Name)); }
Page 175 of 296

MCPD Web Developer

Course 70-528

}

}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { DateTime dt = DateTime.Now; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ListBox1.SelectedItem.Value); lblCode.Text = Thread.CurrentThread.CurrentCulture.Name; int integer = 0; lblCurrency.Text = integer.ToString("C", Thread.CurrentThread.CurrentCulture); lblDate.Text = dt.ToString("D", Thread.CurrentThread.CurrentCulture); } } From Lesson 2 : Using Local Resource file Create web form like below:

Code for Calendar’s SelectionChanged event protected void Calendar1_SelectionChanged(object sender, EventArgs e) { Label3.Text = Calendar1.SelectedDate.ToLongDateString(); } Choose Menu : “Tools”  “Generate Local Resource”

Page 176 of 296

MCPD Web Developer

Course 70-528

Re-Edit Defautl2.aspx.resx

Re-write default2.aspx.vi.resx

Page 177 of 296

MCPD Web Developer

Course 70-528

Run your website (default language en-us)

Change language to vietnamese in IE by moving up Vietnamese to the top of the Language List

Page 178 of 296

MCPD Web Developer

Course 70-528

Then Refresh the page

From Lesson 3 : Using Globl Resource file
Page 179 of 296

MCPD Web Developer

Course 70-528

a. Create Web Form interface below

Page 180 of 296

MCPD Web Developer

Course 70-528

Add Global Resource Folder : App_GlobalResources

- Add resource file :

Page 181 of 296

MCPD Web Developer

Course 70-528

-

Add 2 resource file : named Resource.resx, Resource.vi-VN.resx Resource.vi-VN.resx

Resource.resx

Source code
using System; using System.Globalization; using System.Threading; public partial class Default3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) SetUIByCulture("en-US"); } public void SetUIByCulture(string culture) { Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); lblTitle.Text = (string)GetGlobalResourceObject("Resource", "lblTitle"); lblName.Text = (string)GetGlobalResourceObject("Resource", "lblName"); lblAddress.Text = (string)GetGlobalResourceObject("Resource", "lblAddress"); lblPhone.Text = (string)GetGlobalResourceObject("Resource", "lblPhone"); lblEmail.Text = (string)GetGlobalResourceObject("Resource", "lblEmail"); lblCompany.Text = (string)GetGlobalResourceObject("Resource", "lblCompany"); lblCompanyAddress.Text = (string)GetGlobalResourceObject("Resource", "lblCompanyAddress"); btnOK.Text = (string)GetGlobalResourceObject("Resource", "btnOK"); } //For Link Button “Tiếng Việt” protected void lbVietnam_Click(object sender, EventArgs e) { SetUIByCulture("vi-VN"); } //For Link Button “English” protected void lbEnglish_Click(object sender, EventArgs e) { SetUIByCulture("en-US"); } }

Page 182 of 296

MCPD Web Developer

Course 70-528

EXERCISE
1) Scenario

Company Information Portal (Multi-Language)
2) Database

3) Web Form

Page 183 of 296

MCPD Web Developer

Course 70-528

Dynamic Templates: Create 2 User Control :
template1.ascx

Source view
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyCompanyTemplate1.ascx.cs" Inherits="MyCompanyTemplate1" %> <asp:LinkButton ID="lbMenu" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name_VN") %>'> </asp:LinkButton>&nbsp; <asp:Label ID="lblID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ID") %>' Visible="False"> </asp:Label> template2.ascx

Source view
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyCompanyTemplate2.ascx.cs" Inherits="MyCompanyTemplate2" %> <asp:LinkButton ID="lbMenu" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name_EN") %>'> </asp:LinkButton> <asp:Label ID="lblID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ID") %>' Visible="False"> </asp:Label>

Source Code : MyCompany.aspx
Page 184 of 296

MCPD Web Developer

Course 70-528

using using using using

System; System.Data; System.Data.SqlClient; System.Web.UI.WebControls;

public partial class MyCompany : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection( "server=.;uid=sa;pwd=sa;database=MyCompany"); private SqlDataAdapter da = new SqlDataAdapter(); private DataSet ds; protected void Page_Load(object sender, EventArgs e) { string cul = Request.QueryString["mode"]; if (cul == "VN" | cul == "") { cul = "VN"; dlMenu.ItemTemplate = Page.LoadTemplate("MyCompanyTemplate1.ascx"); dlSubmenu.ItemTemplate = Page.LoadTemplate("MyCompanyTemplate1.ascx"); } else if (cul == "EN") { dlMenu.ItemTemplate = Page.LoadTemplate("MyCompanyTemplate2.ascx"); dlSubmenu.ItemTemplate = Page.LoadTemplate("MyCompanyTemplate2.ascx"); } Session["Cul"] = cul; GetMenuData(); string parent_id = Request.QueryString["parent_id"]; if (parent_id!=null && parent_id != "") GetSubMenuList(parent_id); string submenu_id = Request.QueryString["submenu_id"]; if (submenu_id!=null && submenu_id != "") GetContent(submenu_id); dlMenu.SelectedIndex = Convert.ToInt32(Session["menu_index"]); dlSubmenu.SelectedIndex = Convert.ToInt32(Session["submenu_index"]); } public void GetMenuData() { conn.Open(); da = new SqlDataAdapter("Select * From Menu Where Parent_ID is null", conn); ds = new DataSet(); da.Fill(ds, "menu"); da.Dispose(); conn.Close(); dlMenu.DataSource = ds.Tables["menu"]; dlMenu.DataBind(); } public void GetSubMenuList(string parent_id) { conn.Open(); da = new SqlDataAdapter("Select * From Menu Where Parent_ID=" + parent_id, conn); ds = new DataSet(); da.Fill(ds, "sub"); da.Dispose(); conn.Close(); dlSubmenu.DataSource = ds.Tables["sub"]; dlSubmenu.DataBind(); } public void GetContent(string submenu_id)
Page 185 of 296

MCPD Web Developer

Course 70-528

{

conn.Open(); da = new SqlDataAdapter("Select * From Content Where Menu_ID=" + submenu_id, conn); ds = new DataSet(); da.Fill(ds, "content"); da.Dispose(); conn.Close(); if ((string)Session["Cul"] == "VN") lblContent.Text = ds.Tables["content"].Rows[0]["Content_VN"].ToString(); else if ((string)Session["Cul"] == "EN") lblContent.Text = ds.Tables["content"].Rows[0]["Content_EN"].ToString();

} protected void dlMenu_ItemCommand(object source, DataListCommandEventArgs e) { string menu_id; menu_id = ((Label)e.Item.Controls[0].FindControl("lblID")).Text; Session["menu_index"] = e.Item.ItemIndex; Response.Redirect("MyCompany.aspx?mode=" + (string)Session["Cul"] + "&parent_id=" + menu_id); } protected void dlSubmenu_ItemCommand(object source, DataListCommandEventArgs e) { string submenu_id; submenu_id = ((Label)e.Item.Controls[0].FindControl("lblID")).Text; Session["submenu_index"] = e.Item.ItemIndex; Response.Redirect("MyCompany.aspx?mode=" + (string)Session["Cul"] + "&parent_id=" + Request.QueryString["parent_id"] + "&submenu_id=" + submenu_id); } protected void btnVN_Click(object sender, EventArgs e) { Response.Redirect("MyCompany.aspx?mode=VN"); } protected void btnEN_Click(object sender, EventArgs e) { Response.Redirect("MyCompany.aspx?mode=EN"); } }

Page 186 of 296

MCPD Web Developer

Course 70-528

LAB 9 : MASTER PAGES, PROFILES, THEMES AND SKINS
FROM LESSON
From Lesson 1 : Using MasterPage Create “Master Page” : Right click Project Name  Add New Item : choose Master Page Template

Create Master Page like below : banner at top, footer at bottom, menu in the left with 4 hyperlinks to 4 pages (in our lab)

Page 187 of 296

MCPD Web Developer

Course 70-528

After create Master Page, add new Web Form to Project, and choose Master Page for it

Then choose MasterPage.master file

Page 188 of 296

MCPD Web Developer

Course 70-528

Your default.aspx page will now be :

Now Run it (default.aspx)

Page 189 of 296

MCPD Web Developer

Course 70-528

From Lesson 2 : Using Profiles to store private information Create Login.aspx page like below (note: using Login control) (using MasterPage for your page)

Create new folder to your project named : “RequiredLogin” folder (using MasterPage above)

Add a “web.config” file to “RequiredLogin” folder with below content:

Page 190 of 296

MCPD Web Developer

Course 70-528

Add a Web Form to RequiredLogin folder named default2.aspx (using MasterPage) and design the page like below:

Back to Web.config (outside RequiredLogin folder), add new config tab (inside system.web tag) like below :

Write code for default2.aspx: using System; public partial class _default : System.Web.UI.Page { protected void btnSave_Click(object sender, EventArgs e) { Profile.FirstName = txtFirstName.Text; Profile.LastName = txtLastName.Text; lblStatus.Text = "Your Profile is saved!"; } protected void btnGetProfile_Click(object sender, EventArgs e) { if(Profile.FirstName != null && Profile.LastName!=null) { lblFirstName.Text = Profile.FirstName; lblLastName.Text = Profile.LastName;
Page 191 of 296

MCPD Web Developer

Course 70-528

} else { } } }

lblStatus.Text = "There is no stored-profiles!";

Now run default2.aspx , and notice what happen ?

Login Required when your access default2.aspx ? Username/Password is needed to continue In Visual Studio 2005, choose menu “Website  ASP.NET Configuration”

Page 192 of 296

MCPD Web Developer

Course 70-528

Click “Security”

Then click Create user, and create your desired account  click “Create User” button

Page 193 of 296

MCPD Web Developer

Course 70-528

Now Run default2.aspx again, and login with username/password registered above:

Then test profile function in default2.aspx

Page 194 of 296

MCPD Web Developer

Course 70-528

From Lesson 3 : Using Themes and Skin Create new webpage named “default3.aspx” in “RequiredLogin” folder (using MaterPage.master) and design it like below:

In web.config file (outside RequiredLogin folder), add new property tab for profile tab like below:

Page 195 of 296

MCPD Web Developer

Course 70-528

Create App_Theme folder by right-clicking project name  Add ASP.NET Folder  Theme. Then add 2 SubFolder : Classic and Colorful

Add Skin file to Classic folder by right-clicking Classic folder  Add New Item  choose Skin file template (named it Classic.skin)

Page 196 of 296

MCPD Web Developer

Course 70-528

Classic.skin file content : <asp:Calendar runat="server" Width="220px" Font-Names="Verdana" Font-Size="8pt" Height="200px" BorderColor="#FFCC66" ForeColor="#663399" BackColor="#FFFFCC" DayNameFormat="FirstLetter" BorderWidth="1px" ShowGridLines="True"> <SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" /> <SelectorStyle BackColor="#FFCC66" /> <OtherMonthDayStyle ForeColor="#CC9966" /> <TodayDayStyle BackColor="#FFCC66" ForeColor="White" /> <NextPrevStyle ForeColor="#FFFFCC" Font-Size="9pt" /> <DayHeaderStyle Height="1px" Font-Bold="True" BackColor="#FFCC66" /> <TitleStyle ForeColor="#FFFFCC" Font-Size="9pt" Font-Bold="True" BackColor="#990000" /> </asp:Calendar> <asp:Label runat="server" Width="256px" Font-Bold="True" Font-Names="Arial Narrow" Font-Size="Medium" BackColor="#FFFFC0" /> <asp:Button runat="server" Width="90px" Font-Bold="True" />

- Similarly, add Colorful.skin to Colorful Theme folder with content:
<asp:Calendar runat="server" Width="400px" Font-Names="Times New Roman" Font-Size="10pt" Height="220px" BorderColor="Black" ForeColor="Black" BackColor="White" NextPrevFormat="FullMonth" TitleFormat="Month" DayNameFormat="FirstLetter"> <SelectedDayStyle ForeColor="White" BackColor="#CC3333" /> <SelectorStyle ForeColor="#333333" Font-Names="Verdana"
Page 197 of 296

MCPD Web Developer

Course 70-528

Font-Size="8pt" Font-Bold="True" Width="1%" BackColor="#CCCCCC" /> <OtherMonthDayStyle ForeColor="#999999" /> <TodayDayStyle BackColor="#CCCC99" /> <DayStyle Width="14%" /> <NextPrevStyle ForeColor="White" Font-Size="8pt" /> <DayHeaderStyle ForeColor="#333333" Height="10pt" Font-Size="7pt" Font-Bold="True" BackColor="#CCCCCC" /> <TitleStyle ForeColor="White" Height="14pt" Font-Size="13pt" Font-Bold="True" BackColor="Black" /> </asp:Calendar> <asp:Label runat="server" Width="256px" Font-Bold="True" Font-Names="Arial Narrow" Font-Size="Medium" /> <asp:Button runat="server" Width="90px" Font-Bold="True" /> Code for default3.aspx : using System; public partial class default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { String[] themes = System.IO.Directory.GetDirectories(Request.PhysicalApplicationPath + "App_Themes"); ddlThemes.Items.Clear(); foreach(string theme in themes) ddlThemes.Items.Add(theme.Substring(theme.LastIndexOf("\\") + 1)); if (Profile.Theme != "") ddlThemes.SelectedValue = Profile.Theme; } } protected void btnSetTheme_Click(object sender, EventArgs e) { Profile.Theme = ddlThemes.SelectedValue; } protected void Page_PreInit(object sender, EventArgs e) { String theme = Request["ddlThemes"]; if (theme==null || theme == "") Page.Theme = Profile.Theme; else Page.Theme = theme; } } Run & test your webpage

Page 198 of 296

MCPD Web Developer

Course 70-528

EXERCISE
Description

: Using Profile to implement Shopping Cart (Anonymous user)

Create shopping.aspx (using MasterPage.master) like below :

Add App_Code folder to your application :

Page 199 of 296

MCPD Web Developer

Course 70-528

Then add file : Cart.cs to App_Code folder: using System; using System.Data; using System.Xml.Serialization; [Serializable] public struct itemType { public string isbn; public string name; public int qty; } [Serializable, XmlInclude(typeof(itemType))] public class Cart { public DataTable items; public Cart() { items = new DataTable(); items.Columns.Add(new DataColumn("ISBN")); items.Columns.Add(new DataColumn("NAME")); items.Columns.Add(new DataColumn("QUANTITY")); } public bool itemExist(string isbn) { foreach (DataRow row in items.Rows) { if (ReferenceEquals(row["ISBN"], isbn)) { row[2] = (int)row[2] + 1; return true; } } return false; } public void AddItem(string isbn, string name, int qty) { if (!itemExist(isbn)) { DataRow dr = items.NewRow(); dr[0] = isbn; dr[1] = name; dr[2] = qty; items.Rows.Add(dr);
Page 200 of 296

MCPD Web Developer

Course 70-528

} }

}

In web.config file (outside RequiredLogin folder), rewrite like below : <anonymousIdentification enabled="true"/> <profile> <properties> <add name="FirstName" type="System.String"/> <add name="LastName" type="System.String"/> <add name="Theme" type="System.String"/> <add name="shoppingcart" allowAnonymous="true" type="Cart" serializeAs="Binary"/> </properties> </profile> Write code for 2 button : Add To Cart with the same event-method using System; using System.Web.UI.WebControls; public partial class shopingcart : System.Web.UI.Page { protected void btnAddtoCart1_Click(object sender, EventArgs e) { Cart myCart; myCart = Profile.shoppingcart; if (myCart == null) myCart = new Cart(); string isbn = ""; string name = ""; int qty = 0; switch (((Button)sender).ID) { case "btnAddtoCart1": isbn = "0-596-00536-9"; name = "Windows XP Unwired"; qty = 1; break; case "btnAddtoCart2": isbn = "0-596-00757-4"; name = ".NET Compact Framework Pocket Guide "; qty = 1; break; } myCart.AddItem(isbn, name, qty); Profile.shoppingcart = myCart; GridView1.DataSource = myCart.items; GridView1.DataBind(); } }

- Run & test your shopping cart

Page 201 of 296

MCPD Web Developer

Course 70-528

LAB 10 : WEB PARTS
FROM LESSON
From Lesson 1 : Create a simple webpart page Create 2 usercontrols : ChooseDateTime.ascx, Search.ascx like below :

Create 1 Web Form page with 1 WebPartManager, 2 WebPartZone and Drag 2 usercontrol to 2 WebPartZone



Run your webpage, notice that your webpart can be minimize and close:

Page 202 of 296

MCPD Web Developer

Course 70-528

From Lesson 2 : Move your webparts from one zone to another Create Web Form with 3 webpartzone : WebPartZone1, WebPartZone2 and WebPartZone3 and drag 2 usercontrols in lesson1 to webpartzone1, webpartzone2 and Drag 1 radiobuttonlist control (named rblMode, set AutoPostBack property to true) to Web Form like below :

Write code for RadioButtonList (SelectedIndexChanged event) using System.Web.UI.WebControls.WebParts; public partial class default2 : System.Web.UI.Page { protected void rblMode_SelectedIndexChanged(object sender, System.EventArgs e) {
Page 203 of 296

MCPD Web Developer

Course 70-528

} } Run & test your Web Form: (choose DesignDisplayMode). Notice that in DesignDisplayMode, you can move your webpart from one zone to another by dragging it anywhere in the form and drop it to another webpartzone.

switch(rblMode.SelectedIndex) { case 0: WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode; break; case 1: WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode; break; }

From Lesson 3 : Restore closed webparts and add declarative webpart at run-time a) Restore closed webparts:

Notice that when you close a webpart ,you cannot restore it ,even refresh your page.To restore a webpart, a Catalogzone and a PageCatalog must be used
Create Web Form with 2 webpartzones with 2 usercontrols in previous FromLesson and add “CatalogZone” control and “PageCatalog” control (inside CatalogZone), then add 1 RadioButtonList control (id=rblMode) with 2 mode like below:

Page 204 of 296

MCPD Web Developer

Course 70-528

Write code for RadioButtonList (rblMode) using System.Web.UI.WebControls.WebParts; public partial class default2 : System.Web.UI.Page { protected void rblMode_SelectedIndexChanged(object sender, System.EventArgs e) { switch(rblMode.SelectedIndex) { case 0: WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode; break; case 1: WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode; break; case 3: WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode; break; }
Page 205 of 296

MCPD Web Developer

Course 70-528

} } Run & Test your webpage. Notice that you can add closed-webpart in CatalogDisplayMode by choose ClosedWebPart and click “Add” button

b) Add declarative webpart Using Web Form above, add “DeclarativeCatalogPart” to “CatalogZone”

Page 206 of 296

MCPD Web Developer

Course 70-528

Right click DeclarativeCatalogPart to Edit ItemTemplate for it : choose “Edit Template”  WebPartTemplate

Drag Search.ascx to DeclarativeWebPart Template

Page 207 of 296

MCPD Web Developer

Course 70-528

Then right click DeclarativeCatalogPart and choose “End Template Editting”

Now Run & Test your Web Form, you can add as many webparts as you want to any webpartzone in the form

Page 208 of 296

MCPD Web Developer

Course 70-528

Page 209 of 296

MCPD Web Developer

Course 70-528

EXERCISE
Exercise 1 : Edit WebPart format at run-time

Notice : to Edit webpart format like : Title, Border, Width, …. We muse use EditorZone control, AppearanceEditorPart control, LayoutEditorPart control
Use Web Form from previous lesson to continue our lesson. Drag EditorZone control to Web Form ,and 1 AppearanceEditorPart, 1 LayoutEditorPart inside it

Then add 1 item to your RadioButtonList (rblMode) like below :

Re-write code for RadioButtonList (rblMode) protected void rblMode_SelectedIndexChanged(object sender, System.EventArgs e) { switch(rblMode.SelectedIndex) {
Page 210 of 296

MCPD Web Developer

Course 70-528

case 0: WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode; break; case 1: WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode; break; case 3: WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode; break; } }

Run & test your Web Form (choose Editor Display Mode)

When you click Edit , EditorZone will display and let you edit the webpart

Page 211 of 296

MCPD Web Developer

Course 70-528

Exercise 2 : Create connection between webparts

Notice : To create connection between 2 webparts, connectionmode must be enable, and a ConnectionZone must be use to edit connection In this Exercise, we will use 2 usercontrol from Previous FromLesson : Search.ascx, ChooseDateTime.ascx
Create folder : App_Code and create file ISelectedDate.cs in this folder:
Page 212 of 296

MCPD Web Developer

Course 70-528

public interface ISelectedDate { System.DateTime SelectedDate { get; } } Rewrite code for ChooseDateTime.ascx : using System.Web.UI.WebControls.WebParts; partial class ChooseDateTime : System.Web.UI.UserControl, ISelectedDate { public System.DateTime SelectedDate { get { return Calendar1.SelectedDate.Date; } } [ConnectionProvider("SelectedDate", "SelectedDate")] public ISelectedDate GetSelectedDate() { return this; } } Rewrite code for Search.ascx using System.Web.UI.WebControls.WebParts; partial class Search : System.Web.UI.UserControl { private ISelectedDate selectedDate; [ConnectionConsumer("SelectedDate", "SelectedDate")] public void setSearchText(ISelectedDate SearchText) { selectedDate = SearchText; } protected void Page_PreRender(object sender, System.EventArgs e) { if (selectedDate != null) { TextBox1.Text += selectedDate.SelectedDate.ToShortDateString(); } } } Create new Web Form with 2 webpartzone contain 2 above usercontrols (ChooseDateTime.ascx, Search.ascx). Add “ConnectionZone” control to Web Form and a checkbox to enable/disable connection mode like below:

Page 213 of 296

MCPD Web Developer

Course 70-528

In source-view code (file .aspx) of this page, add a “StaticConnection” tab to webpartmanage tab like below: <asp:WebPartManager ID="WebPartManager1" runat="server"> <StaticConnections> <asp:WebPartConnection ID="Connection" ConsumerConnectionPointID="SelectedDate" ConsumerID="Search1" ProviderConnectionPointID="SelectedDate" ProviderID="ChooseDateTime1"> </asp:WebPartConnection> </StaticConnections> </asp:WebPartManager> Write code for CheckBox CheckedChanged event to enable/disable connection-mode: using System.Web.UI.WebControls.WebParts; partial class Default7 : System.Web.UI.Page { protected void CheckBox1_CheckedChanged(object sender, System.EventArgs e) { WebPartManager1.DisplayMode = WebPartManager.ConnectDisplayMode; } } Run & test your Web Form : notice that when you choose a date in ChooseDateTime.ascx , textbox in Search.ascx will display selected date
Page 214 of 296

MCPD Web Developer

Course 70-528

In connection mode you can edit connection by clicking “Connect” menu, with this mode you can connect/disconnect between webparts

Page 215 of 296

MCPD Web Developer

Course 70-528

Exercise 3 : Create Custom WebPart Create new “Visual C# / Windows / Web Control Library” Project, named Translation

Add 1 class to this application : TranslationWebPart.cs using System.Web.UI; using System.Web.UI.WebControls; public class CompositeControl : Control, INamingContainer { public string Username { get { TextBox txtBox = (TextBox)Controls[1]; EnsureChildControls(); return txtBox.Text; } set
Page 216 of 296

MCPD Web Developer

Course 70-528

{

TextBox txtBox = (TextBox)Controls[1]; EnsureChildControls(); txtBox.Text = value;

} } public string Password { get { TextBox txtBox = (TextBox)Controls[4]; EnsureChildControls(); return txtBox.Text; } set { TextBox txtBox = (TextBox)Controls[4]; EnsureChildControls(); txtBox.Text = value; } } protected override void CreateChildControls() { Controls.Add(new LiteralControl("Username ")); TextBox txtUsername = new TextBox(); Controls.Add(txtUsername); Controls.Add(new LiteralControl("<br>")); Controls.Add(new LiteralControl("Password ")); TextBox txtPassword = new TextBox(); txtPassword.TextMode = TextBoxMode.Password; Controls.Add(txtPassword); Controls.Add(new LiteralControl("<br>")); } } Build this project  TranslationWebPart.dll file (bin/Debug folder) In website project ,add new Web Form, add this dll file to Toolbox (right click Toolbox  Choose Items  Browse to this dll file)

Page 217 of 296

MCPD Web Developer

Course 70-528

Drag TranslationWebPart from Toolbox to WebPartZone

Run & test your application

Page 218 of 296

MCPD Web Developer

Course 70-528

LAB 11 : WEB SERVICES
FROM LESSON
From Lesson 1: Create and Using web service with Web Reference Create new ASP.NET Web Service project : File  New  Website, choose “ASP.NET Web Service” (Project name : WSLab11)

- Code for Service.asmx using System.Web.Services; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { public Service () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public int AddNumber(int value1, int value2) { return value1 + value2; } [WebMethod] public int SubtractNumber(int value1, int value2) { return value1 - value2;
Page 219 of 296

MCPD Web Developer

Course 70-528

} [WebMethod] public int MultipleNumber(int value1, int value2) { return value1 * value2; } [WebMethod] public int DeviceNumber(int value1, int value2) { if (value2 != 0) return value1 / value2; else return 0; } }

6. Build and Run

Click AddNumber

Page 220 of 296

MCPD Web Developer

Course 70-528

Then click “Invoke”

From Lesson 2 : Calling web service from Web Form

a) Add Web Reference to Web Form
Page 221 of 296

MCPD Web Developer

Course 70-528

Add New ASP.NET Web Project (project name : ASPLab11)

Right click project name, choose “Add Web Reference”

Page 222 of 296

MCPD Web Developer

Course 70-528

Click “Web services in this solution”

Page 223 of 296

MCPD Web Developer

Course 70-528

Click “Service” link in the Services Column of the Service List Table. Then rename “Web reference name” : Calculation. Then click “Add Reference”

Create Web Form like below :

Page 224 of 296

MCPD Web Developer

Course 70-528

Source code: using System; using localhost; public partial class _default : System.Web.UI.Page { private readonly Service cal = new Service(); protected void btnAdd_Click(object sender, EventArgs e) { int value1= Convert.ToInt32(txtValue1.Text); int value2 = Convert.ToInt32(txtValue2.Text); lblResult.Text = cal.AddNumber(value1, value2).ToString(); } protected void btnMultiple_Click(object sender, EventArgs e) { int value1 = Convert.ToInt32(txtValue1.Text); int value2 = Convert.ToInt32(txtValue2.Text); lblResult.Text = cal.SubtractNumber(value1, value2).ToString(); } protected void Button3_Click(object sender, EventArgs e) { int value1 = Convert.ToInt32(txtValue1.Text); int value2 = Convert.ToInt32(txtValue2.Text); lblResult.Text = cal.MultipleNumber(value1, value2).ToString(); } protected void btnDivice_Click(object sender, EventArgs e) { int value1 = Convert.ToInt32(txtValue1.Text); int value2 = Convert.ToInt32(txtValue2.Text); lblResult.Text = cal.DeviceNumber(value1, value2).ToString(); } }

Run & test your Web Form:
Page 225 of 296

MCPD Web Developer

Course 70-528

From Lesson 3 : Calling Web Service using Proxy Class. Create file .dll:

o Run your Web Service above in IE:

Then add to the tail of the url string : “?wsdl” , for ex :

http://localhost:1076/WSLab11/Service.asmx?wsdl then enter

Page 226 of 296

MCPD Web Developer

Course 70-528

Save this file to some locations in your hard disk ,ex : D:\Projects\70-528\WSLab11.wsdl

Open “Visual Studio 2005 Command Prompt” : Start menu  Visual Studio 2005  Visual Studio Tools  Visual Studio 2005 Command Prompt Change to the directory which is used to store WSLab11.wsdl file

Page 227 of 296

MCPD Web Developer

Course 70-528

In “VS Command Prompt”, type command : wsdl /l:vb /o:WSLab11.cs WSLab11.wsdl

Page 228 of 296

MCPD Web Developer

Course 70-528

Then type command : Vbc /t:library /out:WSLab11.dll WSLab11.cs

Use file WSLab11.dll file in Web Form : In the asp.net webproject, Add Reference to file WSLab11.dll by rightclicking project name  Add Reference ,then browse to WSLab11.dll file)

Page 229 of 296

MCPD Web Developer

Course 70-528

Create Web form like above example :

Page 230 of 296

MCPD Web Developer

Course 70-528

Source Code : using System; partial class Default4 : System.Web.UI.Page { readonly Service cal = new Service(); protected void btnAdd_Click(object sender, EventArgs e) { lblResult.Text = cal.AddNumber(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString(); } protected void btnSubtract_Click(object sender, EventArgs e) { lblResult.Text = cal.SubstractNumber(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString(); } protected void btnMultiply_Click(object sender, EventArgs e) { lblResult.Text = cal.MultiplyNumber(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString(); } protected void btnDivide_Click(object sender, EventArgs e) { lblResult.Text = cal.DivideNumber(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString(); } } Run & test your application:

Page 231 of 296

MCPD Web Developer

Course 70-528

Page 232 of 296

MCPD Web Developer

Course 70-528

EXERCISE
In this exercise, you will use webservice to get data from SQL Server
Create new WebService file (WSData.asmx) : right click web service project  add new item : choose WebService template

Code for WSData.asmx : using System.Data; using System.Data.SqlClient; using System.Web.Services; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WSData : WebService { [WebMethod()] public DataSet GetData() { SqlConnection conn = new SqlConnection("server=.;database=Northwind;Integrated Security=True"); conn.Open(); SqlDataAdapter da = new SqlDataAdapter("select * from customers", conn); DataSet ds = new DataSet(); da.Fill(ds); conn.Close(); return ds; } } Create Web Form like below :
Page 233 of 296

MCPD Web Developer

Course 70-528

Add web reference to WSData service :

Named this web reference : WSData, then click “Add Reference”

Page 234 of 296

MCPD Web Developer

Course 70-528

Source code for Web Form: using localhost; partial class Default3 : System.Web.UI.Page { protected void btnGet_Click(object sender, System.EventArgs e) { WSData ws = new WSData(); GridView1.DataSource = ws.GetData(); GridView1.DataBind(); } } Run & test Web Form: (click “Get Data” button to get data from SQL Server)

Page 235 of 296

MCPD Web Developer

Course 70-528

Page 236 of 296

MCPD Web Developer

Course 70-528

LAB 12 : AN INTRODUCTION TO AJAX
FROM LESSON
From Lesson 1: Using UpdatePanel to prevent Postback Add ScriptManager control from Ajax Toolbox to Web Form Add UpdatePanel to Web Form Design Web Form like below with 2 parts, which are similar. One part is put in the UpdatePanel, other is not.

Source code : using System; using System.Data; using System.Data.SqlClient; public partial class _default : System.Web.UI.Page { private void GetData(int gridnum) { SqlConnection conn = new SqlConnection("server=.;database=ASPLab12;uid=sa;pwd=sa"); conn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * From SmallData", conn); DataSet ds = new DataSet(); da.Fill(ds); if (gridnum == 1) { GridView1.DataSource = ds; GridView1.DataBind(); } else { GridView2.DataSource = ds; GridView2.DataBind(); } conn.Close();
Page 237 of 296

MCPD Web Developer

Course 70-528

} Run and Test your form, notice 2 parts and postback event, the part which is in UpdatePanel does not require a postback, other does. From Lesson 2 : Get a big data and display Waiting Status using UpdateProgress panel

} protected void Button1_Click(object sender, EventArgs e) { GetData(1); } protected void Button2_Click(object sender, EventArgs e) { GetData(2); }

Add new Web Form Add ScriptManager, UpdatePanel, UpdateProgress to Web Form In Update Panel 1 button, 1 Gridview, in UpdateProgress add 1 animator-image and 1 label like below :

Source code : using System; using System.Data; using System.Data.SqlClient; public partial class default2 : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) {
Page 238 of 296

MCPD Web Developer

Course 70-528

SqlConnection conn = new SqlConnection("server=.;database=ASPLab12;uid=sa;pwd=sa"); conn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * From BigData", conn); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close(); } } Run & test your Web Form

From Lesson 3 : Using Timer control
In this exercise, you will use AJAX Timer to set up a bomb timer and once the bomb started, every 10 seconds, one person is killed (one row in database is deleted)
Add new Web Form, add Scriptmanager, UpdatePanel, 1 Timer and other control like below

Page 239 of 296

MCPD Web Developer

Course 70-528

Source code : using System; using System.Data; using System.Data.SqlClient; public partial class default3 : System.Web.UI.Page { private SqlConnection conn = new SqlConnection("server=.;database=ASPLab12;uid=sa;pwd=sa"); protected void Timer1_Tick(object sender, EventArgs e) { if(lblTime.Text == "") lblTime.Text = "0"; int value = Convert.ToInt32(lblTime.Text); if (value == 10) { conn.Open(); SqlCommand cmd = new SqlCommand("Delete From TestData Where ID = (Select Top 1 ID from TestData)", conn); cmd.ExecuteNonQuery(); conn.Close(); GetData(); lblTime.Text = "0"; } lblTime.Text = (value+1).ToString(); } private void GetData()
Page 240 of 296

MCPD Web Developer

Course 70-528

{

conn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * From TestData", conn); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close();

} protected void btnStart_Click(object sender, EventArgs e) { Timer1.Enabled = true; btnStart.Enabled = false; btnStop.Enabled = true; } protected void btnStop_Click(object sender, EventArgs e) { Timer1.Enabled = false; btnStart.Enabled = true; btnStop.Enabled = false; lblTime.Text = "0"; } }

Run & test your Web Form

Page 241 of 296

MCPD Web Developer

Course 70-528

Page 242 of 296

MCPD Web Developer

Course 70-528

EXERCISE From Now On, you can use AJAX Control Toolkit to add rich GUI to your Web Form application:
Add AjaxControlToolkit to Toolbox : right click Toolbox  Add Tab  type “AJAX Control Toolkit”

Right click new-added Tab  Choose Items

Browse to AjaxControlToolkit.dll file

Page 243 of 296

MCPD Web Developer

Course 70-528

Now, AJAX control toolkit was added to Toolbox and ready to use

Page 244 of 296

MCPD Web Developer

Course 70-528

Exercise 1 : Display AJAX Calendar by using CalendarExtender control
Add new Web Form, add ScriptManager control, CalendarExtender control, a textbox and a button like below:

Page 245 of 296

MCPD Web Developer

Course 70-528

Set property of CalendarExtender control : TargetControlID=TextBox1, PopupButtonID = Button1, Format = d/M/yyyy

Run & test your Web Form : click button to view calendar and choose a date:

Page 246 of 296

MCPD Web Developer

Course 70-528

Exercise 2 : Using CollapsiblePanelExtender to implement Collapsible panel
Add new Web Form, add ScriptManager, CollapsiblePanelExtender, 1 label (Label1), 2 image (Image1,Image2), 1 Panel (Panel1)

Page 247 of 296

MCPD Web Developer

Course 70-528

Set Property

o of CollapsiblePanelExtender1 : TargetControlID = Panel1 o of Panel1 :  CollapsiblePanelExtender : • ExpandControlID : Image1 • CollapseControlID : Image2 • TextLabelID : Label1
Run & test your Web Form

Exercise 3 : Using AlwaysVisibleControlExtender
Add new Web Form and controls like image below : AlwaysVisibleControlExtender, DropDownList1, 1 Image (image1) and a very long text below that. Set property

o AlwaysVisibleControlExtender : TargetControlID = Image1 o DropDownList1 : AutoPostBack = True

Page 248 of 296

MCPD Web Developer

Course 70-528

Source code (for DropDownList1’s SelectedIndexChanged) using System; public partial class Default6 : System.Web.UI.Page { protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { switch (DropDownList1.SelectedIndex) { case 0: AlwaysVisibleControlExtender1.Enabled = false; break; case 1: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Top; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Left; break; case 2: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Top; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Center; break; case 3: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Top; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Right; break; case 4: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Middle;
Page 249 of 296

MCPD Web Developer

Course 70-528

AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Left; break; case 5: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Middle; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Center; break; case 6: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Middle; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Right; break; case 7: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Bottom; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Left; break; case 8: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Bottom; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Center; break; case 9: AlwaysVisibleControlExtender1.Enabled = true; AlwaysVisibleControlExtender1.VerticalSide = AjaxControlToolkit.VerticalSide.Bottom; AlwaysVisibleControlExtender1.HorizontalSide = AjaxControlToolkit.HorizontalSide.Right; break; } } }

Run & test your application (change the DropDownList SelectedItem to view the page’s change)

Exercise 4 : Using DropDownExtender
Add new Web Form and control like image below :

Page 250 of 296

MCPD Web Developer

Course 70-528

Set property :

o DropDownExtender1 : TargetControlID = Label1 o Label1 :  DropDownExtender : • DropDownControlID = Menu1
Run & test your Web Form

Exercise 5 : Using DropShadowExtender to make controls’ DropShadow
Add new Web Form and controls like image below : (1 DropDownExtender, 1 Panel, 1 LoginControl)

Page 251 of 296

MCPD Web Developer

Course 70-528

Set property :

o DropShadowExtender1 : TargetControlID = Panel1 o Panel1:  DropShadowExtender: • Rounded = True
Run & test your Web Form :

Exercise 6 : Using FilteredTextBoxExtender
Add new Web Form and controls : 1 ToolkitScriptManager, 1 FilteredTextBoxExtender, 1 Textbox like image below :

Page 252 of 296

MCPD Web Developer

Course 70-528

Set Property :

o FilteredTextBoxExtender1 : TargetControlID = TextBox1 o TextBox1:  FilteredTextBoxExtender : FilterType = Numbers
Run & test your Web Form, notice that the textbox only accept numbers

Exercise 7 : Using ListSearchExtender
Add new Web Form and controls: 1 ToolkitScriptManager, 1 ListSearchExtender, 1 ListBox like image below

Add Items to ListBox (Items collection property)

Page 253 of 296

MCPD Web Developer

Course 70-528



Run & test your Web Form, notice that you can type to search an item

Exercise 8 : Using MaskedEditExtender

Add new Web Form and controls : 1 ToolkitScriptManager, 1 MaskedEditExtender, 1 TextBox like image below :

Page 254 of 296

MCPD Web Developer

Course 70-528



Set property :

o MaskedEditExtender : TargetControlID = TextBox1 o Textbox1 :  MaskedEditExtender : Mask = 99/99/9999, UserDateFormat = DayMonthYear •
Run & test your Web Form:

Exercise 9 : Using PagingBulletedListExtender

Add new Web Form and controls : 1 ToolkitScriptManager, 1 PagingBulletedListExtender, 1 BulletedList like image below :

Page 255 of 296

MCPD Web Developer

Course 70-528



Set property :

o PagingBulletedListExtender: TargetControlID = BulletedList
• Source code: using System.Data; using System.Data.SqlClient; partial class Default13 : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { SqlConnection conn = new SqlConnection( "server=.;database=ASPLab12;uid=sa;pwd=sa"); conn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * From AlphabetData", conn); DataSet ds = new DataSet(); da.Fill(ds); BulletedList1.DataSource = ds; BulletedList1.DataTextField = "Name"; BulletedList1.DataValueField = "ID"; BulletedList1.DataBind(); conn.Close(); } } }



Run & test Web Form

Exercise 10 : Using PasswordStrength control
Add new Web Form and controls : 1 ToolkitScriptManager, 1 PasswordStrength, 1 Textbox like image below :



Set property :

o PasswordStrength : TargetControlID = Textbox1
Page 256 of 296

MCPD Web Developer

Course 70-528



Run & test your Web Form ,notice that password strength is always display when you enter characters to textbox

Exercise 11 : Using ReorderList control

Add new Web Form and controls : ToolkitScriptManager, ReorderList. Add 2 label (label1,label2) to ReorderList control like image below :



Edit DataBindings for 2 labels :

Page 257 of 296

MCPD Web Developer

Course 70-528

• Edit DataBindings for Label1 : DataBinder.Eval(Container.DataItem,"FirstName") • Edit DataBindings for Label2 : DataBinder.Eval(Container.DataItem,"LastName") • • • Source code: using System.Data; using System.Data.SqlClient; partial class Default15 : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { SqlConnection conn = new SqlConnection("server=.;database=ASPLab12;uid=sa;pwd=sa"); conn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * From SmallData", conn); DataSet ds = new DataSet(); da.Fill(ds); ReorderList1.DataSource = ds; ReorderList1.DataBind(); conn.Close(); } } }



Run & test your Web Form, notice that you can drag and drop the item to reorder the list

Page 258 of 296

MCPD Web Developer

Course 70-528

Exercise 12 : Using SliderExtender control

Add new Web Form and controls : ToolkitScriptManager, 1 SliderExtender, 1 Textbox like image below :



Set property :

o SliderExtender : TargetControlID = TextBox1 •
Run & test your Web Form: notice that Textbox now appears as a slider

Page 259 of 296

MCPD Web Developer

Course 70-528

Exercise 13 : Using TabContainer control

Add new Web Form and control : ToolkitScriptManager, 1 TabContainer. Then click “Add New Tab” like image below :



Rename tab1 as “Login Tab”. Add Login control to this tab

Page 260 of 296

MCPD Web Developer

Course 70-528



Then add another tab to control by right clicking tablcontainer  choose “Add Tab Panel”



Rename this tab as “New User Tab”:



Add “CreateUserWizard” control to this tab :

Page 261 of 296

MCPD Web Developer

Course 70-528



Run & test your Web Form :

Exercise 14 : Using TextBoxWatermarkExtender and ValidatorCalloutExtender

Add new Web Form with controls : ToolkitScriptManager, 1 TextboxWatermarkExtender, 2 Textbox(Textbox1,Textbox2), 1 ValidatorCalloutExtender, 1 RequiredFieldValidator for Textbox2, 1 Button like image below :

Page 262 of 296

MCPD Web Developer

Course 70-528



Set property :

o TextboxWatermarkExtender1 : TargetControlID = Textbox1 o Textbox1 :  TextboxWatermarkExtender : WatermarkText = “Click here” o RequiredFieldValidator1 :  ErrorMessage : This field is required  ControlToValidate : Textbox2 o ValidatorCalloutExtender1 : TargetControlID = RequiredFieldValidator1 •
Run & test your Web Form

Page 263 of 296

MCPD Web Developer

Course 70-528

LAB 13: ASP.NET PERFORMANCE
FROM LESSON
From Lesson 1: Using Caching
a. Simple Caching • Open a web form and add a label to it.

• From aspx page, go to the Source View and write the following directive to it. (Below the Page directive) <%@ OutputCache Duration="20" VaryByParam="none"%> • In the Page_Load event write the following code. Label1.Text= "page Cached on " + DateTime.Now.ToString(); • Save and run the project to see the following output.




Put a breakpoint in Page_Load event Refresh page until Page Load new time, notice that in 20s ,the time string doesn’t change and the breakpoint become useless

b. Data Caching Creat Web Form



Page_Load event

if(!IsPostBack) { Cache.Insert("mykey", "hello", null, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration); }
Page 264 of 296

MCPD Web Developer

Course 70-528

• OR if(!IsPostBack) { Cache.Insert("mykey", "hello", null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10)); } • Button click event protected void Button1_Click(object sender, EventArgs e) { if (Cache["mykey"] != null) Label1.Text = Cache["mykey"].ToString(); else Label1.Text = ""; }

c. Fragment Caching Usercontrol Caching
• • Open a project and include a new User Control in it. And save it as MyUC.ascx. In this User Control add a Label and set its text property to blank.

• In Page_Load event of the user control add the following line of code. Label1.Text = "From User Control on" + DateTime.Now.ToString(); • In the Source-view of the User Control write the following line of code. <%@ OutputCache Duration="60" VaryByParam="none" %> • Save the user Control and drag it on the Web Form.
Now add the following line of code in the Page_Load event of the Web Form. Label1.Text = "From Web Form at " + DateTime.Now.ToString(); • Save and run the project, note the time in both the labels and hit refresh, notice that the User Control output is cached and the web Page is being dynamically generated and fetched from the server

• •

In the Web Form again add a Label and set its text property to blank.

From Lesson 2 : State Management
Out – of – Process SQL Server 1) Start / Run /
Page 265 of 296

MCPD Web Developer

Course 70-528

2) Type cmd 3) Change directory to \Windows\Microsoft.NET \Framework \v1.1.4322\

4) Type command OSQL –S <SQLSERVERNAME> -U <sqlusername> -P <sqlpass> <InstallSqlState.sql

5) Open your SQL Server , a new database named ASPState created.

6) To use SQL Server session state management. Change your web.config file
<sessionState mode="SQLServer" sqlConnectionString="server=.;uid=sa;pwd=sa"> </sessionState>

7) Create new Web Form and write Code in Page_Load event
using System; public partial class Default4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["testvar"] == null) Session["testvar"] = 1; else Session["testvar"] = Convert.ToInt32(Session["testvar"]) + 1;
Page 266 of 296

MCPD Web Developer

Course 70-528

Response.Write("Session State for this user stored in SQL Server : " + Session["testvar"]); } }

8) Open SQL Server to check Session state storing.

From Lesson 3: Error Handling
I) • Exception Handling

Create Web Form

1. Try/Catch Handling:
• Coding using System; partial class Default5 : System.Web.UI.Page { public void sum(string val1, string val2) { try { int intA = Convert.ToInt32(val1); int intB = Convert.ToInt32(val2); Response.Write(" sum = " + (intA + intB)); }catch(Exception ex) { Response.Write("Not able to convert Strings to Numbers..."); } return;
Page 267 of 296

MCPD Web Developer

Course 70-528

}

} protected void Button1_Click(object sender, EventArgs e) { sum("abc", "xyz"); }

2. Custom Error Pages
• Write the following code at appropriate location in the Web.Config file. <customErrors defaultRedirect="MyErrorPage.aspx" mode="On" /> • Create a new web form and save it as “MyErrorPage.aspx” and write some error message in it, say “Oops Error occurred !!!!”

• •

Create a Web Form and write the following code in Page_Load event SqlConnection con=null; Response.Write(con.ToString()); Run & test your Web Form to get the following output

From Lesson 4: Tracing
Writing Trace Information
• Test Page Tracing : In Source View, add into @Page directive : Trace = True

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="default7.aspx.cs" Inherits="default7" Trace="true"%>



Run your Web Form :

Page 268 of 296

MCPD Web Developer

Course 70-528

Page Tracing with Trace object programming •
In Page_Load event, using Trace object with code below : using System; using System.Data.SqlClient; partial class Default7 : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { Trace.Write(" This is a trace message"); Trace.Write("MyCategory", " This is a categorized message"); try { SqlConnection con = new SqlConnection(); con.Open(); } catch (Exception excp) { Trace.Warn("Error", "No connection to open!!", excp); } } }

Page 269 of 296

MCPD Web Developer

Course 70-528

Page 270 of 296

MCPD Web Developer

Course 70-528

EXERCISE

Scenario
Implementing Shopping cart for your online-bookshop

Web Form
BookSale.aspx
• Item-template mode



Binding Data for Item-Template :

ControlID lnkTitle lbAuthor lbPublisher lbPrice lblID

Item Template DataBinder.Eval(Container.DataItem,"TITLE") DataBinder.Eval(Container.DataItem,"AUTHOR") DataBinder.Eval(Container.DataItem,"PUBLISHER") DataBinder.Eval(Container.DataItem,"PRICE") DataBinder.Eval(Container.DataItem,"ID")



Design mode

Page 271 of 296

MCPD Web Developer

Course 70-528



Running mode:

Shoppingcart.aspx
• Design mode:

Page 272 of 296

MCPD Web Developer

Course 70-528

CODING
BookSale.aspx
using System; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; partial class BookSale : System.Web.UI.Page { private readonly SqlConnection conn = new SqlConnection("server=.;database=BookSale;Integrated Security=True"); private SqlDataAdapter da; private readonly DataSet ds = new DataSet(); private readonly PagedDataSource pager = new PagedDataSource(); public DataTable CreateShoppingCart() { DataTable retVal = new DataTable("eCart"); retVal.Columns.Add(new DataColumn("STT")); retVal.Columns.Add(new DataColumn("TUA")); retVal.Columns.Add(new DataColumn("SOLUONG")); retVal.Columns.Add(new DataColumn("GIA")); retVal.Columns.Add(new DataColumn("ID")); retVal.Columns.Add(new DataColumn("THANHTIEN")); return retVal; } public void BindPage(int pageIndex) { if ((Session["Book"] != null)) { pager.DataSource = (DataView)Session["Book"]; pager.AllowPaging = true; pager.PageSize = 5; pager.CurrentPageIndex = pageIndex; dlstBook.DataSource = pager; dlstBook.DataBind(); Session["CurrentPageIndex"] = pageIndex; lblPage.Text = (pager.CurrentPageIndex + 1).ToString(); } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) {
Page 273 of 296

MCPD Web Developer

Course 70-528

conn.Open(); da = new SqlDataAdapter("Select * From Book", conn); da.Fill(ds, "book"); Session["Book"] = ds.Tables["book"].DefaultView; int additionPage = ((ds.Tables["book"].Rows.Count % 10) > 0 ? 1 : 0); Session["LastPageIndex"] = ds.Tables["book"].Rows.Count / 5 + additionPage - 1; pager.DataSource = ds.Tables["book"].DefaultView; pager.AllowPaging = true; pager.PageSize = 5; pager.CurrentPageIndex = 0; Session["CurrentPageIndex"] = 0; lblPage.Text = (pager.CurrentPageIndex + 1).ToString(); dlstBook.DataSource = pager; dlstBook.DataBind(); conn.Close(); if ((Session["eCart"] == null)) Session["eCart"] = CreateShoppingCart(); } } public bool BookCurrentExist(int bookID) { bool retVal = false; DataTable eCart = (DataTable)Session["eCart"]; foreach (DataRow dr in eCart.Rows) { if (Convert.ToInt32(dr[4]) == bookID) { dr[2] = Convert.ToInt32(dr[2]) + 1; dr[5] = Convert.ToDouble(dr[2]) * Convert.ToDouble(dr[3]); retVal = true; break; } } Session["eCart"] = eCart; return retVal; } protected void dlstBook_ItemCommand(object source, DataListCommandEventArgs e) { try { int bookID = Convert.ToInt32(((Label)e.Item.FindControl("lblID")).Text); if (!BookCurrentExist(bookID)) { DataTable eCart = (DataTable)Session["eCart"]; DataRow dr = eCart.NewRow(); dr[0] = eCart.Rows.Count + 1; dr[1] = ((HyperLink)e.Item.FindControl("lnkTitle")).Text; dr[2] = 1; dr[3] = ((Label)e.Item.FindControl("lbPrice")).Text; dr[4] = bookID; dr[5] = Convert.ToDouble(dr[2]) * Convert.ToDouble(dr[3]); eCart.Rows.Add(dr); Session["eCart"] = eCart; } Response.Write("<script language=javascript>alert('Đã cho vào giỏ hàng ! ')</script>"); } catch (Exception ex) {
Page 274 of 296

MCPD Web Developer

Course 70-528

}

Response.Write("Error:" + ex.StackTrace);

}

} protected void btnFirst_Click(object sender, EventArgs e) { BindPage(0); } protected void btnPrevious_Click(object sender, EventArgs e) { int currentPageIndex = (int)Session["CurrentPageIndex"]; if (currentPageIndex > 0) { currentPageIndex = currentPageIndex - 1; BindPage(currentPageIndex); } } protected void btnNext_Click(object sender, EventArgs e) { int currentPageIndex = (int)Session["CurrentPageIndex"]; if (currentPageIndex < (int)Session["LastPageIndex"]) { currentPageIndex = currentPageIndex + 1; BindPage(currentPageIndex); } } protected void btnLast_Click(object sender, EventArgs e) { BindPage((int)Session["LastPageIndex"]); }

Shoppingcart.aspx
using System; using System.Collections; using System.Data; using System.Web.UI.WebControls; partial class shoppingcart : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable eCart = (DataTable)Session["eCart"]; if (eCart.Rows.Count > 0) { dgCart.DataSource = eCart; dgCart.DataBind(); double totalPrice = 0; foreach (DataRow dr in eCart.Rows) totalPrice += Convert.ToDouble(dr[5]); lblTotalPrice.Text = totalPrice.ToString(); btnUpdate.Enabled = true; } else { lblCategoryName.Text = lblCategoryName.Text + " chưa có cuốn sách nào cả !!!"; btnUpdate.Enabled = false; } } }
Page 275 of 296

MCPD Web Developer

Course 70-528

protected void btnUpdate_Click(object sender, EventArgs e) { try { DataTable eCart = (DataTable)Session["eCart"]; double totalPrice = 0; int i = 0; ArrayList delRows = new ArrayList(); foreach (DataGridItem item in dgCart.Items) { int soluong = Convert.ToInt32( ((TextBox)item.Cells[2].FindControl("txtQuantity")).Text); if (((CheckBox)item.FindControl("chkDel")).Checked == false) { if (soluong > 0) { eCart.Rows[i][2] = soluong; eCart.Rows[i][5] = Convert.ToDouble(eCart.Rows[i][2]) * Convert.ToDouble(eCart.Rows[i][3]); totalPrice += Convert.ToDouble(eCart.Rows[i][5]); } else delRows.Add(eCart.Rows[i]); } else delRows.Add(eCart.Rows[i]); i = i + 1; } foreach (DataRow dr in delRows) eCart.Rows.Remove(dr); if (eCart.Rows.Count > 0) { int k = 1; foreach (DataRow dr in eCart.Rows) { dr[0] = k; k = k + 1; } } Session["eCart"] = eCart; dgCart.DataSource = eCart; dgCart.DataBind(); lblTotalPrice.Text = totalPrice.ToString(); } catch (Exception ex) { Response.Write("Error:" + ex.StackTrace); } } }

Page 276 of 296

MCPD Web Developer

Course 70-528

LAB 14 : DEPLOYING AND SECURING A MICROSOFT ASP.NET WEB APPLICATION
FROM LESSON From Lesson 1 : Securing a Microsoft ASP.NET Web Application
1) Create Project Create Web Form default.aspx with 1 DataGrid

Coding
using System; using System.Data; using System.Data.SqlClient; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { String connstr = "server=.;database=Northwind;Integrated Security=True"; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter da = new SqlDataAdapter("select * from Customers", conn); DataSet ds = new DataSet(); da.Fill(ds, "Customers"); GridView1.DataSource = ds.Tables["Customers"]; GridView1.DataBind(); } } }

2) ASP.NET Authentication
Page 277 of 296

MCPD Web Developer

Course 70-528

a. Windows-based authentication Web.config
<authentication mode="Windows" />

i. Anonymous Access
• • • • • • • Open IIS. Right click Lab10 Web Project in IIS. Choose Properties. Choose Directory Security Tab. Click Edit in Anonymous access and authentication control Uncheck “Enable anonymous access“ Uncheck “Basic Authentication” Uncheck “Integrated Windows Authentication”



Run Application by typing address to IE Address Bar (ex: http://localhost/70-528/ASPLab14/default.aspx)

Page 278 of 296

MCPD Web Developer

Course 70-528

ii. Authenticated Access : Used when anonymous access is disabled Using Basic Authentication
• • • • • • • Open IIS. Right click Lab10 Web Project in IIS. Choose Properties. Choose Directory Security Tab. Click Edit in Anonymous access and authentication control Uncheck “Enable anonymous access“ Check “Basic Authentication” Uncheck “Integrated Windows Authentication”

Page 279 of 296

MCPD Web Developer

Course 70-528

Grant Permission to website
• • • • In Windows Explorer : Right Click ASPLab14 Folder Choose Properties Choose Security Tab Add a user (ex: user test, note : use Control Panel/User Accounts to add users)

Page 280 of 296

MCPD Web Developer

Course 70-528



Click OK to Finnish Granting User to ASPLab14 folder.



Run Application by typing address to IE Address Bar (ex: http://localhost/70-528/ASPLab14/default.aspx)

Page 281 of 296

MCPD Web Developer

Course 70-528



Enter username/password (granted below) to enter website.

Page 282 of 296

MCPD Web Developer

Course 70-528

b. Forms based authentication •
Add Web Form page : login.aspx ,and add 1 Login control to Web Form

i. With available created user accounts defined in web.config Web.config
<authentication mode="Forms"> <forms name="Lab10" loginUrl="login.aspx" path="/" protection="All" timeout="60"> <credentials passwordFormat="Clear"> <user name="admin" password="admin"/> <user name="test" password="test"/> </credentials> </forms> </authentication>

Login.aspx

Page 283 of 296

MCPD Web Developer

Course 70-528

Login.aspx code – Button Click
using System.Web.Security; using System.Web.UI.WebControls; public partial class login : System.Web.UI.Page { protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { if(FormsAuthentication.Authenticate(Login1.UserName, Login1.Password)) FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false); else lblErr.Text = "Invalid Credentials !! Please try again..."; } }

default.aspx
using System; using System.Data; using System.Data.SqlClient; public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { if(User.Identity.IsAuthenticated)
Page 284 of 296

MCPD Web Developer

Course 70-528

Label1.Text = User.Identity.Name + ", You have successful logged on to myapp !"; String connstr = " server=.;database=Northwind;Integrated Security=True"; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter da = new SqlDataAdapter("select * from Customers", conn); DataSet ds = new DataSet(); da.Fill(ds, "Customers"); GridView1.DataSource = ds.Tables["Customers"]; GridView1.DataBind(); } else Response.Redirect("login.aspx"); } }

From Lesson 2 : Deploying ASP.NET web site
• Right click your website in Visual Studio 2005, then choose “Publish Web Site”



Choose a folder to store the published-web

Page 285 of 296

MCPD Web Developer

Course 70-528



Then open the published-web in VS2005



Add Deployment project to this solution : File  Add  New Project



Then choose : Other Projects Type  Setup and Deployment  Web Setup Project

Page 286 of 296

MCPD Web Developer

Course 70-528



Right click Setup project : choose Add  Project Output

Page 287 of 296

MCPD Web Developer

Course 70-528



Then click OK. Right click Setup Project  choose Build to compile project to file .exe, file .msi



Install : Run .exe (or .msi) file located in /Debug folder of web setup project

Page 288 of 296

MCPD Web Developer

Course 70-528



Control Panel  Administrative Tools  Internet Information Services Manager : right click Setup project  choose Properties : choose tab ASP.NET, choose .NET Framework 2.0

Page 289 of 296

MCPD Web Developer

Course 70-528



Type

url to IE , ex: http://localhost/ASPLab14Setup/default.aspx

UnInstall: Control Panel  Add/Remove Program

Page 290 of 296

MCPD Web Developer

Course 70-528

EXERCISE: CODE-MODEL
Scenario: Get all customers in CUSTOMERS tables of Northwind Database

Exercise 1 : Implementing simple 3-tiers code-model
1) Writing Stored-Procedure in SQL Server (tier 1)
Page 291 of 296

MCPD Web Developer

Course 70-528

Create a Store Procedure for get all customers
CREATE PROCEDURE GET_ALL_CUSTOMER AS SELECT * FROM CUSTOMERS GO

2) Create Data Access Project (Class Library Project) : handling all tasks related with database (tier 2)
• Add new Project



Add new class file

Page 292 of 296

MCPD Web Developer

Course 70-528

Coding for DBAccess.cs class
using using using using System; System.Data; System.Data.SqlClient; BusinessEntity;

namespace DataAccess { public class DBAccess { private readonly SqlConnection conn = new SqlConnection("server=.;database=Northwind;uid=sa;pwd=sa"); private SqlDataAdapter da; private SqlCommand cmd; public DataTable GetAllCustomers() { DataTable dt = new DataTable("Customers"); conn.Open(); cmd = new SqlCommand("GET_ALL_CUSTOMERS", conn); cmd.CommandType = CommandType.StoredProcedure; da = new SqlDataAdapter(cmd); da.Fill(dt); conn.Close(); return dt; } } } • Build it

3) Create code for Web Form (using tier 2 – dll files reference)
• Add Reference from web application to class library project DataAccess

Page 293 of 296

MCPD Web Developer

Course 70-528



Create Web Form

Code for Web Form
using System; using BusinessEntity; using DataAccess; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DBAccess dbaccess = new DBAccess(); CustomerCollection cusColl = dbaccess.GetAllCustomers(); GridView1.DataSource = cusColl; GridView1.DataBind(); } } }
Page 294 of 296

MCPD Web Developer

Course 70-528

Exercise 2 : Implementing Object Oriented code-model
1. Create code for Business Entities class Customer , CustomerCollection
• Add 1 class-library project named BusinessEntities Create 2 class file : Customer.cs, CustomerCollection.cs



Customer.cs
using System; using System.Collections.Generic; using System.Text; namespace BusinessEntity { public class Customer { private string _customerID; private string _companyName; private string _contactName; public string CustomerID { get { return _customerID; } set { _customerID = value; } } public string CompanyName { get { return _companyName; } set { _companyName = value; } } public string ContactName { get { return _contactName; } set { _contactName = value; } } } }

CustomerCollection.cs
using System.Collections; namespace BusinessEntity { public class CustomerCollection : CollectionBase { public int Add(Customer cus) { return List.Add(cus); } } } • • • Build it 2. Write DataAccess class Add 1 class library project named DataAccess Add Reference to BusinessEntities Project Add 1 class file : DBAccess.cs



Page 295 of 296

MCPD Web Developer

Course 70-528

Code for DBAccess.cs using System; using System.Data; using System.Data.SqlClient; using BusinessEntity; namespace DataAccess { public class DBAccess { private SqlConnection conn = new SqlConnection("server=.;database=Northwind;uid=sa;pwd=sa"); private SqlCommand cmd; private SqlDataReader dr; public CustomerCollection GetAllCustomers() { conn.Open(); cmd = new SqlCommand("GET_ALL_CUSTOMERS", conn); cmd.CommandType = CommandType.StoredProcedure; dr = cmd.ExecuteReader(); CustomerCollection cusCollection = new CustomerCollection(); while (dr.Read()) { Customer cus = new Customer(); cus.CustomerID = dr["CustomerID"].ToString(); cus.CompanyName = dr["CompanyName"].ToString(); cus.ContactName = (ReferenceEquals(dr["ContactName"], DBNull.Value) ? "" : dr["ContactName"]).ToString(); cusCollection.Add(cus); } conn.Close(); return cusCollection; } } }

1. Write code for Web Form
• Add Reference to 2 previous project : BusinessEntities, DataAccess Project



Code for Web Form using System; using BusinessEntity; using DataAccess; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DBAccess dbaccess = new DBAccess(); CustomerCollection cusColl = dbaccess.GetAllCustomers(); GridView1.DataSource = cusColl; GridView1.DataBind(); } } }

Page 296 of 296

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close