In this example we will briefly touch ADO.Net , to understand dataset, data-adapter, command

Ado.Connected and ADO.Disconnected Model. : In the connected model the you code will connect and disconnect with the data source. There are three classes will mainly hold the information to get back to the data source.  Where as in the dis-connected model Data can be obtained once, then remains disconnected from the data source.

LINQ from Microsoft offering a choice to the programmer Not Knowing enough of ADO.NET (Good or Bad too)

  • ADO.Connected , threre are three main and fundamental classes. These classes will store data using these classes.
    • Connection : SqlConnection
    • command:    SqlCommand
    • DataReader : Read the data base (it is faster than DadaAdapter) forward only
  • ADO Disconnected
    • DataAdapter : SqlDataAdapter : transfer data from physical database to the memory.
      • will have choice of choosing the command type for batch operation.
    • DataTable : in-memory database table to work with
    • DataView : in memory data view
    • DadaSet : in-memory Dataset capable to edit original data in bulk. There fore there is no need of keeping the connection-link alive
  • DataRow Extract Data, serialize as in a Label.Text from DataSet.Table
  • ForEach loop
  • using (SqlConnection connection = new SqlConnection(connectionString))

Objectives to Learn

  • Creating New DataBase Using Server Explorer.
  • Crating a table as Database owner as dbo,
  • Here the default page will have the "Connection String to the database.
  • Note :
    • When you are adding an existing database, Visual Studio just creating a Replica or Representation-Copy of the original Database, meaning that one point many users can use/edit/develop this database, ( Note: think about Conflicts during simultaneous edit/commit/new data entry-- we deal with those conflicts later).
    • Connection to database would connect you to the database, add a string to Web.config
  • Using Dataset
  • Using Code We created two SQL table and also showed that same can be done using Generate Script
  • Retrieving Row values from GridView , Using 'foreach loop" , DataSet and DataRow subsequently.

 

Step 1: Create New Web Site ( http://manas6/aspnet.35/mm.codedataset/ )

Step 2 Create new Database using

Step 3: Create a table using this code or use GUI to create the table

CREATE TABLE Dset1
( sid nchar(10) NOT NULL, FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
Note varchar(50) NULL)

You may also use this DROP statement to destroy the table and recreate it. However, you may skip this learning SQL language and use Generate Change Script to save the code for you.

/*
Thursday, November 13, 20084:39:18 PM
User:
Server: MANAS6\SQLEXPRESS
Database: CodeDataSet
Application:
*/

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Table1
(
id nchar(10) NOT NULL,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
Note varchar(MAX) NULL
) ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.Table1 ADD CONSTRAINT
PK_Table1 PRIMARY KEY CLUSTERED
(
id
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
COMMIT
 

Step 4 : create another table dsMain that will hold "mid" and will be used to create a relationship with the other tables.

Add/Fill data using the Visual tool " Server Explorer > Tables > Show Table Data

Now we start editing the existing code in Default.aspx.cs

//wrong
//Data Source=MANAS6\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False
//correct
// Data Source=MANAS6\\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False
private string strCnn= "Data Source=MANAS6\\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False";
// private string strcnn2 = "Data Source=(MANAS6\\SQLEXPRESS);Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False";
 

Now add two Label and One GirdView control

Code Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>mm.CodeDataSet: Query.SQL</title>
<style type="text/css">
body { background-color :Gray; }
#div1 { background-color:#FFFFCC; width: 350px; height:auto; }
#div2 { background-color:#FFFFCC; width: 350px;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div >
<div id="div1"><asp:Label ID="L1" runat="server" Text="Connection: Operation <br/>"></asp:Label>
</div>
<asp:GridView ID="GridView1" runat="server" BackColor="#CCFFCC" Caption="Code Filled GridView"
>
</asp:GridView><br />
<div id="div2"><asp:Label ID="L2" runat="server" Text="Read Rows as String : </br/>"></asp:Label></div>
</div>
</form>
</body>
</html>
 

Code Default.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
//
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
//wrong
//Data Source=MANAS6\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False
//correct
// Data Source=MANAS6\\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False
private string strCnn= "Data Source=MANAS6\\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False; ";
// private string strcnn2 = "Data Source=(MANAS6\\SQLEXPRESS);Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False";

protected void Page_Load(object sender, EventArgs e)
{
string connectionString = GetConnectionString();
data_loader(connectionString);

}
protected void data_loader(string connectionString)

{
using (SqlConnection connection = new SqlConnection(connectionString))

{
//Create a SqlDataAdapter for the Suppliers table.
SqlDataAdapter adapter = new SqlDataAdapter();
// A table mapping names the DataTable.
adapter.TableMappings.Add("Table", "Dest1");
try
{
// Open the connection.
connection.Open();
L1.Text += "<br/>The SqlConnection is open.";
// Create a SqlCommand to retrieve Dset1 data.
SqlCommand command = new SqlCommand("SELECT * FROM dbo.Dset1;",connection);
command.CommandType = CommandType.Text;
L1.Text += "<br/>The command text ." + command.ToString();
// Set the SqlDataAdapter's SelectCommand.
adapter.SelectCommand = command;
L1.Text += "<br/>The DataAdpater worked through command .";
// Fill the DataSet.
DataSet dataSet1 = new DataSet("Dset1");
/*
* as an alternate we could have used i
* DataSet dataSet2 = new DataSet();
* adapter.Fill(dataSet2, "Dset1");
*/

adapter.Fill(dataSet1);
L1.Text += "<br/>The Is Filled .Databale started ";
GridView1.DataSource = dataSet1;
GridView1.DataBind();
L2.Text += "Show Id, FirstName LastName";
foreach (DataRow row in dataSet1.Tables["Dest1"].Rows)
{
L2.Text += "-----<br/> " + row["id"].ToString() + " ---" +
row["FirstName"].ToString() + " --- " +row["LastName"].ToString();
}
}
catch (Exception error)
{
L1.Text = error.Message.ToString();
}
finally
{
connection.Close();
L1.Text += "<br/>The Connection Closed .";
}
}
}
private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
//Data Source=MANAS6\SQLEXPRESS;Initial Catalog=CodeDataSet;Integrated Security=True;Pooling=False
return strCnn;
}
}
 

An alternate way to fill SQLDataAdapter

Runtime analysis, and clues to understand GrivView Events

 

 

Mix -Match & Disconnected model

MSDN : Source bridging two concepts connected and disconnected

The .NET Framework Data Providers are components that have been 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 that were made to the data in the DataSet back to the data source. For more information, see .NET Framework Data Providers (ADO.NET) and Retrieving and Modifying Data in ADO.NET.

Choosing a DataReader (Connected ) or a DataSet (Disconnected)

When you decide whether your application should use a DataReader (see Retrieving Data Using a DataReader (ADO.NET)) or a DataSet (see DataSets, DataTables, and DataViews (ADO.NET)), consider the type of functionality that your application requires. Use a DataSet to do the following:
  • Cache data locally in your application so that you can manipulate it. If you only need to read the results of a query, the DataReader is the better choice.
  • Remote data between tiers or from an XML Web service.
  • Interact with data dynamically such as binding to a Windows Forms control or combining and relating data from multiple sources.
  • Perform extensive processing on data without requiring an open connection to the data source, which frees the connection to be used by other clients.

If you do not require the functionality provided by the DataSet, you can improve the performance of your application by using the DataReader to return your data in a forward-only, read-only manner. Although the DataAdapter uses the DataReader to fill the contents of a DataSet (see Populating a DataSet from a DataAdapter (ADO.NET)), by using the DataReader, you can boost performance because you will save memory that would be consumed by the DataSet, and avoid the processing that is required to create and fill the contents of the DataSet.

 

Connected ADO :
Being Connected
Before deciding when to use a DataReader, it is smart to understand its features and limitations. The DataReader has a defined set of operations that revolve around its connected, forward-only, read-only nature (the read-only DataReader is also known as the firehose cursor of ADO.NET). A DataReader is a stream of data that is returned from a database query. When the query is executed, the first row is returned to the DataReader via the stream. The stream then remains connected to the database, poised to retrieve the next record. The DataReader reads one row at a time from the database and can only move forward, one record at a time. As the DataReader reads the rows from the database, the values of the columns in each row can be read and evaluated, but they cannot be edited.
Unlike the DataSet, the DataReader is not implemented directly in the System.Data namespace. Rather, the DataReader is implemented through a specific managed provider's namespace such as System.Data.SqlClient.SqlDataReader. Because all DataReaders, including the OleDbDataReader, the SqlDataReader, and other managed provider's DataReaders implement the same IDataReader interface, they should all provide the same base set of functionality. Each DataReader is optimized for a specific data provider. If the database you are developing against has a managed provider for ADO.NET, then you should take advantage of it. Otherwise, you can use the System.Data.OleDb or the System.Data.Odbc namespaces, which expose more generic managed providers that can access a variety of data sources. If you are developing against SQL Server™ or Oracle, it would be more efficient to use the provider that was made specifically for these databases. In this column, I will query the SQL Server Northwind database using the System.Data.SqlClient namespace.
The fact that the SqlDataReader is part of a specific managed provider's feature set further differentiates it from the DataSet. The SqlDataReader can only retrieve one row at a time from the data source and in order for it to get the next record, it has to maintain its connection to the data source. The DataSet, however, doesn't need to know about where it gets its data. The DataReader can only get its data from a data source through a managed provider. The DataSet can also get its data from a data source via a managed provider, but the data source can also be loaded manually, even from an XML file on a hard drive. If the .NET Framework does not provide a managed provider that is specifically designed for your database, it is certainly worth checking to see if the manufacturer or a third party has one available since they should perform better than the generic OLE DB and ODBC providers.
In ASP.NET, DataReader objects can be used for more robust situations such as binding themselves to an ASP.NET DataGrid or a DropDownList server control. The following code demonstrates how to retrieve a list of products from the Northwind database using a SqlDataReader object:
string sSQL = "SELECT * FROM Products";
string sConnString =
    "Server=(local);Database=Northwind;Integrated Security=SSPI;";
using (SqlConnection oCn = new SqlConnection(sConnString))
{
    SqlCommand oSelCmd = new SqlCommand(sSQL, oCn);
    oSelCmd.CommandType = CommandType.Text;
    oCn.Open();
    SqlDataReader oDr = oSelCmd.ExecuteReader();
    DataGrid1.DataSource = oDr;
    DataGrid1.DataBind();
}
Both a SqlConnection and a SqlCommand object are created. The SqlConnection is opened and the SqlCommand object executes the SQL query, returning the first row to the SqlDataReader. At this point the connection to the database is still open and associated with the SqlDataReader. This code shows how a SqlDataReader can be bound to a bindable object such as an ASP.NET DataGrid.
Alternatively, a DataReader could be used to retrieve the rows and then loop through them manually, one by one. It can support several resultsets as well. For example, a list of products and categories could be retrieved from a database. The following code retrieves a SqlDataReader and loops through its rows, writing the first column's value for each row to the console:
SqlDataReader oDr = oCmd.ExecuteReader();
while(oDr.Read()) {
    Console.WriteLine(oDr[0]);
}

 

 

The Disconnected Side
The DataSet is the main data storage tool in the ADO.NET disconnected architecture. Unlike the DataReader, the DataSet is not connected directly to a database through a Connection object when you populate it. Instead, to fill a DataSet from a database you first create a DataAdapter object (such as a SqlDataAdapter) for the provider and associate it with a SqlConnection object. Then the SqlDataAdapter can broker the data retrieval for the DataSet by issuing a SqlCommand against the database through the SqlConnection, retrieving the data, and filling the DataSet.
You can think of the SqlDataAdapter as a bridge between the connected and disconnected objects. One of its purposes is to serve as the route for a rowset to get from the database to the DataSet. For example, when the SqlDataAdapter's Fill method is executed it opens its associated SqlConnection object (if not already open) and issues its associated SqlCommand object against the SqlConnection. Behind the scenes, a SqlDataReader is created implicitly and the rowset is retrieved one row at a time in succession and sent to the DataSet. Once all of the data is in the DataSet, the implicit SqlDataReader is destroyed and the SqlConnection is closed.
The following code shows how a DataSet can be filled from the Products table of the Northwind database. Notice that there is no explicit SqlDataReader object in this code sample:
string sSQL = "SELECT * FROM Products";
string sConnString = 
    "Server=(local);Database=Northwind;Integrated Security=SSPI;";
SqlDataAdapter oDa = new SqlDataAdapter();
DataSet oDs = new DataSet();
using(SqlConnection oCn = new SqlConnection(sConnString))
{
    SqlCommand oSelCmd = new SqlCommand(sSQL, oCn);
    oSelCmd.CommandType = CommandType.Text;
    oDa.SelectCommand = oSelCmd;
    oDa.Fill(oDs, "Products");
}
The DataSet can read and load itself from an XML document as well as export its rowset to an XML document. Because the DataSet can be represented in XML, it can be easily transported across processes, a network, or even the Internet via HTTP. Unlike the DataReader, the DataSet is not read-only. A DataSet can be modified, and rows can be added or deleted. Changes to a DataSet can be sent to the database via a managed provider's objects. Another key difference between the DataSet and the DataReader is that the DataSet is fully navigable. Its rows can be traversed forward or backward. The DataReader can be traversed forward only. In addition, a DataSet is highly flexible in that its DataTable objects can be filtered vertically or horizontally and they can be sorted or even searched. The DataSet is independent of any one data provider as it relies on a DataAdapter specific to each provider to broker the data between the DataSet and the database.
Not only can the DataSet be loaded from XML, it can also be loaded manually. Notice in Figure 2 how a DataTable is created and its columns added manually. A primary key constraint is established as well as an auto-incrementing value for the key field. Then the DataTable is added to an empty DataSet (though is doesn't have to be empty) and the rows are added one by one to the DataTable, all without ever connecting to a data source.
//-- Create the table
DataTable oDt = new DataTable("Employees");
DataRow oRow;
oDt.Columns.Add("EmployeeID", System.Type.GetType("System.Int32"));
oDt.Columns.Add("FirstName", System.Type.GetType("System.String"));
oDt.Columns.Add("LastName", System.Type.GetType("System.String"));
oDt.Constraints.Add("PK_Employees", oDt.Columns["EmployeeID"], true);
oDt.Columns["EmployeeID"].AutoIncrement = true;
oDt.Columns["EmployeeID"].AutoIncrementSeed = -1000;
oDt.Columns["EmployeeID"].AutoIncrementStep = -1;
oDs.Tables.Add(oDt);

//-- Add the rows
oRow = oDs.Tables["Employees"].NewRow();
oRow["FirstName"] = "Haley";
oRow["LastName"] = "Smith";
oDs.Tables["Employees"].Rows.Add(oRow);
oRow = oDs.Tables["Employees"].NewRow();
oRow["FirstName"] = "Madelyn";
oRow["LastName"] = "Jones";
oDs.Tables["Employees"].Rows.Add(oRow);

//-- Bind it to a DataGrid
grdEmployees.DataSource = oDs.Tables["Employees"];
Because the DataSet is disconnected, its use can reduce the demand on database servers. It does, however, increase the memory footprint in the tier where it is stored, so be sure to account for that when designing around a DataSet as your data store. Scaling up on the middle tier using parallel servers and load balancing is a common way to handle the increased load so that session-based information can be stored in objects such as the DataSet.

 

Some Tips

CREATE

USE [adoConnect1]
GO
/****** Object: Table [dbo].[Main] Script Date: 11/25/2008 12:58:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Main](
[sid] [int] NOT NULL,
[Job] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[FirstName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[LastName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Note] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Main] PRIMARY KEY CLUSTERED
(
[sid] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF

INSERT

INSERT INTO [adoConnect1].[dbo].[Main]
([sid] ,[Job],[FirstName],[LastName],[Note])
VALUES
(<sid, int,>,<Job, varchar(50),>,<FirstName, varchar(50),>,<LastName, varchar(50),>,<Note, text,>)

UPDATE

UPDATE [adoConnect1].[dbo].[Main]
SET [sid] = <sid, int,>
,[Job] = <Job, varchar(50),>
,[FirstName] = <FirstName, varchar(50),>
,[LastName] = <LastName, varchar(50),>
,[Note] = <Note, text,>
WHERE <Search Conditions,,>

DELETE

DELETE FROM [adoConnect1].[dbo].[Main]
WHERE <Search Conditions,,>