Develop BTOC e-commerce system (asp.net)

Source: Internet
Author: User
Tags define definition count interface tostring root directory visual studio
There are two other figures in the original.
After the basic understanding of the programming model of asp.net Web Forms, it is necessary to improve the understanding of the internal operation mechanism of ASP.net Web Forms by applying the practical development cases, and to control the system architecture. We do not have a noble posture for programming, and we are deeply aware of the ability to develop efficient, robust, and powerful applications that are always the ultimate in programming. The following is a complete BTOC e-commerce system development process to show how the ASP.net Web form can be specifically built for the next generation network platform.
This is a typical based on B/S (browser/server) three-tier structure of food, beverage e-commerce Retail system-"corn place snack shop." Front end for the product browser, for consumers to browse/buy goods, order shopping and other aspects of the function of the middle tier for the seller of tax rates, concessions and other business logic, backend for the entire retail system related to products, customers, orders and other databases. We build front-end and middle tier using Asp.net+iis 5来, SQL Server 2000来 Manage backend database, the whole system runs on Windows XP. As long as the related hardware configuration satisfies the basic configuration of the above software, the system performance can be guaranteed. The following is an illustration of the front-end interface of the online retail system:

Before preparing the commercial front-end and middle tier of Web forms, it is necessary to make a simple introduction to the backend database. The back-end database Cornfieldgrocer consists of 4 tables: Product Category table categories, detail table details, Product table products, customer information table customers. Considering the simplicity of the demo system, we have not added related stored procedures, views, rules, etc., which are necessary to improve the performance of the system in the actual development of the system, especially in the case of large amount of data. The following is an illustration of the 4-table field:

The table semantics for the fields of each table are already fairly clear, and we don't repeat them here. We will show you the entire E-commerce retail system-"corn snack Shop" physical file composition and structure, the following figure is schematic:

All files are located under the asp.net site Directory cornfieldgrocer, and there are files in the picture subdirectory images for Web Form pages that are no longer listed here.
Here we start writing front-end and middle-tier code to show the Web Form ASP more clearly. NET, we use Notepad to complete the whole code writing process. It needs to be explained that in real project development practice, the development efficiency will be greatly improved by using visual integrated development tools such as Visual Studio.NET. However, in the case of the low-level mechanism of ASP.net code is not familiar with, I strongly recommend that early development learning may be placed in the Windows system with the "notepad" the simple but can expose the code is quite clear tool.
Because of its limited space, it is impossible for us to show all the code here. As mentioned earlier, web.config is an xml-based configuration file for each site level, responsible for some asp.net security certifications, coding options, diagnostic tests, and other asp.net configuration work, the first stop when the browser requests asp.net Web forms to be processed via IIS. Here's what it is:

<configuration>
<system.web>
<globalization requestencoding= "UTF-8" responseencoding= "UTF-8"/>
</system.web>
</configuration>


It is easy to see that the configuration content here is fairly simple, specifying that only the requested/sent encoding is "UTF-8". We will not dwell on this.
The Global.asax file, together with the Bin\cornfieldgrocer.dll compiled by the back-end code file Global.asax.cs, constitutes the ASP.net application definition for the online retail system. Let's look at the file global.asax:

<%@ application inherits= "Cornfieldgrocer.global"%>

The file has only one line indicator, which means that the definition of the ASP.net application inherits from the global class, and the global class is defined in the Global.asax.cs file:

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Web;
Using System.Web.SessionState;

Namespace Cornfieldgrocer
{
public class Global:System.Web.HttpApplication
{
protected void Session_Start (Object sender, EventArgs e)
{
if (session["shoppingcart"] = = null)
{
session["ShoppingCart"] = new cornfieldgrocer.orderlist ();
}
}
}
}

In the global class, we define the shopping card (ShoppingCart) in the sense of section (session)--Here we use the indexer in C #. The type of the shopping card is the OrderList class in the Cornfieldgrocer namespace and is defined in the CornfieldGrocer.cs file. We can, of course, combine the contents of the above two files in the form of a scripting language in the Global.asax file. But that's not what ASP.net recommended, because the first execution of the scripting language also has to be dynamically compiled, which loses some of the performance, while compiling the CS file into a DLL file in advance will reduce the cost Of course, the meaning of compiling here refers to the process of compiling CS source code file into Microsoft intermediate language. Second, the principle of separating pages from back-end code is easy to project management, and is a recommended engineering practice by Visual Studio.NET.
The file default.aspx the HTML code for the front-end page of the entire online retail system, Default.aspx.cs the CS code that controls the behavior of the Web form for the backend. Because of the length of the relationship here we no longer repeat the HTML code, in fact, from the front of the front-end interface diagram, we can understand the basic default.aspx HTML code structure. Style.css file for Default.aspx file page style definition file, define some elements of the page color, format, spacing and other cosmetic things, we also no longer speak. Here are just a few Default.aspx page indicators to show you:

<%@ autoeventwireup= "false" inherits= "Cornfieldgrocer.mainform"%>

We use the "inherits=" Cornfieldgrocer.mainform "" to indicate that our page inherits from the MainForm class, so that we realize the separation of the control code of the ASP.net Web form behavior from the HTML of the page display. where "autoeventwireup=" false "" indicates that page events are not automatically enabled--page events do not automatically make it possible for all page events to be triggered by a user-specific action, because the property defaults to "True" to indicate that it is automatically enabled, But our business logic requirements are not automatic, so the statement here is necessary, otherwise it will cause confusion in the system processing. Now let's look at the MainForm class:

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;

Namespace Cornfieldgrocer
{
public class MainForm:System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label currentcategory;
protected System.Web.UI.WebControls.Label Name;
protected System.Web.UI.WebControls.Label SubTotal;
protected System.Web.UI.WebControls.ImageButton Imagebutton1;
protected System.Web.UI.WebControls.Label Description;
Protected System.Web.UI.WebControls.Label Company;
protected System.Web.UI.WebControls.Repeater detailslisting;
protected System.Web.UI.WebControls.DataList productlisting;
protected System.Web.UI.WebControls.DataList shoppingcartlist;
protected System.Web.UI.HtmlControls.HtmlSelect categorylist;
protected System.Web.UI.WebControls.Button Btnselect;
protected System.Web.UI.WebControls.Label Tax;
protected System.Web.UI.WebControls.Label Total;
protected System.Web.UI.WebControls.ImageButton Imagebutton4;
protected System.Web.UI.WebControls.ImageButton Imagebutton5;
protected System.Web.UI.WebControls.ImageButton Imagebutton6;
protected System.Web.UI.HtmlControls.HtmlInputText Qty;
protected System.Web.UI.HtmlControls.HtmlGenericControl Checkoutpanel;
protected System.Web.UI.HtmlControls.HtmlImage selectedprodpicture;

Public MainForm ()
{
Page.Init + = new System.EventHandler (Page_Init);
}
private void Page_Load (object sender, System.EventArgs e)
{
if (! IsPostBack)
{
Productlisting.selectedindex = 0;

Updateproducts ();
Updateshoppingcart ();
}
}
private void Page_Init (object sender, EventArgs e)
{
InitializeComponent ();
}
private void InitializeComponent ()
{
This.btnSelect.Click =
New System.EventHandler (this. Categorylist_select);
This. productlisting.selectedindexchanged+=
New System.EventHandler (this. Productlisting_select);
This. imagebutton1.click+=
New Imageclickeventhandler (this. Addbtn_click);
This. imagebutton4.click+=
New Imageclickeventhandler (this. Recalculate_click);
This. imagebutton6.click+=
New Imageclickeventhandler (this. Clearcart_click);
This. Load + =
New System.EventHandler (this. Page_Load);
}
private void Categorylist_select (Object sender, EventArgs e)
{
Currentcategory.text =
Categorylist.items[categorylist.selectedindex]. Text;
Updateproducts ();
}
private void Productlisting_select (Object sender, EventArgs e)
{
Updateproducts ();
}
private void Addbtn_click (Object sender, ImageClickEventArgs e)
{
int ProductID = Int32.Parse
(Productlisting.datakeys[productlisting.selectedindex]. ToString ());

Inventorydb market = new Inventorydb ();
DataRow Product = market. GetProduct (ProductID);

Cornfieldgrocer.orderlist ShoppingCart =
((cornfieldgrocer.orderlist) session["ShoppingCart"]);

Shoppingcart.add (New Cornfieldgrocer.orderitem (ProductID,
(String) product["ProductName"],
Double.Parse (product["UnitPrice"). ToString ()), 1));

Updateshoppingcart ();
}
private void Recalculate_click (Object sender, ImageClickEventArgs e)
{
Cornfieldgrocer.orderlist ShoppingCart =
((cornfieldgrocer.orderlist) session["ShoppingCart"]);

for (int i=0; i<shoppingcartlist.items.count; i++) >
{
HtmlInputText Qty =
(HtmlInputText) Shoppingcartlist.items[i]. FindControl ("Qty");
Try
{
shoppingcart[(String) shoppingcartlist.datakeys][i]]. Quantity
= Int32.Parse (Qty. Value);
}
catch (Exception)
{
}
}
Updateshoppingcart ();
}
private void Clearcart_click (Object sender, ImageClickEventArgs e)
{
Cornfieldgrocer.orderlist ShoppingCart =
((cornfieldgrocer.orderlist) session["ShoppingCart"]);

Shoppingcart.clearcart ();
Updateshoppingcart ();
}
void Updateproducts ()
{
Inventorydb market = new Inventorydb ();

int CategoryID = Int32.Parse
(Categorylist.items[categorylist.selectedindex]. Value);
Productlisting.datasource =
Market. GetProducts (CategoryID). DefaultView;
Productlisting.databind ();

int ProductID = Int32.Parse
(Productlisting.datakeys[productlisting.selectedindex]. ToString ());
DataRow Product = market. GetProduct (ProductID);

Name.text = product["ProductName"]. ToString ();
SELECTEDPRODPICTURE.SRC = product["ImagePath"]. ToString ();
Description.text = product["ProductDescription"]. ToString ();
Company.text = product["Manufacturer"]. ToString ();

Detailslisting.datasource =
Market. Getproductcalories (ProductID). DefaultView;
Detailslisting.databind ();
}
void Updateshoppingcart ()
{
Cornfieldgrocer.orderlist ShoppingCart =
((cornfieldgrocer.orderlist) session["ShoppingCart"]);

Subtotal.text = String.Format ("{0:c}", shoppingcart.subtotal);
Tax.text = String.Format ("{0:c}", Shoppingcart.tax);
Total.text = String.Format ("{0:c}", shoppingcart.total);

Shoppingcartlist.datasource=shoppingcart.values;
Shoppingcartlist.databind ();
}
}
}
There are 11 methods in the MainForm class, 19 protected domains. The 19 protection domains correspond to the page elements shown in the front-end interface diagram, and are not discussed here. In 11 methods, MainForm () is the builder, which adds the page initialization event Page_Init (), which is the first event that asp.net Web Forms handle, and generally carries out some basic initialization operations. We can see the operation of initializing the component InitializeComponent () in Page_Init (). Page_Load () event occurs when the user makes a request, the page is loaded, where the general can do some business logic initialization aspects of operations, such as database connection, shopping card initialization. We have here a product display updateproducts () and shopping card initialization updateshoppingcart () operation.
The other four methods are the selection of the product category Productlisting_select (), the purchase of the product add Addbtn_click (), Shopping card recalculation Recalculate_click (), Shopping card removal clearcart_ Click () completes the business logic by triggering the corresponding event by manipulating the ASP.net control. The above code has been shown fairly clearly and we are not going to repeat it.
The last thing we want to show you is the component of the middle-tier business logic. It is composed of three classes: Inventory data class Inventorydb, Order item class OrderItem and Order list class orderlist. Together, they are defined in the file CornfieldGrocer.cs file. Since the interpretation of the programming method has been quite clear of their structure display, we only give the file the CS source code:

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Collections;

Namespace Cornfieldgrocer
{
public class Inventorydb
{
Public DataTable getproducts (int CategoryID)
{
SqlConnection sqlconnect= New SqlConnection
("server= (local);d atabase=cornfieldgrocer; Trusted_connection=yes ");
SqlDataAdapter sqlAdapter1 = new SqlDataAdapter
("SELECT * from the products where categoryid=" +categoryid,sqlconnect);
DataSet products = new DataSet ();
Sqladapter1.fill (Products, "products");
return products. Tables[0];
}
Public DataRow getproduct (int productID)
{
SqlConnection sqlconnect= New SqlConnection
("server= (local);d atabase=cornfieldgrocer; Trusted_connection=yes ");
SqlDataAdapter sqlAdapter1 = new SqlDataAdapter
("SELECT * from the products where productid=" + ProductID, sqlConnect);
DataSet Product = new DataSet ();
Sqladapter1.fill (Product, "product");
Return product. Tables[0]. Rows[0];
}
Public DataTable getproductcalories (int productID)
{
SqlConnection sqlConnect = new SqlConnection
("server= (local);d atabase=cornfieldgrocer; Trusted_connection=yes ");
SqlDataAdapter sqlAdapter1 = new SqlDataAdapter
("SELECT * from Details where productid=" +productid,sqlconnect);
DataSet details = new DataSet ();
Sqladapter1.fill (Details, "details");
return details. Tables[0];
}
}

public class OrderItem
{
public int ProductID;
public int quantity;
public String name;
public double price;
public OrderItem (int productID, String name, double, int quantity)
{
This.productid = ProductID;
this.quantity = quantity;
THIS.name = name;
This.price = Price;
}
public int ProductID
{
get {return ProductID;}
}
public int Quantity
{
get {return quantity;}
set {Quantity=value;}
}
Public String Name
{
get {return name;}
}
Public double Price
{
get {return price;}
}
Public double Total
{
get {return quantity * price;}
}
}

public class OrderList
{
Private Hashtable orders = new Hashtable ();
Private double taxrate = 0.08;
Public double SubTotal
{
Get
{
if (orders. Count = 0)
return 0.0;
Double subTotal = 0;
IEnumerator items = orders. Values.getenumerator ();
while (items. MoveNext ())
{
SubTotal + = ((orderitem) items. Current). Price *
((OrderItem) items. Current). Quantity;
}
return subTotal;
}
}
Public double TaxRate
{
get {return taxrate;}
set {taxrate = value;}
}
Public double Tax
{
get {return SubTotal * taxrate;}
}
Public double Total
{
get {return SubTotal * (1 + taxrate);}
}
Public ICollection Values {
get {
return orders. Values;
}
}
Public OrderItem this[string Name] {
get {
Return (OrderItem) orders[name];
}
}
public void Add (OrderItem value)
{
if (Orders[value. Name] = = null) {
Orders. ADD (value. Name, value);
}
Else
{
OrderItem OI = (orderitem) orders[value. Name];
oi.quantity = oi.quantity + 1;
}
}
public void Clearcart () {
Orders. Clear ();
}
}
}

What needs to be explained is that we have three files Cornfieldgrocer.cs,default.aspx.cs,global.asax.cs using the compile command "Csc/t:library/out:cornfieldgrocer.dll Cornfieldgrocer.cs Default.aspx.cs Global.asax.cs "encapsulates them all in the Cornfieldgrocer namespace, although this is not necessary." The above compiler outputs the CornfieldGrocer.dll file, and when we configure the online retail site, we simply copy the file to the bin directory in the root directory of the site.
So far, we have fully demonstrated the use of ASP.net Web forms to build a small online trading system coding, configuration and so on. Of course, as a demo case, it has no real system for the perfect performance, security, interface and other aspects of optimization considerations and design. But it shows us the ASP.net Web Form model is very typical and low-level, we can not do this on the basis of continuous modification and expansion to develop their own trading system. For example, what happens when the page is run when the autoeventwireup= "false" in the Default.aspx file is set to "true" or the statement is removed? Through these exercises will continue to deepen our understanding of the bottom of the ASP.net, and finally reach the grasp of ease. In fact, technical learning, especially programming, in addition to a certain degree of interest and understanding, a large number of code instances of the exercise is also very necessary, which itself is the author of a process of growth, but also in this article I am trying to show you.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.