用C#创建Web应用程序

用C#创建Web应用程序

Author: bluestar  From:Internet

  使用微软正在推行的.NET技术和C#语言可以快速建立Web应用程序,其安全性和可升级性都大大胜过普通的ASP应用程序。在这篇文章里,我们将使用.NET和C#一步一步的建立一个应用程序。
 
    系统需求:
 
    Internet Explorer 5.5
 
    Windows 2000 Professional, Server 或 Advanced Server
 
    ASP+/Microsoft .NET (预览版可以在 http://msdn.microsoft.com/net 下载)
 
    SQL Server 7.0  SP1 或更高版本
 
    使用微软 .NET的高级对象模型(Advanced Object Model)可以快速建立安全的,易于升级性的Web应用程序。
 
    微软的 .NET是一个开发商业解决方案的理想技术。.NET技术结合C#的弹性和高性能,开发商业程序比以往仅仅使用ASP的方法更为简单。
 
    在这篇文章里,我们将使用 .NET和C#来建立一个简单的商业应用程序--一个能够让客户浏览你的产品目录的程序。
 
    这个程序包含了最基本的.NET和C#技术,在本文中,将涉及到如何建立和编译C#的商业应用层组件。也将谈到怎样使用ASPX页面存取组件和绑定数据。综合使用这些技术,可以花费比传统的ASP方法更少的时间建立Web应用程序。
 
    稳固的.NET应用程序仍然依靠于稳固的数据库计划和精心编写的存储过程。
 
    应用程序可以通过组件调用已经写好的存储过程。大部分多层方法都不推荐直接从程序中调用数据,那样会降低程序的速度,也不利于调试。
 
    本文主要讨论C#和ASP+,不过多的讨论建立数据库和存储过程。
 
  组件的开发
    我们将要编写的c#组件同时作为逻辑层和数据存取层。
 
    如果打算将来把程序移植到另一种数据库中,比如Oracle,那么需要把逻辑层和数据存取层分别放在两个组件中。本文中只使用SQL Server,所以不需要分开它们。
 
    这个应用程序需要两个页面:Default.aspx 和 ProductList.aspx。 Default.aspx 是用户访问Web首先看见的页面,它列出所有的产品种类。用户从Default.aspx菜单中选择种类后,将进入ProductList.aspx页面,这个页面显示了当前类所有产品的列表。
 
    在用户使用这两个页面的过程中,发生了两个动作:第一个是在菜单中列出产品种类(Default.aspx),第二个是在产品列表的页面中列出产品(ProductList.aspx)。我们可以建立两个函数来完成这两个任务,这两个函数都通过调用存储过程获取数据。对应这两个函数,我们在一个叫做CommerceDotNet的名字空间中建立起两个类:Category 和 Product。(图1)使用CommerceDotNet.Categories实例化Categories类,使用CommerceDotNet.Products实例化Products类。为了使代码清晰,我们在不同的文件中分别声明这两个类。由于他们共享一个名字空间,即使在不同的文件声明,在编译后也将成为一个单独的组件。
 
 
    CategoryList方法传递了一个包含所有产品种类的数据集给系统。在Categories类中加入CategoryList的方法。
 
    代码如下:
 
    namespace CommerceDotNet {
       public class Categories {
        public DataSet CategoryList() {
        }
     }
    }
 
    建立了这个类以后,开始为CategoryList方法添加代码。
 
    CategoryList方法获取数据的过程分为四步:1.通过SQLConnection和SQLDataSetCommand对象建立数据连接和命令对象。2.把命令对象类型设置为存储过程。3.把存储过程ListCategory的结果送入数据集。4.把包含结果的数据集返回给调用它的函数。
 
    完整的CategoryList方法代码如下:
 
    public DataSet CategoryList() {
 
      // 建立数据连接和命令对象
 
      SQLConnection myConnection = new SQLConnection
 
      ("server=localhost;uid=sa;pwd=;database=commercedotnet");
 
      SQLDataSetCommand myCommand = new SQLDataSetCommand("ListCategory", myConnection);
 
      // 设置命令对象类型为存储过程
 
      myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
 
      // 建立和填充数据集
 
      DataSet myDataSet = new DataSet();
 
      myCommand.FillDataSet(myDataSet, "CategoryList");
 
      // 返回数据集
 
      return myDataSet;
 
     }
 
    ProductsList方法和CategoryList方法类似,但是ProductsList向存储过程传递了一个参数。
 
    代码如下:
 
    public DataSet ProductsList(int categoryID) {
 
      // 建立数据连接和命令对象
 
      SQLConnection myConnection = new SQLConnection
 
      ("server=localhost;uid=sa;pwd=;database=commercedotnet");
 
      SQLDataSetCommand myCommand = new SQLDataSetCommand("ListProducts", myConnection);
 
      // 设置命令对象类型为存储过程
 
      myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
 
      // 向存储过程传递参数
 
      SQLParameter parameterCategoryID = new SQLParameter("@CategoryID", SQLDataType.Int, 4);
 
      parameterCategoryID.Value = categoryID;
 
      myCommand.SelectCommand.Parameters.Add(parameterCategoryID);
 
      // 建立和填充数据集
 
      DataSet myDataSet = new DataSet();
 
      myCommand.FillDataSet(myDataSet, "Products");
 
      // 返回数据集
 
      return myDataSet;
 
     }
 
    两个类都建立好以后,编译程序。
 
    使用命令:csc /out:../bin/CommerceDotNet.dll /t:library /r:System.Data.dll CategoryDB.cs ProductDB.cs
 
    "/out:"开关指定编译库名和存放位置,"/t:"开关告诉编译器建立库,"/r:"开关指出组件涉及到的其他库,完整的源程序在文末后面列出。
 
  ASP+页面的开发
    建立好组件以后,下面的工作是开发作为用户界面ASP+页面。前面的部分,我们设计了default.aspx 和 productslist.aspx 页,Default.aspx页是站点被装入后的第一页,我们就从建立这个缺省页面开始。
 
    当页面读入时,触发Page_Load()方法,这个方法完成了从数据库获取的数据并绑定到MyList的任务。首先,声明一个ICollection型变量menuItems。然后,实例化组件,调用CategoryList方法,把数据集存放在menuItems对象中。设置MyList的数据源为menuItems。执行MyList.DataBind方法把数据绑定到MyList。
 
    这部分代码如下:
 
    <script language="C#" runat="server">
 
     void Page_Load(Object sender, EventArgs e) {
 
     ICollection menuItems;
 
      CommerceDotNet.Categories categories = new CommerceDotNet.Categories();
 
  menuItems = categories.CategoryList().Tables[0].DefaultView;
 
      MyList.DataSource = menuItems;
 
      MyList.DataBind();
 
     }
 
    </script>
 
    default.aspx中其他代码与传统的ASP页面类似,请参见文末列出的代码。
 
    ProductList.aspx与default.aspx类似,但是,绑定数据的代码有些变化,因为,在开发C#组件的时候,我们在CommerceDotNet.ProductsList方法中向存储过程中传递了参数,所以,ASP+页面中也需要有相应的变化。
 
    CommerceDotNet.Products products = new CommerceDotNet.Products();
 
    MyProductList.DataSource = products.ProductsList(categoryId).Tables[0].DefaultView;
 
    MyProductList.DataBind();
 
    至此,两个ASP+页面也创建完毕。
 
    这样,结合C#和ASP+的最基础的应用程序就创建好了。
 
    这个程序展示了微软.NET和C#技术的强大威力,在这个基础上,再作进一步的增添和修改,很容易开发出强大的站点。
 
  附原码:
 
  附:
  ----------------------CategoryDB.cs---------------------------
  using System;
  using System.Data;
  using System.Data.SQL;
 
  namespace CommerceDotNet {
 
      public class Categories {
 
          public DataSet CategoryList() {
 
              // Create Instance of Connection and Command Object
              SQLConnection myConnection = new SQLConnection("server=localhost;uid=sa;pwd=;database=commercedotnet");
              SQLDataSetCommand myCommand = new SQLDataSetCommand("ListCategory", myConnection);
 
              // Mark the Command as a SPROC
              myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
 
              // Create and Fill the DataSet
              DataSet myDataSet = new DataSet();
              myCommand.FillDataSet(myDataSet, "CategoryList");
 
              // Return the DataSet
              return myDataSet;
          }
  }
  }
 
  ----------------------ProductDB.cs----------------------------
 
  using System;
  using System.Data;
  using System.Data.SQL;
 
  namespace CommerceDotNet {
 
      public class Products {
 
          public DataSet ProductsList(int categoryID) {
 
              // Create Instance of Connection and Command Object
              SQLConnection myConnection = new SQLConnection("server=localhost;uid=sa;pwd=;database=commercedotnet");
              SQLDataSetCommand myCommand = new SQLDataSetCommand("ListProducts", myConnection);
 
              // Mark the Command as a SPROC
              myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
 
              // Add Parameters to SPROC
              SQLParameter parameterCategoryID = new SQLParameter("@CategoryID", SQLDataType.Int, 4);
              parameterCategoryID.Value = categoryID;
              myCommand.SelectCommand.Parameters.Add(parameterCategoryID);
 
              // Create and Fill the DataSet
              DataSet myDataSet = new DataSet();
              myCommand.FillDataSet(myDataSet, "Products");
 
              // Return the DataSet
              return myDataSet;
          }
  }
  }
 
  ----------------------default.aspx----------------------------
 
  <% @Page Language="C#" %>
 
  <HTML>
  <HEAD>
  <META NAME="GENERATOR" C>
  <TITLE></TITLE>
 
  <!-- Insert Style Sheet Here -->
  <LINK rel="stylesheet" type="text/css" href="Main.css">
  <!-- End Style Sheet -->
 
  <script language="C#" runat="server">
 
      void Page_Load(Object sender, EventArgs e) {
 
          ICollection menuItems;
 
          CommerceDotNet.Categories categories = new CommerceDotNet.Categories();
    menuItems = categories.CategoryList().Tables[0].DefaultView;
 
          // Associate the list of menu items into the list and bind to the list
          MyList.DataSource = menuItems;
          MyList.DataBind();
      }
 
  </script>
 
  </HEAD>
  <BODY topmargin=5 leftmargin=5>
 
  <TABLE WIDTH=600 BORDER=0 CELLSPACING=0 CELLPADDING=0>
  <TR>
  <TD colspan=2 align="right" valign=top>
    <IMG SRC="" align=left>
  </td>
  </tr>
  <tr>
  <td valign=top>
    <!-- Menu Cell -->
 
          <asp:DataList id="MyList" runat="server" cellpadding="3" cellspacing="0" width="145" SelectedItemStyle-BackColor="dimgray" SelectedItemStyle-CssClass="dimgray" maintainstate="false">
 
              <template name="ItemTemplate">
                  <asp:HyperLink class="MenuText" id=HyperLink1 Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' NavigateUrl='<%# "productlist.aspx?CategoryID="  DataBinder.Eval(Container.DataItem, "CategoryID") %>' runat="server" />
              </template>
 
              <template name="SelectedItemTemplate">
                  <asp:HyperLink class="MenuText" id=HyperLink2 Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' NavigateUrl='<%# "productlist.aspx?CategoryID="  DataBinder.Eval(Container.DataItem, "CategoryID") %>' runat="server" />
              </template>
 
          </asp:DataList>
 
    <!-- End Menu Cell -->
  </TD>
  <td width=450 valign=top>
    <table width=100% border=0 cellspacing=0 cellpadding=0>
    <tr>
    <td>
      <div class="pageheadertext">Welcome!</div>
      <br>
      This is a sample eCommerce site that was developed using the Microsoft .NET platform and C#.  This is only a sample site used for education purposes only.
 
    </td>
    </tr>
    </table>
  </td>
  </TR>
  </TABLE>
 
 
  </BODY>
  </HTML>
 
  ----------------------ProductList.aspx----------------------------
  <% @Page Language="C#" %>
 
  <HTML>
  <HEAD>
  <META NAME="GENERATOR" C>
  <TITLE></TITLE>
 
  <!-- Insert Style Sheet Here -->
  <LINK rel="stylesheet" type="text/css" href="Main.css">
  <!-- End Style Sheet -->
 
  <script language="C#" runat="server">
 
      void Page_Load(Object sender, EventArgs e) {
 
          ICollection menuItems;
 
          CommerceDotNet.Categories categories = new CommerceDotNet.Categories();
    menuItems = categories.CategoryList().Tables[0].DefaultView;
 
          // Associate the list of menu items into the list and bind to the list
          MyList.DataSource = menuItems;
          MyList.DataBind();
 
    // Obtain categoryId from QueryString
    int categoryId = Int32.Parse(Request.Params["CategoryID"]);
 
    // Obtain products and databind to an asp:datalist control
    CommerceDotNet.Products products = new CommerceDotNet.Products();
    MyProductList.DataSource = products.ProductsList(categoryId).Tables[0].DefaultView;
    MyProductList.DataBind();
      }
 
  </script>
 
  </HEAD>
  <BODY topmargin=5 leftmargin=5>
 
  <TABLE WIDTH=600 BORDER=0 CELLSPACING=0 CELLPADDING=0>
  <TR>
  <TD colspan=2 align="right" valign=top>
    <IMG SRC="" align=left>
  </td>
  </tr>
  <tr>
  <td valign=top>
    <!-- Menu Cell -->
 
          <asp:DataList id="MyList" runat="server" cellpadding="3" cellspacing="0" width="145" SelectedItemStyle-BackColor="dimgray" SelectedItemStyle-CssClass="dimgray" maintainstate="false">
 
              <template name="ItemTemplate">
                  <asp:HyperLink class="MenuText" id=HyperLink1 Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' NavigateUrl='<%# "productlist.aspx?CategoryID="  DataBinder.Eval(Container.DataItem, "CategoryID") %>' runat="server" />
              </template>
 
              <template name="SelectedItemTemplate">
                  <asp:HyperLink class="MenuText" id=HyperLink2 Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' NavigateUrl='<%# "productlist.aspx?CategoryID="  DataBinder.Eval(Container.DataItem, "CategoryID") %>' runat="server" />
              </template>
 
          </asp:DataList>
 
    <!-- End Menu Cell -->
  </TD>
  <td width=450 valign=top>
    <table width=100% border=0 cellspacing=0 cellpadding=0>
    <tr>
    <td>
 
                  <asp:DataList id="MyProductList" CellPadding="4" CellSpacing="4" RepeatDirection="Vertical" RepeatColumns="1" runat="server" AlternatingItemStyle-BackColor="#FFFCCC">
 
                      <template name="ItemTemplate">
 
                          <div class="ProductTitleText"><%# DataBinder.Eval(Container.DataItem, "Title") %></div>
                          <div class="ProductDescriptionText"><%# DataBinder.Eval(Container.DataItem, "Description") %></div>
                          <div class="ProductCostText">Cost: <%# DataBinder.Eval(Container.DataItem, "Cost", "{0:c}") %></div>
        <asp:HyperLink Text='Add To Cart' NavigateUrl='<%# "cart.aspx?ProductID="  DataBinder.Eval(Container.DataItem, "ProductID") %>' runat="server" />
        <br><br>
 
                      </template>
 
                      <template name="AlternatingItemTemplate">
 
                          <div class="ProductTitleText"><%# DataBinder.Eval(Container.DataItem, "Title") %></div>
                          <div class="ProductDescriptionText"><%# DataBinder.Eval(Container.DataItem, "Description") %></div>
                          <div class="ProductCostText">Cost: <%# DataBinder.Eval(Container.DataItem, "Cost", "{0:c}") %></div>
        <asp:HyperLink Text='Add To Cart' NavigateUrl='<%# "cart.aspx?ProductID="  DataBinder.Eval(Container.DataItem, "ProductID") %>' runat="server" />
        <br><br>
 
                      </template>
 
                  </asp:DataList>
 
    </td>
    </tr>
    </table>
  </td>
  </TR>
  </TABLE>
 
 
  </BODY>
  </HTML>
  ----------------------------------------------------------------------
  (完)
 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 警告:持续变种木马正在发起农历新年攻势!
 您可能对 [C#] 的这些文章也感兴趣:
论C#变得越来越臃肿是不可避免的
查询IP所在区段(C#)
在C#中利用SharpZipLib进行文件的压缩和解压缩
C# - Append a host header by code in IIS
在C#中调用Microsoft.VisualBasic命名空间下的类型验证函数
使用泛型实现单例提供者(原创翻译)
C#2 anonymous methods
Master Pages: Tips, Tricks, and Traps
Microsoft .NET 框架资源基础
基于.Net平台应用程序唯一运行实例实现
.net Framework 2.0 专门提供了配置文件的操作
正确实现 IDisposable