You are on page 1of 13

Explain the namespaces in which .NET has the data functionality class. System.data contains basic objects.

These objects are used for accessing and sto ring relational data. Each of these is independent of the type of data source an d the way we connect to it. These objects are: DataSet DataTable DataRelation. System.Data.OleDB objects are used to connect to a data source via an OLE-DB pro vider. These objects have the same properties, methods, and events as the SqlClient equ ivalents. A few of the object providers are: OleDbConnection OleDbCommand System.Data.SqlClient objects are used to connect to a data source via the Tabul ar Data Stream (TDS) interface of only Microsoft SQL Server. The intermediate layers required by an OLE-DB connection are removed in this. This provides better performance. System.XML contains the basic objects required to create, read, store, write, an d manipulate XML documents according to W3C recommendations.

-Overview of ADO.NET architecture. Data Provider provides objects through which functionalities like opening and cl osing connection, retrieving and updating data can be availed. It also provides access to data source like SQL Server, Access, and Oracle). Some of the data provider objects are: Command object which is used to store procedures. Data Adapter which is a bridge between datastore and dataset. Datareader which reads data from data store in forward only mode. A dataset object is not in directly connected to any data store. It repres ents disconnected and cached data. The dataset communicates with Data adapter th at fills up the dataset. Dataset can have one or more Datatable and relations. * DataView object is used to sort and filter data in Datatable. ADO.NET architecture - June 06, 2009 at 10:00 AM by Shuchi Gauri Overview of ADO.NET architecture. ADO.NET provides access to all kind of data sources such as Microsoft SQL Server , OLEDB, Oracle, XML. ADO.NET separates out the data access and data manipulation componenets. ADO.NET * * * *

includes some providers from the .NET Framework to connect to the database, to execute commands, and finally to retrieve results. Those results are either dire ctly used or can be put in dataset and manipulate it. Define connected and disconnected data access in ADO.NET Data reader is based on the connected architecture for data access. Does not all ow data manipulation Dataset supports disconnected data access architecture. This gives better perfor mance results. Define connected and disconnected data access in ADO.NET Data reader is based on the connected architecture for data access. Does not all ow data manipulation Dataset supports disconnected data access architecture. This gives better perfor mance results. Describe CommandType property of a SQLCommand in ADO.NET. CommandType is a property of Command object which can be set to Text, Storedproc edure. If it is Text, the command executes the database query. When it is Stored Procedure, the command runs the stored procedure. A SqlCommand is an object that allows specifying what is to be performed in the database. Access database at runtime using ADO.NET SqlConnection sqlCon = new SqlConnection(connectionString) sqlCon.Open(); string strQuery = "select CategoryName from abcd"; SqlCommand cmd = new SqlCommand(strQuery, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader [0]); } reader.Close(); con.Close(); -Difference between dataset and datareader. Dataset DataSet object can contain multiple rowsets from the same data source as well as from the relationships between them Dataset is a disconnected architecture Dataset can persist data. Datareader DataReader provides forward-only and read-only access to data. Datareader is connected architecture Datareader can not persist data. --

Difference between dataset and datareader. Dataset a. b. c. d. Disconnected Can traverse data in any order front, back. Data can be manipulated within the dataset. More expensive than datareader as it stores multiple rows at the same time.

Datareader a. b. c. d. -Command objects uses, purposes and their methods. The command objects are used to connect to the Datareader or dataset objects wit h the help of the following methods: ExecuteNonQuery: This method executes the command defined in the CommandText property. The connection used is defined in the Connection property for a query. It returns an Integer indicating the number of rows affected by the query. ExecuteReader: This method executes the command defined in the CommandText property. The connection used is defined in the Connection property. It returns a reader object that is connected to the resulting rowset within the database, allowing the rows to be retrieved. ExecuteScalar: This method executes the command defined in the CommandText property. The connection used is defined in the Connection property. It returns a single value which is the first column of the first row of the resu lting rowset. The rows of the rest of the result are discarded. It is fast and efficient in cases where a singleton value is required. -Command objects uses, purposes and their methods. Command objects are used to execute the queries, procedures. Sql statements etc. It can execute stored procedures or queries that use parameters as well. It works on the basis of certain properties like ActiveConnection, CommandText, CommandType, Name etc. Command object has three methods: a) Execute: executes the queries, stored procedures etc. b) Cancel: stops the method execution c) CreateParameter: to create a parameter object Connection needs to be maintained all the time Can traverse only forward. It is read only therefore, data cannot be manipulated. It is less costly because it stores one row at a time

-Explain the use of data adapter. The data adapter objects connect a command objects to a Dataset object. They provide the means for the exchange of data between the data store and the t ables in the DataSet. An OleDbDataAdapter object is used with an OLE-DB provider A SqlDataAdapter object uses Tabular Data Services with MS SQL Server. Use of data adapter in ADO.NET - June 06, 2009 at 10:00 AM by Shuchi Gauri Explain the use of data adapter. Data adapters are the medium of communication between datasource like database a nd dataset. It allows activities like reading data, updating data.

-The most commonly used methods of the DataAdapter are: Fill: This method executes the SelectCommand to fill the DataSet object with data from the data source. Depending on whether there is a primary key in the DataSet, the fill can also be u sed to update an existing table in a DataSet with changes made to the data in th e original datasource. FillSchema This method executes the SelectCommand to extract the schema of a table from the data source. It creates an empty table in the DataSet object with all the corresponding const raints. Update This method executes the InsertCommand, UpdateCommand, or DeleteCommand to updat e the original data source with the changes made to the content of the DataSet. -Explain the basic methods of Dataadapter Some basic methods of dataadpater are: a. Fill: adds or updates the rows to dataset from the datasource b. FillSchema: adds a datatable with the sameschema as in the datasource c. Update: it calls insert, update, delete sql commands for transferring all the changes from the dataset to the datasource d. Dispose : releases all the resources -What is Dataset object? Explain the various objects in Dataset.

The DataSet object is a disconnected storage. It is used for manipulation of relational data. The DataSet is filled with data from the store We fill it with data fetched from the data store. Once the work is done with the dataset, connection is reestablished and the changes are reflected back into th e store. Dataset has a collection of Tables which has DataTable collection which further has DataRow DataColumn objects collections. It also has collections for the primary keys, constraints, and default values ca lled as constraint collection. A DefaultView object for each table is used to create a DataView object based on the table, so that the data can be searched, filtered or otherwise manipulated while displaying the data. -What is Dataset object? Explain the various objects in Dataset. The DataSet object represents imported or linked data from an application e.g. m anually created Pushpins etc. This object is invalidated once the application is closed. Dataset contains another collection known as DataTable object. Each Dat aTable contains a collection of DataRow objects and each DataRow is a collection of DataColumn objects. -What are the steps involved to fill a dataset? The DataSet object is a disconnected storage. It is used for manipulation of relational data. The DataSet is filled with data from the store We fill it with data fetched from the data store. Once the work is done with the dataset, connection is reestablished and the changes are reflected back into th e store. -What are the steps involved to fill a dataset? a. Create a connection object. b. Create an adapter by passing the string query and the connection object as pa rameters. c. Create a new object of dataset. d. Call the Fill method of the adapter and pass the dataset object. Example: VB.NET Code:Dim strSQL as String strSQL = "SELECT * from tbl" Dim sqlCmd As New SqlCommand(strSQL, sqlConn) Dim sda As New SqlDataAdapter(sqlCmd) Dim ds As New DataSet sda.Fill(ds) --

How can we check that some changes have been made to dataset since it was loaded ? The changes made to the dataset can be tracked using the GetChanges and HasChang es methods. The GetChanges returns dataset which are changed since it was loaded or since Ac ceptchanges was executed. The HasChanges property indicates if any changes were made to the dataset since it was loaded or if acceptchanges method was executed. The RejectChanges can be used to revert thee changes made to the dataset since i t was loaded.

-How can we check that some changes have been made to dataset since it was loaded ? a. GetChanges: gives the dataset that has changed since newly loaded or since Ac cept changes has been executed. b. HasChanges: this returns a status that tells if any changes have been made to the dataset since accept changes was executed. -How can we add/remove row s in DataTable object of DataSet ?

NewRow method is provided by the Datatable to add new row to it. DataTable has DataRowCollection object which has all rows in a DataTable object. Add method of the DataRowCollection is used to add a new row in DataTable. We fill it with data fetched from the data store. Once the work is done with the dataset, connection is reestablished Remove method of the DataRowCollection is used to remove a DataRow object from Data Table . RemoveAt method of the DataRowCollection is used to remove a DataRow object from Da taTable per the index specified in the DataTable.

-How can we add/remove row s in Datatable has a -How do we use stored procedure in ADO.NET and how do we provide parameters to th e stored procedures? CREATE PROCEDURE RUPDATE (@RID INTEGER, @RDESC NCHAR(50)) AS SET NOCOUNT OFF UPDATE Region DataTable object of DataSet ?

NewRow method that allows addition of a new row to the datatable.

SET RDESC = @RDESC SqlCommand command = new SqlCommand("RUPDATE",con); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@RID",SqlDbType.Int,0,"RID")); command.Parameters.Add(new SqlParameter("@RDESC",SqlDbType.NChar,50,"RDESC")); command.Parameters[0].Value=4; command.Parameters[1].Value="SouthEast"; int i=command.ExecuteNonQuery(); -How do we use stored procedure in ADO.NET and how do we provide parameters to th e stored procedures? SqlCommand cmd1 = new SqlCommand("Employee", conn); Employee is the name of the stored procedure cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@empID", empId)); -Explain the basic use of DataView and explain its methods.

A DataView is a representation of a full table or a small section of rows. It is used to sort and find data within Datatable. Following are the methods of a DataView: Find : Parameter: An array of values; Value Returned: Index of the row FindRow : Parameter: An array of values; Value Returned: Collection of DataRow AddNew : Adds a new row to the DataView object. Delete : Deletes the specified row from DataView object

-Explain the basic use of DataView and explain its methods.

It is a customizable view of a datatable that allows filtering, searching, editi ng, navigation. DataView method: a. AddNew: To add a new row to the DataView. b. BeginInit: Begins the initialization of a DataView. c. CopyTo: items are copied into an array. d. Delete: Used to delete a row at the specified position. e. Dispose: Releases the resources. f. EndInit: Ends the initialization of a DataView. g. Equals: Compares object instances are equal or not.

h. Find: Finds a specific row in the DataView. i. FindRows: Returns an array of DataRowView j. GetEnumerator: Gets an enumerator. k. GetHashCode: it is used in hashing algorithms. l. GetService : fetches the implementer of the IServiceProvider. m. GetType : fetches the current instance type. n. ToString : Returns a String. o. Close: Used to close a DataView. p. ColumnCollectionChanged: Occurs after a DataColumnCollection is successfully changed q. Dispose: can be overloaded r. Finalize: Used to free resources and cleanup before objects are handeled by g arbage collection. s. IndexListChanged: This event tab=kes place when DataView has been changed suc cessfully. t. MemberwiseClone : Creates a shallow copy. u. OnListChanged: Raises the ListChanged event. v. Open: To open a DataView.

-Differences between Dataset DataSet object can contain multiple rowsets from the same data source as well as from the relationships between them Dataset is a disconnected architecture Dataset can persist data. A DataSet is well suited for data that needs to be retrieved from multiple table s. Due to overhead DatsSet is slower than DataReader. Datareader DataReader provides forward-only and read-only access to data. Datareader is connected architecture. It has live connection while reading data DataSet and DataReader .

Datareader can not persist data. Speed performance is better in DataReader. -Explain how to load multiple tables in a DataSet. MyDataSet myds = new MyDataSet(); SqlDataAdapter myda = new SqlDataAdapter ("procId", this.Connection); myda.SelectCommand.CommandType = CommandType.StoredProcedure; myda.SelectCommand.Parameters.AddWithValue ("@pId", pId); myda.TableMappings.Add ("Table", myds.xval.TableName); myda.Fill (myds); ADO.NET Code showing Dataset storing multiple tables. DataSet ds = new DataSet(); ds.Tables.Add(dt1); ds.Tables.Add(dt2); ds.Tables.Add(dtn); -What is the use of CommandBuilder? CommandBuilder builds Parameter Example: Dim pobjCommandBuilder As New OleDbCommandBuilder(pobjDataAdapter) pobjCommandBuilder.DeriveParameters(pobjCommand) If DeriveParameters method is used, an extra trip to the Datastore is madewhich can highly affect the efficiency. -What is the use of CommandBuilder? CommandBuilder is used to build complex queries. It can even build commands that are based on the returned results. CommandBuilder is less error prone and more readable than the command object. -What s difference between Optimistic and Pessimistic locking? objects automatically.

In pessimistic locking, when a user opens a data to update it, a lock is granted . Other users can only view the data until the whole transaction of the data upd ate is completed. In optimistic locking, a data is opened for updating by multiple users. A lock i s granted only during the update transaction and not for the entire session. Due to this concurrency is increased and is a practical approach of updating the da ta.

-What s difference between Optimistic and Pessimistic locking?

Pessimistic locking: On updating the data, the record gets locked and no one els e can access that record for updating. It becomes a read-only record till the lo ck is released. Once the lock gets released, the record can be locked again and get updated for a different user. Optimistic locking: This allows multiple user to open up the same record for upd ation . Record gets locked only while updating the record. This is the most pref erred way of locking for the web application. -How can we perform transactions in .NET? Following are the general steps that are followed during a transaction: * Open connection * Begin Transaction: the begin transaction method provides with a connection object this can be used to commit or rollback. * Execute the SQL commands * Commit or roll back * Close the database connection -How can we perform transactions in .NET? Steps to perform a transaction a. Call the BeginTransaction. This marks the beginning of the transaction. b. Assign the Transaction object returned by BeginTransaction to the Transaction property of the SqlCommand. c. Execute the command. d. Call the Commit method from SqlTransaction object to save the changes made to the data through the transaction. Call Rollback undo all the transaction which belong to this transaction. -What is connection pooling and what is the maximum Pool Size in ADO.NET Connecti on String? A connection pool is created when a connection is opened the first time. The nex t time a connection is opened, the connection string is matched and if found exa ctly equal, the connection pooling would work. Otherwise, a new connection is opened, and connection pooling won't be used. Maximum pool size is the maximum number of connection objects to be pooled. If the maximum pool size is reached, then the requests are queued until some con nections are released back to the pool. It is therefore advisable to close the c

onnection once done with it. -What is connection pooling and what is the maximum Pool Size in ADO.NET Connecti on String? Connection pooling is a method of reusing the active database connections instea d of creating new ones every time the user request one. Connection pool manager keeps track of all the open connections. When a new request comes in, the pool m anager checks if there exists any unused connections and returns one if availabl e. If all connections are busy and the maximum pool size has not been reached, a new connection is formed and added to the pool. And if the max pool size is rea ched, then the requests gets queued up until a connection in the pool becomes av ailable or the connection attempt times out. Connection pooling behavior is controlled by the connection string parameters. T he following are four parameters that control most of the connection pooling beh avior: Default max pool size is 100. -Can you explain how to enable and disable connection pooling? Set Pooling=true. However, it is enabled by default in .NET. To disable connection pooling set Pooling=false in connection string if it is an ADO.NET Connection. If it is an OLEDBConnection object set OLEDB Services=-4 in the connection strin g.

-Can you explain how to enable and disable connection pooling? To enable connection pooling: SqlConnection myConnection = new SqlConnection(@"Data Source=(local)\SQLEXPRESS; Initial Catalog=TEST;Integrated Security=SSPI;"); This has connection pooling on by default To disable connection pooling: SqlConnection myConnection = new SqlConnection(@"Data Source=(local)\SQLEXPRESS; Initial Catalog=TEST;Integrated Security=SSPI;Pooling=false;");

--------------------

ADO.NET overview

ADO.NET is design to provide data access. ADO.NET supports disconnected database access model which means that connection is open long enough to perform data op eration and is closed. When data is requested by the application, connection is opened, required data is loaded to the application and connection gets close. So in ADO.NET, connection is only available when it is required. This model reduce s system resource usage and thus enhances performance. ADO.NET is shipped with the Microsoft .NET Framework. It is used to access rela tional data sources, XML, and application data. ADO.NET uses XML for data transaction between client application and database. To access data using ADO.NET's DataAdapter objects Create connection using connection object. * * * * -Advantages and disadvantages of using multithreading Advantages: Simultaneous access to multiple applications Reduced number of required servers Improved performance and concurrency Simplified coding of remote procedure calls and conversations Disadvantages: Code writing, debugging, managing concurrency, testing, porting existing code is difficult in multithreading and multicontexting. Programmers need to remove static variables and replace any code that is not thr ead-safe to introduce threading into a previously non threaded application. -How does multi-threading work in .NET? There are two main ways of multi-threading which .NET encourages: To start your own threads with ThreadStart delegates, you should create a new th read "manually" for long-running tasks. Using the ThreadPool class either directly (using ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as Stream.BeginRead, or calling B eginInvoke on any delegate). Use the thread pool only for brief jobs. -Benefits of using the Thread Pool. Benefits of using the Thread Pool. Create Dataset object using DataAdapter object. Load data into Dataset using fill method of DataAdapter. Display Data using Dataset object. Close connection

The benefits of using a Thread Pool are: Thread creation and destruction overhead is negated, Better performance and better system stability. It is better to use a thread pool in cases where the number of threads is very l arge. -Limitations of using the Thread Pool. A thread pool executes on a single processor. But they are theoretically associa ted to server farms in which a master process distributes tasks to worker proces ses on different computers to increase the overall throughput. However, parallel problems are highly open to this approach. -Explain how to create and manage threads using Thread class in the System.Thread ing namespace in .NET. using System.Threading; private void ThreadTask() { int x; int val; Random r=new Random(); while(true) { x=this.progressBar1.Step*r.Next(-1,2); val = this.progressBar1.Value + x; if (val > this.progressBar1.Maximum) val = this.progressBar1.Maximum; else if (val < this.progressBar1.Minimum) val = this.progressBar1.Minimum; this.progressBar1.Value = val; Thread.Sleep(100); } } You need to write these lines first: Thread t1 = new Thread(new ThreadStart(this.ThreadTask)); t1.IsBackground = true; t1.Start();

--

You might also like