ASP.NET 遗漏点(迭代器、验证控件、DataReader、SqlParameter、DataTable 、事务、状态管理、两种验证模型)

1、迭代器的使用
public class DaysofTheWeek:System.Collections.IEnumerable
{
//定义一周7天
string[] m_Days={"Sun","Mon","Tue","Wed","Thr","Fri","Sat"};
//定义迭代器返回内容
public System.Collections.IEnumerator GetEnumerator()
{
for(int i=0;i<my_Days.Length;i++)
{
yield return m_Days[i];//返回元素值
}
}
}

protected void Page_Load(object sender,EventArgs e)
{
//创建类的一个对象
DaysOfTheWeek week=new DaysOfTheWeek();
//用foreach遍历并输出结果
foreach(string day in week)
{
Console.Write(day+" ");
}
}

2、6个验证控件RequiredFieldValidator

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequedFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrotMessage="必须输入内容">


CompareValidator
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1" ControlToValidate="TextBox2" ErroMessage="两个密码不相同">
</asp:CompareValidator>

3、DataReader类读取数据
Protected static SqlDataReader sdr;
SqlConnection conn=new SqlConnection();
conn.ConnectionString=ConfigrationManager.ConnectionStrings["connectionstrig"].ToString();
conn.open();
SqlCommand cmd=new SqlCommand();
comd.Connection=conn;
cmd.CommandText="Select * form Works";
sdr=cmd.ExecuteReader();//返回数据集
Response.Write(sdr.FieldCount.ToString());//显示字段数
if(sdr.HasRows)
Response.Write("有记录");
else
Response.Write("无记录");
string str="";
while(sdr.Read())
{
str=sdr.GetString(0)+","+sdr.GetString(1);
}
sdr.Close();
Response.Write(str);//显示结果

4、SqlParameter表示一个参数,默认情况下是input函数,表示的事输入的参数,就是从程序中读取的参数,还有输出参数,具体哪一个还需要通过SqlParameters的属性Direcion属性来表示,三种类型参数主要有Input,InputOutput,ReturnValue
//默认打开的连接名为Connection,testproc
SqlCommand command=new SqlCommand("testoroc",connection);
command.CommandType=CommandType.StoredProcedure;//命令类型是存储过程
SqlParameter parameter=command.Parameters.Add("RRTURU_VALUE"),SqlDbType.Int);
//设置存储过程的参数
parameter.Direction=ParameterDirection.ReturnValue;//指定参数类型

parameter=command.Parameters.Add("@InputParm",SqlDbType.NVarChar,12);\创建一个输入参数
parameter.Value="Test Value";\指定参数的值

parameter=command.Parameters.Add("@OutputParm",SqlDbType.NVarChar,28);
parameter.Direction=ParameerDirection.OutPut;\指定参数类型为输出参数
connecion.open();
SqlDataReader reader=command.ExecuteReader();\执行获取数据集的命令
reader.close();//关闭打开的阅读器
Response.Write(command.Parameters["@OutputParm"].value);//输出参数和RetrunValue的值
Response.Write(command.Parameters["RETURN_VALUE"].value);
5、适配器表示一组SQL命令和一个数据库连接,用于填充DataSet数据集合更新数据源,用作DataSet和数据源之间的桥接器,DataAdapter通过映射Fill和Update这两个方法来提供这桥接器。
string conn="DataSource=.;Initial Catalog=Nothwind;Itergrated Security=True"
string sqlstr="Select * from Catagories";
//利用构造函数,创建DataAdapter
SqlDataAdapter da=new SqlDataAdapter(sqlStr,conn);
DataSet ds=new DataSet();
Da.Fill(ds,"Catagories");
//以下代码将更新到DataSet里的数据
//在DataSet里的名为"Catagories"的DataTable中添加一个用于描述行记录的DataRow对象
DataRow dr=ds.Tables["Categories"].NewRow();
//通过DataRow对象添加一条记录
dr["CategoryName"]="计算机分类";
dr["Description"]="从计算机分类里单独列出来的一个分支";
ds.Table["Categories"].Rows.Add(dr);
//更新到数据库里
SqlCommandBuilder scb=new SqlCommandBuilder(da);
da.Update(ds,"Categories");
6、DataTable workTable=new DataTable("Works");
DataColumn workCol=workTable.Columns.Add("CustID",typeof(Int32));
workCol.AllowDBNull=false;
workCol.Unique=ture;
//添加一列内容
WorkTable.Columns.Add("CustLName",typeof(String));
或者
workTable.Rows.Add(new object[]{1,"Smith","Right",600});
workTable.Rows.Add(new objext[]{1,"Tomas","Edison",900});
7、事务是一个整体操作,共封装了多个操作,一个操作执行不成功,则其他所有的操作都不成功
using(SqlConnection conn=new SqlConnection(connectionString))
{
conn.open();
SqlCommand cmd=connection.CreateCommand();
SqlTransaction trans;
//开始一个本地的事务
trans=connection.BeginTransaction("SampleTransaction");
cmd.Connection=conn;
cmd.Transaction=trans;
try
{
//第一个操作,更新数据
cmd.CommandText="Update moneytable set money=money-200";
cmd.ExecuteNonQuery();
//第二个操作,插入数据
cmd.CommandText="Insert into moneyhistory values('name',200,'2006-07-04')";
cmd.ExecuteNonQuery();
trans.Commit();
Response.Write("两条语句都执行完毕");
}
catch(Exception ex)
{
Response.Write("提交错误类型:{0}".ex.GetType());
Response.Write("出错信息:{0}",ex.Message);
try
{
trans.Rollback();
}
catch(Exception ex2)
{
Response.Write("提交错误类型:{0}".ex.GetType());
Response.Write("出错信息:{0}",ex.Message);
}
}

}
--------------------------------------------------------------------------------------
8、只能对数据控件内的绑定使用Eval()方法
当数据可以被修改时还是要使用Bind()方法绑定,一般在数据控件的EditItemTemplate模板和InsertItemTemplate模板中要使用Bind()函数
--------------------------------------------------------------------------------------
9、ASP.NET的状态管理
Cookie与Session对象类似,Session对象的所有信息保存在服务器上,而Cookie对象的所有信息保存在客户机上。
//传给下个页面这个值
Response.Redirect("Update.aspx?id=" + Convert.ToInt32(e.CommandArgument) + "");
获取从页面传来的值Request.QueryString["user"];
------------------------------------------------------------Cookie的使用
///写入Cookie
protected void btnWrite_Click(object sender,EventAgrs e)
{
HttpCookies CookieTest=new HttpCookie("Password");
CookieTest.value="TestCookieValue";//设置Cookie值
Response.Write("<p>Cookie已成功写入");
}
//读取Cookie
protected void btnRead_Click(object sender,EventArgs e)
{
string Cookie=Request.Cookies["Password"].Value.ToString();
Response.Write("<p>读出Cookie的值:");
Response.Write("<h3>"+Cookie+"</h3>");
}
------------------------------------------------
if(Session["test"]!=null)
{
Response.Write(Session["test"].ToString());
}//在另一个页面里也可以用
--------------------------------------------------
要使用回话状态的事件处理程序,可以在Global.asax中添加一个名为Application_Start()和Application_End()事件处理程序,来对回话状态进行管理
void Application_Start(object sender,EventArgs e)
{
//当应用程序启动时运行的代码
}
void Application_End(object sender,EventArgs e)
{
//当应用程序关闭时运行的代码
}
还可以在Web应用程序的Global.asax文件中,以直接声明的方式向StaticObjects集合中添加对象
<object runat="server" scope="application" ID="MyApp" PROGID="MyApp.wyf"></object>
然后就可以在应用程序的任何地方通过代码对所定义的应用程序状态访问
Label1.Text=MyApp.Title;

Application["属性名"]存取公用数据,例如访问人数,网页计数器等不随用户变化的数据。

10、两种验证模型:身份验证和授权验证
有些用户可以看到工资单,有的用户看不到。
配置身份验证属性
<authentication mode="Forms">//基于窗体的
<forms name=".ASPXAUTH" loginUrl="default.aspx" protection="All" timeout="30"
path="/"//默认路径
requireSSL="false"
slidingExpiration="UseDeciceProfile" domain=""
enableCrossAppRedirects="false"/>
<credentials passwordFormat="SHAI"/>//密码的加密方式
</forms>
<passport redirectUrl="internal"/>
</authentication>

11、应用表单验证
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms"/>//将网页的验证模式设置为表单验证
<comlication debug="true">//将程序运行模式设置为调试模式
</system.web>
</configurarion>

12、窗口验证
<Configuration>
<system.web>
<authentication mode="Windows">//设置验证模式为表单验证模式
<comlication debug="true">//将程序运行模式设置为调试模式
</system.web>
</Configuration>

protected void Page_load(object sender,EventArgs e)
{
if(User.IsInRole("Administrators"))
{
Response.Write("您具备管理员的资格!<br/>");
Response.Write("您的登录名为:"+User.Identity.Name);
}
}
13、不止一个应用程序要在一台计算机上使用基于窗体的身份验证服务,每个应用程序应配置唯一的Cookie值,ASP.NET在设置身份验证时,将/用作path值,使Cookies被送回站点的每个应用程序上

原文地址:https://www.cnblogs.com/d685600/p/3650354.html