Friday, November 27, 2009

C# Realtime Interview Questions

#.NET Interview Questions and Realtime Discussions ,C# Realtime Interview Questions,C# Questions for MNCs like Cap Gemini,CTS,HP,Patni,Sasken

What is the top .NET class that everything is derived from?
System.Objects

What is an abstract class?
The abstract modifier can be used with classes, methods, properties, indexers, and events.
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:
An abstract method is implicitly a virtual method.
Abstract method declarations are only permitted in abstract classes.
Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:
public abstract void MyMethod();
________________________________________
abstract class is a prototype of a class. it is used to provide partial
class implementation. abstract class contain abstract method which can be implemented by derived class.
some rules for abstract class are following-:
1) an object of an abstract class can never be created.
2)you can not declare an abstract method outside the abstract class.
3)can not be declared sealed.

WHAT IS THE ADVANTAGE OF SERIALIZATION?
Serialization is the process of maintaing object in the form stream. it is useful in case of remoting.
Serialization is the process of converting object into byte stream which is useful to transport object(i.e remoting),persisting object(i.e files,database)
SERIALIZATION IS PROCESS OF LOADING THE OBJECT STATE IN THE FORM OF BYTE STREAMS IN DATABASE/FILE SYATEM.

Can we inherit the java class in C# class,how?
Java Programming language is not supported with .Net Framework hence you cannot inherit javaclass in C# class.Also Java has JavaByte code after compiling similar to MSIL which is similar but cannot inherit due to framework support.

Are C# destructors the same as C++ destructors?
No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.
To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the ‘using’ construct to make this easier.

What is wrapper class? is it available in c#?
Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility method to access it . For eg you can store list of int values in a vector class and access the class. Also the methods are static and hence you can use them without creating an instance . The values are immutable .
wrapper class are those class in which we can not define and call all predefined function .it is possible in java not C#.

Which tool is used to browse the classes, structs, interfaces etc. in the BCL?
wincv as in Windows Class View

How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable, and thus the Dispose() method) goes out of scope, even if it does so by an exception being thrown, and thus that resources are always released.

What happens when a C# project has more than 1 Main methods
f the project is compiled using /main switch with the compiler then the project compiles successfully.

For example:
class A
{
public static void Main(string[] args)
{
Console.WriteLine("Main in class A");
}
}

class B
{
public static void Main(string[] args)
{
Console.WriteLine("Main in class B");
}
}

Now compile with the /main switch with the C# compiler like
csc MultipleMain.cs /main:A

This will compile without error and while executing it will show Main in class A

Attempting to compile an application consisting of multiple classes with defined Main methods and not specifying the /main switch will result in a compiler error.
How do you refer parent classes in C#? A) Super B) This C) Base
This keyword is used for reffering current object and Base keyword is used for referring parrent class. so ans. is C.
Super: Super is used to Refer the Base Class in JAVA
This: This is used to Refer the Current or Child Class in C#
Base: Base is used to Refer The Parent or Base Class

What is object pooling
Defination: A performance optimization based on using collections of pre-allocated resources, such as objects or database connections
With the advent of the .NET platform, writing code that pools objects and threads has become a simple task. By using the Threading and Collections namespaces, you can create robust object pooling applications. This could also be done by implementing COM+ interop interfaces into your code.

Which method is actually called ultimately when Console.WriteLine( ) is invoked?
A) Append( )
B) AppendFormat( )
C) Tostring( )
Ans: B, AppendFormat() method is called.

What is an Assembly?
An assembly is a file that is automatically generated by the compiler upon successful compilation of every .NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. The entire process will run in the background of your application; there is no need for you to learn deeply about assemblies. However, a basic knowledge about this topic will help you to understand the architecture behind a .NET application.
An assembly is used by the .NET CLR (Common Language Runtime) as the smallest unit for: deployment; version control; security; type grouping and code reuse. Assemblies consists of a manifest and one or more modules and/or files like HTML, XML, images, video clips,...

An assembly can be thought of as a logical DLL and must contain a single manifest and may optionally contain type meta data, MSIL (Microsoft Intermediate Language) and resources.

Assemblies come in 2 flavors: application private and shared. Application private assemblies are used by one application only. This is the default style of assembly. Such assemblies must reside in the application folder.

Shared assemblies are meant to be used by more than one application. They must have a
globally unique name and must be defined in the GAC (Global Assembly Cache). To learn more about viewing the GAC
Basically there are two kind of assemblies when it comes to deployment.
Private Assemblies
Shared Assemblies

Private assemblies are the ones which are in your application folder itself. They can be easily and uniquely identified by their name.
These type of assemblies can be deployed simply by copying them to the bin folder of your application.

Shared Assemblies are those which can be shared by multiple applications on the machine.
For this we have to place the Shared assembly in the GAC.

Now since we can install any application or assembly created by any company, that is we install assemblies from oracle, microsoft and similarly from many other companies.

There is always a possiblity that they may use the same assembly name as your assembly name.
If such type of assemblies are placed in the GAC then we cannot uniquely identify a particular assembly.But if we give a strong name to the assmebly then it is like a unique identifier for the assembly.It is Globally unique.

Strong name consists of
1. Name of the assembly
2. Public key token
3. optionally any resources
4. Version Number

So basically to uniquely identify a particular assembly from the GAC we have to give it a strong name. Its that simple.
The Shared assembly can be deployed in to GAC by using the GACUTIL tool with the -i switch
gacutil -i assemblyname
or simply copying it to the assembly folder in the windows directory (XP) or WINNT directory(others)
Also there are Satellite Assemblies which contian only resources like strings, images etc.
Also there are dynamic assemblies which are generated on the fly dynamically.

Real world examples of abstract classes and interfaces

An abstract class is a class that you cannot create an instance of. It can provide basic functionality, but in order for that functionality to be used, one or more other classes must derive from the abstract class. One of the major benefits of abstract classes is that you can reuse code without having to retype it. That has a plethora of benefits, such as reducing bugs and making coding faster. A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.
Now, an interface is like an abstract class, except it does not contain any logic. Rather, it specifies an interface. So, there might be an interface called IFly. This might have the methods GoForward and GoDown. Those methods would not actually contain any logic... each class that implements interface IFly would have to implement those GoForward and GoDown methods. You could have classes Duck and Finch implement interface IFly. Then, if you want to keep a list of instances that can fly, you just create a list that contains items of type IFly. That way, you can add Ducks and Finches and any other instance of a class the implements IFly to the list.
So, abstract classes can be used to consolidate and share functionality, while interfaces can be used to specify what the common functionality that will be shared between different instances will be, without actually building that functionality for them. Both can help you make your code smaller, just in different ways. There are other differences between interfaces and abstract classes, but those depend on the programming language, so I won't go into those other differences here.

Or
Do you mean real-world as in "A live software system which includes  Abstract classes or interfaces" or do you mean "A contrived example which demonstrates their usefullness"?
If you mean the latter think of Vehicle as an abstract class. You can't yet do anything with it because you have no idea what it does, or how to drive it.
abstract class Vehicle{}
Vehicles could be split into morotized and pedal-powered, but still this is abstract, we still dont know what to do with it.

abstract class MotorVehicle : Vehicle {}
abstract class PedaledVehicle : Vehicle {}
You could now define a concrete (non-abstract) class, like car.
class MotorCar : MotorVehicle {}
 Intefaces come in handy you can only inherit from one base class. So imagine some vehicles are drivable, others are remote controlled, some vehicles use a stearing wheel, others dont
interface IDrivable{}
interface IHasStearingWheel{}
Now you could derive a DrivableMotorCar from its base clas, and also implement other behaviours.
class DrivableMotorCar : MotorVehicle, IDrivable, IHasStearingWheel {}


or 

I Just find a suitable reference... Pls refer to this...


http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

Deligates Using C#.net

A delegate in C# is similar to a function pointer in C or C++.
Using a delegate allows the programmer to encapsulate a reference to a method inside
a delegate object. The delegate object can then be passed to code which can call the
referenced method, without having to know at compile time which method will be
invoked.
using System;

          namespace Akadia.BasicDelegate

               {

                   // Declaration

                   public delegate void SimpleDelegate();

              

                   class TestDelegate

                   {

                       public static void MyFunc()

                       {

                          
              Console.WriteLine("I was called by delegate ...");

                       }

              

                       public static void Main()

                       {

                           // Instantiation

                           SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

              

                           // Invocation

                          
              simpleDelegate();

                       }

                   }

               }
        
 http://www.akadia.com/services/dotnet_delegates_and_events.html

Using JavaScript with ASP.Net GridView Control

am explaining how to make use JavaScript in the ASP.Net GridView control and make it more elegant by reducing postbacks.

Functions such as

1. Highlighting selected row

2. Check/Uncheck all records using single checkbox.

3. Highlight row on mouseover event.

The above three functions can be easily achieved using JavaScript thus avoiding postbacks.

To start with I have a GridView control with a header checkbox and checkbox for each individual record

To start with I have a GridView control with a header checkbox and checkbox for each individual record



































Above you will notice I am calling two JavaScript functions checkAll and Check_Click which I have explained later. Also I have attached a RowDataBound event to the GridView to add mouseover event





Highlight Row when checkbox is checked



The above function is invoked when you check / uncheck a checkbox in GridView row First part of the function highlights the row if the checkbox is checked else it changes the row to the original color if the checkbox is unchecked. The Second part loops through all the checkboxes to find out whether at least one checkbox is unchecked or not. If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it Check all checkboxes functionality The above function is executed when you click the Header check all checkbox When the Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows. And when unchecked it restores back the original color of the row and unchecks the checkboxes. Note: The check all checkboxes checks all the checkboxes only for the current page of the GridView and not all. Highlight GridView row on mouseover event



The above JavaScript function accepts the reference of the GridView Row and the event which has triggered it.

Then based on the event type if event is mouseover it highlights the row by changing its color to orange else if the event is mouseout it changes the row’s color back to its original before the event occurred.

The above function is called on the mouseover and mouseout events of the GridView row. These events are attached to the GridView Row on the RowDataBound events refer the code below




C#

protected void RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow )

{

e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");

e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

}

}



VB.Net

Protected Sub RowDataBound(ByVal sender As Object,

ByVal e As GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then

e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)")

e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)")

End If

End Sub



You can try out the functionality discussed above using the sample GridView here


CustomerID City Country PostalCode
ALFKI Berlin Germany 12209
ANATR México D.F. Mexico 05021
ANTON México D.F. Mexico 05023
AROUT London UK WA1 1DP
BERGS Luleå Sweden S-958 22
BLAUS Mannheim Germany 68306
BLONP Strasbourg France 67000
BOLID Madrid Spain 28023
BONAP Marseille France 13008
BOTTM Tsawassen Canada T2F 8M4


The above JavaScript functions are tested in the following Browsers

1. Internet Explorer 7

2. Mozilla Firefox 3

3. Google Chrome





http://www.aspsnippets.com/post/2009/03/13/Using-JavaScript-with-ASPNet-GridView-Control.aspx

difference between gridview,data list and repeater control

Explanation:
In ASP .NET basically there are three kinds of the Data
Presentation Controls.


GridView (or DataGrid)
DataList
Repeater


When we talk about usage of one Data Presentation Controls
then many of us get confused about choosing one. When you
need to use one of the data Presentation Control then You
have to see what kind of behavior you need in your Data
Display.


Do you want to show Data in many Pages or in one page?
Do you have to Display more then one column in a Row ?

Do you want to have a Row repeating Possibility?

Will users be able to update, Insert and delete the Data?

We are going provide a list of different abilities of
Repeater Control, Datalist Control and GridView Control.



Features of a GridView
•Displays data as a table
•Control over
–Alternate item
–Header
–Footer
–Colors, font, borders, etc.
–Paging
•Updateable
•Item as row

Features of Repeater
•List format
•No default output
•More control
•More complexity
•Item as row
•Not updateable


Features of DataList
•Directional rendering
•Good for columns
•Item as cell
•Alternate item
•Updateable

Repeater :

It contains Header Template, Item template , alternate
Item template and footer template . it can't support
Selection, editing, sorting and paging. this is read only
and fast.


Datalist :

It contains Header Template, Item template , alternate
Item template , Edit itm template and footer template . it
can't support sorting and paging but support selection and
editing


DataGrid(or GridView) :

It contains Header Template, Item template , alternate Item
template , Edit itm template and footer template . it can
support selection, editing , sorting and paging . Mostly
every developer caught used this control .

Nesting the DropDownList to Gridview in ASP.NET 2.0(C#)

To nest the DropDownList control to GridView control is very helpful to show the data by selectable criteria. The DropDownList control can be easily nested to the GridView control. In this sample, each DropDownList is binded for different data. For instance, we can use GridView to show each category data in Northwind database, while we can use DropDownList to show all products under the selected category in each line. We will show you this tutorial by ASP.NET 2.0 and C#.

To nest the DropDownList control to GridView control is very helpful to show the data by selectable criteria. The DropDownList control can be easily nested to the GridView control. In this sample, each DropDownList is binded for different content. For instance, we can use GridView to show each category data in northwind database, and we can use DropDownList to show all products under the selected category in each line.

First, to connect to the sample database, you will need to import the System.Data.SqlClient namespace.

The front GridviewNestingDropdowlist.aspx page looks something like this:

GridviewNestingDropdowlist















The flow for the code behind page is as follows.
using System; using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class GridviewNestingDropdowlist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gridview1.DataSource = getdataset().Tables[0];
gridview1.DataBind();
}

private DataSet getdataset()
{
string connectionstring = "Data Source=localhost;Initial Catalog=northwind;User ID=sa;password=";
string query = "select p.categoryid,p.productid, p.productname,c.categoryid,c.categoryname from products p,categories c where p.categoryid=c.categoryid and c.categoryid<3";
SqlConnection myconnection = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(query, myconnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

protected void gridview1_rowdatabound(object sender, GridViewRowEventArgs e)
{
DataTable mytable = new DataTable();
DataColumn productidcolumn = new DataColumn("productid");
DataColumn productnamecolumn = new DataColumn("productname");

mytable.Columns.Add(productidcolumn);
mytable.Columns.Add(productnamecolumn);

DataSet ds = new DataSet();
ds = getdataset();
int categoryid = 0;
string expression = string.Empty;

if (e.Row.RowType == DataControlRowType.DataRow)
{
categoryid = Int32.Parse(e.Row.Cells[0].Text);
expression = "categoryid = " + categoryid;
DropDownList ddl = (DropDownList)e.Row.FindControl("dropdownlist1");
DataRow[] rows = ds.Tables[0].Select(expression);

foreach (DataRow row in rows)
{
DataRow newrow = mytable.NewRow();
newrow["productid"] = row["productid"];
newrow["productname"] = row["productname"];
mytable.Rows.Add(newrow);
}
ddl.DataSource = mytable;
ddl.DataTextField = "productname";
ddl.DataValueField = "productid";
ddl.DataBind();
}
}
}

Change background color of GridView's Rows


...



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// searching through the rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
bool isnew = (bool)DataBinder.Eval(e.Row.DataItem, "IsNew");
if ( isnew ) e.Row.BackColor = Color.FromName("#FAF7DA"); // is a "new" row
}
}

Difference between BoundField and TemplateField?

Bound field

By using bound field we can bind the data directly by using header text and datafield with out using any controls.

Headertext : we can specify header for the data

Datafield : Its the field which gets the data from dataset.

Example : if we specify a field name in datafield it searches in dataset with the same column name and binds the data.

we can define our own asp controls in bound field column only thing we can do is only binding the data.

Template field

We can define our own asp controls in template field.

and we can bind the data from dataset to template field columns directly.

Row Command Firing twice in GridView Control

I am using a GridView control with a ButtonField and receiving 2 row command
events for each click of the button. Is there a configuration switch that I
can turn that will ensure I only receive one call to my handler? I'm using
the most basic wiring as it comes out of VS 2005.. Thanks in advance for your
help!

ex/

<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default2.aspx.cs" Inherits="Default2" %>





Untitled Page









SelectCommand="SELECT [EventId], [EventStartDate],
[EventEndDate], [EventDescription], [EventTypeId], [EventHours],
[EventEmployeeId], [EventCreatorId], [EventCreationDate],
[EventLastModifierId], [EventLastModifiedDate], [EventApproved],
[EventApproverId], [EventApprovedDate] FROM [Events]">





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


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{


}
}
protected void ApprovalGrid_RowCommand(object sender,
GridViewCommandEventArgs e)
{
// Get the index of the clicked row
int rowindex = Convert.ToInt32(e.CommandArgument);

switch (e.CommandName)
{
case "ApproveEvent":

break;
case "EditEvent":

break;
}
}
}

--

Exporting GridView to Excel

I will show how you can export data from a GridView control to a Microsoft Excel spreadsheet.

Default.aspx








Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}

private void BindData()
{
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}


private string ConnectionString
{
get { return @"Server=localhost;Database=NorthWind;Trusted_Connection=true"; }

}
protected void BtnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";

// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}



doubts:Connect To This Link:http://aspalliance.com/771_CodeSnip_Exporting_GridView_to_Excel




http://www.nateirwin.net/2007/04/16/formatting-gridview-control-and-exporting-to-excel/

Dynamically Add new row for Grid View Control























private void BindData()

{

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM tblPerson", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "tblPerson");

GridView1.DataSource = ds;

GridView1.DataBind();

}

Catching the Event Generated by Button Click in the Footer:

As you have already noticed that there is also a Button control inside the Footer of the GridView control. We can easily catch the events and access the TextBox which resides in the Footer.

GridView RowCommand event is generated when ever any event occurs inside the GridView control. This is the best place to catch the Button click event.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

// We are checking against the "ADD"

if (e.CommandName == "ADD")

{

string name = ((TextBox) GridView1.FooterRow.FindControl("txtName")).Text;

AddNewRecord(name);

}

}

Now that we have got the text in the string variable we are ready to insert the new data. The new data is inserted by a small method named AddNewRecord(string name).
private void AddNewRecord(string name)

{

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

SqlConnection myConnection = new SqlConnection(connectionString);

string query = @"INSERT INTO tblPerson(Name) VALUES(@Name)";

SqlCommand myCommand = new SqlCommand(query, myConnection);

myCommand.Parameters.AddWithValue("@Name", name);

myConnection.Open();

myCommand.ExecuteNonQuery();

myConnection.Close();

BindData();

}