Monday, October 11, 2010

AcceptChanges and RejectChanges


AcceptChanges and RejectChanges

The AcceptChanges( ) and RejectChanges( ) methods either accept or reject the changes that have been made to the DataSet since it was last loaded from the data source or since AcceptChanges( ) was last called.
The AcceptChanges( ) method commits all pending changes within the DataSet. Calling AcceptChanges( ) changes the RowState of Added and Modified rows to Unchanged. Deleted rows are removed. The Original values for the DataRow are set to the Current values. Calling the AcceptChanges( ) method has no effect on the data in the underlying data source.
The AcceptChanges( ) method is implicitly called on a row when the DataAdapter successfully updates that row back to the data source when the Update( ) method is called. As a result, when a DataAdapter is used to update the data source with the changes made to the DataSet, AcceptChanges( ) doesn't need to be called. Calling AcceptChanges( ) on a DataSet filled using a DataAdapter effectively removes all information about how the DataSet has been changed since it was loaded. This makes it impossible to reconcile those changes back to the data source using the Update( ) method of the DataSet.
The following example demonstrates the AcceptChanges( ) method:
ds.AcceptChanges();
The RejectChanges( ) method cancels any pending changes within the DataSet. Rows marked as Added are removed from the DataSet. Modified and Deleted rows are returned to their Original state. The following example demonstrates the RejectChanges( ) method:
ds.RejectChanges();
The following example illustrates the concepts just explained:
// create a table with one column
DataTable dt = new DataTable();
dt.Columns.Add("MyColumn",  typeof(System.String));
 
// add three rows to the table
DataRow row;
 
row = dt.NewRow();
row["MyColumn"] = "Item 1";
dt.Rows.Add(row);
 
row = dt.NewRow();
row["MyColumn"] = "Item 2";
dt.Rows.Add(row);
 
row = dt.NewRow();
row["MyColumn"] = "Item 3";
dt.Rows.Add(row);
 
dt.AcceptChanges();
 
// modify the rows
 
dt.Rows[0]["MyColumn"] = "New Item 1"; // DataRowState=Modified
dt.Rows[1].Delete();                   // DataRowState=Deleted
//dt.Rows[2]                           // DataRowState=Unchanged
 
dt.Rows[0].AcceptChanges();            // DataRowState=Unchanged,
                                       // MyColumn value="New Item 1";
dt.Rows[1].RejectChanges();            // DataRowState=Unchanged,
                                       // row not deleted
The DataTable and DataRow objects also expose an AcceptChanges( ) method and a RejectChanges( ) method. Calling these methods on the DataSet implicitly calls these methods for all DataRow objects in the DataSet.

HasChanges and GetChanges

The HasChanges( ) method of the DataSet indicates whether the DataSet has changes, including Added, Deleted, or Modified rows. The method accepts an optional DataRowState argument that causes the method to returns a value from the DataSetRow enumeration if the DataSet has changes:
// check if there are any changes to the DataSet
Boolean hasChanges = ds.HasChanges();
 
// check if there are modified rows in the DataSet
Boolean hasModified = ds.HasChanges(DataRowState.Modified);
The GetChanges( ) method creates a copy of the DataSet containing all the changes that have been made since it was last loaded or since AcceptChanges( ) was called. The method takes an optional DataRowState argument that specifies the type of row changes the DataSet should include. The GetChanges( ) method can select the data that has been modified in a DataSet so that only the changed data rather than the entire DataSet is returned. This subset of the DataSet that contains just the changed data can improve performance of disconnected applications by reducing the amount of information that needs to be transmitted between different application domains.
The HasChanges( ) method can be called first to determine whether GetChanges( ) needs to be called. The following example show how to use the HasChanges( ) and GetChanges( ) methods:
// check to see whether GetChanges needs to be called
if (ds.HasChanges())
{
    // create a DataSet containing all changes made to DataSet ds
    DataSet dsChange = ds.GetChanges();
 
    // create a DataSet containing only modified rows in DataSet ds
    DataSet dsModified = ds.GetChanges(DataRowState.Modified);
}

Adding Custom Information


Adding Custom Information

The DataSet contains a PropertyCollection that is exposed through the ExtendedProperties property. This collection allows a user to add custom information to the DataSet such as the date and time when the DataSet should be refreshed. The following example sets an extended property indicating that the DataSet should be refreshed in 20 minutes:
ds.ExtendedProperties.Add("RefreshDateTime",
    DateTime.Now.AddMinutes(20).ToString());
The following code can then check that value to see if the DataSet needs to be refreshed:
if(DateTime.Now>Convert.ToDateTime(
    ds.ExtendedProperties["RefreshDateTime"].ToString( ) ))
{
    // ... code to refresh the DataSet
}
Extended properties must be of type String, or else they will not persist when the DataSet is written as XML.
The DataTable, DataColumn, DataRelation, and Constraint objects also have a similar collection of extended properties.

Cloning the Schema

The Clone( ) method creates a new DataSet with the same structure, including table schemas and relations, as the original but containing none of the data in the original DataSet. The following example uses the Clone( ) method to create a new DataSet:
// create a DataSet object variable to receive the clone
DataSet cloneDs;
cloneDs = ds.Clone();

Cloning the Schema

The Clone( ) method creates a new DataSet with the same structure, including table schemas and relations, as the original but containing none of the data in the original DataSet. The following example uses the Clone( ) method to create a new DataSet:
// create a DataSet object variable to receive the clone
DataSet cloneDs;
cloneDs = ds.Clone();

Copying the DataSet

The Copy( ) method of the DataSet creates a new DataSet with the same structure, including tables schemas and relations, and data as the original DataSet. The following example uses the Copy( ) method to create a new DataSet:
// create a DataSet object variable to receive the copy
DataSet copyDs;
copyDs = ds.Copy();

Removing All Data

The Clear( ) method removes all rows from all tables in the DataSet:
ds.Clear();

Removing All Data

The Clear( ) method removes all rows from all tables in the DataSet:
ds.Clear();

Committing and Discarding Changes

When a DataRow is modified, ADO.NET marks the row as having a changes and sets the RowState of the DataRow to Added, Modified, or Deleted, as appropriate. ADO.NET also maintains version information by storing both Original and Current versions of each row. Together, this information allows ADO.NET or an application to identify the rows and columns that have been changed.

Adding and Removing Relations


Adding and Removing Relations

Relations belonging to the DataSet are stored as DataRelation objects in a DataRelationCollection object and are accessed through the Relations property of the DataSet. Each DataRelation object represents the relationship between a parent and child table in the DataSet. This section examines some methods and properties of the DataRelationCollection.
Relations are added to the DataSet using the Add( ) method of the DataRelationCollection, as shown in the following example:
ds.Relations.Add("MyDataRelation", parentTable.Columns["PrimaryKeyField"],
    childTable.Columns["ForeignKeyField"]);
The Remove( ) method removes a relation matching the relation-name argument. The following example removes the relation added in the previous example:
ds.Relations.Remove("MyDataRelation");
The Contains( ) method can determine if a specific relation exists as shown in the following example:
Boolean exists = ds.Relations.Contains("MyRelation");

Creating an Untyped DataSet


Creating an Untyped DataSet

There are several ways a DataSet can be created. In the simplest case, a DataSet is created using the new keyword. The constructor accepts on optional argument that allows the DataSetName property to be set. If the DataSetName argument isn't supplied, the default name of the DataSet will be NewDataSet.
DataSet ds = new DataSet("MyDataSet");
A DataSet can also be created from another DataSet. The Copy( ) method can create a new DataSet containing both the schema and data from the original DataSet. The Clone( ) method creates a new DataSet with the same schema, but none of the data of the original. Finally, the GetChanges( ) method creates a new DataSet containing data that has changed since the DataSet was last loaded or the pending changes were accepted.

Working with Tables in the DataSet

Tables belonging to the DataSet are stored as DataTable objects in a DataTableCollection object and accessed through the Tables property of the DataSet. This section examines some methods and properties of the DataTableCollection.
Tables are added to the DataSet using the Add( ) method of the DataTableCollection. The Add( ) method takes an optional table name argument. If this argument isn't supplied, the tables are automatically named Table, Table1, and so on. The following example adds a table to a DataSet:
DataSet ds = new DataSet("MyDataSet");
DataTable dt = new DataTable("MyTable");
ds.Tables.Add(dt);
The AddRange( ) method allows more than one table to be added to the DataSet in the same statement. The method takes an array of DataTable objects as the argument, as the following example shows:
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
ds.Tables.AddRange(new DataTable[] {dt1, dt2});
A DataTable can also be created automatically in a DataSet when the Fill() or FillSchema() method of the DataAdapter is called. A new table is created and filled with the data or schema, respectively, from the data source, as illustrated in the following code:
// connection and select command strings
String connString = "Data Source=(local);Integrated security=SSPI;" + 
    "Initial Catalog=Northwind;";
String selectSql = "SELECT * FROM Orders";
 
// create a new DataSet to receive the data
DataSet ds = new DataSet();
 
SqlDataAdapter da = new sqlDataAdapter(selectSql, connString);
 
// an empty table named OrdersSchema will be created in the DataSet
da.FillSchema(ds, SchemaType.Mapped, "OrdersSchema");
 
// a table named Orders will be created in the DataSet
// filled with data as specified by the SQL statement
da.Fill(ds, "Orders");
Existing tables within the DataSet can be accessed by an indexer, which usually is passed the table name or the position of the table within the DataTableCollection as an argument as shown in the following examples:
// using the table name
DataTable dt = ds.Tables["MyTable"];
 
// using the table ordinal
DataTable dt = ds.Tables[0];
The Count property returns the number of tables within the DataSet:
Int32 tableCount = ds.Tables.Count;
The Contains( ) method determines whether a table with a specified table name exists within a DataSet:
// Boolean tableExists = ds.Tables.Contains("MyTable");
The IndexOf( ) method returns the index of the table within the collection using either a reference to the table object or the name of a table. The following example demonstrates both techniques:
// get the index using the name of the table
Int32 tableIndex = ds.Tables.IndexOf("MyTable");
 
// get the index using a reference to a table
DataTable dt = ds.Tables.Add("MyTable")
 
// ... build the table and do some work
 
// get the index of the table based on the table reference
Int32 tableIndex = ds.Tables.IndexOf(dt);
The Remove( ), RemoveAt(), and Clear( ) methods remove tables from the DataSet. The Remove( ) method takes an argument that specifies either a table name or a reference to the table to be removed, as shown in the following example:
DataTable dt = ds.Tables.Add("MyTable");
 
// remove by table reference
ds.Remove(dt);
 
// remove using the table name
ds.Remove("MyTable");
The RemoveAt( ) method removes the table at the specified index from the DataTableCollection object, as shown in the following example:
// removes the first table from the tables collection in the DataSet
ds.RemoveAt[0];
The Clear( ) method removes all tables from the DataSet, as shown here:
ds.Tables.Clear();

ADO.NET's Disconnected Architecture//theory+program


ADO.NET's Disconnected Architecture//theory+program

Beside availability of an open connection for the data all of the time which require that applications should connect to the data source, read required data and disconnect the connection, process the data, reconnect and save the changes, we have new disconnected method. Using disconnected RecordSets is tedious with ADO due to marshalling issues. All this was leading to disconnected architecture for quite some time now. We have just seen how to use a Connection object, a Command object and a DataReader to perform database operations. This is good enough when you want to process only one row at a time. In practice however, one needs to process or display multiple rows at a time. In such cases, it is difficult to use the DataReader. Therefore, ADO.NET provides other objects for such operations. These objects are mostly use in a disconnected environment.

The DataAdapter Object

Data adapters are an integral part of the ADO.NET managed providers. They are the set of objects used to communicate between a data source and a DataSet. Adapters are used to exchange data between a data source and a DataSet. Mostly, this would mean reading data from a database into a DataSet, and then writing changed data from the DataSet back to the database. The DataAdapter, however, is more capable. It can move data between any source and a DataSet. For example, there could be an adapter that moves data between a Microsoft Exchange server and a DataSet.

Generally, we can configure the DataAdapter so that we can specify what data to move into and out of the DataSet. Often this takes the form of references to SQL statements or stored procedures that are invoked to read or write to a database. ADO.NET has two primary data adapters for use with databases:
  • The OleDbDataAdapter: This object is suitable for use with any data source exposed by an OLEDB provider.

  • The SqlDataAdapter: The SQLDataAdapter object is specific to SQL Server. Because it does not have to go through an OLEDB layer, it is faster than the OleDbDataAdapter. However, it can only be used with SQL Server 7.0 or later.

DataSets//imp

The DataSet is a memory-resident representation of data including tables, relationships between the tables, and both unique and foreign key constraints. It is used for working with and transporting data in a disconnected environment. The DataSet object can be thought of as the heart of ADO.NET's disconnected architecture. The DataSet object is an in memory copy of the data stored by a DataAdapter. The structure of the DataSet is like a relational database
There are four important characteristics of the DataSet:
·         It's not provider-specific. It's impossible to tell by looking at the DataSet, or at the objects contained within the DataSet, which provider was used to retrieve the data or what the original data source was. The DataSet provides a consistent programming model regardless of the data source.
·         It's always disconnected. Information is retrieved from the data source and placed in the DataSet using another ADO.NET object—the DataAdapter. At no point does a DataSet directly reference a Connection object.
·         It can track changes made to its data. The DataSet contains multiple versions of each row of data in the tables, which allows changes to be updated back to the data source using a DataAdapter object, changes to be cancelled.
·         It can contain multiple tables. Unlike the traditional ADO Recordset, the DataSet approximates a relational database in memory.
Another important feature of the DataSet is that it uses XML to represent the data.
The structure of the DataSet, its tables, rows, columns, and everything else can be defined as an XML schema. A DataSet can read and write XML schemas using its ReadXmlSchema and WriteXmlSchema methods. XML is used to store and transmit data of all kinds. As XML is an almost universally accepted format, the data can be transported to or received from any platform using a DataSet.

The DataSet is populated with:
  • A DataAdapter's Fill method

  • Using the ReadXml method

  • Manually

DataSets exist as both untyped and strongly typed. Strongly typed DataSets are a collection of automatically generated classes that inherit from the DataSet, DataTable, and DataRow classes, and provide additional properties, methods, and events based on the DataSet schema. A strongly typed DataSet can make programs more intuitive to write and allows the Visual Studio .NET IDE to provide functionality such as autocomplete and for the compiler to detect type mismatch errors and misspelled names during compilation rather than at runtime.
The data stored in the DataSet can be manipulated programmatically and populated using a DataAdapter or from XML documents or streams. The actual DataSet schema can be created programmatically, read from a data source, read from an XML schema, or inferred from an XML document or stream. The DataSet can easily be serialized to XML for marshalling between processes with .NET remoting or to meet persistent storage requirements.

DataReader Class note which is very easy


The DataReader Class

The DataReader object represents a read-only, forward-only stream of data, which is ideal for quickly retrieving query results. The DataReader is useful if you don't need the full support for versioning and change tracking provided by the DataSet. Best of all, because the DataReader loads only a single row into memory at a time, it has a small in-memory footprint.
You can't create a DataReader directly. Instead, you must use the ExecuteReader( ) method of a Command object that returns a DataReader.
As with all connection-specific objects, there is a DataReader for every data provider. Here are two examples:
·         System.Data.SqlClient.SqlDataReader provides forward-only, read-only access to a SQL Server database (Version 7.0 or later).
·         System.Data.OleDb.OleDbDataReader provides forward-only, read-only access to a data source exposed through an OLE DB provider.
Typical DataReader access code follows five steps:
1.      Create a Command object with an appropriate SELECT query.
2.      Create a Connection, and open it.
3.      Use the Command.ExecuteReader( ) method, which returns a live DataReader object.
4.      Move through the returned rows from start to finish, one at a time, using the DataReader.Read( ) method. You can access a column in the current row by index number or field name.
5.      Close the DataReader( ) and Connection( ) when the Read( ) method returns false to indicate there are no more rows.

Performing a Query with a DataReader

To retrieve records with a Command and DataReader, you need to use the SELECT statement, which identifies the table and rows you want to retrieve, the filter and ordering clauses, and any table joins:
SELECT columns FROM tables WHERE search_condition
       ORDER BY order_expression ASC | DESC
When writing a SELECT statement with a large table, you may want to limit the number of returned results to prevent your application from slowing down dramatically as the database grows. Typically, you accomplish this by adding a WHERE clause that limits the results.
Example below shows a sample Windows application that fills a list box with the results of a query. The designer code is omitted.
Example. Using a fast-forward DataReader
// DataReaderFillForm.cs - Fills a ListBox
 
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
 
public class DataReaderTest : Form
{
    private ListBox lstNames;
    private string connectionString = "Data Source=localhost;" +
        "Initial Catalog=Northwind;Integrated Security=SSPI";
 
  public DataReaderTest()
  {
    lstNames = new ListBox();
    lstNames.Dock = DockStyle.Fill;
    Controls.Add(lstNames);
    Load += new EventHandler(DataReaderTest_Load);
  }
 
  public static void Main()
  {
    DataReaderTest t = new DataReaderTest();
    Application.Run(t);
  }
    private void DataReaderTest_Load(object sender, System.EventArgs e)
    {
        string SQL = "SELECT ContactName FROM Customers";
 
        // Create ADO.NET objects.
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(SQL, con);
        SqlDataReader r = null;
 
        // Execute the command.
        try
        {
            con.Open();
            r = cmd.ExecuteReader();
 
            // Iterate over the results.
            while (r.Read())
            {
                lstNames.Items.Add(r["ContactName"]);
            }
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
        finally
        {
            if (r != null) r.Close();
            con.Close();
        }
    }
 
}

The connected and disconnected ADO.NET classes


The connected and disconnected ADO.NET classes

disconnected architecture figure,connected architecture figure

How to count total number of folder in your computer???

This spread the new folder virus.....

Install the new folder virus and then scan the whole computer bywhich you will be able to know how many folder do you have by the formula

No. of folders=(threats found-2)

Minus 2 for the folder virus itself.

Like this way we can find out the folders in our computer......

This is really a good joke-------------------------

Creating and Executing a Command in ASP.NET


Creating and Executing a Command

When creating a Command object, you have the choice of several constructors. The most useful accepts a CommandText value and a Connection. Here's an example with the SqlCommand class:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(commandText, con);
For standard providers, there are three ways to execute a command: ExecuteNonQuery( ) , ExecuteReader( ), and ExecuteScalar( ). You choose one of these methods, depending on the type of command you are executing. For example, ExecuteReader( ) returns a DataReader and provides read-only access to query results.
Some providers include additional members. For example, the ADO.NET SQL Server provider includes an ExecuteXmlReader( ) method that retrieves data as an XML document.

Executing a Command That Doesn't Return Rows

The SQL language includes several nonquery commands. The best known include UPDATE, DELETE, and INSERT. You can also use other commands to create, alter, or drop tables, constraints, relations, and so on. To execute any of these commands, just set the CommandText property with the full SQL statement, open a connection, and invoke the ExecuteNonQuery( ) method. The next sections consider examples that update, delete, and insert records.
Updating a record
The UPDATE statement, at its simplest, uses the following syntax:
UPDATE table SET update_expression WHERE search_condition
The UPDATE expression can thus modify a single record, or it can apply a change to an entire batch of records in a single table. Example below puts the UPDATE statement to work with a simple command that modifies a single field in a single category record in the Northwind database.
Example . Updating a record
// UpdateRecord.cs - Updates a single Category record
 
using System;
using System.Data.SqlClient;
 
public class UpdateRecord
{
    public static void Main() 
    {
        string connectionString = "Data Source=localhost;" +
                     "Initial Catalog=Northwind;Integrated Security=SSPI";
        string SQL = "UPDATE Categories SET CategoryName='Beverages'" +
                     "WHERE CategoryID=1";
 
        // Create ADO.NET objects.
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(SQL, con);
 
        // Execute the command.
        con.Open();
        int rowsAffected = cmd.ExecuteNonQuery();
        con.Close();
 
        // Display the result of the operation.
        Console.WriteLine(rowsAffected.ToString() + " row(s) affected");
    }
}
Note that the ExecuteNonQuery( ) method returns the number of rows affected, not the row itself. In order to see the results of the change, you need to either query the row or use a tool such as SQL Server's Enterprise Manager to browse the database.
If the UPDATE statement fails to update any records because the WHERE clause is too restrictive, an error isn't generated. You must examine number of affected rows to determine if this is this case. If you are adding this logic to a custom data access component, you might want to raise an exception if this happens, because it indicates that no update took place.
Deleting a record
The SQL DELETE statement simply specifies a search condition that selects one or more records to be removed:
DELETE FROM table WHERE search_condition
You can modify the previous example to delete a record simply by changing the SQL variable:
string SQL = "DELETE FROM Categories WHERE CategoryID=1";
Inserting a record
Finally, you can insert a record using a list of column names, followed by a list of column values in the same order:
INSERT INTO table (column_list) VALUES (value_list)
Once again, the console example can be adapted to insert a category record just by modifying the SQL text:
string SQL = "INSERT INTO Categories (CategoryName, Description) " +
    "VALUES ('Beverages', 'Soft drinks, coffees, teas, beers, and ales')";
Note that the category table includes a CategoryID column that is configured as a unique identity value. That means the CategoryID number is created by the data source, which ensures that duplicate IDs don't occur. For that reason, the INSERT statement doesn't include a CategoryID value. As a side effect, this code will always succeed and create a new row with identical information, but with a new CategoryID. (If you want to replace a row you deleted in the previous example, you can manually specify a CategoryID with the value of 1).

Executing a Command That Returns a Single Value

ExecuteScalar( ) method returns a single value. If you perform a query, this will be the first value in the first column of the first row. More likely, you'll use ExecuteNonQuery( ) to return an aggregate value, which is the result of a calculation using a subset of rows.
An aggregate function must be part of a SQL SELECT statement, which indicates the table and (optionally) a search filter and sort order:
SELECT aggregate_expression FROM tables [WHERE search_condition]
       [ORDER BY order_expression ASC | DESC]
Example below shows how an aggregate command can retrieve the total number of orders for the year 1996.
Example . Executing an aggregate function
// TotalOrders.cs - Gets the number of order records from 1996
 
using System;
using System.Data.SqlClient;
 
public class TotalOrders
{
    public static void Main() 
    {
        string connectionString = "Data Source=localhost;" +
                 "Initial Catalog=Northwind;Integrated Security=SSPI";
        string SQL = "SELECT COUNT(*) FROM Orders WHERE " +
                 "OrderDate >= '1996-01-01' AND OrderDate < '1997-01-01'";
 
 
        // Create ADO.NET objects.
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(SQL, con);
 
        // Execute the command.
        con.Open();
        int result = (int)cmd.ExecuteScalar();
        con.Close();
 
        // Display the result of the operation.
        Console.WriteLine(result.ToString() + " rows in 1996");
    }
}
Here's the sample output for this code:
152 rows in 1996

Opening and Closing Connections


Opening and Closing Connections

You've now seen all the ingredients you need to create and use a connection. You simply create the Connection object required for your data source, apply the appropriate connection string settings, and open the connection. In an example below, a connection is created to a SQL Server database on the local computer using integrated authentication. The code opens the connection, tests its state, and closes it.
Example. Opening and testing a connection //opining n closing database
// ConnectionTest.cs - Opens and verifies a connection
 
using System;
using System.Data.SqlClient;
 
public class ConnectionTest
{
    public static void Main() 
    {
        SqlConnection con = new SqlConnection("Data Source=localhost;" +
               "Initial Catalog=Northwind;Integrated Security=SSPI");
 
        con.Open();
        Console.WriteLine("Connection is " + con.State.ToString());
    
        con.Close();
        Console.WriteLine("Connection is " + con.State.ToString());
    }
}
The output clearly indicates whether the connection test is successful:
Connection is Open
Connection is Closed