圣殿祭司的ASP.NET 2.0开发详解

【书名    】:圣殿祭司的ASP.NET 2.0开发详解
【出版社  】:电子工业出版社
【作者    】:奚江华
【评价    】:★★★★★★★☆☆☆
【正文    】:

----------------------------------------------------------------------------------------------------
0001:
    如何固定ASP.NET 2.0Web服务器端口:
    ●项目-属性-Web
    ●特定端口:8080,这样每次启动的时候都使用8080这个端口
----------------------------------------------------------------------------------------------------
0002:
    网站数据库的注册:aspnet_regsql -S smartkernel-PC/SQLSERVER2005 -U sa -P sa -d aspnetdb -A all
----------------------------------------------------------------------------------------------------
0003:
    数据库连接字符串的读取:
    Web.config文件:
    <connectionStrings>
        <add name="SQLCONN" connectionString="Server=smartkernel-PC/SQLSERVER2005;DataBase=aspnetdb;uid=sa;pwd=sa"/>
    </connectionStrings>

    读取代码:string sqlconn = ConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString;
----------------------------------------------------------------------------------------------------
0004:
    Web.config中的数据库连接字符串,可以使用aspnet_regiis命令来加密。加密之后的数据库连接字符串的读取
部分不用修改。注意,网站如果不在默认的C:/Inetpub/wwwroot目录中就会一直提示路径错误。
----------------------------------------------------------------------------------------------------
0005:
    当使用VS2005来开发ASP.NET应用程序时,之所以将许多文件放在特殊文件夹下,是因为安全性的考虑。凡是存
放在这些特殊文件夹中的文件,对于网页的Request则都不会响应。
    ●App_Browsers:包含浏览器定义,ASP.NET会使用这些文件来辨别浏览器及浏览器的能力。
    ●App_Code:程序源代码。在动态编译的应用程序中,ASP.NET会在应用程序发出初试要求时,编译App_Code文
件夹中的程序代码。检测到任何变更时,就会重新编译这个文件夹中的项目。
    ●App_Data:包含应用程序数据文件,这包括MDF文件、XML文件和其他数据存储区文件。ASP.NET 2.0会使用App_Data
文件夹存放应用程序的本地数据库,这个数据库可用来维护成员资格和角色信息。
    ●App_GlobalResources:包含资源文件,这些资源文件会编译成具有全局范围的组件。其中的资源是强类型的,
并且可用程序设计的方式存取。
    ●App_LocalResources:包含资源文件,这些资源会与特定的页面、用户控件或应用程序的母板页相关联。
    ●App_Themes:包含文件集合,可定义ASP.NET网页和控件的外观。
    ●App_WebReferences:包含.wsdl、.xsd、.disco等文件。
    ●Bin:包含控件、组件或要在应用程序中引用其他程序代码的已编译组件。
    ASP.NET会针对这些特殊目录编译成一个独立的.dll组件,也就是有几个特殊目录就会有几个组件。
----------------------------------------------------------------------------------------------------
0006:
    预先编译不但连程序代码都可以编译进去,甚至连.aspx网页中HTML标签也可以一并编译进去,对于程序代码的
保护可以说就此多了一层保障与选择。可以使用aspnet_compiler命令。如果新建的是网站模式,还可以使用“发布
网站”命令生成预编译的文件。
----------------------------------------------------------------------------------------------------
0007:
    跨网页POST:
    WebForm1.aspx文件:
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/WebForm2.aspx"/>

    WebForm2.aspx文件:
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox aTextBox = (TextBox)PreviousPage.FindControl("TextBox1");
        this.Response.Write(aTextBox.Text);
    }
    PreviousPage本身属于Page类型,并只有在来源网页和目标网页属于相同的ASP.NET应用程序中,目标网页的
PreviousPage属性才会包含来源网页的引用;如果网页不是跨网页POST的目标,或者网页在不同的应用程序中,就
不会初始化PreviousPage属性。因此,在获取PreviousPage引用之前,应该先检查其可用性。
    跨网页发布只能用在Button类型的控件中。经常用来传递参数,当参数非常多的时候,使用跨网页POST,比使
用URL传递参数要简洁的多。
----------------------------------------------------------------------------------------------------
0008:
    使用@PreviousPageType指令实现强类型的跨网页POST:在一个网页中只能有一个@PreviousPageType指令。
    WebForm1.aspx文件:
    //源网页的一个属性
    public DateTime MyDateTime
    {
        get { return DateTime.Now; }
    }

    WebForm2.aspx文件:
    <%@ PreviousPageType VirtualPath="~/WebForm1.aspx" %>
    protected void Page_Load(object sender, EventArgs e)
    {
        //可以直接读取源网页对象的这个属性,必须是公有的
        this.Response.Write(PreviousPage.MyDateTime.ToLongTimeString());
    }
----------------------------------------------------------------------------------------------------
0009:
    使用@Reference指令实现跨网页POST:在一个网页中可以使用多个@Reference指令。
    WebForm1.aspx文件:
    //源网页的一个属性
    public DateTime MyDateTime
    {
        get { return DateTime.Now; }
    }

    WebForm2.aspx文件:
    <%@ Reference VirtualPath="~/WebForm1.aspx" %>
    protected void Page_Load(object sender, EventArgs e)
    {
        //可以先声明一个源网页的对象 
        WebForm1 aWebForm2 = (WebForm1)PreviousPage;
        //可以直接读取源网页对象的这个属性,必须是公有的
        this.Response.Write(aWebForm2.MyDateTime.ToLongTimeString());
    }
----------------------------------------------------------------------------------------------------
0010:
    判断是否是跨网页POST的方法:在目标网页中可以添加下面的判断逻辑
    if (this.PreviousPage != null && this.PreviousPage.IsCrossPagePostBack == true)
    {

    }
----------------------------------------------------------------------------------------------------
0011:
    跨网页POST的原理:
    ●跨网页POST是通过Button按钮的PostBackUrl属性实现的。在用户按下按钮之后才会提交跨网页POST。
    ●目标网页将源网页的ViewState另外储存一份后,随即删除源网页的ViewState。
    ●当在目标网页使用到PreviousPage对象时,系统会自动初始化与来源网页同一类型的Page,并且在目标网页
的Load_Complete阶段将原先所储存保留下来的ViewState还原到PreviousPage。
    ●而PreviousPage表示一个与来源网页相同新生的实体,并且注入了原先所保存的ViewState状态,所以这就是
为什么在目标网页中可以访问到来源网页控件或值的原因。

    注意,保存源网页的ViewState并且再恢复是个比较耗费资源的操作。所以应该权衡使用。
----------------------------------------------------------------------------------------------------
0012:
    HtmlHead类:设置样式的实现
    protected void Button1_Click(object sender, EventArgs e)
    {
        Style bodyStyle = new Style();
        bodyStyle.BackColor = System.Drawing.Color.Gray;
        this.Page.Header.StyleSheet.CreateStyleRule(bodyStyle,null,"body");
        this.Page.Header.Title = "测试应用程序";
    }
----------------------------------------------------------------------------------------------------
0013:
    设置焦点的方法:this.Page.SetFocus(this.Button1);//或者this.Button1.Focus();
----------------------------------------------------------------------------------------------------
0014:
    默认按钮的实现:
    <form id="form1" runat="server" defaultbutton="Button2">
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button"/>
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button"/>
    </form>
    注意,默认按钮只能是按钮,而设置焦点没有这个限制
----------------------------------------------------------------------------------------------------
0015:
    动态注册JavaScript脚本文件:
    HTML部分:<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Show('你好')"/>
    代码部分:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "MessageBox") == false)
        {
            this.Page.ClientScript.RegisterClientScriptInclude("MessageBox", "./MessageBox.js");
        }
    }
----------------------------------------------------------------------------------------------------
0016:
    动态注册JavaScript脚本块:
    HTML部分:<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Show('你好')"/>
    代码部分:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "MessageBox") == false)
        {
            string script =
                            "<script type='text/javascript'>" +
                            "function Show(msg)" +
                            "{" +
                            "   alert(msg);" +
                            "}" +
                            "</script>";
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MessageBox", script);
        }
    }
----------------------------------------------------------------------------------------------------
0017:
    异步调用:
    HTML部分:
    <form id="form1" runat="server">
        <script type="text/javascript">
        //客户端直接调用的客户端方法
        function search()
        {
            var TextBox1 = document.getElementById("TextBox1");
            getServerData(TextBox1.value,"");
        }
        //处理服务器返回的数据
        function handlerServerData(msg)
        {
            var Div1 = document.getElementById("Div1");
            Div1.innerText = msg;
        }
        </script>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="button" οnclick="javascript:search();"/>   
        <div id="Div1"></div>
    </form>

    代码部分:
    public partial class WebForm1 : System.Web.UI.Page,ICallbackEventHandler
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "getServerData") == false)
            {
                string handlerServerDataReference = this.Page.ClientScript.GetCallbackEventReference(this, "arg", "handlerServerData", "context");
                string getServerDataScript =
                                                "function getServerData(arg,context)" +
                                                "{" +
                                                    handlerServerDataReference +
                                                "}";
                this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "getServerData", getServerDataScript, true);
            }
        }
        private string msg = "";
        //将服务器的数据传递给客户端
        public string GetCallbackResult()
        {
            return this.msg;
        }
        //服务器处理客户端的异步调用,参数eventArgument是callServer客户端函数的arg参数
        public void RaiseCallbackEvent(string eventArgument)
        {
            if (eventArgument != null)
            {
                System.Threading.Thread.Sleep(3000);
                this.msg = "参数是:" + eventArgument;
            }
        }
    }
----------------------------------------------------------------------------------------------------
0018:
    时钟的实现:基于Atlas
    HTML部分:
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Image ID="Image1" runat="server" />
            <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
            </asp:Timer>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
        </Triggers>
    </asp:UpdatePanel>

    代码部分:
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        this.Image1.ImageUrl = "GetTimeHandler.ashx";
    }

    GetTimeHandler.ashx文件:
    public void ProcessRequest(HttpContext context)
    {
        Bitmap image = new Bitmap(500,100);
        Graphics g = Graphics.FromImage(image);
        SolidBrush pen = new SolidBrush(Color.White);
        g.FillRectangle(pen,0,0,500,800);
        Array array = Enum.GetValues(typeof(System.Drawing.Drawing2D.HatchStyle));
        int i = (new Random()).Next(array.Length);
        HatchStyle style = (HatchStyle)array.GetValue(i);
        HatchBrush brush = new HatchBrush(style,Color.White,Color.Black);
        g.DrawString(DateTime.Now.ToLongTimeString(),new Font("Arial Black",48),brush,0,0);
        MemoryStream ms = new MemoryStream();
        image.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
        byte[] buffer = new byte[ms.Length];
        ms.Seek(0,SeekOrigin.Begin);
        ms.Read(buffer,0,(int)ms.Length);
        ms.Close();
        context.Response.OutputStream.Write(buffer,0,buffer.Length);
        context.Response.OutputStream.Close();
        buffer = null;
        image.Dispose();
        g.Dispose();
    }
----------------------------------------------------------------------------------------------------
0019:
    UpdatePanel控件:
    ●Mode属性:有Always和Conditional两种。Always是每次Postback后,UpdatePanel会连带被更新。相反,Conditional
只针对特定情况才会被更新。如果一个网页上有多个UpdatePanel,那么防止其他UpdatePanel提交更新时,其也提
交,需要将其Mode属性设置为Conditional。
    ●Triggers:是设置UpdatePanel的触发事件。Trigger为要监视的事件,当然可以添加多个监视的事件。
----------------------------------------------------------------------------------------------------
0020:
    数据源控件绑定到数据库连接字符串的方法:<%$ ConnectionStrings:SQLCONN %>这个语法可以绑定到配置文
件的数据库连接字符串节点。
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQLCONN %>"></asp:SqlDataSource>
----------------------------------------------------------------------------------------------------
0021:
    GridView控件的常用属性:
    ●BackImageUrl;//背景图片
    ●EmptyDataText;//没有任何数据时显示的文字
    ●GridLines;//网格线的样式
    ●ShowHeader;//是否显示页首
    ●ShowFooter;//是否显示页尾
    ●AllowSorting;//是否允许排序
    ●AutoGenerateColumns;//是否自动产生数据列,自动绑定数据源中存在的列
    ●AutoGenerateDeleteButton;//是否自动产生删除按钮
    ●AutoGenerateEditButton;//是否自动产生编辑按钮
    ●AutoGenerateSelectButton;//是否自动产生选择按钮
    ●EnableSortingAndPagingCallbacks;//是否启用排序和分页的异步支持
    ●EnableTheming;//是否启用主题
    ●EnableViewState;//是否启用ViewState状态
    ●DataKeyNames;//主键值的字段名称,是string[]数据类型
    ●DataMember;//绑定的数据源清单
    ●DataSourceID;//数据源控件的ID
    ●Caption;//设置标题文字
    ●CaptionAlign;//标题文字的对齐方式
    ●AlternatingRowStyle;//设置交换数据行的外观
    ●EditRowStyle;//设置编辑模式下数据行的外观
    ●EmptyDataRowStyle;//设置空数据行的外观
    ●FooterStyle;//设置页尾数据行的外观
    ●HeaderStyle;//设置页首数据行的外观
    ●PagerStyle;//设置页面导航栏的外观
    ●RowStyle;//设置数据行的外观
    ●SelectedRowStyle;//设置已选择数据行的外观
----------------------------------------------------------------------------------------------------
0022:
    一定要了解新技术的架构和底层运作的原理才能真正的得心应手。
----------------------------------------------------------------------------------------------------
0023:
    GridView控件的DataSourceID和DataSource属性:注意,不可以同时使用两个属性来设置数据源
    ●DataSourceID:这个属性是专门搭配ASP.NET 2.0的DataSource控件的。若GridView以DataSourceID指定DataSource
控件就能够享有内置的分页、排序、更新、删除,一行程序都不必写,甚至连DataBind()都不用调用。应该优先使
用这个属性。
    ●DataSource:这是以前就存在的属性,若GridView使用这个属性来绑定数据,那就必须调用DataBind(),且
不能获得内置的分页、排序、更新、删除等支持。
----------------------------------------------------------------------------------------------------
0024:
    GridView列的类型:
    ●BoundField(数据绑定列):将DataSource数据源的字段数据以文本方式显示。
    ●ButtonFiled(按钮列):在数据绑定控件中显示命令按钮。根据控件的不同,它可让您显示具有自定义按钮
按钮(如:添加、删除等)的数据列,按下时会引发RowCommand事件。
    ●CommandFiled(命令列):显示含有命令的Button按钮,包括了Select、Edit、Update、Delete命令按钮。
    ●CheckBoxField(CheckBox列):通常用于布尔值的显示。
    ●HperLinkField(超级连接列):将DataSource数据源字段数据显示成超级连接,并可指定另外的NavigateUrl
超级连接。
    ●ImageField(图像列):在数据绑定控件中显示图像字段。
    ●TemplateField(模版列):显示用户自定义的模版内容。
----------------------------------------------------------------------------------------------------
0025:
    当GridView不是使用自动产生列的方式绑定的话,排序功能必须指定排序列的排序表达式才能正常工作。例如,
使用BoundField绑定到了一个数据表的City列,那么这个列的SortExpression属性也应该设置为City。这样,这个
列就会根据City列来排序。
----------------------------------------------------------------------------------------------------
0026:
    标准数值格式化字符串:
    ●{0:C2}:显示货币符号格式
    ●{0:D}:显示十进制格式,限用于整数
    ●{0:E2}:显示科学符号格式
    ●{0:F4}:显示固定小数位数格式
    ●{0:N3}:显示有逗号固定小数格式
    ●{0:P}:显示百分比格式
    ●{0:X}:显示十六进制格式
    ●{0:00####.00}:显示自定义的数字格式

    格式转化的用法:在数据绑定的时候,也可以用(GridView)
    double i = 2008.8;
    this.Response.Write(string.Format("{0:####.##00}",i));
----------------------------------------------------------------------------------------------------
0027:
    GridView的BoundField字段的格式化必须将“HtmlEncode”属性设置为false(默认为true),否则格式化不会
起作用。但是HtmlEncode设置为true,可以防止恶意的客户端脚本破坏ASP.NET系统。
----------------------------------------------------------------------------------------------------
0028:
    ButtonField绑定列的常用属性:
    ●ButtonType:支持三种按钮型式Button、Image、Link
    ●DataTextField:将数据源字段数据绑定到Button按钮的文本属性中
    ●DataTextFormatString:将DataTextField数据源字段值加以格式化
    ●ImageUrl:当按钮是Image时,指定Image所在的Url
    ●CauseValidation:按下按钮时是否会引发Validation控件验证
    ●CommandName:按下ButtonField按钮时所要运行的命令名称
    ●ValidationGroup:ButtonField按钮所要引发的ValidationGroup名称

    ●当ButtonField按钮字段被按下时,GridView会引发RowCommand事件,而DetailsView控件会引发ItemCommand
事件。
    ●若要判断引发命令事件之数据行的索引,可以使用事件自变量的CommandArgument属性,会将该事件自变量传
递至数据绑定控件的命令事件,ButtonField类会自动用适当的索引值填入CommandArgument属性。
    ●使用Text属性设置按钮的文本,则整个一列的显示都是相同的文本。
    ●如果设置绑定按钮的DataTextField属性为绑定的数据源列,则按钮的文本就是数据源中的内容。
----------------------------------------------------------------------------------------------------
0029:
    ButtonField的用法:
    HTML部分:
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:BoundField HeaderText="名称" DataField="Name"/>
            <asp:ButtonField ButtonType="Button" Text="显示" CommandName="Button"/>
        </Columns>
    </asp:GridView>

    代码部分:
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //只有CommandName为Button时才处理,对于其他的命令不处理,例如分页。分页为Page
        if (e.CommandName == "Button")
        {
            //获得行的索引
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow selectRow = this.GridView1.Rows[index];
            TableCell nameCell = selectRow.Cells[0];
            this.Response.Write(nameCell.Text);
        }
    }
----------------------------------------------------------------------------------------------------
0030:
    ButtonField列如果的DataTextField如果绑定到数据源列,则按钮的宽度会随着数据源中字符的长短而有变化,
如果想固定这个宽度,可以设置ControlStyle的Width为一个固定值。
----------------------------------------------------------------------------------------------------
0031:
    CommandField列:用来显示预先定义好的按钮来运行Select、Edit、Update、Delete与Insert的命令。外观上
CommandField很像ButtonField。ButtonField只是单纯的按钮,不具备内置命令的功能,所以必须自行撰写相关程
序,而CommandField内置的命令字段可以省掉不少代码。若GridView能支持编辑、删除与更新作用,必须将SqlDataSource
的UpdateCommand、DeleteCommand、InsertCommand设置相应的命令。
----------------------------------------------------------------------------------------------------
0032:
    向页面中添加消息提示信息:
    Literal msg = new Literal();
    msg.Text = "<script type=text/javascript>alert('消息');</script>";
    Page.Controls.Add(msg);
----------------------------------------------------------------------------------------------------
0033:
    如果GridView的数据行很多,那么会遇到一个问题,无论单击选取、编辑还是删除按钮,网页PostBack后,界
面会进行刷新。通常会回到浏览器的最顶端。ASP.NET 2.0增加了一个功能,就是可以设置页面刷新后还显示在原来
的位置:<%@ Page Language="C#" MaintainScrollPositionOnPostback="true" %>
----------------------------------------------------------------------------------------------------
0034:
    CheckBoxField复选框列:经常用来显示布尔值,在显示状态下,默认是Disabled的。只有在编辑模式下,才能
进行修改。如果数据库中表的列的数据为字符串类型,那么可以直接存入'true','false'。这样在绑定的时候,会
自动进行匹配。如果不是,还需要在获得数据的时候转换为true和false字符串列。
----------------------------------------------------------------------------------------------------
0035:
    HyperLinkField列常用属性:
    ●DataTextField:绑定数据源字段显示成超连接文字
    ●DataNavigateUrlFields:将数据字段绑定到超连接的Url属性。可以设置多个值。

    下面给出一个例子:
    ●HeaderText:产品明细
    ●Text:详细
    ●DataNavigateUrlFields:ProductID,PersonID
    ●DataNavigateUrlFormatString:ProductDetails.aspx?ProductID={0}&PersonID={1}
    ●DataTextField:ProductName
    ●DataTextFormatString:查看{0}的明细
----------------------------------------------------------------------------------------------------
0036:
    当GridView所预定的几种字段都无法满足需求的时候,就可以使用TemplateField。TemplateField模版字段类
型:
    ●ItemTemplate:字段项目模版
    ●AlternatingItemTemplate:字段间隔项目模版,若设置这个字段后,奇数行会显示ItemTemplate,偶数行显
示AlternatingItemTemplate。
    ●EditItemTemplate:编辑模式模版
    ●HeaderTemplate:表头模版
    ●FooterTemplate:表尾模版
----------------------------------------------------------------------------------------------------
0037:
    模版列的使用:
    HTML部分:
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:TemplateField HeaderText="姓名">
                <ItemTemplate>
                    <asp:Label BackColor="DarkOrange" ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                </ItemTemplate>
                <AlternatingItemTemplate>
                    <asp:Label BackColor="gray" ID="Label2" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                </AlternatingItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="Button1" runat="server" CommandName="DeleteCommand"  CommandArgument ='<%#Eval("Name") %>' Text="删除" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

    代码部分:
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteCommand")
        {
            this.Response.Write(e.CommandArgument.ToString());
        }
    }
----------------------------------------------------------------------------------------------------
0038:
    Eval和Bind的关系:它们的作用都是作为数据绑定的语法,Eval是单向只读的,而Bind是双向可更新的。例如:
    <asp:TextBox ID="TextBox1" runat="server" Text='<%#Bind("Name") %>'>'></asp:TextBox>
----------------------------------------------------------------------------------------------------
0039:
    GridView中的删除确认功能的实现:
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="Button1" runat="server" CommandName="DeleteCommand" OnClientClick="JavaScript:return confirm('确认删除么?');" CommandArgument ='<%#Eval("Name") %>' Text="删除" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
----------------------------------------------------------------------------------------------------
0040:
    GridView的默认AJAX功能有个缺陷,首先是这个功能只支持分页和排序,对编辑、选择、删除或更新等等的操
作没有作用;其次,如果使用了AJAX,就不支持DataView了。
----------------------------------------------------------------------------------------------------
0041:
    GridView现在可以只专心于数据的显示,而将真正的数据访问Select、Insert、Update和Delete等操作全部委
托给SqlDataSource等数据源控件处理。
----------------------------------------------------------------------------------------------------
0042:
    GridView的事件:
    ●DataBinding:在服务器控件绑定至数据源时发生。
    ●DataBound:在服务器控件绑定至数据源后发生。
    ●PageIndexChanged:在GridView分页完成后发生。
    ●PageIndexChanging:在GridView进行分页前发生。
    ●RowCancelingEdit:在数据行按下取消按钮结束编辑模式前发生。
    ●RowCommand:按下GridVIew控件中的Button按钮时发生。
    ●RowCreated:创建GridView控件中的数据行时发生。
    ●RowDataBound:数据行绑定至GridView控件中的数据时发生。
    ●RowDeleted:在GridView控件删除数据行后发生。
    ●RowDeleting:在GridView控件删除数据行前发生。
    ●RowEditing:在GridView进入编辑模式前发生。
    ●RowUpdated:在GridView控件更新数据行后发生。
    ●RowUpdating:在GridView控件更新数据行前发生。
    ●SelectIndexChanged:在GridView控件完成选取作业后发生。
    ●SelectIndexChanging:在GridView控件进行选取作业前发生。
    ●Sorted:在GridView控件完成排序作业后发生。
    ●Sorting:在GridView控件进行排序作业前发生。
----------------------------------------------------------------------------------------------------
0043:
    GridView鼠标滑过的光棒效果:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.IsPostBack == false)
        {
            ViewState["LINE"] = "奇数列";
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
            {
                e.Row.BackColor = System.Drawing.Color.FromArgb(153,0,0);
                e.Row.ForeColor = System.Drawing.Color.White;
                break;
            }
            case DataControlRowType.DataRow:
            {
                if (ViewState["LINE"].ToString() == "奇数列")
                {
                    e.Row.BackColor = System.Drawing.Color.FromArgb(255, 251, 214);
                    e.Row.Attributes.Add("onmouseout","this.style.backgroundColor='#FFFBD6';this.style.color='black'");
                    e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#C0C0FF';this.style.color='#FFFFFF'");
                    ViewState["LINE"] = "偶数列";
                }
                else
                {
                    e.Row.BackColor = System.Drawing.Color.White;
                    e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#C0C0FF';this.style.color='#FFFFFF'");
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF';this.style.color='black'");
                    ViewState["LINE"] = "奇数列";
                }
                break;
            }
            default:
                break;
        }
    }
----------------------------------------------------------------------------------------------------
0044:
    GridView可以设置标题:
    this.GridView1.Caption = "信息表";
    this.GridView1.CaptionAlign = TableCaptionAlign.Top;
----------------------------------------------------------------------------------------------------
0045:
    设置GridView的选择行颜色:
    if (this.IsPostBack == false)
    {
        this.GridView1.SelectedRowStyle.BackColor = System.Drawing.Color.FromArgb(230,230,230);
    }
----------------------------------------------------------------------------------------------------
0046:
    设置GridView的主键列:DataKeyNames="Name,Sex"
----------------------------------------------------------------------------------------------------
0047:
    多重表头的实现:
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //第一行表头
            TableCellCollection tcHeader = e.Row.Cells;
            tcHeader.Clear();//清除现有表头
            tcHeader.Add(new TableHeaderCell());//加入新的空表头单元格
            tcHeader[0].Attributes.Add("rowspan","3");//三行表头
            tcHeader[0].Attributes.Add("bgcolor", "LightCyan");
            tcHeader[0].Text = " ";
            tcHeader.Add(new TableHeaderCell());
            tcHeader[1].Attributes.Add("colspan","3");//跨越三列
            tcHeader[1].Text = "人员基本信息</th></tr></tr>";

            //第二行表头
            tcHeader.Add(new TableHeaderCell());
            tcHeader[2].Attributes.Add("bgcolor", "Gray");
            tcHeader[2].Text = "基本信息";
            tcHeader.Add(new TableHeaderCell());
            tcHeader[3].Attributes.Add("colspan", "2");//跨越二列
            tcHeader[3].Attributes.Add("bgcolor", "Blue");
            tcHeader[3].Text = "附加信息</th></tr></tr>";

            //第三行表头
            tcHeader.Add(new TableHeaderCell());
            tcHeader[4].Attributes.Add("bgcolor", "Red");
            tcHeader[4].Text = "姓名";
            tcHeader.Add(new TableHeaderCell());
            tcHeader[5].Attributes.Add("bgcolor", "Red");
            tcHeader[5].Text = "年龄";
            tcHeader.Add(new TableHeaderCell());
            tcHeader[6].Attributes.Add("bgcolor", "Red");
            tcHeader[6].Text = "性别";
        }
    }
----------------------------------------------------------------------------------------------------
0048:
    设置GridView表头的背景图片:
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection headerCells = e.Row.Cells;
            headerCells.Clear();
            TableHeaderCell headerCell = new TableHeaderCell();
            System.Web.UI.WebControls.Image headerImage = new Image();
            headerImage.ImageUrl = "~/image/HeaderBackground.jpg";
            headerCell.Controls.Add(headerImage);
            headerCells.Add(headerCell);
            headerCells[0].Attributes.Add("colspan","4");
        }
    }
----------------------------------------------------------------------------------------------------
0049:
    GridView使用ButtonField绑定列(注意,如果使用模版列中加入按钮,就获得不了行的索引)
    HTML部分:
    <asp:GridView ID="GridView1" runat="server" EmptyDataText="没有数据可以显示" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="姓名" />
            <asp:BoundField DataField="Age" HeaderText="年龄" />
            <asp:BoundField DataField="Sex" HeaderText="性别" />
            <asp:ButtonField ButtonType="Button" CommandName="BUTTONCLICK" Text="查看" />
        </Columns>
    </asp:GridView>

    代码部分:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.IsPostBack == false)
        {
            GridViewDataBind();
        }
    }
    private void GridViewDataBind()
    {
        SqlConnection aSqlConnection = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString);
        SqlCommand aSqlCommand = aSqlConnection.CreateCommand();
        aSqlCommand.CommandText = @"SELECT TOP 10 [Name],[Age],[Sex] FROM [Person]";
        SqlDataAdapter aSqlDataAdapter = new SqlDataAdapter(aSqlCommand);
        DataTable dt = new DataTable();
        aSqlDataAdapter.Fill(dt);
        this.GridView1.DataSource = dt;
        this.GridView1.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //获得单击所在的行
        int index = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "BUTTONCLICK")
        {
            GridViewRow aGridViewRow = this.GridView1.Rows[index];
            TableCell nameCell = aGridViewRow.Cells[0];
            this.Response.Write(nameCell.Text);
        }
    }
----------------------------------------------------------------------------------------------------
0050:
    模版列:注意,如果使用了模版列,就不能在GridView1_RowCommand中通过TableCell访问这个单元格了
    HTML部分:
    <asp:GridView ID="GridView1" runat="server" EmptyDataText="没有数据可以显示" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>姓名</HeaderTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:ButtonField ButtonType="Button" CommandName="BUTTONCLICK" Text="查看" />
        </Columns>
    </asp:GridView>
----------------------------------------------------------------------------------------------------
0051:
    可以通过这个语句设置GridView中字体的大小:this.GridView1.Font.Size = FontUnit.Small;
----------------------------------------------------------------------------------------------------
0052:
    直接声明字符串数组的方法:string[] strs = new string[] { "世界", "你好" };
----------------------------------------------------------------------------------------------------
0053:
    完全使用后台代码添加绑定列:
    BoundField nameField = new BoundField();
    nameField.DataField = "Name";
    nameField.HeaderText = "姓名";
    nameField.ItemStyle.Width = 100;

    ButtonField seeField = new ButtonField();
    seeField.ButtonType = ButtonType.Button;
    seeField.Text = "查看";
    seeField.CommandName = "BUTTONCLICK";
    seeField.ItemStyle.Width = 50;

    this.GridView1.Columns.Add(nameField);
    this.GridView1.Columns.Add(seeField);
----------------------------------------------------------------------------------------------------
0054:
    完全通过后台代码实现数据源控件:
    private SqlDataSource aSqlDataSource;
    protected void Page_Load(object sender, EventArgs e)
    {
        aSqlDataSource = new SqlDataSource();
        aSqlDataSource.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString;
        aSqlDataSource.SelectCommand = @"SELECT [Name],[Age],[Sex] FROM [Person]";
        aSqlDataSource.DataSourceMode = SqlDataSourceMode.DataSet;
        aSqlDataSource.ID = "MySqlDataSource";
        this.Page.Controls.Add(aSqlDataSource);
        this.GridView1.DataSourceID = aSqlDataSource.ID;
        this.GridView1.AllowPaging = true;
        this.GridView1.AutoGenerateColumns = true;
    }
----------------------------------------------------------------------------------------------------
0055:
    显示目前所在的页在整体的什么位置:
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string msg = "目前所在分页码:" + Convert.ToString(this.GridView1.PageIndex + 1) + "/" + this.GridView1.PageCount.ToString();
        this.Label1.Text = msg;
    }
----------------------------------------------------------------------------------------------------
0056:
    自定义的上一页、下一页翻页按钮:
        protected void Page_Load(object sender, EventArgs e)
        {
            this.GridView1.AllowPaging = true;
            //隐藏现在的分页样式
            this.GridView1.PagerSettings.Visible = false;

            LinkButton preButton = new LinkButton();
            preButton.Text = "上一页";
            preButton.ID = "preButton";

            preButton.Click += new EventHandler(preButton_Click);

            LinkButton nextButton = new LinkButton();
            nextButton.Text = "下一页";
            nextButton.ID = "nextButton";
            nextButton.Click += new EventHandler(nextButton_Click);

            //直接加到Page上是不行的
            this.PlaceHolder1.Controls.Add(preButton);
            this.PlaceHolder1.Controls.Add(nextButton);
        }
        private void preButton_Click(object sender, EventArgs e)
        {
            int i = this.GridView1.PageIndex - 1;
            if (i > 0)
            {
                this.GridView1.PageIndex = i;
            }
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            int i = this.GridView1.PageIndex + 1;
            if (i < this.GridView1.PageCount)
            {
                this.GridView1.PageIndex = i;
            }
        }
----------------------------------------------------------------------------------------------------
0057:
    排序事件的应用:根据升序和降序使用不同的效果
    protected void GridView1_Sorted(object sender, EventArgs e)
    {
        switch(this.GridView1.SortDirection)
        {
            case SortDirection.Ascending:
            {
                this.GridView1.BackColor = System.Drawing.Color.FromArgb(50,150,50);
                break;
            }
            case SortDirection.Descending:
            {
                this.GridView1.BackColor = System.Drawing.Color.FromArgb(150, 50, 150);
                break;
            }
            default:
                break;
        }
    }
----------------------------------------------------------------------------------------------------
0058:
    DetailsView控件的使用:在GridView中选择一条数据,则在DetailsView中显示这个数据的详细信息
    HTML部分:
    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" CellPadding="2">
        <Fields>
            <asp:BoundField DataField="Name" HeaderText="姓名" />
            <asp:BoundField DataField="Sex" HeaderText="性别" />
            <asp:BoundField DataField="Age" HeaderText="年龄" />
        </Fields>
    </asp:DetailsView>

    代码部分:
    private SqlDataSource aSqlDataSource;
    protected void Page_Load(object sender, EventArgs e)
    {
        aSqlDataSource = new SqlDataSource();
        aSqlDataSource.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString;
        aSqlDataSource.SelectCommand = @"SELECT [Name],[Age],[Sex] FROM [Person] WHERE [ID] = @ID";
        aSqlDataSource.ID = "aDetailsViewSqlDataSource";
        Parameter aParameter = new Parameter("ID");
        aSqlDataSource.SelectParameters.Add(aParameter);
        this.Page.Controls.Add(aSqlDataSource);
        this.DetailsView1.DataSourceID = aSqlDataSource.ID;
        this.GridView1.SelectedRowStyle.BackColor = System.Drawing.Color.FromArgb(200,200,200);
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        if (e.NewSelectedIndex >= 0)
        {
            aSqlDataSource.SelectParameters["ID"].DefaultValue = this.GridView1.Rows[e.NewSelectedIndex].Cells[0].Text;
           
            this.DetailsView1.Visible = true;
        }
        else
        {
            this.DetailsView1.Visible = false;
        }
    }
----------------------------------------------------------------------------------------------------
0059:
    代码实现的模版列绑定:
    public class RowTemplate:ITemplate
    {
        private DataControlRowType templateType;
        private string columnName;
        public RowTemplate(DataControlRowType templateType, string columnName)
        {
            this.templateType = templateType;
            this.columnName = columnName;
        }
        public void InstantiateIn(Control container)
        {
            if (this.templateType == DataControlRowType.DataRow)
            {
                TextBox aTextBox = new TextBox();
                aTextBox.DataBinding += new EventHandler(aTextBox_DataBinding);
                container.Controls.Add(aTextBox);
            }
        }
        private void aTextBox_DataBinding(object sender, EventArgs e)
        {
            TextBox aTextBox = (TextBox)sender;
            //获得包含这个控件的行
            GridViewRow row = (GridViewRow)aTextBox.NamingContainer;
            aTextBox.Text = DataBinder.Eval(row.DataItem, this.columnName).ToString();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        TemplateField nameField = new TemplateField();
        nameField.ItemTemplate = new RowTemplate(DataControlRowType.DataRow,"Name");
        this.GridView1.Columns.Add(nameField);
    }
    //列的标题需要在行创建的时候加上
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[6].Text = "姓名";
        }
    }
----------------------------------------------------------------------------------------------------
0060:
    数据源控件很大程度上是为了给初学者使用的,因为数据源控件丧失了对ADO.NET的完全掌控。有经验的程序员,
还是会自己来实现的。
----------------------------------------------------------------------------------------------------
0061:
    SqlDataSource支持很多种数据库类型,而不是只支持SQL Server。
----------------------------------------------------------------------------------------------------
0062:
    使用DataView作为数据源的实现:
    protected void Page_Load(object sender, EventArgs e)
    {
        string sqlConn = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString;
        SqlConnection aSqlConnection = new SqlConnection(sqlConn);
        SqlCommand aSqlCommand = aSqlConnection.CreateCommand();
        aSqlCommand.CommandText = @"SELECT * FROM [Person]";
        SqlDataAdapter aSqlDataAdapter = new SqlDataAdapter(aSqlCommand);
        DataTable dt = new DataTable();
        aSqlDataAdapter.Fill(dt);
        DataView dv = new DataView(dt);
        dv.RowFilter = "ID < 5";
        this.GridView1.DataSource = dv;
        this.GridView1.AutoGenerateColumns = true;
        this.GridView1.DataBind();
    }
----------------------------------------------------------------------------------------------------
0063:
    如果数据源控件的DataSourceMode模式设置为DataReader,则GridView将不支持分页和排序。
----------------------------------------------------------------------------------------------------
0064:
    .net的事务处理:
    string sqlConn = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString;
    SqlConnection aSqlConnection = new SqlConnection(sqlConn);
    SqlCommand aSqlCommand = aSqlConnection.CreateCommand();
    aSqlConnection.Open();

    SqlTransaction aSqlTransaction = aSqlConnection.BeginTransaction();
    //这个是必须的
    aSqlCommand.Transaction = aSqlTransaction;
    try
    {
        aSqlCommand.CommandText = @"DELETE FROM [Person] WHERE [ID] = 10";
        aSqlCommand.ExecuteNonQuery();

        aSqlCommand.CommandText = @"DELETE FROM [Person] WHERE [ID] = 11";
        aSqlCommand.ExecuteNonQuery();

        aSqlTransaction.Commit();
        this.Response.Write("事务已提交!");
    }
    catch(Exception err)
    {
        aSqlTransaction.Rollback();
        this.Response.Write("事务已回滚!");
    }
    finally
    {
        aSqlConnection.Close();
        aSqlTransaction.Dispose();
        aSqlCommand.Dispose();
    }
----------------------------------------------------------------------------------------------------
0065:
    如果将网站导航文件以非.sitemap扩展名存储,则会出现安全性问题,因为系统默认会自动保护.sitemap类型
文件不被用户下载。若您有特殊需求必须以其他扩展名表示,则可以将任何不是.sitemap的扩展名自定义网站导航
数据文件,置于App_Data文件夹中。
----------------------------------------------------------------------------------------------------
0066:
    TreeView控件的使用:
    数据库表结构:
    CREATE TABLE [dbo].[TreeViewDataSource] (
     [ID] [int] IDENTITY (1, 1) NOT NULL ,
     [Context] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
     [ParentID] [int] NULL
    ) ON [PRIMARY]

    测试数据:
    SET IDENTITY_INSERT TreeViewDataSource ON
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 1,'中国',0)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 2,'北京',11)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 3,'天津',11)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 4,'河北省',1)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 5,'广东省',1)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 6,'广州',5)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 7,'四川省',1)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 8,'成都',7)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 9,'深圳',5)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 10,'石家庄',4)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 11,'辽宁省',1)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 12,'大连',11)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 13,'上海',1)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 14,'天河软件园',6)
    insert TreeViewDataSource (ID,Context,ParentID)  values ( 15,'汕头',5)
    SET IDENTITY_INSERT TreeViewDataSource off

    代码:
    protected void Page_Load(object sender, EventArgs e)
    {
        // 定义数据库连接
        SqlConnection CN = new SqlConnection();
        try
        {
            //初始化连接字符串
            CN.ConnectionString = @"Server=./SQLSERVER2005;DataBase=Test;uid=sa;pwd=sa";
            CN.Open();
            SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM TreeViewDataSource", CN);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            this.ViewState["ds"] = ds;
        }
        catch (Exception ex)
        {
            Session["Error"] = ex.ToString();
            Response.Redirect("error.aspx");//̀跳转程序的公共错误处理页面
        }
        finally
        {
            CN.Close();
        }
        //调用递归函数,完成树形结构的生成
        AddTree(0, (TreeNode)null);
    }

    //递归添加树的节点
    public void AddTree(int ParentID, TreeNode pNode)
    {
        DataSet ds = (DataSet)this.ViewState["ds"];
        DataView dvTree = new DataView(ds.Tables[0]);
        //过滤ParentID,得到当前的所有子节点
        dvTree.RowFilter = "[PARENTID] = " + ParentID;

        foreach (DataRowView Row in dvTree)
        {
            TreeNode Node = new TreeNode();
            if (pNode == null)
            {    //添加根节点
                Node.Text = Row["ConText"].ToString();
                TreeView1.Nodes.Add(Node);
                Node.Expanded = true;
                AddTree(Int32.Parse(Row["ID"].ToString()), Node);    //再次递归
            }
            else
            {   //̀添加当前节点的子节点
                Node.Text = Row["ConText"].ToString();
                pNode.ChildNodes.Add(Node);
                Node.Expanded = true;
                AddTree(Int32.Parse(Row["ID"].ToString()), Node);     //再次递归
            }
        }
    }
----------------------------------------------------------------------------------------------------
0067:
    使用aspnet_regsql注册的数据库,需要修改连接属性:
    <connectionStrings>
        <remove name="LocalSqlServer"/>
        <add name="LocalSqlServer" connectionString="Server=./SQLSERVER2005;DataBase=AspNetDB;uid=sa;pwd=sa"/>
    </connectionStrings>
----------------------------------------------------------------------------------------------------
0068:
    读取数据库连接字符串:
    <connectionStrings>
        <add name="SQLCONN" connectionString="..."/>
    </connectionStrings>

    string sqlConn = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SQLCONN"].ConnectionString;
----------------------------------------------------------------------------------------------------
0069:
    读取Mail的设置:
    <configuration>
        <system.net>
            <mailSettings>
              <smtp from="admin@126.com">
                <network host="192.168.3.4" password="" userName=""/>
              </smtp>
            </mailSettings>
        </system.net>
    </configuration>

    Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(this.Request.ApplicationPath);
    System.Net.Configuration.MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
    this.Response.Write(mailSettings.Smtp.From);
    this.Response.Write(mailSettings.Smtp.Network.Host);
----------------------------------------------------------------------------------------------------
0070:
    对Web.config中的<appSettings>节点进行加密:
    //DPAPI方式加密
    Configuration config = WebConfigurationManager.OpenWebConfiguration(this.Request.ApplicationPath);
    ConfigurationSection appSettings = config.GetSection("appSettings");
    if (appSettings.SectionInformation.IsProtected == false)
    {
        appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
        config.Save();
    }

    //RSA方式加密
    Configuration config = WebConfigurationManager.OpenWebConfiguration(this.Request.ApplicationPath);
    ConfigurationSection appSettings = config.GetSection("appSettings");
    if (appSettings.SectionInformation.IsProtected == false)
    {
        appSettings.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
        config.Save();
    }

    //解密:两种加密方式的解密方式是相同的
    Configuration config = WebConfigurationManager.OpenWebConfiguration(this.Request.ApplicationPath);
    ConfigurationSection appSettings = config.GetSection("appSettings");
    if (appSettings.SectionInformation.IsProtected == true)
    {
        appSettings.SectionInformation.UnprotectSection();
        config.Save();
    }
    加密之后的数据不用进行解密就可以直接使用以前的读取方法读取,会自动解密的。其它节点的加密和解密类
似。例如:config.GetSection("connectionStrings");
----------------------------------------------------------------------------------------------------
0071:
    每天工作,解决企业需求问题与解决技术问题的比例表示着工作的效能。

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值