Friday, January 15, 2010

ADO.Net Interview Questions

Can you give an overview of ADO.NET architecture?
The most important section in ADO.NET architecture is “Data Provider”. Data Provider provides access to data source (SQL SERVER, ACCESS, ORACLE).In short it provides object to achieve functionalities like opening and closing connection, retrieve data, and update data. In the below figure, you can see the four main sections of a data provider:-

• Connection
• Command object (This is the responsible object to use stored procedures)
• Data Adapter (This object acts as a bridge between data store and dataset)
• Data reader (This object reads data from data store in forward only mode).
• Dataset object represents disconnected and cached data. If you see the diagram, it is not in direct connection with the data store (SQL SERVER, ORACLE etc) rather it talks with Data adapter, who is responsible for filling the dataset. Dataset can have one or more Data table and relations.


What is the use of connection object?
They are used to connect a data to a Command object.
• An OleDbConnection object is used with an OLE-DB provider.
• A SqlConnection object uses Tabular Data Services (TDS) with MS SQL Server.

Difference between OLEDB Provider and SqlClient ?
SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better performance), and it was written with lots of help from the SQL Server team.

Which is the default Provider Name of the Providers used to access the DataBase?
System.Data.SqlClient

What extra features does ADO.Net 2.0 have?
Bulk Copy Operation
Bulk copying of data from a data source to another data source is a newly added feature in ADO.NET 2.0. ADO.NET inrtoduces bulk copy classes which provide fastest way to transfer\ data from once source to the other. Each ADO.NET data provider has bulk copy classes. For example, in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which can read a DataSet, DataTable, DataReader, or XML objects.

Data Paging
A new method is introduced ExecutePageReader which takes three parameters - CommandBehavior, startIndex, and pageSize. So if you want to get rows ony from 10 - 20, you can simply call this method with start index as 10 and page size as 10.

Batch Update
If you want to update large number of data on set ADO.NET 2.0 provides UpdateBatchSize property, which allows you to set number of rows to be updated in a batch. This increases the performance dramatically as round trip to the server is minimized.

Load and Save Methods
In previous version of ADO.NET, only DataSet had Load and Save methods. The Load method can load data from objects such as XML into a DataSet object and Save method saves the data to a persistent media. Now DataTable also supports these two methods. You can also load a DataReader object into a DataTable by using the Load method.

New Data Controls
In toolbox you can see three new controls - DataGridView, DataConnector, and DataNavigator.

DataReader's New Execute Methods
Some new execute methods introduced are ExecutePageReader, ExecuteResultSet, and ExecuteRow.


Name the classes that are contained in System.Data NameSpace?
DataSet
DataTable
DataColumn
DataRow
DataRealation
Constraint


Name the classes are found in System.Data.Common NameSpace?
1)DataColumnMapping
2)DataTableMapping

DataReader
How do you create an instance of SqlDataReader class?To create an instance of SqlDataReader class, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor. You Cannot use SqlDataReader() constructor to create an instance of SqlDataReader class

//Error!
SqlDataReader ReaderObject = new SqlDataReader();

//Call the ExecuteReader method of the SqlCommand object
SqlCommand CommandObject = new SqlCommand();
SqlDataReader ReaderObject = CommandObject.ExecuteReader();

Creating an instance of SqlDataReader class using SqlDataReader() constructor generates a compile time error - The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined.

How do you programatically check if a specified SqlDataReader instance has been closed?Use the IsClosed property of SqlDataReader to check if a specified SqlDataReader instance has been closed. If IsClosed property returns true, the SqlDataReader instance has been closed else not closed.

How do you get the total number of columns in the current row of a SqlDataReader instance?
FieldCount property can be used to get the total number of columns in the current row of a SqlDataReader instance.

How do you retrieve two tables of data at the same time by using data reader?
Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.

The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.
//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
ConnectionObject.Open();
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
{
while (ReaderObject.Read())
{
//Do Something
}
}
//Close the Reader
ReaderObject.Close();
//Close the Connection
ConnectionObject.Close();

Using ADO.NET Datareader a user extracted data from a database table having 5 records.What happens if another user adda 5 more records to the table same time.Can the first user extracted records become 10 instead of 5 or will it remain same 5? what about same case when ADO ? pls explain in detail.
It will remain 5, the DataReader object is a forward-only, read-only object, it can't be updated to read newly added records. DataReader object isn't available in ADO.

Which method is used to Gets the name of the specified column using DataReader?
GetName

How can you update the records in database using datareader?You cannot update. DataReader is just used for reading the data in forward only mode. You can achieve this using Dataset but not by DataReader.


Which ADO.NET object is very fast in getting data from database?
SqlDataReader object. (Even datasets also use SqlDataReader objects internally for retriving data from database.)

What is the difference between DataReader and DataAdapter?
1. Data Reader is read only forward only and much faster than DataAdapter.
2. If you use DataReader you have to open and close connection explicitly where as if you use DataAdapter the connection is automatically opened and closed.
3. DataReader is connection oriented where as Data Adapter is disconnected

Using ADO.NET Datareader a user extracts data from a database table having 1000 rows.He closed his browser in between. that is after fetching only 50 records.
What happens to the Datareader?will it remain connected? and will fetch 1000 records and what after? will garbage collector collect and dispose it soon?

DataReader isn't connected, so the rows will be lost and the object will be destroyed.

why datareader is forward only?
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.
Generally we use datareader ado.net control where we don't need go to previous row like binding a dropdown or data repeater control. To keep it light weighted microsoft support forward only functionality in datareader control.

Typed and Untyped Datasets

What are typed datasets?
A typed dataset is a dataset that is first derived from the base DataSet class and then uses information in an XML Schema file (an .xsd file) to generate a new class. Information from the schema (tables, columns, and so on) is generated and compiled into this new dataset class as a set of first-class objects and properties.

A strongly typed DataSet is actually a class that inherits from the System.Data.DataSet class and adds a few extra features of its own. The class file is generated from the XSD file. You can regenerate the class file by right-clicking in the XSD's designer view and selecting Generate DataSet (alternatively, you can use the xsd.exe command-line utility). The class file actually contains a series of classes that inherit from and extend the DataSet, DataTable, DataRow, and EventArgs classes. Because of this inheritance, developers do not lose any functionality by using a strongly typed DataSet. For example, even though you can refer to a DataTable via a property with the same name as the table, you can still refer to the table through the Tables collection. The following two lines evaluate to the same DataTable object:

oDs.Tables["Orders"]
oDs.Orders



Why would you use typed datasets or Advantages of Typed Datasets?
Typed data sets provide three features that aren't part of the base DataSet class.
1)They provide a designer surface for laying out relationships and constraints.
2)They provide type-checked operations, i.e. retrieval, inserts and updates.
3)They provide a special constructor to add serialization support to your typed data set. All of the rest of the functionality, e.g. finding rows, comes from the DataSet and related classes themselves

What are the differences between typed and Untyped Datasets ?
Strongly Typed DataSet
1)It provides additional methods, properties and events and thus it makes it easier to use
2)You will get type mismatch and other errors at compile time.
3)You will get advantage of intelliSense in VS. NET
4)Performance is slower in case of strongly typed dataset
5)In complex environment, strongly typed dataset's are difficult to administer.

Untyped DataSet
1)It is not as easy to use as strongly typed dataset.
2)You will get type mismatch and other errors at runtime
3)You can't get an advantage of intelliSense.
4)Performance is faster in case of Untyped dataset.
5)Untyped datasets are easy to administer.

Questions and Answers on Constructors and Destructors in C#

Constructors
Is the Constructor mandatory for the class ?
Yes, It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier.

What if I do not write the constructor ?
In such case the compiler will try to supply the no parameter constructor for your class behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor ( with or without parameters), then compiler will not make any such attempt.

What if I have the constructor public myDerivedClass() but not the public myBaseClass() ?
It will raise an error. If either the no parameter constructor is absent or it is in-accessible ( say it is private ), it will raise an error.

Can we access static members from the non-static ( normal ) constructors ?
Yes, We can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.

How can one constructor call another?
To call one C# constructor from another, before the body of the constructor, use either:
: base (parameters)
: this (parameters)
Example :
public class mySampleClass
{
public mySampleClass(): this(10)
{
}
public mySampleClass(int Age)
{
}
}


Are C# constructors inherited?
No. C# constructors cannot be inherited. If constructor inheritance were allowed, then necessary initialization in a base class constructor might easily be omitted. This could cause serious problems which would be difficult to track down. For example, if a new version of a base class appears with a new constructor, your class would get a new constructor automatically. This could be catastrophic.

How call a virtual method from a constructor or destructor?
The C# compiler inserts a call to the base class constructor at the beginning of any derived constructor in order to maintain OO semantics, i.e. that the base class constructor is called first. In a similar fashion, when C# destructors call virtual methods, virtual method calls from a base destructor are directed to the derived implementation. Therefore, in C#, a virtual method can be called from a constructor or destructor. But, usually, it is a bad idea.

What is the syntax for calling an overloaded constructor from within a constructor?
We can not use this() and constructor-name(). It gives a compile time error.
The syntax for calling another constructor is as follows:

class A
{
A (int i) { }
}

class B : A
{
B() : base (10) // call base constructor A(10)
{ }

B(int i) : this() // call B()
{ }

public static void Main() {}
}

Why must struct constructors have at least one argument?
The .NET Common Language Runtime (CLR) does not guarantee that parameterless constructors will be called. If structs were permitted to have default, parameterless constructors, the implication would be that default constructors would always be called. Yet, the CLR makes no such guarantee.

For instance, an array of value types will be initialized to the initial values of its members—i.e., zero for number type primitive members, null for reference types, and so forth—and not to the values provided in a default constructor. This feature makes structs perform better; because, constructor code need not be called.

So, requiring that a constructor contain a minimum of one parameter reduces the possibility that a constructor will be defined which is expected to be called every time the struct type is built.

C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

If I have a constructor with a parameter, do I need to explicitly create a default constructor?
Yes

Can I call a virtual method from a constructor/destructor?
Yes, but it's generally not a good idea.In .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)

The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

What are static constructors?
This is a new concept introduced in C#. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
The syntax of writing the static constructors :

public class myClass
{
static myClass()
{
}
}

Does a static constructor have a access modifier?
There should be no access modifier in static constructor definition. to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it

Can a static constructors have parameters?
The static constructor should be without parameters. is going to be called by CLR, who can pass the parameters to it, if required, No one, so we cannot have parameterized static constructor.

How will you access non static members of a class from your static constructor?
Non-static members in the class are specific to the object instance so static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.

Can you overload a static constructor?
Overloading needs the two methods to be different in terms to methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.

Is this code valid then?
public class myClass
{
static myClass()
{
public myClass()
{
}
}
}
This is perfectly valid.Because the time of execution of the two method are different. One is at the time of loading the assembly and one is at the time of object creation.

What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Does C# provide copy constructor?
No, C# does not provide copy constructor.

If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Destructors
How do destructors work in C#?
A destructor is a method that is called when an object is destroyed—it's memory is marked unused. C++ destructors are used to free up memory and other resources and to perform housekeeping tasks. In .NET, the Garbage Collector (GC) performs much of this type of work automatically. Generally, rather than define a destructor for manual cleanup, let the Common Language Runtime (CLR) handle it.

In C#, the Finalize method performs the operations that a standard C++ destructor might perform. Finalizers are similar to destructors except that it is not guranteed that they will be called by the CLR.

Here is a sample finalizer specification using the C++ destructor syntax which places a tilde (~) symbol before the class name:

class Test
{
~Test()
{
...
}

public static void Main() {}
}When defining a C# finalizer, it is not named Finalize. However, finalizers do override object.Finalize(), which is called during the garbage collection process.

How make a C# destructor virtual?
By definition, a C# destructor is virtual. Because, a C# destructor is basically an override of the Finalize method of System.Object. Therefore, these is no need to make a C# destructor virtual.

Why am I blogging :)

To begin with, this is a place to store all questions that i have collected till now for C# and Sql Server. Hope it helps you...