Академический Документы
Профессиональный Документы
Культура Документы
HTTP is a stateless protocol. After every web request, the client disconnects from the
server, and the ASP.NET engine discards the objects that were created for the page. So that State
Management techniques used to maintaining information on the server and on the client. You
choose the right option depending on the data you need to store, the length of time you want to
store it, the scope of your data (whether it's limited to individual or shared across multiple
requests), and additional security and performance considerations.
1. View State
2. Query String
3. Custom Cookies
4. Session State
5. Application State
6. Profile
7. Caching
1. View State
Allowed data types: All serializable .NET data types.
Storage location: A hidden field in the current web page.
Lifetime: Retained permanently for postbacks to a single page.
Scope: Limited to the current page.
Security: Tamper-proof by default but easy to read.
Performance: Storing a large amount of information will slow transmission but will not
affect server performance.
Typical use: Page-specific settings (Maintaining state/information for each page).
ViewState["Counter"] = 1;
int counter;
counter = (int) ViewState["Counter"];
2. Query String
Allowed data types: A limited amount of string data.
Storage location: The browser's URL string.
Lifetime: Lost when the user enters a new URL or closes the browser.
Scope: Limited to the target page.
Security: Clearly visible and easy for the user to modify.
Performance: None, because the amount of data is trivial.
Typical use: Sending information from current page to target page.
3. Cookies
Allowed data types: String data.
Storage location: The client's computer.
Lifetime: Set by the programmer.
Scope: The whole ASP.NET application.
Security: Insecure and can be modified by the user.
Performance: None, because the amount of data is trivial.
Typical use: Personalization preferences for a website.
4. Session State
Allowed data types: All serializable .NET data types. Nonserializable types are supported if
you are using the default in-process state service.
Storage location: Server memory (by default), or a dedicated database, depending on
the mode you choose.
Lifetime: Times out after a predefined period (usually 20 minutes but can be altered
globally or programmatically).
Scope: The whole ASP.NET application.
Security: Secure.
Performance: Storing a large amount of information can slow down the server.
Typical use: Maintain information/state for individual users.
Session Architecture
Session management is not part of the HTTP standard. As a result, ASP.NET needs to do some
extra work to track session information and bind it to the appropriate response.
ASP.NET tracks each session using a unique 120-bit identifier. ASP.NET uses a proprietary
algorithm to generate this value [Session Id]. This ID is the only piece of information that is
transmitted between the web server and the client. When the client presents the sessionID,
ASP.NET looks up the corresponding session, retrieves the serialized data from the state server,
converts it to live objects, and places these objects into special collection so they can be accessed
in code. This process takes place automatically.
Class: System.Web.SessionState.HttpSessionState
Session state can be lost in several ways:
>> Close and restarts the browser
>> Access the same page through a different browser window.
>> Session Time out.
>> Calling Session.Abandon()
<configuration>
<system.web>
<sessionState mode="StateServer/SQLServer/Off/Custom/InProc"
stateConnectionString ="tcpip=127.0.0.1:42424"
stateNetworkTimeout ="10"
sqlConnectionString ="data source=127.0.0.1;
Integrated Security=SSPI"
sqlCommandTimeout ="30"
allowCustomSqlDatabase ="false"
useHostingIdentity ="true"
cookieless ="UseCookies"
cookieName ="ASP.NET_SessionId"
regenerateExpiredSessionId ="false"
timeout ="20"
customProvider ="" />
</system.web>
</configuration>
Off: This setting disables session state management for every page in the application.
InProc: Default option. It instructs ASP.NET to store information in the current application
domain.
StateServer: Use a separate Windows service for state management.
SQLServer: Use a SQL Server database to store session information. as identified by the
sqlConnectionString attribute.
5. Application State
6. Profiles
7. Caching
Page.IsPostBack Property
Gets a value indicating whether the page is being loaded in response to a client postback, or if it
is being loaded and accessed for the first time.
Property Value
True if the page is being loaded in response to a client postback; otherwise, false.
Overview of ADO.NET
ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as
data sources exposed through OLE DB and XML. Data-sharing consumer applications can use
ADO.NET to connect to these data sources and retrieve, manipulate, and update data.
ADO.NET includes .NET Framework data providers for connecting to a database, executing
commands, and retrieving results. Those results are either processed directly, or placed in an
ADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combined
with data from multiple sources, or remoted between tiers. The ADO.NET DataSet object can
also be used independently of a .NET Framework data provider to manage data local to the
application or sourced from XML.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes
found in System.Xml.dll. When compiling code that uses the System.Data namespace, reference
both System.Data.dll and System.Xml.dll.
ADO.NET Architecture
ADO.NET Components
The ADO.NET components have been designed to factor data access from data manipulation.
There are two central components of ADO.NET that accomplish this: the DataSet, and the .NET
Framework data provider, which is a set of components including the Connection, Command,
DataReader, and DataAdapter objects.
The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET.
The DataSet is explicitly designed for data access independent of any data source. As a result it
can be used with multiple and differing data sources, used with XML data, or used to manage
data local to the application. The DataSet contains a collection of one or more DataTable
objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and
relation information about the data in the DataTable objects.
The DataTable Object represents tabular data as rows, columns and constraints. Use the
DataTable object to hold data in memory while performing disconnected data operations.
class Program
{
private DataTable getDataTable()
{
//Create the DataTable named "employee".
DataTable employee = new DataTable("Employee");
DataView
static void Main(string[] args)
{
DataSet ds = new DataSet();
Program p = new Program();
ds.Tables.Add(p.getDataTable());
//Sort and Display
DataView view = new DataView(ds.Tables[0]);
view.Sort = "LastName ASC, FirstName ASC, Salary DESC";
view.RowFilter = "LastName like 'A%' and Salary > 15";
GridView.DataSource = view;
GridView1.DataBind();
Console.ReadLine();
}
Using ADO.NET Connected Classes
The other core element of the ADO.NET architecture is the .NET Framework data provider,
whose components are explicitly designed for data manipulation and fast, forward-only, read-
only access to data. The Connection object provides connectivity to a data source. The
Command object enables access to database commands to return data, modify data, run stored
procedures, and send or retrieve parameter information. The DataReader provides a high-
performance stream of data from the data source. Finally, the DataAdapter provides the bridge
between the DataSet object and the data source. The DataAdapter uses Command objects to
execute SQL commands at the data source to both load the DataSet with data, and reconcile
changes made to the data in the DataSet back to the data source.
A .NET Framework data provider is used for connecting to a database, executing commands, and
retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet
in order to be exposed to the user in an ad-hoc manner, combined with data from multiple
sources, or remoted between tiers. The .NET Framework data provider is designed to be
lightweight, creating a minimal layer between the data source and your code, increasing
performance without sacrificing functionality.
The following table outlines the four core objects that make up a .NET Framework data provider.
Object Description
Connection Establishes a connection to a specific data
source.
Command Executes a command against a data source.
Exposes Parameters and can execute within the
scope of a Transaction from a Connection.
DataReader Reads a forward-only, read-only stream of data
from a data source.
DataAdapter Populates a DataSet and resolves updates with
the data source.
The following table shows the providers have been tested with ADO.NET.
Driver Provider
SQLOLEDB Microsoft OLE DB Provider for SQL Server
MSDAORA Microsoft OLE DB Provider for Oracle
Microsoft.Jet.OLEDB.4.0 OLE DB Provider for Microsoft Jet
Choosing a .NET Framework Data Provider
Depending on the design and data source for your application, your choice of .NET Framework
data provider can improve the performance, capability, and integrity of your application. The
following table discusses the advantages and limitations of each .NET Framework data provider.
Provider Notes
.NET Framework Data Recommended for middle-tier applications using Microsoft SQL Server
Provider for SQL 7.0 or later.
Server
Recommended for single-tier applications using Microsoft Data Engine
(MSDE) or Microsoft SQL Server 7.0 or later.
For Microsoft SQL Server version 6.5 and earlier, you must use the
OLE DB Provider for SQL Server with the .NET Framework Data
Provider for OLE DB.
.NET Framework Data Recommended for middle-tier applications using Microsoft SQL Server
Provider for OLE DB 6.5 or earlier, or any OLE DB provider that supports the OLE DB
interfaces listed in OLE DB Interfaces Used by the .NET Framework
Data Provider for OLE DB (OLE DB 2.5 interfaces are not required).
For Microsoft SQL Server 7.0 or later, the .NET Framework Data
Provider for SQL Server is recommended.
The .NET Framework Data Provider for Oracle classes are located in
the System.Data.OracleClient namespace and are contained in the
System.Data.OracleClient.dll assembly. You need to reference both
the System.Data.dll and the System.Data.OracleClient.dll when
compiling an application that uses the data provider.
System.Data.Common Namespace
The System.Data.Common namespace contains classes shared by the .NET Framework data
providers.
A .NET Framework data provider describes a collection of classes used to access a data source,
such as a database, in the managed space. Supported providers include the .NET Framework
Data Provider for ODBC, the .NET Framework Data Provider for OLEDB, the .NET Framework
Data Provider for Oracle, and the .NET Framework Data Provider for SQL Server. The classes in
System.Data.Common are intended to give developers a way to write ADO.NET code that will
work against all .NET Framework data providers.
For conceptual information about how to use this namespace when programming with the.NET
Framework, see Writing Provider Independent Code with ADO.NET.
appSettings Element
Contains custom application settings, such as file paths, XML Web service URLs, or any
information that is stored in the.ini file for an application.
<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>
<appSettings file="">
<settings>
<clear />
</settings>
</appSettings>
<appSettings>
<add key="DocumentPath" value="~/DocumentPath/"/>
<add key="FileType" value=".doc,.jpg,.bmp,.gif,.pdf"/>
<!-- File Limit 4 MB ( 4096 ) -->
<add key="FileSizeLimit" value="4096"/>
<add key="debugMode" value="0"/>
<add key="LogFilePath"
value="D:\backup\Projects\MFDA.S.0007.MOBLD\Source
Code\MOBLD\MOWebSite\Log\mobld.log"/>
<add key="ServiceUser" value="mfdawebadmin"/>
<add key="ServicePwd" value="~password"/>
<add key="HelpFile" value="~/Help/MFDA_help.pdf"/>
<add key="MOWebService.moservice"
value="http://localhost:2914/MOService/MOService.asmx"/>
<add key="UMWebService.umservice"
value="http://localhost:2918/UMService/UMService.asmx"/>
<add key="FCKeditor:UserFilesPath" value="~/UserFiles/" />
</appSettings>
====================================================================
string sSmtpServer =
System.Configuration.ConfigurationManager.AppSettings["SmtpServer"];
ConnectionStrings Element
<connectionStrings >
<add /> Adds a connection string as a name/value pair to the collection of
connection strings.
<clear /> Removes all references to inherited connection strings, allowing
only the connection strings that are added by the current add element.
<remove /> Removes a reference to an inherited connection string from the
collection of connections strings.
</connectionStrings>
<connectionStrings>
<add name="MOBLDUM" connectionString="Data Source=svr2k02;Initial
Catalog=MFDAUM;Persist Security Info=True;User ID=sa;PWD=password;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
string ConnectionString =
WebConfigurationManager.ConnectionString["NorthWind"].ConnectionSrting;
cmd.Connection = con;
OR
===============================================================
cmd.CommandType = CommandType.StoredProcedure;
1. SqlCommand.ExecuteNonQuery Method
Executes a Transact-SQL statement against the connection and returns the number of rows
affected. E.g. SELECT, INSERT, DELETE, UPDATE etc.
2. SqlCommand.ExecuteScalar Method
Executes the query, and returns the first column of the first row in the result set returned by the
query. Additional columns or rows are ignored.
3. SqlCommand.ExecuteReader Method
Executes a SELECT query and returns a DataReader object that wraps a read-only, forward-only
cursor.
@TitleOfCourtesy varchar(25),
@LastName varchar(20),
@FirstName varchar(10),
AS
string connectionString =
WebConfigurattionManager.ConnectionStrings["Northwind"].ConnectionString;
cmd.Parameters["TitleOfCourtesy"].value = title;
cmd.Parameters["@EmployeeID"].Direction = ParameterDirection.Output;
Transactions
Transactions in ADO.NET are used when you want to bind multiple tasks together so that
they execute as a single unit of work.
</Columns>
</asp:GridView>
}
protected void Button1_Click(object sender, EventArgs e)
{
//wsObj.WSUpdateStatus(1, 1);
int i;
//for (i = 0; i < CheckBoxList1.Items.Count - 1; i++)
//{
// if (CheckBoxList1.Items[i].Selected)
// wsObj.WSUpdateStatus(1,
Convert.ToInt32(CheckBoxList1.Items[i].Value));
// else
// wsObj.WSUpdateStatus(0,
Convert.ToInt32(CheckBoxList1.Items[i].Value));
//}
//for (i = 0; i < RadioButtonList1.Items.Count - 1; i++)
//{
// if (RadioButtonList1.Items[i].Selected)
// wsObj.WSUpdateStatus(1,
Convert.ToInt32(RadioButtonList1.Items[i].Value));
// else
// wsObj.WSUpdateStatus(0,
Convert.ToInt32(RadioButtonList1.Items[i].Value));
//}
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = bindGrid();
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//string aa = e.SortExpression;
if (ViewState["SortExp"] != null)
{
if (ViewState["Exp"].ToString() == "Asc")
{
ViewState["SortExp"] = e.SortExpression + " Desc";
ViewState["Exp"] = "Desc";
}
else
{
ViewState["SortExp"] = e.SortExpression + " Asc";
ViewState["Exp"] = "Asc";
}
}
else
{
ViewState["SortExp"] = e.SortExpression + " Asc";
ViewState["Exp"] = "Asc";
}
GridView1.DataSource = bindGrid();
GridView1.DataBind();
}
}
<br />
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="~/Files/Indexdotnet.pdf">Link</asp:HyperLink><br />
<br />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
if (status)
{
DataRow dr = dt.NewRow();
dr["Sl"] = Convert.ToInt32(GridView1.Rows[i].Cells[0].Text);
dr["Name"] = GridView1.Rows[i].Cells[0].Text;
dr["Address"] = GridView1.Rows[i].Cells[0].Text;
dr["status"] = status;
dt.Rows.Add(dr);
}
}
if (dt.Rows.Count > 0)
{
ds.Tables.Add(dt);
objService.WSWriteXML(ds);
}
}
}
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
MakeDataTables();
}
dataSet.Tables.Add(table);
DataSet
The DataSet, which is an in-memory cache of data retrieved from a data source, is a major
component of the ADO.NET architecture. The DataSet consists of a collection of DataTable
objects that you can relate to each other with DataRelation objects.
Creating a DataSet
You create an instance of a DataSet by calling the DataSet constructor. Optionally specify a
name argument. If you do not specify a name for the DataSet, the name is set to "NewDataSet".
ADO.NET enables you to create DataTable objects and add them to an existing DataSet. You can
set constraint information for a DataTable by using the PrimaryKey and Unique properties.
DataColumn pkOrderID =
ordersTable.Columns.Add("OrderID", typeof(Int32));
ordersTable.Columns.Add("OrderQuantity", typeof(Int32));
ordersTable.Columns.Add("CompanyName", typeof(string));
A DataView enables you to create different views of the data stored in a DataTable, a capability
that is often used in data-binding applications. Using a DataView, you can expose the data in a
table with different sort orders, and you can filter the data by row state or based on a filter
expression.
Creating a DataView
There are two ways to create a DataView. You can use the DataView constructor, or you can
create a reference to the DefaultView property of the DataTable. The following code example
demonstrates how to create a DataView using the DataView constructor. A RowFilter, Sort
column, and DataViewRowState are supplied along with the DataTable.
The following code example demonstrates how to obtain a reference to the default DataView of
a DataTable using the DefaultView property of the table.
The DataView provides several ways of sorting and filtering data in a DataTable:
• You can use the Sort property to specify single or multiple column sort orders and include
ASC (ascending) and DESC (descending) parameters.
http://msdn.microsoft.com/en-us/library/03c7a3zb.aspx
There are two methods you can use to delete a DataRow object from a DataTable object: the
Remove method of the DataRowCollection object, and the Delete method of the DataRow
object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the
Delete method only marks the row for deletion. The actual removal occurs when the application
calls the AcceptChanges method. By using Delete, you can programmatically check which rows
are marked for deletion before actually removing them. When a row is marked for deletion, its
RowState property is set to Deleted.
When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data
source, use the Delete method of the DataRow to remove the row. The Delete method marks the
row as Deleted in the DataSet or DataTable but does not remove it. Instead, when the
DataAdapter encounters a row marked as Deleted, it executes its DeleteCommand method to
delete the row at the data source. The row can then be permanently removed using the
AcceptChanges method. If you use Remove to delete the row, the row is removed entirely from
the table, but the DataAdapter will not delete the row at the data source.
The Remove method of the DataRowCollection takes a DataRow as an argument and removes
it from the collection, as shown in the following example.
workTable.Rows.Remove(workRow);
In contrast, the following example demonstrates how to call the Delete method
on a DataRow to change its RowState to Deleted.
workRow.Delete();
If a row is marked for deletion and you call the AcceptChanges method of the DataTable
object, the row is removed from the DataTable. In contrast, if you call RejectChanges, the
RowState of the row reverts to what it was before being marked as Deleted.