Tuesday, February 2, 2010

C# Serialization Interview Questions

Define Serilization
Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

why should you use serilization when the values of obj can be stored on disk and later used whenever required?
It is often necessary to store the value of fields of an object to disk and then retrieve this data at a later stage. Although this is easy to achieve without relying on serialization, this approach is often cumbersome and error prone, and becomes progressively more complex when you need to track a hierarchy of objects. Imagine writing a large business application containing many thousands of objects and having to write code to save and restore the fields and properties to and from disk for each object. Serialization provides a convenient mechanism for achieving this objective with minimal effort.

Explain how CLR manages serilization?
The Common Language Runtime (CLR) manages how objects are laid out in memory and the .NET Framework provides an automated serialization mechanism by using reflection. When an object is serialized, the name of the class, the assembly, and all the data members of the class instance are written to storage. Objects often store references to other instances in member variables. When the class is serialized, the serialization engine keeps track of all referenced objects already serialized to ensure that the same object is not serialized more than once. The serialization architecture provided with the .NET Framework correctly handles object graphs and circular references automatically. The only requirement placed on object graphs is that all objects referenced by the object that is being serialized must also be marked as Serializable. If this is not done, an exception will be thrown when the serializer attempts to serialize the unmarked object.


Why would you want to use serialization?
The two most important reasons are to persist the state of an object to a storage medium so an exact copy can be recreated at a later stage, and to send the object by value from one application domain to another.

Give examples where serialization is used?For example, Serialization is used to save session state in ASP.NET and to copy objects to the clipboard in Windows Forms.It is also used by remoting to pass objects by value from one application domain to another.

How will you serialize a class?
The easiest way to make a class serializable is to mark it with the Serializable attribute as follows:
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}

How will you deserialize an object?
First, create a formatter and a stream for reading, and then instruct the formatter to deserialize the object.
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin",
FileMode.Open,
FileAccess.Read,
FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(fromStream);
stream.Close();

Which class is responsible for binary serialization?
The BinaryFormater is the class responsible for the binary serialization and It's commonly used for the .Net Remoting.

What does it take to make my object serializable?
Your class must have the attribute SerializableAttribute and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute. Private and public fields are serialized by default.

What are the main advantages of binary serialization?
Smaller
Faster
More powerful (support complex objects and read only properties)

Will my read only properties be serialized?
Yes if the properties encapsulate a field. By default all the private and public fields are serialized. Binary serialization is not related to properties.

Is it possible to have circular reference?
Yes it is, you can have circular reference and the binary serialization process will work fine. .Net generate the object graph before the executing the serialization and finally generate the stream. Unlike Xml serialization process, the BinaryFormater has no problem with the circular reference.

Why my Dataset is so big when it's serialized in binary?
By default the DataSet is serialized in Xml and the binary stream only wraps the Xml Data inside it. That's mean that the size is similar to the Xml size. .Net 2.0 add a new property named RemotingFormat used to change the binary serialization format of the DataSet. SerializationFormat.Binary will generate a better result.
For previous version, it's also possible to download the DataSetSurrogate to reduce the size and increase the performance.

How can I implement a custom serialization?
If you need to control the serialization process of your class, you can implement the ISerializable interface which contains a method GetObjectData and a special constructor .

Why use custom serialization ?
By using it you will be able to handle version change in your class or get a better performance result. An exception of type SerializationException is raised if the fields does not exists.
#region ISerializable Members
//Special constructor
protected CustomInvoice(SerializationInfo info, StreamingContext context) {
clientName = info.GetString("clientName");
date = info.GetDateTime("date");
total = info.GetDouble("total");
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("clientName", clientName);
info.AddValue("date", date);
info.AddValue("total", total);
}
#endregion

When does a change in my object break the deserialization?
Binary serialization is not tolerant to version change. There is no problem when a new field is added but if a field is missing, an exception is throw. New field will get the default value. .Net 2.0 include a new attribute named OptionalFieldAttribute. For previous version, you must implement your own custom serialization and handle manually the changes.

When does a change in my object NOT break the deserialization?
Version fault exception are only checked if the assembly is signed, all version change are ignored otherwise.

How can I make my object version tolerant?
Use the OptionalFieldAttribute or implement your own custom serialization with ISerializable.

Why set VersionAdded of OptionalFieldAttribute since it's a free text?
The parameter is only for informative purpose. .Net never checked it by default but it could be used in a custom serialization. Use the reflection to get the attribute of field and check the added version value.

Does BinaryFormatter from .Net 1.1 is compatible with the BinaryFormatter 2.0?
Absolutely, the BinaryFormatter 2.0 is 100% with other version, but it's not the case with the SoapFormatter.

How can I modify a value just before the serialization or just after the deserialization?
You can add custom attribute to some method. Your marked method will get called a the right time. This is usefull to initialize a property after the deserialization or to clean up your instance before the serialization.
OnDeserializingAttribute :This event happens before deserialization
OnDeserializedAttribute :This event happens after deserialization
OnSerializingAttribute :This event happens before serialization
OnSerializedAttribute :This even happens after serialization
[Serializable]
public class SecurityToken {
private string password;
private string userName;

private string Decrypt(string aPassword) {
// Decrypt the password here !!!
return password;
}
private string Encrypt(string aPassword) {
// Encrypt the password here !!!
return password;
}
[OnSerializing()]
internal void OnSerializingMethod(StreamingContext context) {
password = Encrypt(password);
}
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context) {
password = Decrypt(password);

// Set the default
if (userName == null) {
userName = Environment.UserName;
}
}
public string Password {
get {
return password;
}
set {
password = value;
}
}
public string UserName {
get {
return userName;
}
set {
userName = value;
}
}
}

How can I create a generic Binary deserialization method?
// Binary deserialization (generic version with the return value casted)
public static T DeserializeBinary(string aFileName) {
using (FileStream _FileStream = new FileStream(aFileName, FileMode.Open)) {
BinaryFormatter _Formatter = new BinaryFormatter();
return (T)_Formatter.Deserialize(_FileStream);
}
}

Which class is responsible for Xml serialization?
XmlSerializer is responsible of the Xml serialization.

What is the difference between the SoapFormatter and the XmlSerializer?
SoapFormatter is used to create a Soap envelop and use an object graph to generate the result. The XmlSerializer process use only the public data and the result is a more common xml file. The Web Service in .Net use an XmlSerializer to generate the output contained in the Soap message. The SoapFormatter and the BinaryFormatter are used in the .Net Remoting serialization process.
What does it take to make my object serializable?
Nothing, but there is some constraint :
Your object must have a public empty constructor.
Field or property must be public
Their return type must also respect serialization rules.
Property must be read write.

What are the main advantages of Xml serialization?
Based on international standard (XML).
Cross platforms.
Readable and can be edited easily.

How do I encapsulate the Xml serialization method?
public static void SerializeXml( object aObject, string aFileName) {
using (FileStream _FileStream = new FileStream(aFileName, FileMode.Create)) {
XmlSerializer _Serializer = new XmlSerializer ( aObject.GetType());
_Serializer.Serialize(_FileStream, aObject);
}
}

How do I encapsulate the Xml deserialization method?
public static object DeserializeXml( string aFileName, Type aType) {
using (FileStream _FileStream = new FileStream(aFileName, FileMode.Create)) {
XmlSerializer _Serializer = new XmlSerializer (aType);
return _Serializer.Deserialize(_FileStream);
}
}

How can I create a generic Xml deserialization method?
public static T DeserializeXml(string aFileName) {
using (FileStream _FileStream = new FileStream(aFileName, FileMode.Open)) {
XmlSerializer _Serializer = new XmlSerializer (typeof(T));
return (T)_Serializer.Deserialize(_FileStream);
}
}

How can I ignore a property in serialization?
If you use a XmlSerializer, mark your property with the custom attribute XmlIgnoreAttribute and if you use a SoapFormatter, use a SoapIgnoreAttribute instead.

How can I rename a field or a property in the Xml output?
Use the attribute XmlElementAttribute or XmlAttributeAttribute with the new name as parameter. To rename a class, use the XmlTypeAttribute.
[XmlType("city")]
public class Town {
private string name;
private string state;
[XmlElement("townname")]
public string Name {
get {
return name;
}
set {
name = value;
}
}
[XmlAttribute("state")]
public string State {
get {
return state;
}
set {
state = value;
}
}
}

How can I serialize a property as an Xml attribute?
By default properties are serialized as Xml elements, but if you add an XmlAttributeAttribute to a property, .Net will generate an attribute instead. It's must be type compatible with an Xml attribute. See example here
[XmlAttribute("state")]
public string State {
get {
return state;
}
set {
state = value;
}
}

How can I implement custom serialization?
You need to Implement the interface IXmlSerializable. This class is available in the .Net 1.X but it's was not documented. It's now official available with .Net 2.0. With custom serialization, it's possible to optimize the output and generate only what is needed. In this example, we generate only the non empty properties
public class SessionInfo : IXmlSerializable {
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema() {
return null;
}
public void ReadXml(XmlReader reader) {
UserName = reader.GetAttribute("UserName");

while (reader.Read()) {
if (reader.IsStartElement()) {
if (!reader.IsEmptyElement) {
string _ElementName = reader.Name;
reader.Read(); // Read the start tag.
if(_ElementName == "MachineName") {
MachineName = reader.ReadString();
} else {
reader.Read();
}
}
}
}
}
public void WriteXml(XmlWriter writer) {
if (!String.IsNullOrEmpty(UserName))
writer.WriteAttributeString("UserName", UserName);

if (!String.IsNullOrEmpty(MachineName))
writer.WriteElementString("MachineName", MachineName);
}
#endregion
private string machineName;
private string userName;

public string MachineName {
get {
return machineName;
}
set {
machineName = value;
}
}
public string UserName {
get {
return userName;
}
set {
userName = value;
}
}
}

How can I serialize a property array?
Array are compatible with the serialization, but all elements must be of the same type.

How can I serialize an array with different types?
It's possible to tag the array with all the possible type. Use XmlInclude on the class containing the array or XmlArrayItem. All the possible types must be specified with the attributes. Array types must be known because of the Xml schema. XmlInclude could be used for property that returned differente types. It's complicate object inheritance since all types must be known. This example will fail with a message "There was an error generating the XML document." because the Cars could contain undefined types.
public class Car {}
public class Ford : Car{}
public class Honda: Car {}
public class Toyota: Car {}
public class CarSeller {
private List cars = new List();
public List Cars {
get {
return cars;
}
set {
cars = value;
}
}
}
...
Ford _Ford = new Ford();
Honda _Honda = new Honda();
Toyota _Toyota = new Toyota();
CarSeller _Seller = new CarSeller();
_Seller.Cars.Add(_Ford);
_Seller.Cars.Add(_Honda);
_Seller.Cars.Add(_Toyota);
SerializationHelper.SerializeXml(_Seller, @"seller.xml");
Three possible solutions:
#1 Add XmlIncludeAttribute to the Seller class:
[XmlInclude(typeof(Ford))]
[XmlInclude(typeof(Honda))]
[XmlInclude(typeof(Toyota))]
public class CarSeller {
private List cars = new List();

public List Cars {
get {
return cars;
}
set {
cars = value;
}
}
}

#2 Add XmlArrayItem to the property named Cars:
public class CarSeller {
private List cars = new List();

[XmlArrayItem(typeof(Ford))]
[XmlArrayItem(typeof(Honda))]
[XmlArrayItem(typeof(Toyota))]
public List Cars {
get {
return cars;
}
set {
cars = value;
}
}
}

#3 Implement our own serialization with IXmlSerializable :
see items above

How can I serialize a collection?
Collection are serialized correctly, but they must contains only object of same types. Read only properties of type ArrayList, List and other collections will be serialized and deserialized correctly.
Public class Role {
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class UserAccount {
private string userName;

public string UserName {
get {
return userName;
}
set {
userName = value;
}
}
// Generic version
private List roles = new List();

public List Roles {
get {
return roles;
}
}
// ArrayList version
private ArrayList roleList = new ArrayList();

public ArrayList RoleList {
get {
return roleList;
}
}
// String collection version
private StringCollection roleNames = new StringCollection();

public StringCollection RoleNames {
get {
return roleNames;
}
}
UserAccount _UserAccount = new UserAccount();
_UserAccount.UserName = "dhervieux";

Role _RoleAdmin = new Role();
_RoleAdmin.Name = "Admin";
Role _RoleSales = new Role();
_RoleSales.Name = "Sales";
_UserAccount.RoleList.Add(_RoleAdmin);
_UserAccount.RoleList.Add(_RoleSales);
_UserAccount.Roles.Add(_RoleAdmin);
_UserAccount.Roles.Add(_RoleSales);
_UserAccount.RoleNames.Add("Admin");
_UserAccount.RoleNames.Add("Sales");
SerializationHelper.SerializeXml(_UserAccount, @"useraccount.xml");
UserAccount _Result =
SerializationHelper.DeserializeXml(@"useraccount.xml");


Why is the first serialization of each type of object is so long?
XmlSerializer generate an assembly in memory optimized for each type. That's explain why the first call to a Web Service is so long. In .Net 2.0, there is an option in the project properties of Visual Studio to generate the Xml serialization assembly. Use it directly in the IDE or use sgen.exe, this tools come with the .Net Framework SDK.

How can I optimize the serialization process?
Pregenerate your serialization assembly with Visual Studio or sgen.exe. Implementing your own serialization could also increase the performance.

How can I serialize an array directly to stream?
Yes it possible. .Net will name the Array and save the content. All the data must be of the same type.
bool[] _BoolArray = new bool[] { true, false, false, true };
// Serialization
SerializationHelper.SerializeXml(_BoolArray, @"boolarray.xml");
//Deserialization
_Result = SerializationHelper.DeserializeXml(@"directboolarray.xml");
will produce:


true
false
false
true


Which serializer is used by a Web Services?
Web Services are using SOAP to communicate, but returned objets or parameters are serialized with the XmlSerializer.

Does read only properties are serialized?
No, they are not, except for collections.

How can I serialize a multidimensional array
You need to encapsulate your array in a structure or a class an serialize it. Multidimensional array are not serializable by default.

How can I avoid serialization for an empty list or property with a default value?
There is an undocumented way of doing that, you need to create a method named ShouldSerialize where is replaced by the property name. This method should return a boolean that indicate if the property must be serialized or not. For exemple, if you have list with no item, there is no need to serialize an empty list.
public class Registration {
private string[] users = new string[0];
public bool ShouldSerializeUsers() {
return users.Length > 0;
}
public string[] Users {
get {
return users;
}
set {
users = value;
}
}
}
Result :


Without the ShouldSerializeUsers :





Why my object is marked as Serializable (like SortedList) and it's does not work?
The SerializationAttribute is only used for the binary serialization. That does not mean that it will work with an XmlSerializer. That's the case of the SortedList.

How to remove the default namespace in the serialization?
It's possible to remove the xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema" from the serialization result, it's possible to add an XmlSerializerNamespaces with an empty namespace mapping.
User _User = new User(new string[] { "Admin", "Manager" });
using (FileStream _FileStream = new FileStream("user.xml", FileMode.Create)) {
XmlSerializer _Serializer = new XmlSerializer(_User.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
_Serializer.Serialize(_FileStream, _User, ns);
}

A good article on Serilization : http://msdn.microsoft.com/en-us/magazine/cc163902.aspx

What is new in VS 2008?

New Features of Visual Studio 2008 for .NET Professionals

1. LINQ Support
LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless.

The benefits of using LINQ are significant – Compile time checking C# language queries, and the ability to debug step by step through queries.

2. Expression Blend Support
Expression blend is XAML generator tool for silverlight applications. You can install Expression blend as an embedded plug-in to Visual Studio 2008. By this you can get extensive web designer and JavaScript tool.

3. Windows Presentation Foundation
WPF provides you an extensive graphic functionality you never seen these before. Visual Studio 2008 contains plenty of WPF Windows Presentation Foundation Library templates. By this a visual developer who is new to .NET, C# and VB.NET can easily develop the 2D and 3D graphic applications.

Visual Studio 2008 provides free game development library kits for games developers. currently this game development kits are available for C++ and also 2D/3D Dark Matter one image and sounds sets.

4. VS 2008 Multi-Targeting Support
Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run, debug the .NET 2.0, .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.

5. AJAX support for ASP.NET
Previously developer has to install AJAX control library separately that does not come from VS, but now if you install Visual Studio 2008, you can built-in AJAX control library. This Ajax Library contains plenty of rich AJAX controls like Menu, TreeView, webparts and also these components support JSON and VS 2008 contains in built ASP.NET AJAX Control Extenders.

6. JavaScript Debugging Support
Since starting of web development all the developers got frustration with solving javascript errors. Debugging the error in javascript is very difficult. Now Visual Studio 2008 makes it is simpler with javascript debugging. You can set break points and run the javaScript step by step and you can watch the local variables when you were debugging the javascript and solution explorer provides javascript document navigation support.

7. Nested Master Page Support
Already Visual Studio 2005 supports nested master pages concept with .NET 2.0, but the problem with this Visual Studio 2005 that pages based on nested masters can't be edited using WYSIWYG web designer. But now in VS 2008 you can even edit the nested master pages.

8. LINQ Intellisense and Javascript Intellisense support for silverlight applications
Most happy part for .NET developers is Visual Studio 2008 contains intellisense support for javascript. Javascript Intellisense makes developers life easy when writing client side validation, AJAX applications and also when writing Silverlight applications

Intellisense Support: When we are writing the LINQ Query VS provides LINQ query syntax as tool tips.

9. Organize Imports or Usings
We have Organize Imports feature already in Eclipse. SInce many days I have been waiting for this feature even in VS. Now VS contains Organize Imports feature which removes unnecessary namespaces which you have imported. You can select all the namespaces and right click on it, then you can get context menu with Organize imports options like "Remove Unused Usings", "Sort Usings", "Remove and Sort". Refactoring support for new .NET 3.x features like Anonymous types, Extension Methods, Lambda Expressions.

10. Intellisense Filtering
Earlier in VS 2005 when we were typing with intellisense box all the items were being displayed. For example If we type the letter 'K' then intellisense takes you to the items starts with 'K' but also all other items will be presented in intellisense box. Now in VS 2008 if you press 'K' only the items starts with 'K' will be filtered and displayed.

11. Intellisense Box display position
Earlier in some cases when you were typing the an object name and pressing . (period) then intellisense was being displayed in the position of the object which you have typed. Here the code which we type will go back to the dropdown, in this case sometimes programmer may disturb to what he was typing. Now in VS 2008 If you hold the Ctrl key while the intellisense is dropping down then intellisense box will become semi-transparent mode.

12. Visual Studio 2008 Split View
VS 205 has a feature show both design and source code in single window. but both the windows tiles horizontally. In VS 2008 we can configure this split view feature to vertically, this allows developers to use maximum screen on laptops and wide-screen monitors.

Here one of the good feature is if you select any HTML or ASP markup text in source window automatically corresponding item will be selected in design window.

13. HTML JavaScript warnings, not as errors:
VS 2005 mixes HTML errors and C# and VB.NET errors and shows in one window. Now VS 2008 separates this and shows javascript and HTML errors as warnings. But this is configurable feature.

14. Debugging .NET Framework Library Source Code:
Now in VS 2008 you can debug the source code of .NET Framework Library methods. Lets say If you want to debug the DataBind() method of DataGrid control you can place a debugging point over there and continue with debug the source code of DataBind() method.

15. In built Silverlight Library
Earlier we used to install silverlight SDK separately, Now in VS 2008 it is inbuilt, with this you can create, debug and deploy the silverlight applications.

16. Visual Studio LINQ Designer
Already you know in VS 2005 we have inbuilt SQL Server IDE feature. by this you no need to use any other tools like SQL Server Query Analyzer and SQL Server Enterprise Manger. You have directly database explorer by this you can create connections to your database and you can view the tables and stored procedures in VS IDE itself. But now in VS 2008 it has View Designer window capability with LINQ-to-SQL.

17. Inbuilt C++ SDK
Earlier It was so difficult to download and configure the C++ SDK Libraries and tools for developing windows based applications. Now it is inbuilt with VS 2008 and configurable

18. Multilingual User Interface Architecture - MUI
MUI is an architecture contains packages from Microsoft Windows and Microsoft Office libraries. This supports the user to change the text language display as he wish.

Visual Studio is now in English, Spanish, French, German, Italian, Chinese Simplified, Chinese Traditional, Japanese, and Korean. Over the next couple of months. Microsoft is reengineering the MUI which supports nine local languages then you can even view Visual studio in other 9 local languages.

19. Microsoft Popfly Support
Microsoft Popfly explorer is an add-on to VS 2008, by this directly you can deploy or hosting the Silverlight applications and Marshup objects

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...