In the Session

Download Report

Transcript In the Session

PLACING ORDERSSHOPPPING CARTS
Introduction
 There are several stages to the order
process, starting with an order page, which
allows customers to add products to a
shopping cart.
 Once customers have selected their order
items, they can then proceed to the checkout,
where the delivery address and credit card
details need to be collected.
 Finally, you create the order in the database,
and all the updates to the database as well as
the real delivery of the products are going to
be done.
Essential Background
 Learn how to create custom classes
 See how to use the Session object to store
the shopping cart
 Learn about the ObjectDataSource control
The Order Process
 Before building the order pages, you must
work out the process of ordering items. This
will give you an indication of exactly what you
will need. Following are the things you will
need:



An order page, where you can select the
product items.
A shopping cart, to store the selected
products.
A page to collect the delivery details and credit
card payment.
The Order Process-Continue
 Each of the previous pages needs some thought,
with the process of ordering and storing data worked
out in advance.
 For example, you must decide whether to have an
order page that is separate from the catalogue page.
Keeping them the same would mean that you can
simply add a button alongside each item. This would
add the item to the shopping cart.
 Alternatively, you could have a text area allowing the
user to enter the number of items to be added. This
makes the page a little harder to code.
Where to store orders
 Once you’ve decided on the way orders will be performed, you can decide
where to store them before
 the order is confirmed—the shopping cart.
 There are places to store shopping carts:
 In a database —As the user adds items to the cart, the items could be
added to a table in the database. When the order is confirmed, the
entries could be copied into the OrderItems table. One problem with
this approach is that if the user leaves the site without confirming the
order, then the shopping cart table will have unused data in it, which
will need to be removed.
 In the Profile —The Profile is a feature of ASP.NET 2.0 that allows
storage of data against a user. We won’t be using the Profile, but one
problem with using the Profile for storing the shopping cart is that the
Profile is meant for long-lived data—data that persists across user
sessions. Some sites allow shopping carts to keep their data for when
you come back to the site.
 In the Session —The Session contains data about the active session.
It starts when you first access the site and ends when you exit the site
(plus a timeout value). Any data stored in the session will be held only
while you are browsing the site.
Developing a Shopping Cart
 Many ecommerce web sites require a shopping cart
as an essential part. There are many ways to develop
these shopping carts.



Some of them are - cookie based,
session based and
database driven.
 Each technique has advantages and disadvantages
of its own.
 We will explore each technique with code sample and
finally present you a generic solution that will work in
any of these situations.
Using Cookies for state storage
 Any shopping cart essentially needs to store product details
such as product code, product name, unit price and quantity.
 You will be presenting a product catalog to the user from
which he can select the products. He may also navigate to
other parts of the site while he is shopping. You need to
maintain his selection across the pages so that finally when
he visits the shopping cart page you can show collective
details there.
 Cookies can be used to preserve this state information
across the requests. In ASP.NET cookie is represented by a
class called HttpCookie. We will be using multi-value
cookies for our example.
Developing a simple product listing
page
 We will first build a simple web form that lists
the Products table of the database in a
DataGrid.
 Add a web form called ProductCatalog.aspx
to your project
 Drag and drop a DataGrid control on it.
 Write a function called BindGrid() as shown
below:
BindGrid()
private void BindGrid()
{
SqlDataAdapter da=new SqlDataAdapter ("select *
from products", @"data source=.\vsdotnet;initial
catalog=_________;user id=__");
DataSet ds=new DataSet();
da.Fill(ds,"products");
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}
In the Page_Load event handler
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindGrid();
}
}
In the SelectedIndexChanged event
of the DataGrid
private void DataGrid1_SelectedIndexChanged (object sender,
System.EventArgs e)
{
HttpCookie c=null;
if(HttpContext.Current.Request.Cookies["shoppingcart"]==null)
c=new HttpCookie("shoppingcart");
else
c=HttpContext.Current.Request.Cookies["shoppingcart"];
string itemdetails;
itemdetails=DataGrid1.SelectedItem.Cells[1].Text +
"|" + DataGrid1.SelectedItem.Cells[2].Text +
"|" + DataGrid1.SelectedItem.Cells[3].Text;
c.Values[DataGrid1.SelectedItem.Cells[1].Text]=itemdetails;
Response.Cookies.Add(c);
}
Shopping Cart Cookies
 Here, we created a cookie called
shoppingcart. This cookie further contains
subkey-value pairs. Based on user selection
we simply add sub keys to this cookie with
product id as the key. Then we write that
cookie to Response.Cookies collection.
 Drag and drop a button control on the web
form and write the following code in the click
event handler.
click event handler
 Here, we are simply navigating to the
cart.aspx page which displays the shopping
cart.
private void Button1_Click
(object sender, System.EventArgs e)
{
Response.Redirect("cart.aspx");
}
 So we also need to create the shopping cart
web form
Creating the shopping cart web form
 Add another web form to your project called
cart.aspx
 Create a class called CShoppingCartItem as
shown below:
The Code for the CShoppingCartItem
Continue
 This class is going to represent one item of the
shopping cart.
 Drag and drop a DataGrid on the web form.
 Create a function called FillCartFromCookies() as
shown below
 Here, we are reading the cookies that we set
previously and constructing CShoppingCartItem
instances based on the selected values. These
instances are then added to an ArrayList. Finally,
this ArrayList is bound with the DataGrid.
Code for the FillCartFromCookies()
Write some code for the Recalculate
event
 Drag and drop a button called Recalculate
and write following code to its click event
handler.
 This code calculates the total amount of the
items selected based on the quantity entered
and displays it in a label.
The Code for the Recalculate event
Code to delete items from the cart
Problems with the above Shopping
Carts
 We saw how to use cookies to preserve
shopping cart values.
 This approach is quick and easy to code but
has one big disadvantage.
 Not all browsers will have cookies enabled.
Hence, you should use this technique with
care.
 NOTE I will give you a full working example
using a Shopping Cart using COOKIES
Shopping Carts with Sessions
 In the previous slides we saw how to create a




shopping cart using cookies.
Continuing the concept further in the following slides
we will illustrate how to use session variables to
create a shopping cart.
First we again have to develop a simple product
listing page.
We will then build a simple web form that lists
Products table coming from our database in a
DataGrid control.
We also write a function called BindGrid() as shown
below:
Code for the Datagrid
In the Page_Load event handler
Code in the SelectedIndexChanged
event of the DataGrid
What Are Sessions?
You can use the Session objects to store values that are global rather
than page-specific for either a particular user (the Session) or to all
users (the Application). The Session variables are stored on the
server. Client browsers are then attached to the session through a
cookie. As a result, the client must have cookies enabled in the
browser for Session and Application variables to work.
How to Use Session Variables The power of the Session object
comes from the fact that it can store variables that are global to just
that specific user; as a result, each user can have their own individual
value for that variable.
Session objects are not always created automatically for every user
when they enter your application. However, storing or accessing a
variable in the Session object creates the Session object and fires
the Session_OnStart event.
To demonstrate how to use the Session object in an ASP page, follow
these steps:
Sessions Continue
 Paste the following code between the <BODY>
</BODY> tags of the ASP page that you created
earlier :

<% 'Store information in a Session variable.
Session("myInformation") = "somevalue" 'Display the
contents of the Session variable. Response.Write
Session("myInformation") %>
 Click View in Browser from the View menu.
 When you are prompted to save the file, click OK.
 The browser displays the information in the variable.
Need a Button for Handling
 Notice that we created an ArrayList for storing the
selected products.
 We check whether if we have already stored it in the
session or no. If we have already stored then we get hold
of the existing session variable else we create a new
session variable.
 Then we to Drag and drop a button control on the web
form and write following code in the it's click event
handler, simply navigating to the cart.aspx page which
displays the shopping cart
Creation of the Cart Page- Creation of
the CShoppingCartItem CLASS
 This class is going to represent one item of the shopping cart.
Addition of a DataGrid on the web
form.
 Drag and drop a DataGrid on the web form.
 Create a function called FillCartFromSession() as shown
below.
 Here, we get hold of the ArrayList that we saved in the
session previously and then bind the grid with the arraylist.
Addition of the Recalculate button -Its click event handler
 This code calculates the total amount of the items selected based on the
quantity entered and displays it in a label.
The code to delete items from the cart
 We simply iterate through the ArrayList stored
in the session and remove the item based on
ProductID
Summary
 We saw how to use Session variables to store shopping





cart.
This approach has an advantage as compared to cookie
driven cart that you need not worry whether client
browser is supporting cookies.
On the downside you are putting burden on the server
because in default mode Session variables are stored in
the memory of the web server.
So, this technique is suitable to small to moderately
trafficked web sites.
In the next example we will see how to store shopping
cart in SQL Server database.
NOTE : I will give you a complete working example of
shopping cart using Session Variables
Introduction to Database Driven
Shopping Carts
 In the previous example we saw how to create a
shopping cart using session variables.
 Continuing the concept further the following example
will illustrate how to use the database in order to
store your shopping cart in a database.
 This technique is more robust and scalable that the
previous two techniques.
 Before you proceed with any coding, you need to
create the following table
Creation of the Shopping Cart Table
Developing a simple product listing
page
 We will first build a simple web form that lists
Products from the corresponding table of your
database in a DataGrid control.
 Add a web form called ProductCatalog.aspx t
 Drag and drop a DataGrid control on it.
 Write a function called BindGrid() as shown
below:
Code for BindGrid()
In the Page_Load event handler
private void Page_Load(object sender,
System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindGrid();
}
Code in the SelectedIndexChanged
event of the DataGrid
The CShoppingCartItem class
Addition of a button to redirect to the
Cart page
 private void Button1_Click
(object sender, System.EventArgs e)
{
Response.Redirect("cart.aspx");
}
Here, we are simply navigating to the cart.aspx
page which displays the shopping cart.
The CShoppingCart class
 This is the most important class in our
application because it actually performs the
job of storing or retrieving shopping cart items
into a database table.
 This class uses SqlConnection, SqlCommand
and SqlDataReader classes to perform
various tasks such as INSERT, UPDATE and
SELECT.
 It consists of static methods and looks as
shown below:
Creating the shopping cart web form
 Add another web form to the above project called cart.aspx
 Drag and drop a DataGrid on the web form.
 Create a function called FillCartFromDb() as shown below:
private void FillCartFromDb()
{
DataSet ds=CShoppingCart.GetAll(Session.SessionID);
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
Button1_Click(null,null);
}
Here, we call the GetAll method of the
CShoppingCart class which returns a DataSet. This
DataSet acts as a datasource for the DataGrid
control.
The code for the Recalculate Button
 This code calculates the total amount of the items selected based on
the quantity entered and displays it in a label.
Finally, the code to delete items from
the cart.
 We simply simply delete a particular product
by calling the DeleteItem method of
CShoppingCart class.
Summary
 In this example we saw how to use SQL Server database to store a
shopping cart.
 This approach though requires more coding is recommended for
big sites. Since you are storing the data in a SQL server database,
you are not putting any overhead on the web server (as against
Session variables).
 Also, this approach is better than cookies because you are not
dependent of client browser supporting cookies. In terms of
performance this approach will however be slower than the other
two techniques. However, overall it is more robust and scalable than
cookies or sessions.
 Can somebody think of how to create a single wrapper to all he
three approaches so that without any code change you can switch
between these three techniques??????????
