进行NUnit测试我的网站。 [英] Conducting NUnit Test For my website.
问题描述
我是单元测试的新手;如果有人可以指导我的数据库驱动的网站进行单元测试会很有帮助。
这个网站的工作是将数据从excel上传/传输到数据库并显示记录在网格视图中。如果用户想要进行一些更改,例如编辑/删除数据,他/她将能够通过GridView完成。
我想使用NUnit,为我的网页进行单元测试。
我也附上代码供参考。如果有人可以在这个问题上帮助我,那将非常有帮助。
提前致谢。
Dipak
我的代码
-------------
I am new to unit testing; it would be helpful if anybody can guide to conduct unit testing for my database driven website.
This website’s job is to upload/transfer data from excel to database and display records in the Grid View. If user wants to make some changes e.g. Edit/Delete to the data, he/she will be able to do it through GridView.
I want to use NUnit, for conducting unit test for my web page.
I am also attaching the code for reference. If anybody can help me in this issue it would be really helpful.
Thanks in advance.
Dipak
My Code
-------------
public partial class _Default : System.Web.UI.Page
{
string connectionString;
//connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
else { GetData(); }
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
/* Row Color + Hover */
e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//string connectionString = "";
if (FileUpload1.HasFile)
{
//string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
//string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//string fileLocation = Server.MapPath("~/App_Data/Excel_File/" + fileName);
//FileUpload1.SaveAs(fileLocation);
string fileName = Filechecker();
string fileLocation = Server.MapPath("~/App_Data/Excel_File/" + fileName);
DataSet objds = new DataSet();
objds = ImportFromExcel(fileName, fileLocation);
foreach (System.Data.DataTable dt in objds.Tables)
{
//string connectionString;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
//Open a connection with destination database;
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping(0, "cust_name");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping(1, "cust_address");
SqlBulkCopyColumnMapping mapping3 = new SqlBulkCopyColumnMapping(2, "cust_state");
//Open bulkcopy connection.
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(connection))
{
bulkcopy.ColumnMappings.Add(mapping1);
bulkcopy.ColumnMappings.Add(mapping2);
bulkcopy.ColumnMappings.Add(mapping3);
//Set destination table name
//to table previously created.
bulkcopy.DestinationTableName = "dbo.customer";
//Define column mappings
try
{
bulkcopy.WriteToServer(dt);
this.BindData();
}
catch (Exception ex)
{
Page.Response.Write(ex.Message);
}
connection.Close();
}
}
}
}
}
public DataSet ImportFromExcel(string file, string filepath)
{
// Create new dataset
DataSet ds = new DataSet();
// -- Start of Constructing OLEDB connection string to Excel file
Dictionary<string,> props = new Dictionary<string,>();
// For Excel 2007/2010
if (file.EndsWith(".xlsx"))
{
props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
props["Extended Properties"] = "Excel 12.0 XML";
}
// For Excel 2003 and older
else if (file.EndsWith(".xls"))
{
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Extended Properties"] = "Excel 8.0";
}
else
return null;
props["Data Source"] = filepath;
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string,> prop in props)
{
sb.Append(prop.Key);
sb.Append(''='');
sb.Append(prop.Value);
sb.Append('';'');
}
string connectionString = sb.ToString();
// -- End of Constructing OLEDB connection string to Excel file
// Connecting to Excel File
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();
// Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
DataTable dt = new DataTable();
dt.TableName = sheetName.Replace("$", string.Empty);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
// Add table into DataSet
ds.Tables.Add(dt);
}
cmd = null;
conn.Close();
}
return ds;
}
/*------------------------------------------------------------------------------------------------------------------------*/
private void BindData()
{
string strQuery = "select customer.cust_id,customer.cust_name," +
"customer.cust_address,customer.date_of_sale," +
"tbl_state.state_name" +
" from customer, tbl_state where" +
" customer.cust_state=tbl_state.state_id";
SqlCommand cmd = new SqlCommand(strQuery);
//Page.Response.Write(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
//string connectionString;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
this.BindData();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
SetData();
}
protected void Delete(object sender, EventArgs e)
{
}
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
this.txtID.ReadOnly = true;
this.txtID.Text = row.Cells[1].Text;
this.txtName.Text = row.Cells[2].Text;
this.txtAddress.Text = row.Cells[3].Text;
this.txtdate.Text = row.Cells[4].Text;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand sqlcmd = new SqlCommand("select state_id,state_name from tbl_state", con);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
da.Fill(ds);
this.ddState.DataSource = ds;
this.ddState.DataTextField = "state_name";
this.ddState.DataValueField = "state_id";
this.ddState.DataBind();
this.ddState.Items.Insert(0, new ListItem("--Select--", "--Select--"));
this.ddState.Items.FindByText(row.Cells[5].Text).Selected = true;
//this.ddState.Text = row.Cells[4].Text;
popup.Show();
con.Close();
}
}
protected void Add(object sender, EventArgs e)
{
this.txtID.ReadOnly = false;
this.txtName.Text = string.Empty;
this.txtAddress.Text = string.Empty;
this.txtdate.Text = string.Empty;
//
//string connectionString;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand sqlcmd = new SqlCommand("select state_id,state_name from tbl_state", con);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
da.Fill(ds);
this.ddState.DataSource = ds;
this.ddState.DataTextField = "state_name";
this.ddState.DataValueField = "state_id";
this.ddState.DataBind();
this.ddState.Items.Insert(0, new ListItem("--Select--", "--Select--"));
popup.Show();
con.Close();
}
protected void Save(object sender, EventArgs e)
{
Page.Validate(valSummary.ValidationGroup);
if (!Page.IsValid)
{
update.Update();
modalPopupEx.Show();
popup.Show();
}
else
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AddUpdateCust";
cmd.Parameters.AddWithValue("@ID", this.txtID.Text);
cmd.Parameters.AddWithValue("@Name", this.txtName.Text);
cmd.Parameters.AddWithValue("@Address", this.txtAddress.Text);
cmd.Parameters.AddWithValue("@State", this.ddState.SelectedValue.ToString());
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
}
}
}
/*------------------------------------------------------------------------------------------------------------------------*/
protected void btnDelete_Click(object sender, EventArgs e)
{
int count = 0;
SetData();
GridView1.AllowPaging = false;
//GridView1.DataBind();
ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
count = arr.Count;
for (int i = 0; i < this.GridView1.Rows.Count; i++)
{
if (arr.Contains(GridView1.DataKeys[i].Value))
{
DeleteRecord(GridView1.DataKeys[i].Value.ToString());
arr.Remove(GridView1.DataKeys[i].Value);
}
}
ViewState["SelectedRecords"] = arr;
hfCount.Value = "0";
GridView1.AllowPaging = true;
BindData();
ShowMessage(count);
}
private void GetData()
{
ArrayList arr;
if (ViewState["SelectedRecords"] != null)
arr = (ArrayList)ViewState["SelectedRecords"];
else
arr = new ArrayList();
CheckBox chkAll = (CheckBox)GridView1.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (chkAll.Checked)
{
if (!arr.Contains(GridView1.DataKeys[i].Value))
{
arr.Add(GridView1.DataKeys[i].Value);
}
}
else
{
CheckBox chk = (CheckBox)GridView1.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
if (!arr.Contains(GridView1.DataKeys[i].Value))
{
arr.Add(GridView1.DataKeys[i].Value);
}
}
else
{
if (arr.Contains(GridView1.DataKeys[i].Value))
{
arr.Remove(GridView1.DataKeys[i].Value);
}
}
}
}
ViewState["SelectedRecords"] = arr;
}
private void SetData()
{
int currentCount = 0;
CheckBox chkAll = (CheckBox)GridView1.HeaderRow
.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i]
.Cells[0].FindControl("chk");
if (chk != null)
{
chk.Checked = arr.Contains(GridView1.DataKeys[i].Value);
if (!chk.Checked)
chkAll.Checked = false;
else
currentCount++;
}
}
hfCount.Value = (arr.Count - currentCount).ToString();
}
private void ShowMessage(int count)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script type = ''text/javascript''>");
sb.Append("alert(''");
sb.Append(count.ToString());
sb.Append(" records deleted.'');");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(),
"script", sb.ToString());
}
private void DeleteRecord(string CustomerID)
{
//string connectionString;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
string query = "delete from customer " +
"where cust_id=@CustomerID";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@CustomerID", CustomerID);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
/*--------------------------------------------------------------------------------------------------------*/
private string Filechecker()
{
try
{
string UpPath = Server.MapPath("~/App_Data/Excel_File/");
//the directory you want the file uploaded to
//create directory if it doesn''t already exist
if (!Directory.Exists(UpPath))
Directory.CreateDirectory(UpPath.Replace("\\", "\\\\"));
string FileName = FileUpload1.PostedFile.FileName;
string FileType = FileUpload1.PostedFile.ContentType;
string FileSize = FileUpload1.PostedFile.ContentLength.ToString();
string ClientFile = System.IO.Path.GetFileName(FileName);
FileInfo ServerFile = new FileInfo(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile);
int idx = 1;
//increment a number on the end of the filename until it is unique to stop files being overwritten
//will cope with filenames with multiple dots (eg. sunset.photo.12.jpg)
while (ServerFile.Exists)
{
string[] filename = ClientFile.Split(''.'');
ClientFile = "";
int prevIdx = idx - 1;
if (idx > 1)
{
for (int i = 0; i < filename.GetUpperBound(0); i++)
{
ClientFile += filename[i];
if (i < filename.GetUpperBound(0) - 1)
ClientFile += ".";
}
ClientFile = ClientFile.Substring(0, ClientFile.Length - prevIdx.ToString().Length) + idx.ToString() + "." + filename[filename.GetUpperBound(0)];
}
else
{
for (int i = 0; i < filename.GetUpperBound(0); i++)
{
ClientFile += filename[i];
if (i < filename.GetUpperBound(0) - 1)
ClientFile += ".";
} ClientFile += idx.ToString() + "." + filename[filename.GetUpperBound(0)];
}
ServerFile = new FileInfo(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile);
idx++;
}
//save file to server
FileUpload1.PostedFile.SaveAs(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile); return ClientFile;
}
catch (Exception ex) { throw ex; }
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
// turn off paging
GridView1.AllowPaging = false;
//BindData();
if (this.txtSearch.Text == "")
{ BindData(); }
else
{ SearchText(); }
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
// turn the paging on again
GridView1.AllowPaging = true;
//BindData();
if (this.txtSearch.Text == "")
{ BindData(); }
else
{ SearchText(); }
}
public override void VerifyRenderingInServerForm(Control control)
{
//this.VerifyRenderingInServerForm(this.GridView1);
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchText();
}
private void SearchText()
{
string strQuery = "select customer.cust_id,customer.cust_name," +
"customer.cust_address,customer.date_of_sale," +
"tbl_state.state_name" +
" from customer, tbl_state where" +
" customer.cust_state=tbl_state.state_id And tbl_state.state_name=''" + this.txtSearch.Text + "''";
SqlCommand cmd = new SqlCommand(strQuery);
//Page.Response.Write(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
推荐答案
,string.Empty);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
//将表添加到DataSet
ds.Tables.Add(dt);
}
cmd = null;
conn.Close();
}
返回ds;
}
/ * -------------------------------------------------- -------------------------------------------------- -------------------- * /
private void BindData()
{
string strQuery =select customer.cust_id,customer .cust_name,+
customer.cust_address,customer.date_of_sale,+
tbl_state.state_name+
来自客户,tbl_state,其中+
customer.cust_state = tbl_state.state_id;
SqlCommand cmd = new SqlCommand(strQuery);
//Page.Response.Write(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
// string connectionString;
connectionString =;
connectionString =Integrated Security = SSPI; Persist Security Info = False; User ID = sa; Initial Catalog = TEST_DB; Data Source = DELL-PC;
DataTable dt = new DataTable();
using(SqlConnection con = new SqlConnection(connectionString))
{
using(SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
返回dt;
}
}
}
protected void OnPaging(对象发送者,GridViewPageEventArgs e)
{
this.BindData();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
SetData();
}
protected void删除(对象发送者,EventArgs e)
{
}
protected void编辑(对象发送者,EventArgs e)
{
using(GridViewRow row =(GridViewRow)((LinkButton)sender).Parent.Parent)
{
this.txtID.ReadOnly = true;
this.txtID.Text = row.Cells [1] .Text;
this.txtName.Text = row.Cells [2] .Text;
this.txtAddress.Text = row.Cells [3] .Text;
this.txtdate.Text = row.Cells [4] .Text;
connectionString =;
connectionString =Integrated Security = SSPI; Persist Security Info = False; User ID = sa; Initial Catalog = TEST_DB; Data Source = DELL-PC;
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand sqlcmd = new SqlCommand(select state_id,state_name from tbl_state,con);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
da.Fill(ds);
this.ddState.DataSource = ds;
this.ddState.DataTextField =state_name;
this.ddState.DataValueField =state_id;
this.ddState.DataBind();
this.ddState.Items.Insert(0,new ListItem( - Select - , - Select--));
this.ddState.Items.FindByText(row.Cells [5] .Text).Selected = true;
//this.ddState.Text = row.Cells [4] .Text;
popup.Show();
con.Close();
}
}
protected void Add(object sender,EventArgs e)
{
this.txtID.ReadOnly = false;
this.txtName.Text = string.Empty;
this.txtAddress.Text = string.Empty;
this.txtdate.Text = string.Empty;
//
//字符串连接字符串;
connectionString =;
connectionString =Integrated Security = SSPI; Persist Security Info = False; User ID = sa; Initial Catalog = TEST_DB; Data Source = DELL-PC;
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand sqlcmd = new SqlCommand(select state_id,state_name from tbl_state,con);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
da.Fill(ds);
this.ddState.DataSource = ds;
this.ddState.DataTextField =state_name;
this.ddState.DataValueField =state_id;
this.ddState.DataBind();
this.ddState.Items.Insert(0,new ListItem( - Select - , - Select--));
popup.Show();
con.Close();
}
protected void保存(对象发送者,EventArgs e)
{
Page.Validate(valSummary.ValidationGroup);
if(!Page.IsValid)
{
update.Update();
modalPopupEx.Show();
popup.Show();
}
其他
{
使用(SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText =AddUpdateCust;
cmd.Parameters.AddWithValue(@ ID,this.txtID.Text);
cmd.Parameters.AddWithValue(@ Name,this.txtName.Text);
cmd.Parameters.AddWithValue(@ Address,this.txtAddress.Text);
cmd.Parameters.AddWithValue(@ State,this.ddState.SelectedValue.ToString());
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
}
}
}
/ * ----------------------------- -------------------------------------------------- ----------------------------------------- * /
protected void btnDelete_Click(object sender,EventArgs e)
{
int count = 0;
SetData();
GridView1.AllowPaging = false;
//GridView1.DataBind();
ArrayList arr =(ArrayList)ViewState [SelectedRecords];
count = arr.Count;
for(int i = 0; i< this.GridView1.Rows.Count; i ++)
{
if(arr.Contains(GridView1.DataKeys [i] .Value))
{
DeleteRecord(GridView1.DataKeys [i] .Value.ToString());
arr.Remove(GridView1.DataKeys [i] .Value);
}
}
ViewState [SelectedRecords] = arr;
hfCount.Value =0;
GridView1.AllowPaging = true;
BindData();
ShowMessage(count);
}
private void GetData()
{
ArrayList arr;
if(ViewState [SelectedRecords]!= null)
arr =(ArrayList)ViewState [SelectedRecords];
else
arr = new ArrayList();
CheckBox chkAll =(CheckBox)GridView1.HeaderRow
.Cells [0] .FindControl(chkAll);
for(int i = 0; i< GridView1.Rows.Count; i ++)
{
if(chkAll.Checked)
{
if(!arr.Contains(GridView1.DataKeys [i] .Value))
{
arr.Add(GridView1.DataKeys [i] .Value );
}
}
其他
{
CheckBox chk =(CheckBox)GridView1.Rows [ i]
.Cells [0] .FindControl(chk);
if(chk.Checked)
{
if(!arr.Contains(GridView1.DataKeys [i] .Value))
{
arr.Add(GridView1.DataKeys [i] .Value);
}
}
其他
{
if(arr.Contains(GridView1.DataKeys [ i] .Value))
{
arr.Remove(GridView1.DataKeys [i] .Value);
}
}
}
}
ViewState [SelectedRecords] = arr;
}
private void SetData()
{
int currentCount = 0;
CheckBox chkAll = (CheckBox)GridView1.HeaderRow
.Cells[0].FindControl(\"chkAll\");
chkAll.Checked = true;
ArrayList arr = (ArrayList)ViewState[\"SelectedRecords\"];
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i]
.Cells[0].FindControl(\"chk\");
if (chk != null)
{
chk.Checked = arr.Contains(GridView1.DataKeys[i].Value);
if (!chk.Checked)
chkAll.Checked = false;
else
currentCount++;
}
}
hfCount.Value = (arr.Count - currentCount).ToString();
}
private void ShowMessage(int count)
{
StringBuilder sb = new StringBuilder();
sb.Append(\"<script type = ’’text/javascript’’>\");
sb.Append(\"alert(’’\");
sb.Append(count.ToString());
sb.Append(\" records deleted.’’);\");
sb.Append(\"</script>\");
ClientScript.RegisterStartupScript(this.GetType(),
\"script\", sb.ToString());
}
private void DeleteRecord(string CustomerID)
{
//string connectionString;
connectionString = \"\";
connectionString = \"Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC\";
string query = \"delete from customer \" +
\"where cust_id=@CustomerID\";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query,con);
cmd.Parameters.AddWithValue(\"@CustomerID\", CustomerID);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
/*--------------------------------------------------------------------------------------------------------*/
private string Filechecker()
{
try
{
string UpPath = Server.MapPath(\"~/App_Data/Excel_File/\");
//the directory you want the file uploaded to
//create directory if it doesn’’t already exist
if (!Directory.Exists(UpPath))
Directory.CreateDirectory(UpPath.Replace(\"\\\", \"\\"));
string FileName = FileUpload1.PostedFile.FileName;
string FileType = FileUpload1.PostedFile.ContentType;
string FileSize = FileUpload1.PostedFile.ContentLength.ToString();
string ClientFile = System.IO.Path.GetFileName(FileName);
FileInfo ServerFile = new FileInfo(UpPath.Replace(\"\\\", \"\\") + \"\\\" + ClientFile);
int idx = 1;
//increment a number on the end of the filename until it is unique to stop files being overwritten
//will cope with filenames with multiple dots (eg. sunset.photo.12.jpg)
while (ServerFile.Exists)
{
string[] filename = ClientFile.Split(’’.’’);
ClientFile = \"\";
int prevIdx = idx - 1;
if (idx > 1)
{
for (int i = 0; i < filename.GetUpperBound(0); i++)
{
ClientFile += filename[i];
if (i < filename.GetUpperBound(0) - 1)
ClientFile += \".\";
}
ClientFile = ClientFile.Substring(0, ClientFile.Length - prevIdx.ToString().Length) + idx.ToString() + \".\" + filename[filename.GetUpperBound(0)];
}
else
{
for (int i = 0; i < filename.GetUpperBound(0); i++)
{
ClientFile += filename[i];
if (i < filename.GetUpperBound(0) - 1)
ClientFile += \".\";
} ClientFile += idx.ToString() + \".\" + filename[filename.GetUpperBound(0)];
}
ServerFile = new FileInfo(UpPath.Replace(\"\\\", \"\\") + \"\\\" + ClientFile);
idx++;
}
//save file to server
FileUpload1.PostedFile.SaveAs(UpPath.Replace(\"\\\", \"\\") + \"\\\" + ClientFile); return ClientFile;
}
catch (Exception ex) { throw ex; }
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader(\"content-disposition\",\"attachment;filename=FileName.xls\");
Response.Charset =;
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = \"application/vnd.xls\";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
// turn off paging
GridView1.AllowPaging = false;
//BindData();
if (this.txtSearch.Text == \"\")
{ BindData(); }
else
{ SearchText(); }
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
// turn the paging on again
GridView1.AllowPaging = true;
//BindData();
if (this.txtSearch.Text == \"\")
{ BindData(); }
else
{ SearchText(); }
}
public override void VerifyRenderingInServerForm(Control control)
{
//this.VerifyRenderingInServerForm(this.GridView1);
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchText();
}
private void SearchText()
{
string strQuery = \"select customer.cust_id,customer.cust_name,\" +
\"customer.cust_address,customer.date_of_sale,\" +
\"tbl_state.state_name\" +
\" from customer, tbl_state where\" +
\" customer.cust_state=tbl_state.state_id And tbl_state.state_name=’’\" + this.txtSearch.Text + \"’’\";
SqlCommand cmd = new SqlCommand(strQuery);
//Page.Response.Write(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
", string.Empty); OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); // Add table into DataSet ds.Tables.Add(dt); } cmd = null; conn.Close(); } return ds; } /*------------------------------------------------------------------------------------------------------------------------*/ private void BindData() { string strQuery = "select customer.cust_id,customer.cust_name," + "customer.cust_address,customer.date_of_sale," + "tbl_state.state_name" + " from customer, tbl_state where" + " customer.cust_state=tbl_state.state_id"; SqlCommand cmd = new SqlCommand(strQuery); //Page.Response.Write(strQuery); GridView1.DataSource = GetData(cmd); GridView1.DataBind(); } private DataTable GetData(SqlCommand cmd) { //string connectionString; connectionString = ""; connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC"; DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; con.Open(); sda.SelectCommand = cmd; sda.Fill(dt); return dt; } } } protected void OnPaging(object sender, GridViewPageEventArgs e) { this.BindData(); GridView1.PageIndex = e.NewPageIndex; GridView1.DataBind(); SetData(); } protected void Delete(object sender, EventArgs e) { } protected void Edit(object sender, EventArgs e) { using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent) { this.txtID.ReadOnly = true; this.txtID.Text = row.Cells[1].Text; this.txtName.Text = row.Cells[2].Text; this.txtAddress.Text = row.Cells[3].Text; this.txtdate.Text = row.Cells[4].Text; connectionString = ""; connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC"; DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlCommand sqlcmd = new SqlCommand("select state_id,state_name from tbl_state", con); SqlDataAdapter da = new SqlDataAdapter(sqlcmd); da.Fill(ds); this.ddState.DataSource = ds; this.ddState.DataTextField = "state_name"; this.ddState.DataValueField = "state_id"; this.ddState.DataBind(); this.ddState.Items.Insert(0, new ListItem("--Select--", "--Select--")); this.ddState.Items.FindByText(row.Cells[5].Text).Selected = true; //this.ddState.Text = row.Cells[4].Text; popup.Show(); con.Close(); } } protected void Add(object sender, EventArgs e) { this.txtID.ReadOnly = false; this.txtName.Text = string.Empty; this.txtAddress.Text = string.Empty; this.txtdate.Text = string.Empty; // //string connectionString; connectionString = ""; connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC"; DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlCommand sqlcmd = new SqlCommand("select state_id,state_name from tbl_state", con); SqlDataAdapter da = new SqlDataAdapter(sqlcmd); da.Fill(ds); this.ddState.DataSource = ds; this.ddState.DataTextField = "state_name"; this.ddState.DataValueField = "state_id"; this.ddState.DataBind(); this.ddState.Items.Insert(0, new ListItem("--Select--", "--Select--")); popup.Show(); con.Close(); } protected void Save(object sender, EventArgs e) { Page.Validate(valSummary.ValidationGroup); if (!Page.IsValid) { update.Update(); modalPopupEx.Show(); popup.Show(); } else { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "AddUpdateCust"; cmd.Parameters.AddWithValue("@ID", this.txtID.Text); cmd.Parameters.AddWithValue("@Name", this.txtName.Text); cmd.Parameters.AddWithValue("@Address", this.txtAddress.Text); cmd.Parameters.AddWithValue("@State", this.ddState.SelectedValue.ToString()); GridView1.DataSource = this.GetData(cmd); GridView1.DataBind(); } } } /*------------------------------------------------------------------------------------------------------------------------*/ protected void btnDelete_Click(object sender, EventArgs e) { int count = 0; SetData(); GridView1.AllowPaging = false; //GridView1.DataBind(); ArrayList arr = (ArrayList)ViewState["SelectedRecords"]; count = arr.Count; for (int i = 0; i < this.GridView1.Rows.Count; i++) { if (arr.Contains(GridView1.DataKeys[i].Value)) { DeleteRecord(GridView1.DataKeys[i].Value.ToString()); arr.Remove(GridView1.DataKeys[i].Value); } } ViewState["SelectedRecords"] = arr; hfCount.Value = "0"; GridView1.AllowPaging = true; BindData(); ShowMessage(count); } private void GetData() { ArrayList arr; if (ViewState["SelectedRecords"] != null) arr = (ArrayList)ViewState["SelectedRecords"]; else arr = new ArrayList(); CheckBox chkAll = (CheckBox)GridView1.HeaderRow .Cells[0].FindControl("chkAll"); for (int i = 0; i < GridView1.Rows.Count; i++) { if (chkAll.Checked) { if (!arr.Contains(GridView1.DataKeys[i].Value)) { arr.Add(GridView1.DataKeys[i].Value); } } else { CheckBox chk = (CheckBox)GridView1.Rows[i] .Cells[0].FindControl("chk"); if (chk.Checked) { if (!arr.Contains(GridView1.DataKeys[i].Value)) { arr.Add(GridView1.DataKeys[i].Value); } } else { if (arr.Contains(GridView1.DataKeys[i].Value)) { arr.Remove(GridView1.DataKeys[i].Value); } } } } ViewState["SelectedRecords"] = arr; } private void SetData() { int currentCount = 0; CheckBox chkAll = (CheckBox)GridView1.HeaderRow .Cells[0].FindControl("chkAll"); chkAll.Checked = true; ArrayList arr = (ArrayList)ViewState["SelectedRecords"]; for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox chk = (CheckBox)GridView1.Rows[i] .Cells[0].FindControl("chk"); if (chk != null) { chk.Checked = arr.Contains(GridView1.DataKeys[i].Value); if (!chk.Checked) chkAll.Checked = false; else currentCount++; } } hfCount.Value = (arr.Count - currentCount).ToString(); } private void ShowMessage(int count) { StringBuilder sb = new StringBuilder(); sb.Append("<script type = ''text/javascript''>"); sb.Append("alert(''"); sb.Append(count.ToString()); sb.Append(" records deleted.'');"); sb.Append("</script>"); ClientScript.RegisterStartupScript(this.GetType(), "script", sb.ToString()); } private void DeleteRecord(string CustomerID) { //string connectionString; connectionString = ""; connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC"; string query = "delete from customer " + "where cust_id=@CustomerID"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@CustomerID", CustomerID); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } /*--------------------------------------------------------------------------------------------------------*/ private string Filechecker() { try { string UpPath = Server.MapPath("~/App_Data/Excel_File/"); //the directory you want the file uploaded to //create directory if it doesn''t already exist if (!Directory.Exists(UpPath)) Directory.CreateDirectory(UpPath.Replace("\\", "\\\\")); string FileName = FileUpload1.PostedFile.FileName; string FileType = FileUpload1.PostedFile.ContentType; string FileSize = FileUpload1.PostedFile.ContentLength.ToString(); string ClientFile = System.IO.Path.GetFileName(FileName); FileInfo ServerFile = new FileInfo(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile); int idx = 1; //increment a number on the end of the filename until it is unique to stop files being overwritten //will cope with filenames with multiple dots (eg. sunset.photo.12.jpg) while (ServerFile.Exists) { string[] filename = ClientFile.Split(''.''); ClientFile = ""; int prevIdx = idx - 1; if (idx > 1) { for (int i = 0; i < filename.GetUpperBound(0); i++) { ClientFile += filename[i]; if (i < filename.GetUpperBound(0) - 1) ClientFile += "."; } ClientFile = ClientFile.Substring(0, ClientFile.Length - prevIdx.ToString().Length) + idx.ToString() + "." + filename[filename.GetUpperBound(0)]; } else { for (int i = 0; i < filename.GetUpperBound(0); i++) { ClientFile += filename[i]; if (i < filename.GetUpperBound(0) - 1) ClientFile += "."; } ClientFile += idx.ToString() + "." + filename[filename.GetUpperBound(0)]; } ServerFile = new FileInfo(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile); idx++; } //save file to server FileUpload1.PostedFile.SaveAs(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile); return ClientFile; } catch (Exception ex) { throw ex; } } protected void btnExport_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition","attachment;filename=FileName.xls"); Response.Charset = ""; // If you want the option to open the Excel file without saving than // comment out the line below // Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); // turn off paging GridView1.AllowPaging = false; //BindData(); if (this.txtSearch.Text == "") { BindData(); } else { SearchText(); } GridView1.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); // turn the paging on again GridView1.AllowPaging = true; //BindData(); if (this.txtSearch.Text == "") { BindData(); } else { SearchText(); } } public override void VerifyRenderingInServerForm(Control control) { //this.VerifyRenderingInServerForm(this.GridView1); } protected void txtSearch_TextChanged(object sender, EventArgs e) { SearchText(); } private void SearchText() { string strQuery = "select customer.cust_id,customer.cust_name," + "customer.cust_address,customer.date_of_sale," + "tbl_state.state_name" + " from customer, tbl_state where" + " customer.cust_state=tbl_state.state_id And tbl_state.state_name=''" + this.txtSearch.Text + "''"; SqlCommand cmd = new SqlCommand(strQuery); //Page.Response.Write(strQuery); GridView1.DataSource = GetData(cmd); GridView1.DataBind(); } }
NUnitAsp is a tool for automatically testing ASP.NET web pages. [^]-It’’s an extension to NUnit, a tool for test-driven development in .NET.
NUnitAsp tutorial[^]
Unit Testing and Integration Testing in Business Applications[^]
Mock objects and testing code which uses the database[^]
Unit testing enumerations which map to a database table[^]
Data driven test cases in NUnit[^]
Approach to unit testing of .NET database applications with NDbUnit and XPath queries[^]
12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage)[^]
Unit Testing Database Library[^]
NUnitAsp is a tool for automatically testing ASP.NET web pages. [^]-It''s an extension to NUnit, a tool for test-driven development in .NET.
NUnitAsp tutorial[^]
Unit Testing and Integration Testing in Business Applications[^]
Mock objects and testing code which uses the database[^]
Unit testing enumerations which map to a database table[^]
Data driven test cases in NUnit[^]
Approach to unit testing of .NET database applications with NDbUnit and XPath queries[^]
12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage)[^]
Unit Testing Database Library[^]
这篇关于进行NUnit测试我的网站。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!