1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft ASP Net 3.5 Step By Step (phần 12) ppt

30 278 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 30
Dung lượng 1,18 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The LabelShowStringAsSessionState label also shows data because the handler stored that text in session state... Now that you have a working application that uses session state, let’s t

Trang 1

6 Now click Just Submit What happens? Remember, Page_Load simply looks at the

value of the _str member variable and stuffs it into the label Pages (and HTTP handlers in

general) are very short-lived objects They live for the duration of the request and then are destroyed—along with all the data they hold The _str member variable evaporated

as soon as the last request fi nished A new _str member variable (which was empty) was

instantiated as soon as the page was re-created

To sum up, we saw in Chapter 4 that controls manage their own state But in this case, we’re taking the data from the text box and storing them in a member variable in the

Page class The lifetime of the page is very short The page lives long enough to

gener-ate a response, and then it disappears Any stgener-ate you’ve stored as data members in the page disappears too That’s why, when you click the Just Submit button, you don’t see the string displayed You do see the string when Submit String is clicked because the

member variable survives long enough to support the button’s Click event handler

Trang 2

302 Part III Caching and State Management

7 Using session state is a way to solve this issue To show this, add a new label to the

page This one will show the data as retrieved from the Session object:

8 Write code to store the string in session state Have the SubmitString take the text from

the TextBox1 and store it into the Session object Then update the Page_Load method

to display the value as it came from session state as shown below:

public partial class _Default : System.Web.UI.Page

Trang 3

protected void SubmitString_Click(object sender, EventArgs e)

9 Run the program Type in a string and click the Submit String button Both labels

should contain data The LabelShowString label will hold data because the SubmitString

handler made the member variable assignment The LabelShowStringAsSessionState

label also shows data because the handler stored that text in session state

Trang 4

304 Part III Caching and State Management

10 Now click the Just Submit button and see what happens:

In this case, the page was simply submitted, causing only the Page_Load to be

execut-ed Page_Load displays both the _str member variable (which is empty because it lives

and dies with the page) and the data from the Session object (which lives independently

of the page)

As you can see, session state is pretty convenient However, we wouldn’t get very far if all we could do was store simple strings and scalars Fortunately, the session dictionary stores all manner of CLR objects

Session State and More Complex Data

ASP.NET’s Session object will store any (serializable) object running within the CLR That goes

for larger data—not just small strings or other scalar types One of the most common uses for the Session object is for implementing features like shopping carts (or any other data that

has to go with a particular client) For example, if you’re developing a commerce-oriented site for customers to purchase products, you’d probably implement a central database repre-senting your inventory Then, as users sign on, they will have the opportunity to select items

Trang 5

from your inventory and place them in a temporary holding area associated with the session they’re running In ASP.NET, that holding area is typically the Session object

A number of different collections are useful for managing shopping cart-like scenarios Probably the easiest to use is the good ol’ ArrayList—an automatically sizing array that sup-

ports both random access and the IList interface However, for other scenarios you might use

a DataTable, a DataSet, or some other more complex type

We took a quick look at ADO and data access in Chapter 11 The next example revisits bound controls (the DataList and the GridView) We’ll also work with the DataTable in depth

Session state, ADO.NET objects, and data-bound controls

This example illustrates using ADO.NET objects, data-bound controls, and session state to transfer items from an inventory (represented as a DataList) to a collection of selected items

(represented using a GridView)

1 Create a new page on the SessionState site named UseDataList.aspx

Add DataList to the page by copying the following code between the <div> tags on

the generated page The DataList will display the elements in the NET References table

from the Access database we saw in Chapter 11

<asp:DataList ID="DataList1"

runat="server" BackColor="White" BorderColor="#E7E7FF"

BorderStyle="None" BorderWidth="1px" CellPadding="3"

GridLines="Horizontal"

Style="z-index: 100; left: 8px; position: absolute; top: 16px"

OnItemCommand="DataList1_ItemCommand" Caption="Items in Inventory" >

<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

Trang 6

306 Part III Caching and State Management

Text='<%# Eval("Topic") %>'></asp:Label><br />

The Visual Studio designer should appear like this when done

2 Stub out a shell for the SelectItem button on Click handler Select DataList1 on the

page In the Properties dialog box within Visual Studio, click the lightning bolt button

to get the events In the edit box next to the ItemCommand event, type SelectItem

The button handler should be named DataList1_ItemCommand to match the identifi er

Trang 7

in the DataList1 We’ll use it shortly to move items from the inventory to the selected

3 Go back to the code for the page and add some code to open a database and populate

the DataList Name the function GetInventory The examples that come with this book

include a database named ASPDotNetStepByStep.mdb that will work Add the database

from Chapter 11’s example to the App_Data folder of this project You can use the nection string listed below to connect to the database Make sure the database path points to the fi le correctly using your directory structure

con-public partial class UseDataList : System.Web.UI.Page

DataTable dt = new DataTable();

using (DbConnection connection = f.CreateConnection())

{ connection.ConnectionString = strConnection;

connection.Open();

DbCommand command = f.CreateCommand();

command.CommandText = "Select * from DotNetReferences";

Trang 8

308 Part III Caching and State Management

4 Now add a method named CreateSelectedItemsData This will be a table into which

se-lected items will be placed The method will take a DataTable object that will describe

the schema of the data in the live database (we’ll see how to get that soon) You can create an empty DataTable by constructing it and then adding Columns to the column

collection The schema coming from the database will have the column name and the data type

public partial class UseDataList : System.Web.UI.Page

5 Add code to the Page_Load handler When the initial request to a page is made (that

is, if the request is not a postback), Page_Load should call BindToInventory (which

re-turns the DataTable snapshot of the DotNetReferences table) Use the DataTable as

the schema on which to base the selected items table That is, declare an instance of

a DataTable and assign it the result of CreateSelectedItemsTable Then store the (now

empty) table in the Session object using the key tableSelectedItems

public partial class UseDataList : System.Web.UI.Page

Trang 9

}

}

Browse to the Web site to make sure that the database connects It should look thing like this:

6 Now add a GridView to the page Don’t bother to give it a data source It represents

the table of selected items held in session state We’ll add that shortly Make sure the

AutoGenerateColumns property is set to true

Trang 10

310 Part III Caching and State Management

7 Finally, add a handler for the SelectItem button This method should move items from

the inventory to the selected items table You can get the selected item index from the DataListCommandEventArgs coming into the handler Calling BindToInventory will

set up the DataList data source so you can fetch the selected item You may access the

columns within the selected row using ordinal indices From the values in each column, construct a new DataRow and add it to the selected items table Store the modifi ed

table back in session state Finally, apply the new selected items table to the DataSource

in the GridView1 and bind the GridView1

public partial class UseDataList : System.Web.UI.Page

// Order of the columns is:

// ID, Title, FirstName, LastName, Topic, Publisher

DataTable dt = (DataTable)DataList1.DataSource;

String strID = (dt.Rows[nItemIndex][0]).ToString();

String strTitle = (dt.Rows[nItemIndex][1]).ToString();

String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();

String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();

String strTopic = (dt.Rows[nItemIndex][4]).ToString();

String strPublisher = (dt.Rows[nItemIndex][5]).ToString();

8 Run the site When the page fi rst comes up, you should see only the inventory list

on the left side of the page Click the Select Item button on some of the items You should see your browser post back to the server and render the DataList and the GridView with the newly added selected item

Trang 11

Now that you have a working application that uses session state, let’s take a look at the ferent ways in which you may confi gure ASP.NET session state

Confi guring Session State

ASP.NET gives you several choices for managing session state You can turn it off completely, you may run session state in the ASP.NET worker process, you may run it on a separate state server, or you may run it from a SQL Server database Here’s a rundown of the options available:

Don’t use it at all By disabling session state, your application performance will

in-crease because the page doesn’t need to load the session when starting, nor does it need to store session state when it’s going away On the other hand, you won’t be able

to associate any data with a particular user between page invocations

Store session state “in proc.” This is how session state is handled by default In this

case, the session dictionaries (the Session objects) are managed in the same process as

the page and handler code The advantage of using session state in process is that it’s very fast and convenient However, it’s not durable For example, if you restart IIS or somehow knock the server down, all session state is lost In some cases, this may not be

a big deal However, if your shopping cart represents a shopping cart containing sizable orders, losing that might be a big deal In addition, the in-process Session manager is confi ned to a single machine, meaning you can’t use it in a Web farm (A Web farm is a

group of servers tied together to serve Web pages as a single application.)

Trang 12

312 Part III Caching and State Management

Store session state in a state server This option tells the ASP.NET runtime to direct

all session management activities to a separate Windows Service process running on

a particular machine This option gives you the advantage of running your server in a Web farm The ASP.NET Session State facilities support Web farms explicitly To run in

a Web farm, you would direct all your applications to go to the same place to retrieve session information The downside to this approach is that it does impede performance somewhat—applications need to make a network round-trip to the state server when loading or saving session information

Store session state in a database Confi guring your application to use a SQL Server

database for state management causes ASP.NET to store session information within a SQL Server database somewhere on your network Use this option when you want to run your server from within a Web farm when you want session state to be durable and safe When confi guring ASP.NET session state during development, you may edit the confi guration

fi le directly Once your site is deployed, you may prefer to confi gure session state through the session state confi guration page in IIS

Turning Off Session State

The ASP.NET session state confi guration tool available through IIS will touch your Web site’s web.confi g fi le and insert the right confi guration strings to enforce the settings you choose

To turn off session state completely, select Off from the session state mode control

Trang 13

Storing Session State InProc

To store session state in the ASP.NET worker process, select InProc from the session state

mode control Your application will retrieve and store session information very quickly, but it will be available only to your application on the particular server the session information was originally stored within (that is, the session information will not be available to other servers that might be working together on a Web farm)

Storing Session State in a State Server

To have ASP.NET store session state on another server on your network, select StateServer

from the SessionState mode control When you select this item, the dialog box will enable the Connection String text box and the network Timeout text box Insert the protocol, Internet

Protocol (IP) address, and port for the state server in the Connection String text box For

ex-ample, the string

tcpip=loopback:42424

will store the session state on the local machine over port 42424 If you want to store the sion state on a machine other than your local server, change the IP address Before session state is stored on a machine, you need to make sure the ASP.NET state service is running on that machine You may get to it via the Services panel under the control panel and the ad-ministration tools

Trang 14

ses-314 Part III Caching and State Management

Storing Session State in a Database

The fi nal option for storing session state is to use a SQL Server database Select SQLServer

from the ASP.NET session state mode combo box You’ll be asked to enter the connection string to the SQL Server state database Here’s the string provided by default:

data source=localhost;Integrated Security=SSPI

You may confi gure ASP.NET so it references a database on another machine Of course, you need to have SQL Server installed on the target machine to make this work In addition, you’ll fi nd some SQL scripts to create the state databases in your NET system directory (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 on this machine at the time of this writing) The aspnet_regsql.exe tool will set up the databases for you

Tracking Session State

Because Web-based applications rely on HTTP to connect browsers to servers and HTML

to represent the state of the application, ASP.NET is essentially a disconnected architecture When an application needs to use session state, the runtime needs a way of tracking the ori-gin of the requests it receives so that it may associate data with a particular client ASP.NET offers three options for tracking the session ID—via cookies, the URL, or device profi les

Tracking Session State with Cookies

This is the default option for an ASP.NET Web site In this scenario, ASP.NET generates a to-guess identifi er and uses it to store a new Session object You can see the session identifi er

hard-come through the cookie collection if you have tracing turned on Notice how ASP.NET stores the session ID in a request cookie The tracing information also reveals the names and the values of the session variables

Ngày đăng: 07/07/2014, 06:20

TỪ KHÓA LIÊN QUAN