21
Advance Web Technology Anuradha Bhatia INTRODUCTION TO ADO.NET & DATA MANIPULATION CONTENTS I. Introduction to ADO.NET 1. What is database? 2. Writing XML file? 3. ADO.NET Architecture 4. Creating Connection 5. Dataset and Data Reader 6. Types of Data Adaptor and ADO Controls 7. Reading Data into Dataset and Data Adapter 8. Binding Data to Controls 9. Data Table and Data Row II. Accessing and Manipulating Data 1. Selecting Data 2. Insertion, Deletion, Updation, Sorting 3. How to Fill Dataset with Multiple Tables III. Multi-threading 1. Working with Multithreading 2. Synchronization of Threads IV. Migrating from VB 6.0 to VB.NET 1. Updating the Applications Developed in VB to VB.NET

Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

INTRODUCTION TO ADO.NET & DATA MANIPULATION CONTENTS

I. Introduction to ADO.NET 1. What is database? 2. Writing XML file?

3. ADO.NET Architecture

4. Creating Connection 5. Dataset and Data Reader

6. Types of Data Adaptor and ADO Controls 7. Reading Data into Dataset and Data Adapter

8. Binding Data to Controls

9. Data Table and Data Row

II. Accessing and Manipulating Data 1. Selecting Data 2. Insertion, Deletion, Updation, Sorting 3. How to Fill Dataset with Multiple Tables

III. Multi-threading 1. Working with Multithreading 2. Synchronization of Threads

IV. Migrating from VB 6.0 to VB.NET 1. Updating the Applications Developed in VB to VB.NET

Page 2: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

I. Introduction to ADO.NET 1. What is database?

Accessing databases is a common part of most applications and with the introduction of C# and ADO.NET, has become quite simple.

Reading data. This includes various data types such as integers, strings and dates.

Writing data. As with reading we will write these common types. This will be done using a SQL statement.

Updating or modifying data. Again we will use a simple SQL statement. Deleting data. Using SQL.

2. Writing XML file? (Question: Explain the concept of XML file in ADO.NET. Explanation – 2 Marks +

Code – 2 Marks = 4 Marks)

1. XML stands for Extensible Markup Language. 2. The markup language widely used is Hyper Text Markup Language (HTML),

used to create Webpages. 3. A Markup language describes the structure of the document. 4. XML is a meta-markup language which means that it lets us create our own

markup language (our own tags).

XML is popular for the following reasons: 1. It Allows Easy Data Exchange 2. It Allows to Customize Markup languages 3. Makes the data in the document Self-Describing 4. Allows for Structured and Integrated data 5. The current version of XML is 1.0 and XML is case sensitive. 6. Save the following code with a .xml extension.

<?xml version="1.0" encoding="UTF-8"?>

<DOCUMENT>

<WELCOME>

Welcome to XML

</WELCOME>

</DOCUMENT>

Explanation: 1. The document starts with the XML processing instruction <?xml version="1.0"

encoding="UTF-8"?> 2. All XML processing instructions should start and end with? 3. xml version="1.0" means the version of XML, which is currently 1.0 4. UTF-8 is a 8-bit condensed version of Unicode 5. The document starts with the <DOCUMENT> element which may or may not

contain other elements within it and should always end with </DOCUMENT>.

Page 3: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

All other elements should be between <DOCUMENT> and </DOCUMENT> making <DOCUMENT> the root element for this XML page.

6. The next element is <WELCOME> between the <DOCUMENT> and </DOCUMENT> and which contains a message, Welcome to XML.

7. The above code when opened in a browser looks like Figure 1.

Figure 1

8. To format the content of the elements created in the document use a style sheet to tell the browser the way the document should be.

9. The above example using style sheet. <?xml version="1.0" encoding="UTF-8"?>

<?xml-stylesheet type="text/css" href="style.css"?>

<DOCUMENT>

<WELCOME>

Welcome to XML

</WELCOME>

</DOCUMENT>

10. The above code includes a new line <?xml-stylesheet type="text/css"

href="style.css"?> which means that the type of style sheet being used is CSS (Cascading Style Sheet, XSL can also be used) and its name is style.css.

11. The file style.css looks like this: WELCOME{font-size:40pt;font-family:Arial; color:red}

12. This files states that it's customizing the <WELCOME> element to display its content in a 40 pt font with arial as its font and its color as red.

13. To customize different elements to display their content in different fonts and colors.

14. Make sure that the file style.css is saved in the same directory where the xml file is saved.

Page 4: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

15. XML is case sensitive, which means <WeLCOME> and </Welcome> are treated differently. <WELCOME> should be closed with a corresponding</WELCOME> tag.

16. The output after adding the style sheet looks like Figure 2.

Figure 2

(Question: Write a XML method for representation of dataset into file stream. = 4

Marks)

Write XML is a method used to write the XML representation of the DataSet into a file, a stream, an XmlWriter object or a string.Its syntax is:

Public Sub WriteXml(filename As string) Example:

Public class form3

Private Sub Form3_Load(By Val sender As System.Object,ByVal e As

System.Event Args)

handles MyBase.Load

Dim ds As New DataSet(“Contacts”)

Dim dt As New DataTable(“Contacts”)

Dim dr As DataRow

dt.Columns.Add(“FirstName”,System.Type.GetType(“System.String”))

dt.Columns.Add(“LastName”,System.Type.GetType(“System.String”))

ds.Tables.Add(dt)

dr=ds.Tables(“Contact”).NewRow

dr(FirstName”)=”vinay”

dr(LastName”)=”manik”

dt.Rows.Add(dr)

ds.WriteXml(“c:\XMLFile2.xml”)

MsgBox(“XMLFile2.xml is created on c drive”)

End Sub

End Class

Page 5: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

3. ADO.NET Architecture (Question: Explain the ADO.NET architecture. Explanation - 6 Marks +

Diagram- 2 Marks = 8 Marks)

Figure 3

1. ADO.NET consists of a set of objects that expose data access services to the .NET environment.

2. It is a data access technology from Microsoft .NET framework, which provides communication between relational and non-relational systems through a common set of components .

3. System.Data namespace is the coreof ADO.NET and it contains classes used by all dataproviders.

4. ADO.NET is designed to be easy to use, and Visual Studio provides several wizards and other features that you can use to generate ADO.NET data access code.

5. The two key components of ADO.NET are Data Providers and DataSet as shown in Figure 4.

6. The Data Provider classes are meant to work with different kinds of data sources.

Page 6: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

7. They are used to perform all data-management operations on specific databases. DataSet class provides mechanisms for managing data when it is disconnected from the data source.

Figure 4

8. The .NET Framework includes mainly three Data Providers for ADO.NET. 9. They are the Microsoft SQL Server Data Provider , OLEDB Data Provider and

ODBC Data Provider . SQL Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses OdbcConnection Object respectively.

Figure 5

10. A data provider contains Connection, Command, DataAdapter, and dataReader objects. These four objects provides the functionality of Data Providers in the ADO.NET.

11. The Connection Object provides physical connection to the Data Source. Connection object needs the necessary information to recognize the data source and to log on to it properly, this information is provided through a connection string.

Page 7: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

12. The Command Object uses to perform SQL statement or storedprocedure to be executed at the Data Source. The command object provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.

13. The DataReader Object is a stream-based , forward-only, read-onlyretrieval of query results from the Data Source, which do not update the data. DataReader requires a live connection with the databse and provides a very intelligent way of consuming all or part of the result set.

14. DataAdapter Object populate a Dataset Object with results from a Data Source . It is a special class whose purpose is to bridge the gap between the disconnected Dataset objects and the physical data source.

Figure 6

15. DataSet provides a disconnected representation of result sets from the Data Source, and it is completely independent from the Data Source. DataSet provides much greater flexibility when dealing with related Result Sets.

16. DataSet contains rows, columns,primary keys, constraints, and relations with other DataTable objects. It consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. The DataAdapter Object provides a bridge between the DataSet and the Data Source.

Page 8: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

4. Creating Connection The Connection Object

1. The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a wide range of database types like Microsoft Access and Oracle.

2. The Connection object contains all of the information required to open a connection to the database.

5. Dataset and DataReader (Question: Explain the concept of Dataset in ADO.NET = 4 Marks)

DataSet 1. The dataset is a disconnected, in-memory representation of data. It can be

considered as a local copy of the relevant portions of the database. 2. The DataSet is persisted in memory and the data in it can be manipulated and

updated independent of the database. 3. When the use of this DataSet is finished, changes can be made back to the

central database for updating. 4. The data in DataSet can be loaded from any valid data source like Microsoft SQL

server database, an Oracle database or from a Microsoft Access database.

Dim connStr As String = "Provider=VFPOLEDB.1;Data Source=“ &

_“C:\SAMPLES\ DATA\ TESTDATA.DBC"

Dim strSQL As String = "SELECT * FROM Products"

Dim oda As New OleDbDataAdapter(strSQL, connStr)

Dim ds As New DataSet()

Dim dr As DataRow

oda.Fill(ds, "ProductInfo")

For Each dr In ds.Tables("ProductInfo").Rows

lstDemo.Items.Add(dr("Prod_Name").ToString)

Next dr

' Want to bind a Windows Form grid? It's this easy:

dgdDemo.DataSource = ds.Tables("ProductInfo")

The DataReader Object (Question: Explain the concept of DataReader in ADO.NET = 4 Marks)

1. The DataReader object provides a forward-only, read-only, connected stream recordset from a database.

2. DataReader objects cannot be directly instantiated. 3. The DataReader is returned as the result of the Command object's

ExecuteReader method.

Page 9: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

4. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object.

5. The DataReader can provide rows of data directly to application logic when you do not need to keep the data cached in memory.

6. Only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader.

6. Types of Data Adaptor and ADO Controls

The Data Adapter Object

Figure 7

1. The DataAdapter is the class at the core of ADO .NET's disconnected data access. 2. It is essentially the middleman facilitating all communication between the

database and a DataSet. 3. The DataAdapter is used either to fill a DataTable or DataSet with data from the

database with its Fill method. 4. After the memory-resident data has been manipulated, the DataAdapter can

commit the changes to the database by calling the Update method.

ADO Controls 1. The DataAdapter provides four properties that represent database commands:

i. Select Command

ii. Insert Command

iii. Delete Command

SelectComman

InsertComman

DeleteComman

TableMapping

DeleteCommand

InsertCommand

UpdateCommand

SelectCommand

Connection

DataAdapter

Page 10: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

iv. Update Command

2. When the Update method is called, changes in the DataSet are copied back to the database and the appropriate Insert Command, Delete Command, or Update Command is executed. Dim connStr As String = "Provider=VFPOLEDB.1;Data Source=“ &

“C:\SAMPLES\DATA\TESTDATA.DBC"

Dim strSQL As String = "SELECT * FROM Products"

Dim oda As New OleDbDataAdapter(strSQL, connStr)

Dim cmdInsert As New OleDbCommand(“INSERT INTO Products” & _

“(product_id, prod_name) VALUES (?,?)”)

oda.InsertCommand = cmdInsert

7. Reading Data into Dataset and Data Adapter 1. The DataSet is similar to an array of disconnected Recordset objects. 2. It supports disconnected data access and operations, allowing greater scalability

because you no longer have to be connected to the database all the time. 3. DataSet is a copy of an extracted data being downloaded and cached in the client

system. 4. The DataSet object is made up of two objects: 5. DataTableCollection object containing null or multiple DataTable objects

(Columns, Rows, and Constraints). 6. DataRelationCollection object containing null or multiple DataRelation objects

which establish a parent/child relation between two DataTable objects. 7. A DataSet is a container; therefore, you have to fill it with data. 8. DataSet can be populated by using DataAdapter objects and Fill method. 9. Creating DataTable, DataColumn and DataRow objects programmatically. 10. Add new rows of data to the table.

//Create a DataSet

DataSet dset = new DataSet();

string strCon = @"Data Source=SONY\MYSQLSERVER;" + "Initial

Catalog=Northwind;Integrated Security=SSPI"; string strSql="select * from customers";

SqlConnection con=new SqlConnection(strCon);

con.Open();

SqlDataAdapter dadapter=new SqlDataAdapter();

dadapter.SelectCommand=new SqlCommand(strSql,con);

DataSet dset=new DataSet();

dadapter.Fill(dset);

con.Close();

this.dataGrid1.DataSource=dset;

Page 11: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

Example: DataSet dset;

DataTable dtbl;

DataRow drow;

//create a new row

drow=dtbl.NewRow();

//manipulate the newly added row using an index or the column name

drow["LastName"]="Altindag";

drow[1]="Altindag";

//After data is inserted into the new row, the Add method is used

//to add the row to the DataRowCollection

dtbl.Rows.Add(drow);

//You can also call the Add method to add a new row by passing in an

//array of values, typed as Object

dtbl.Rows.Add(new object[] {1, "Altindag"});

DataAdapter

1. The DataAdapter provides four properties that allow us to control how updates are made to the server:

i. Select Command

ii. Update Command

iii. Insert Command

iv. Delete Command

The four properties are set to Command objects that are used when data is manipulated.

The DataAdapter includes three main methods: 1. Fill (populates a DataSet with data). 2. FillSchema (queries the database for schema information that is necessary to

update). 3. Update (to change the database, DataAdapter calls the DeleteCommand, the

InsertCommand and theUpdateCommand properties). Example:

1. The DataAdapter's Fill method to retrieve data from a data source and pour it into a DataSet, the Command object in the SelectCommand property is used.

2. The DataAdapter is the gatekeeper that sits between DataSet and the data source.

3. To get a data connection, DataSet and DataAdapter

//Create an instance of a OleDbDataAdapter

//by passing OleDbConnection object and select.. query

OleDbDataAdapter dAdapter = new

OleDbDataAdapter ("select * from PersonTable", con );

//fill the DataSet with records from the table "PersonTable"

dAdapter.Fill(dSet,"PersonTable");

Page 12: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

public bool fnGetDataConnection()

{

try {

con =new OleDbConnection(conString);

dAdapter=new OleDbDataAdapter("select * from PersonTable", con);

dSet=new DataSet();

//refreshes rows in the DataSet

dAdapter.Fill(dSet,"PersonTable");

}catch(Exception ex) {

MessageBox.Show("Error : "+ex.Message);

//connectection failed

return false;

}//try-catch

//connection ok!

return true;

}

8. Binding data to controls Creating and Configuring the Dataset

1. A dataset is an in-memory cache consisting of tables, relations, and constraints. 2. Each table in the dataset has a collection of columns and rows. Because datasets

are aware of both their original and current state, they can track the changes that occur.

3. The data in a dataset is considered updateable. 4. To begin, create a data adapter that contains the SQL statement that you will use

to populate the dataset. 5. To create the data connection and data adapter: 6. In the Toolbox, on the Data tab, select a SQLDataAdapter. 7. Drag-and-drop it to the form. 8. The Data Adapter Configuration Wizard appears. Click Next. 9. Click New Connection to create a data connection that the data adapter will use. 10. The Data Link Properties dialog box appears as in Figure 2. 11. Figure 5. The Data Link Properties dialog box allows you to specify connection

information for the data underlying the bound form 12. Change the server name to point to the name of your SQL Server. In this

example, it is (local). 13. Change the User name and Password that is needed to log into this SQL Server. 14. Select the Northwind database as the database to be used for the example (see

Figure 2). 15. Click OK to return to the wizard, and then click Next. 16. The wizard allows you to designate the Query Type as in Figure 3. Select Use

SQL statements and click Next. 17. Type a SQL statement or click Query Builder to have the wizard build the SQL

statement for you. For this example, type the following SQL statement: 18. SELECT CustomerID, CompanyName, ContactName, ContactTitle, Country FROM

Customers 19. Click Next and then click Finish to complete the process. Notice that a

SQLConnection object named SQLConnection1 and a SQLDataAdapter object namedSQLDataAdapter1 appear in the Tray of the form.

Page 13: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

20. The SQLConnection1 object contains information about how to access the selected database.

21. The SQLDataAdapter1 object contains a query defining the tables and columns in the database that you want to access.

Figure 8

Page 14: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

Figure 9

9. Data table and Data row Creating a DataTable

1. A DataTable, which represents one table of in-memory relational data, can be created and used independently, or can be used by other .NET Framework objects, most commonly as a member of a DataSet.

2. Create a DataTable object by using the appropriate DataTable constructor. 3. Add to the DataSet by using the Add method to add it to the DataTable object's

Tables collection. 4. Create DataTable objects within a DataSet by using the Fill or FillSchema

methods of the DataAdapter object. 5. To define the schema of the table, create and add DataColumn objects to the

Columns collection of the table. 6. Define a primary key column for the table, and create and add Constraint objects

to the Constraints collection of the table. 7. After the schema is defined for a DataTable, add rows of data to the table by

adding DataRow objects to the Rows collection of the table. 8. The following example creates an instance of a DataTable object and assigns it

the name "Customers." Dim workTable as DataTable = New DataTable("Customers");

Page 15: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

9. The following example creates an instance of a DataTable by adding it to the Tables collection of a DataSet. Dim customers As DataSet = New DataSet

Dim customersTable As DataTable = _

customers.Tables.Add("CustomersTable");

DATA ROW

1. A DataRow represent a row of data in data table. 2. Add data to the data table using DataRow object. 3. A DataRowCollection object represents a collection of data rows of a data table. 4. Use DataTable's NewRow method to return a DataRow object of data table, add

values to the data row and add a row to the data Table again by using DataRowCollection's Add method.

5. Setting values of the Id, Address, and Name Columns of a DataRow

Table 1: The Data Row Class properties

Table 2: The Data Row class Methods

METHOD DESCRIPTION

AcceptChanges Comments all the changes made to this row

BeginEdit Starts an edit operation on a row

CancelEdit Cancels the current edit on a row

Delete Deletes a DataRow

EndEdit Ends the current edit on a row

GetChildRows Returns child rows of a DataRow

GetParentRows Returns parent rows of a DataRow

RejectsChanges Rejects all the changes made since last AcceptChanges

Example: DataRow row1 = custTable.NewRow();

row1["id"] = 1001;

row1["Address"] = "43 Lane wood Road, Cito, ca";

row1["Name"] = "George Bishop";

6. After setting a row member's values, call DataTable's DataRowCollection's Add method though the DataTable.Rows property to add a row to the data table:

custTable.Rows.Add(row1);

PROPERTY DESCRIPITION

Item Represents an item of a row

ItemArray Represents all values in a row

RowState Indicates the current state of a row

Table Returns the DataTable to which this row is attached

Page 16: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

7. The RejectChanges method of the DataRow rejects recent changes on that row. 8. For Example, if you have recently added row1 to the data table, calling the

RejectChanges method as following:

row1.RejectChanges();

II. Accessing and Manipulating Data 1. Selecting Data

1. To select the data reading is done using the ADO DataReader class. 2. The steps to perform the read are; open the database with an ADO Connection.

ADOConnection.conn = new ADOConnection(DB_CONN_STRING);

Conn.Open();

3. Create a SQL statement to define the data to be retrieved. 4. This command is executed to return an ADO DataReader object. 5. The out keyword in the Execute method.

ADODataReader dr;

ADOCommand cmd = new ADOCommand( "SELECT * FROM Person", conn );

cmd.Execute( out dr);

while( dr.Read() )

{ System.Console.WriteLine( dr["FirstName"] );}

2. Insertion, Updation, Deletion

Inserting 1. The given code inserted a record by building a SQL command which was later

executed. 2. Numerical values are presented directly. No single quotes ('). 3. Strings are presented wrapped in single quotes ('blah'). 4. Be sure the strings do not include any embedded single or double quotes. This

will upset things. 5. Date and times are presented wrapped in single quotes in international format

('YYYYY/MM/DD HH:MM:SS'). 6. The following code performs a SQL command to insert a record.

// SQL command

String sSQLCommand = "INSERT INTO Person (Age, FirstName,

Description, Updated)" +"VALUES( 40, 'Anu', 'Is a Writer',

'2014/27/25 20:30:15' );";

// Create the command object

ADOCommand cmdAdder = new ADOCommand(sSQLCommand, DB_CONN_STRING);

cmdAdder.ActiveConnection.Open();

// Execute the SQL command

int nNoAdded = cmdAdder.ExecuteNonQuery();

System.Console.WriteLine( "\nRow(s) Added = " + nNoAdded + "\n" );

Page 17: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

Modifying 1. The UPDATE command indicates the records to be modified and the

modification to be made. 2. The return value of the ExecuteNonQuery() indicates the number of records

changes so this would return 5 if there were 5 Anu in the table. String sSQLCommand = "UPDATE Person SET Age = 40 WHERE FirstName =

'Anu'";

Deleting

1. The DELETE command indicates the records to be deleted. 2. This could be several several records. 3. The return value of the ExecuteNonQuery() indicates the number of records

changes so this would return 2 if there were 2 Anu in the table. Both Anu's would be deleted. String sSQLCommand = "DELETE FROM Person WHERE FirstName = 'Anu'";

3. How to Fill Dataset with Multiple Tables

1. The DataSet represents a complete set of data that includes tables, constraints,

and relationships among the tables. 2. The DataSet is independent of the data source; a DataSet can include data local

to the application, and data from multiple data sources. Interaction with existing data sources is controlled through the DataAdapter.

3. The Select Command property of the DataAdapter is a Command object that retrieves data from the data source.

4. The Insert Command, Update Command, and Delete Command properties of the DataAdapter are Command objects that manage updates to the data in the data source according to modifications made to the data in the DataSet.

5. The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand of the DataAdapter.

6. Fill takes as its arguments a DataSet to be populated, and a DataTable object, or the name of the DataTable to be filled with the rows returned from the Select Command.

7. The Fill method uses the DataReader object implicitly to return the column names and types that are used to create the tables in the DataSet, and the data to populate the rows of the tables in the DataSet.

8. Tables and columns are only created if they do not already exist; otherwise Fill uses the existing DataSet schema.

9. The code creates an instance of a SqlDataAdapter that uses a SqlConnection to the Microsoft SQL Server Northwind database and populates a DataTable in a DataSet with the list of customers.

10. The SQL statement and SqlConnection arguments passed to the SqlDataAdapter constructor are used to create the SelectCommand property of the SqlDataAdapter.

Page 18: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

Example: ' Assumes that connection is a valid SqlConnection object.

Dim queryString As String ="SELECT CustomerID, CompanyName FROM

dbo.Customers"

Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ queryString,

connection)

Dim customers As DataSet = New DataSet

adapter.Fill(customers, "Customers")

III. Multi-threading 1. Working with Multithreading

(Question: explain multithreading in ADO.NET = 4 Marks)

(Question: Explain how threads are created in ADO.NET - Theory – 2 Marks +

Code – 2 Marks = 4 Marks)

1. Multithreading gives programs the ability to do several things at a time. 2. Each stream of execution is called a thread. 3. Multithreading is used to divide lengthy tasks into different segments that

would otherwise abort programs. 4. Threads are mainly used to utilize the processor to a maximum extent by

avoiding its idle time. 5. Threading lets a program seem as if it is executing several tasks at once. What

actually happens is, the time gets divided by the computer into parts and when a new thread starts, that thread gets a portion of the divided time.

6. Threads in VB .NET are based on the namespace System.Threading.

Creating Threads 1. Open a new windows application and name it as Thread and add a class named

count1 using the Projects->Add Class item. 2. This class will count from 1 to a specified value in a data member named

CountTo when you call the Count method. 3. After the count has reached the value in CountTo, a FinishedCounting event will

occur. 4. The code for the Count class looks like this:

Public Class Count1

Public CountTo as Integer

Public event FinishedCounting(By Val NumberOfMatches as Integer)

Sub Count()

Dim ind,tot as Integer

tot=0

For ind=1 to CountTo

tot+=1

Next ind

RaiseEvent FinishedCounting(tot)

'makes the FinishedCounting event to occur

End Sub

End Class

Page 19: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

2. Synchronization of Threads (Question: Explain the concept of suspending and resuming a thread in ADO.NET -

2 Marks each = 4 Marks)

Suspending a Thread 1. Threads can be suspended. 2. Suspending a thread stops it temporarily. 3. Add a button to the form, when this button is clicked the thread is suspended. 4. The code for that looks like this:

Private Sub Button2_Click(ByVal sender as System.Object, ByVal e as

System.EventArgs)

Handles Button2.Click

Thread1.Suspend()

End Sub

Resuming a Thread

1. Threads can be resumed after they are suspended. 2. Add a new button Button3 to the main form, When this button is clicked the

thread is resumed from suspension. 3. The code for that looks like this:

Private Sub Button3_Click(ByVal sender as System.Object, ByVal e as

System.EventArgs)

Handles Button3.Click

Thread1.Resume()

End Sub

Making a Thread Sleep (Question: Explain the concept of making the thread sleep : Explanation - 2 Marks

+ Code – 2 marks = 4 marks)

1. Threads can be made to sleep which means that they can be suspended over a specific period of time.

2. Sleeping a thread is achieved by passing the time (in milliseconds,1/1000 of a second) to the thread's sleep method.

3. Add a new button Button4 to the main form, When this button is clicked the thread is stopped.

4. The code for that looks like this:

Private Sub Button4_Click(ByVal sender as System.Object, ByVal e as

System.EventArgs)

Handles Button4.Click

Thread1.Sleep(100/1000)

End Sub

Page 20: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

Stopping a Thread 1. Threads can be stopped with its abort method. 2. Add a new button Button5 to the main form. 3. When this button is clicked the thread is stopped. 4. The code for that looks like this:

Private Sub Button5_Click(ByVal sender as System.Object, ByVal as

System.EventArgs)_

Handles Button5.Click

Thread1.Abort()

End Sub

Thread Priorities

(Question: Explain how priorities are given to thread. Explanation - 2 Marks +

Code – 2 marks = 4 marks)

1. Threads can also be assigned priority for execution. 2. Thread priority can be set by the thread's Priority property and assigning a

value from predefined Thread Priority enumeration. 3. Values for Thread Priority:

Above Normal -> Gives thread higher priority Below Normal -> Gives thread lower priority Normal -> Gives thread normal priority Lowest ->Gives thread lowest priority Highest -> Gives thread highest priority

4. Add a new button Button6 to the main form, when this button is clicked the thread is assigned highest priority.

5. The code for that looks like this: Private Sub Button6_Click(ByVal sender as System.Object, ByVal e as

System.EventArgs)

Handles Button6.Click

Thread1.Priority=System.Threading.ThreadPriority.Highest

'setting Highest priority for the thread

End Sub

IV. Migrating from VB 6.0 to VB.NET 1. Updating the applications developed in VB to VB .NET

(Question : Give steps to update the VB application to VB.NET application. = 4

Marks)

1. VB.NET has a default migration tool to convert VB 6.0 application to VB.NET. 2. Following steps should be considered while migrating : 3. Decide whether to upgrade or not : Projects with user controls , web controls,

Add-in models, DHTML pages cannot be easily upgraded. 4. They should be checked for compatibility.

Page 21: Advance Web Technology INTRO U TION TO A O.N T & ATA ... · Advance Web Technology Anuradha Bhatia I. Introduction to ADO.NET 1. What is database? Accessing databases is a common

Advance Web Technology

Anuradha Bhatia

5. Remove dead and duplicated code. 6. Upgrade problematic syntaxes and controls. 7. Load your code in VB.NET: At this stage it opens Visual basic Upgrade Wizard. 8. Follow the steps like, selection of type to convert as exe or dll, location,. Click yes

on warning for asking surety of conversion, and upgrade. 9. Fix if there are any compatibility issues. 10. Test the project.