Tải bản đầy đủ (.pdf) (102 trang)

Bài giảng - giáo án: Bài tập thực hành môn lập trình web

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.24 MB, 102 trang )

Flash Cards
FlashCardClass.cs
public class FlashCardClass
{
int mintFirstNumber, mintSecondNumber;
string[] mstrOp_list = { "+", "-", "*", "/", "%" };
string mstrOp="+";
Random mrndNumber;
int min, max;
public int Min
{
get
{
return min;
}
set
{
min = value;
}
}

public int Max
{
get { return max; }
set { max = value; }
}

public FlashCardClass()
{
// Initialize the random number generator object.
mrndNumber = new Random();


}

public void Shuffle()
{
// Get random numbers.
mintFirstNumber = mrndNumber.Next(Min, Max+1);
mintSecondNumber = mrndNumber.Next(Min, Max+1);
mstrOp = mstrOp_list[mrndNumber.Next(0, 5)];
}

public int FirstNumber
{
get
{
return mintFirstNumber;
}
}

public int SecondNumber
{
get
{
return mintSecondNumber;
}
}

public string Operation
{
get
{

return mstrOp;
}
set
{
mstrOp = value;
}
}

// Calculates answer based on current operation.
public int Answer()
{
switch (mstrOp)
{
case "+":
return mintFirstNumber + mintSecondNumber;
case "x":
return mintFirstNumber * mintSecondNumber;
case "*":
return mintFirstNumber * mintSecondNumber;
case "-":
return mintFirstNumber - mintSecondNumber;
case "/":
return mintFirstNumber / mintSecondNumber;
case "%":
return mintFirstNumber % mintSecondNumber;
default:
return 0;
}
}


}
FlashCard.aspx


FlashCard.aspx.cs
public partial class FlashCard : System.Web.UI.Page
{
FlashCardClass FlashCard1;
protected void Page_Load(object sender, EventArgs e)
{
txtAnswer.Focus();
// Run the following code the first time the page is displayed.
if (!IsPostBack)
{
FlashCard1 = new FlashCardClass();
Session["FlashCard"] = FlashCard1;
}
else
{
// Get the Session FlashCard object.
FlashCard1 = (FlashCardClass)Session["FlashCard"];
}
FlashCard1.Min = int.Parse(TextBox1.Text);
FlashCard1.Max = int.Parse(TextBox2.Text);
RefreshDisplay();

}
protected void txtAnswer_TextChanged(object sender, EventArgs e)
{
if (txtAnswer.Text == FlashCard1.Answer().ToString())

{
lblFeedback.Text = "Correct!";
// Get another set of numbers.
FlashCard1.Shuffle();
// Refresh display to show new numbers.
RefreshDisplay();
}
else
{
lblFeedback.Text = "Oops! Try Again.";
}
txtAnswer.Text = "";
}

private void RefreshDisplay()
{
TextBox2.Text = FlashCard1.Max.ToString();
TextBox1.Text = FlashCard1.Min.ToString();
lblFirst.Text = FlashCard1.FirstNumber.ToString();
lblSecond.Text = FlashCard1.Operation +
FlashCard1.SecondNumber.ToString();
}
Translator
TranslatorClass.cs
public class TranslatorClass
{
string mstrText, mstrOriginal;

// Controls access to class-level variables.
public string Text

{
get
{
return mstrText;
}
set
{
mstrText = value;
// Keep a copy of the original for Restore.
mstrOriginal = value;
}
}

// Restores translated text back to the original.
public void Restore()
{
mstrText = mstrOriginal;
}

// Translates the value in the Text property.
public void Translate()
{
string strWord;
string[] arrWords;
bool bCaps = false;
// Convert the string into an array using System.String.
arrWords = mstrText.Split(' ');
for (int intCount = 0; intCount <= arrWords.GetUpperBound(0);
intCount++)
{

// Change to lowercase.
strWord = arrWords[intCount].ToLower();
// Check if word is capitalized.
if (!arrWords[intCount].Equals(strWord))
bCaps = true;
// Do translation.
if (strWord != "")
{
strWord = strWord.Substring(1, strWord.Length - 1) +
strWord.Substring(0, 1) + "ay";
// Recapitalize if necessary.
if (bCaps)
strWord = strWord.Substring(0, 1).ToUpper() +
strWord.Substring(1, strWord.Length - 1);
}
// Store the word back in the array.
arrWords[intCount] = strWord;
// Reset the caps flag.
bCaps = false;
}
// Rebuild the string from the array.
mstrText = String.Join(" ", arrWords);
}
}
Translator.aspx

Translator.aspx.cs
public partial class Translator : System.Web.UI.Page
{
TranslatorClass TransClass;


protected void Page_Load(object sender, EventArgs e)
{
// The first time this page is displayed
if (!IsPostBack)
{
// Create a new Translator object.
TransClass = new TranslatorClass();
// Store the object in a Session state variable.
Session["TransClass"] = TransClass;
}
else
// Get the Session TransClass variable.
TransClass = (TranslatorClass)Session["TransClass"];
}

protected void butTranslate_Click(object sender, System.EventArgs e)
{
// Declare a boolean switch.
bool bSwitch;
// Check if ViewState variable exists.
if (ViewState["bSwitch"] != null)
// Get the value from ViewState and switch it.
bSwitch = !(bool)ViewState["bSwitch"];
else
// Set the switch.
bSwitch = true;
// Save the new value in ViewState.
ViewState["bSwitch"] = bSwitch;
// Use the switch to either translate or restore

// the text in txtSource.
if (bSwitch)
{
// Get the text.
TransClass.Text = txtSource.Text;
// Translate it.
TransClass.Translate();
// Display the text.
txtSource.Text = TransClass.Text;
// Change the Button text.
butTranslate.Text = "Restore";
}
else
{
// Restore the original text.
TransClass.Restore();
// Display the text.
txtSource.Text = TransClass.Text;
// Change the Button text.
butTranslate.Text = "Translate";
}
}
WebTextEditor

SignOn.aspx

public partial class SignOn : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)

{

}
protected void butSignOn_Click(object sender, System.EventArgs e)
{
string strPath;
// If the user exists, there is a directory of the same name.
strPath = Server.MapPath(Request.ApplicationPath) + "\\"
+ txtName.Text;
if (Directory.Exists(strPath))
{
// Set session variables.
Session["Path"] = strPath;
Server.Transfer("FileManager.aspx");
}
else
{
Session["NewName"] = txtName.Text;
// Otherwise, report that user wasn't found.
litNoAccount.Text = "<p>The name " + txtName.Text +
" wasn't found. Check the name, or click " +
"<A href='NewAccount.aspx'>here</A> if you " +
"are a new user.</p>";
}
}

}
NewAccount.aspx

NewAccount.aspx.cs

public partial class NewAccount : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtName.Text=Session["NewName"].ToString();
}

protected void butCreate_Click(object sender, System.EventArgs e)
{
string strPath;
//Check if directory exists.
strPath = Server.MapPath(Request.ApplicationPath) + "\\"
+ txtName.Text;
if (Directory.Exists(strPath))
{
// Tell the user to choose another name.
litNameExists.Text = "<p>The name " + txtName.Text +
" already exists. Please choose a different one.</p>";
return;
}
else
{
try
{
// Create the directory.
Directory.CreateDirectory(strPath);
// Set the session variable.
Session["Path"] = strPath;
// Go to file manager.
Server.Transfer("FileManager.aspx");

}
catch (System.UnauthorizedAccessException ex)
{
Server.Transfer("NotAuthorized.aspx");
}
}
}
FileManager.aspx

FileManager.aspx.cs
public partial class FileManager : System.Web.UI.Page
{
string strPath;
public string[] strFiles;

protected void Page_Load(object sender, System.EventArgs e)
{
// Get path.
strPath = Session["Path"].ToString();
// If this is not a post-back event.
if (!Page.IsPostBack)
{
// Get list of files in the current directory.
strFiles = Directory.GetFiles(strPath);
// Get the short names for the files.
for (int iCount = 0; iCount <= strFiles.GetUpperBound(0);
iCount++)
strFiles[iCount] =
Path.GetFileName(strFiles[iCount]);
}

// Bind lstFiles to file array.
lstFiles.DataSource = strFiles;
lstFiles.DataBind();
}

protected void butNew_Click(object sender, System.EventArgs e)
{
//If there is a file name, then start the editor.
if (!(txtNewFile.Text == ""))
Response.Redirect("EditFile.aspx?file=" +
txtNewFile.Text);
else
// Otherwise, display a message.
litNoFile.Text = "<p>You must enter the name of a file " +
" to create.<p>";
}

protected void butEdit_Click(object sender, System.EventArgs e)
{
// If there is a file name, then start the editor.
if (lstFiles.SelectedItem != null)
Response.Redirect("EditFile.aspx?file=" +
lstFiles.SelectedItem.ToString());
else
// Otherwise, display a message.
litNoneSelected.Text = "<p>You must select a file.<p>";
}

protected void butDelete_Click(object sender, System.EventArgs e)
{

// If there is a file name, then start the editor.
if (lstFiles.SelectedItem != null)
try
{
File.Delete(strPath + "\\" +
lstFiles.SelectedItem.ToString());
lstFiles.Items.Remove(lstFiles.SelectedItem);
}
catch (System.UnauthorizedAccessException ex)
{
Server.Transfer("NotAuthorized.aspx");
}
else
// Otherwise, display a message.
litNoneSelected.Text = "<p>You must select a file.<p>";
}

}


EditFile.aspx

EditFile.aspx.cs
public partial class EditFile : System.Web.UI.Page
{
string strPath;
string strFile;

protected void Page_Load(object sender, System.EventArgs e)
{

// Get the path and file names.
strPath = Session["Path"].ToString();
strFile = Request.QueryString["file"];
// If this is not a post-back event.
if (!Page.IsPostBack)
{
StreamReader strmEditFile;
try
{
// Open the file.
strmEditFile = File.OpenText(strPath + "\\" +
strFile);
// Read its text.
txtEditFile.Text =
strmEditFile.ReadToEnd().ToString();
// Close the file.
strmEditFile.Close();
}
catch (FileNotFoundException ex)
{
// If it doesn't exist, create it.
File.CreateText(strPath + "\\" +
strFile).Close();
// Clear text box.
txtEditFile.Text = "";
}
catch (System.UnauthorizedAccessException ex)
{
Server.Transfer("NotAuthorized.aspx");
}

}
}

protected void butExit_Click(object sender, System.EventArgs e)
{
if ((ViewState["Changed"] != null) &&
(ViewState["Changed"].ToString() == "true"))
SaveFile();
// Return to File Manager.
Server.Transfer("FileManager.aspx");
}

protected void txtEditFile_TextChanged(object sender, System.EventArgs e)
{
// Set changed flag.
ViewState["Changed"] = "true";
}

protected void butSave_Click(object sender, System.EventArgs e)
{
SaveFile();
}

void SaveFile()
{
StreamWriter strmEditWrite;
// Delete the file.
File.Delete(strPath + strFile);
// Create the file with new text.
strmEditWrite = File.CreateText(strPath + "\\" + strFile);

strmEditWrite.Write(txtEditFile.Text);
strmEditWrite.Close();
// Reset changed flag.
ViewState["Changed"] = "false";
}

}
NotAuthorized.aspx




Quản lý thông tin người dùng
SignOn.aspx

SignOn.aspx.cs
public partial class SignOn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSignOn_Click(object sender, EventArgs e)
{
string strPath;
// If the user exists, there is a directory of the same name.
strPath = Server.MapPath(Request.ApplicationPath) + "\\"
+ tbAccount.Text;



if (Directory.Exists(strPath))
{
if (checkPassword(tbAccount.Text, tbPassword.Text) == true)
{
// Set session variables.
Session["Path"] = strPath;
Server.Transfer("UserInformation.aspx");
}
}
else
{
Session["NewName"] = tbAccount.Text;
// Otherwise, report that user wasn't found.
lit.Text = "<p>The name " + tbAccount.Text +
" wasn't found. Check the name, or click " +
"<A href='NewAccount.aspx'>here</A> if you " +
"are a new user.</p>";
}
}

private bool checkPassword(string acc,string pass)
{
string truepas;
string strPath = Server.MapPath(Request.ApplicationPath) + "\\" +
acc;
StreamReader strmEditFile;
try
{
// Open the file.
strmEditFile = File.OpenText(strPath + "\\" + "password.txt");

// Read its text.
truepas = strmEditFile.ReadToEnd().ToString();
// Close the file.
strmEditFile.Close();

if (truepas == pass)
{
return true;
}
else
{
lit.Text = "Password incorrect";
return false;
}
}
catch (FileNotFoundException ex)
{
lit.Text = "Error!Password file doesn't exist";
return false;
}
}
}

NewAccount.aspx

NewAccount.aspx.cs
public partial class NewAccount : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

tbName.Text=Session["NewName"].ToString();
}

protected void btnCreate_Click(object sender, EventArgs e)
{
string strPath;
//Check if directory exists.
strPath = Server.MapPath(Request.ApplicationPath) + "\\"
+ tbName.Text;
if (Directory.Exists(strPath))
{
// Tell the user to choose another name.
lit.Text = "<p>The name " + tbName.Text +
" already exists. Please choose a different one.</p>";
return;
}
else
{
try
{
// Create the directory.
Directory.CreateDirectory(strPath);
SaveInfo(strPath);
// Set the session variable.
Session["Path"] = strPath;
// Go to file manager.
Server.Transfer("UserInformation.aspx");
}
catch { }
/*catch (System.UnauthorizedAccessException ex)

{
Server.Transfer("NotAuthorized.aspx");
}*/
}
}

void SaveInfo(string strPath)
{
StreamWriter strmEditWrite;

strmEditWrite = File.CreateText(strPath + "\\" + "information.txt");

strmEditWrite.Write(tbRealname.Text+"\n"+tbBirthday.Text+"\n"+tbBirthyear.Tex
t);
strmEditWrite.Close();

strmEditWrite = File.CreateText(strPath + "\\" + "password.txt");
strmEditWrite.Write(tbPassword.Text);
strmEditWrite.Close();

}
}
UserInformation.aspx

UserInformation.aspx.cs
public partial class UserInformation : System.Web.UI.Page
{
string strPath;
protected void Page_Load(object sender, EventArgs e)
{

// Get the path and file names.
strPath = Session["Path"].ToString();

// If this is not a post-back event.
if (!Page.IsPostBack)
{
StreamReader strmEditFile;
try
{
// Open the file.
strmEditFile = File.OpenText(strPath + "\\" +
"information.txt");
// Read its text.
string x = strmEditFile.ReadToEnd().ToString();
tbMulti.Text = x;
string[] px = x.Split('\n');
for (int i = 0; i < px.Length; i++)
Response.Write(px[i]+"<br>");
// Close the file.
strmEditFile.Close();
}
catch { }
}
}
}

1/18
BÀI THỰC HÀNH
ContactManagment


Tạo các trang
- SwitchBoard.aspx
- Calls.aspx
- AddContact.aspx
- DeleteContact.aspx
- ContactTypes.aspx

1. Thiết kế trang SwitchBoard.aspx



2. Thiết kế trang AddContact
2/18

3/18


Thêm vào Website class DataSet
4/18





5/18


6/18



7/18



Tạo truy vấn Insert:
8/18



×