Tuesday, November 11, 2008

at 4:12 AM Posted by senthil

OOPS:

1) What is OOPs?

OOPs - Object Oriented Programming Languages & Systems
Everything in the world is an object. The type of the object may vary. In OOPS, we get the power to create objects of our own, as & when required. OOPs is a programming methodology where each entity is an object.
It is a method of computer programming where entities of related data together with routines associated with it are treated as one object in the program.

2) What is a class? What is a Base Class?

A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).

It is important to note that a class is a Reference Type. To know about Reference Types, Click Here

A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.

3) What is Encapsulation?

Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.

Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.

Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);

4) What is inheritance?

Inheritance - is the concept of passing the traits of a class to another class.

A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)

Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon. (Reference)

5) What is a class member? What is an object?

The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.

When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object.

6) What is polymorphism?

Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.

The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.

Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.

Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading

7) What is a property? What is an event?

Property - A property is a thing that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at this definition, we might think we could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the real technical term for a public variable in a class is a field. The main difference between a field and a property is in the inclusion of an interface.

We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set.ss="a">

Private _Color As String
Public Property Color()
Get
Return _Color
End Get
Set(ByVal Value)
_Color = Value
End Set
End Property

Event - An action that an object does. When something happens, we say an event has happened. For example, when a button is clicked, we say it is the click( ) event. When a mouse hovers on an image, we say the mouseover( ) event has taken place.

8) What is an access modifier? What are the different types of Access modifiers?

Access Modifiers - Keywords used to change the way members of a class are accessed. The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.

9) What is Overloading? What is Overloads? What is Overload?

Overloading - is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.

The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.

Overloading is a way through which polymorphism is achieved.

10) What is shared keyword used for? What is static?

Shared and Static mean the same. Shared is used in VB.NET, while Static is used in C#.

11) What is the virtual keyword used for?

Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.

When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.

public class Employee
{
public virtual void SetBasic(float money) //This method may be overriden
{ Basic += money; }
}


public class Manager : Employee
{
public override void SetBasic(float money) //This method is being overriden
{
float managerIncentive = 10000;
base.SetSalary(money + managerIncentive); //Calling base class method
}
}

12) Explain overridable, overrides, notoverridable,mustoverride

These keywords are used in VB.NET.

Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.

Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.

NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.

MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.

13) What is shadowing? Explain shadows keyword

Shadowing - is a concept of altering the behavior of a base class member.

14) What is a constructor? Explain the New Keyword. What is a Private Constructor?

Constructor - A constructor is a function with the same name as that of the class. The Default Constructor of a class is without an argument. The default constructor ensures that every member data is initialized to a default value. Constructors provide a way for classes to initialize a state for their members. Note that constructors dont have a return type(not even void).

public SomeClass()
{
Console.Writeline("Vishal says, Default Constructor is called");
}
\
public SomeClass(string str)
{
Console.Writeline("Vishal says, Custom Constructor is called" + str);
}

When a custom constructor is defined, the Default Constructor is not called. A constructor may also be overloaded.

New - This keyword may be used as a modifier and as an operator. When used as an operator, it creates an object on a heap to invoke constructors. When used an a modifier, it hides an inherited member from the base class member.

As an operator, it can be used to create an object and then to invoke the constructor of the class. See example below.

Example
SomeClass objSomeClass = new SomeClass(); //Creating a class object and invoking its constructor

float amount = new float(); //Creating an object of the type, and invoking its constructor

As a modifier, it is used to explicitly hide a member from the base class. See example.

Example
public class MamaClass
{
public void SomeMethod() { ... }
}

public class BabyClass : MamaClass
{
new public void SomeMethod() { .... }
}

Private Constructor - When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. It is also used to create Singleton classes.

15) What is a static constructor?

Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.

Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}

While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

Can a class be created without a constructor?
No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.

16) What is Serialization? What is serializable attribute used for?

Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter

The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.

SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.

You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.

Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...

Imports System.IOImports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()

Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…

Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( " " & strItem )
Next

Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.
XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.
Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.

17) What is a delegate? What is a Multicast Delegate?

Delegate - It is a type safe function pointer. It is a type that holds the reference of a method. A delegate may be used to call a method asynchronously.
Multicast Delegate - it is a delegate that holds reference of more than one method. Multicast Delegates must have a return type of void.

18) What is an abstract class?

If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated.

19) What is an interface? How to implement an interface?

An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used.
An interface is implemented using implements keyword. A class may implement more than one keyword.
When a class inherits and implements at the same time, the inherited parent class name is written first, followed by the names of the interfaces to be implemented

20) Is multiple inheritance possible in .NET?

No. Multiple inheritance is not possible in .NET. This means it is not possible for one class to inherit from multiple classes. However, a class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.

ASP.NET 2.0

1) Can we bind data to a server control without writing code in .NET?

Yes, that is possible. ASP.NET 2.0 has the feature of declarative solution for data binding which requires no code at all for the most common data scenarios, such as:
* Selecting and displaying
* Data Sorting
* Paging and Caching
* Data Updating
* Inserting and Deleting Data

2) How to use Masterpages and Contentpages in ASP.NET 2.0? What is a Masterpage? What is a ContentPage? How to setup master-content pages in ASP.NET 2.0?

A Master Page is the mother of the page and the content page is the baby! There may be many babies of the mother. A master page may have plenty of content pages within it. There also may be a master page within a master page, which is called a nested master page. Nested Master Pages

So whats a master page in ASP.NET 2.0? A Master Page is a page that contains markup and controls that are shared across multiple pages in your site. For example, if required that all pages should have the same header and footer banners or the common navigation menu, the Master page can be written once, and all the content pages can access the common master page. The content pages inherit the tags inside the master page.

Next question is how to define a master page. The answer is...

To define a Master Page, it may be written like a normal page. Master Pages can contain markup, controls, or code, or any combination of these tags. The Content pages are rendered in a master page control called as ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be exchanged with content from a page associated to the master. A ContentPlaceHolder can also contain default content, when in case the derive page does not need to override this content. Below is the markup of how to use a Contentplaceholder.




Welcome to the .NET Interview Questions website!


A master page has the extension .master, unlike a normal web form that has the extenstion .aspx. A page may derive from a Master Page by defining a MasterPageFile attribute on its Page directive. Below is the markup of a content page.

<%@ Page MasterPageFile="Masterpage.master" %>

Here goes contents of ContentPlaceHolderInterviewQuestions

So how does Content page access a master page? It is also possible for a Content Page to programmatically access a Master Page. A ContentPage may create a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, which specifies the virtual path to the masterpage as below...

<%@ MasterType VirtualPath="Masterpage.master" %>

The Content Page may then reference the Master Page using the Master property of the Page class:

Master.FooterText = "Some text on the footer of .NET Interview Questions page";
Label lb1 = Master.FindControl("label2");

As with the example above, FooterText is a public property exposed on the Master Page, whereas label2 is a server side control on the Master Page.

Note that the FindControl method is a very useful and a very important method, that may be used for finding a control in a content page from a master page and vice versa.

3) What is a nested Masterpage in ASP.NET 2.0? Can there be a master page inside a masterpage?

When a master page is placed inside the contentplaceholder of a masterpage, then the masterpage is said to be nested. In other words, there is one parent masterpage, and the child masterpage is inside the contentplaceholder of the parent masterpage.

Yes, we can have multiple number of Master pages in an ASP.NET 2.0 web application.

4) What is a SiteMapPath control in ASP.NET 2.0?

An asp:SiteMapPath control is a Navigation Control that comes along with the ASP.NET 2.0 framework. The sitemappath control consists site link's data in XML format. The emergence of the Sitemappath control in ASP.NET 2.0 has totally eliminated the clumsy code used in bread crumbs by veteran web developers in Classic ASP and ASP.NET 1.1. These bread crumbs were comparatively tougher to maintain.

Now say you need to maintain a Sitemap of a Site having the following links...

Home Products Medicines Soaps Alcohol Support Phone Support Email Support Contact Us

Instead of hard coding these links inside your code, all this information may be maintained in an XML based Web.sitemap file which can be bind to an asp:SiteMapPath control, and this would display like a website breadcrumb. Easier than before!

The SiteMapPath control's SiteMapProvider property is used to set the site's sitemap provider. This sitemap provider is another control called asp:XmlDataSource control. This needs to be registered in the web.config file. If the SiteMapProvider property is not specified, then the default SiteMap Provider information is picked up from the web.config file.

Note:The other two navigation controls in ASP.NET 2 are the Menu control and the TreeView control.

The XmlDataSource control loads an XML file that is specified using the DataFile property. This control inherits from the HierarchicalDataSourceControl class.

Example XML below:




If DataFile is not used in the XmlDataSource, the siteMapFile property can be set in the web.config.
In order to specify XML Data Source in web.config, see below:











5) How to sort the contents of a GridView control?

The ASP.NET 2.0 GridView control is a powerful control, the enables sorting of the rows based on a column, all this possible, without writing code. Well thats what we call power!

The GridView control relies on the underlying data source control to whom this is bound for the sorting capability. The GridView needs to have an AccessDataSource or an SQlDataSource or an ObjectDataSource (if the SortParameterName property is set to a value allowed.

The AllowSorting property of the GridView control, when set to true, enables sorting of the GridView. A sortable GridView has the Header column represented as a LinkButton control. When this Link Button is clicked, the Sorting event of the GridView is raised server-side, which causes a postback and in turn, sorts the GridView control's records.

6) What does the Hotspot class in .NET do? What is an ImageMap in ASP.NET?

An ImageMap is an ASP.NET control that allows clicks inside a polygon like (called Hotspot) region in a webpage. Well, that actually means you may create a star-shaped or diamond shaped button. Wow!

There are several pre-defined shapes allowed inside an ImageMap for which templates may be used. For example, for a rectangle, an asp:RectangularHotSpot may be used. For a circle, an asp:CircleHotSpot may be used. And for creating stars & diamonds, an asp:PolygonHotSpot may be used. An image may also be put in an ImageMap which may be specified by its ImageUrl property.

In order to invoke an event, the HotSpotMode property needs to be set to PostBack. Further, if several HotSpots are placed inside an ImageMap, the event of the ImageMap may be passed a value using the PostBackValue property.

Code below shows how to create a Polygon HotSpot using an ImageMap.

ImageUrl="Photo.gif" OnClick="SomeEvent"
AlternateText="Click Here"
HotSpotMode="Navigate">

AlternateText="Click Here Too!"
Coordinates="100,150, 250,350, 210,290, 90,350, 60,240"
NavigateUrl="http://www.asp.net"
Target="_blank"/>

7) How do we update and delete data in a gridview? Datakeynames property in .NET?

The best way to Update or Delete a record in a GridView control is to include a CheckBox column and a Submit Button.

The GridView has its own Delete and Edit functionality. If the GridView is populated with data using an SqlDataSource, checkout the wizard that comes along with the SqlDataSource. It may be used to automatically create an SQL Delete command and specify the delete parameters.

The DataKeyNames property of the GridView is set to a field name of the Table.

Follow these links for a detailed understanding of the various ways a GridView record may be updated & deleted.
AspAlliance
EggHeadCafe
ASP.NET QuickStart
MSDN
CodeProject

SqlConnection (.NET)

Standard Security:

"Data Source=UrServerName;
Initial Catalog=pubs;
User Id=myUsername;
Password=myPassword;"

OR

"Server=UrServerName;
Database=pubs;
User ID=myUsername;
Password=myPassword;
Trusted_Connection=False"

Trusted Connection:

"Data Source=UrServerName;
Initial Catalog=pubs;
Integrated Security=SSPI;"

OR

"Server=UrServerName;
Database=pubs;
Trusted_Connection=True;"

(Note: use serverName\instanceName as Data Source to use
an specifik SQLServer instance)

Connect via an IP address:

"Data Source=190.190.200.100,1433;
Network Library=DBMSSOCN;
Initial Catalog=pubs;
User ID=myUsername;
Password=myPassword;"

(Note: DBMSSOCN=TCP/IP instead of Named Pipes,
at the end of the Data Source is the port to use (1433
is the default))

Enabling MARS (multiple active result sets):

"Server=UrServerName;
Database=pubs;
Trusted_Connection=True;
MultipleActiveResultSets=true"

Note- Use ADO.NET 2.0 for MARS functionality. MARS is not
supported in ADO.NET 1.0 nor ADO.NET 1.1


Attach a database file on connect to a local SQL Server
Express instance:

"Server=.\SQLExpress;
AttachDbFilename=c:\asd\qwe\mydbfile.mdf;
Database=dbname;
Trusted_Connection=Yes;"

OR

"Server=.\SQLExpress;
AttachDbFilename=|DataDirectory|mydbfile.mdf;
Database=dbname;
Trusted_Connection=Yes;"

(Note: use |DataDirectory| when your database file resides
in the data directory)


Using "User Instance" on a local SQL Server Express
instance:

"Data Source=.\SQLExpress;
integrated security=true;
attachdbfilename=|DataDirectory|\mydb.mdf;user instance=true;"

Note: The "User Instance" functionality creates a new SQL
Server instance on the fly during connect. This works
only on a local SQL
Server 2005 instance and only when connecting using windows
authentication over local named pipes. The purpose is to
be able to create a full rights SQL Server instance to
a user with limited administrative rights on the computer.

To enable the functionality: sp_configure
'user instances enabled','1' (0 to disable)
Using SQL Server 2005 Express? Don't miss the server name
syntax: SERVERNAME\SQLEXPRESS (Substitute "SERVERNAME" with the name of the computer)

0 comments: