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
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
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
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
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];
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 :
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
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); }
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
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
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
} 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(); } } }
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”
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
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
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
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
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
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(); }
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:
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
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
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
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
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
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
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
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
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
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)
: 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
} } 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
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();
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
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
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\
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
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 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
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(); } } }