You are on page 1of 46

1.Does C# support multiple-inheritance?

Ans. No! It may be achieved however, using interfaces.

2.Who is a protected class-level variable available to?


Ans.It is available to any sub-class (a class inheriting
this class).

3.Are private class-level variables inherited?


Ans. Yes, but they are not accessible. Although
they are not visible or accessible via the class
interface, they are inherited.

4.Describe the accessibility modifier “protected


internal”.
Ans. It is available to classes that are within
the same assembly and derived from the specified base class.

5.What’s the top .NET class that everything is derived from?


Ans.System.Object.

6.What does the term immutable mean?


Ans.The data value may not be changed.
Note: The variable value may be changed, but
the original immutable data value was discarded and
a new data value was created in memory.

7.What’s the difference between System.String


and System.Text.StringBuilder classes?
Ans.System.String is immutable. System.StringBuilder
was designed with the purpose of having a mutable
string where a variety of operations can be performed.

8.What’s the advantage of using System.Text.StringBuilder


over System.String?
Ans.StringBuilder is more efficient in cases where
there is a large amount of string manipulation.
Strings are immutable, so each time a string is
changed, a new instance in memory is created.

9.Can you store multiple data types in System.Array?


Ans.No.

10.What’s the difference between the


System.Array.CopyTo() and System.Array.Clone()?
Ans.The Clone() method returns a new array
(a shallow copy) object containing all the elements
in the original array. The CopyTo() method copies
the elements into another existing array. Both perform
a shallow copy. A shallow copy means the contents
(each array element) contains references to the same
object as the elements in the original array. A deep
copy (which neither of these methods performs) would
create a new instance of each element's object,
resulting in a different, yet identacle object.

11.How can you sort the elements of the array in


descending order?
Ans.By calling Sort() and then Reverse() methods.

12.What’s the .NET collection class that allows an


element to be accessed using a unique key?
Ans.HashTable.

13.What class is underneath the SortedList class?


Ans.A sorted HashTable.

14.Will the finally block get executed if an


exception has not occurred?¬
Ans.Yes.

15.What’s the C# syntax to catch any possible


exception?
Ans.A catch block that catches the exception of
type System.Exception. You can also omit the
parameter data type in this case and just write
catch {}.

16.Can multiple catch blocks be executed for a


single try statement?
Ans.No. Once the proper catch block processed,
control is transferred to the finally block (if
there are any).

17.Explain the three services model commonly know


as a three-tier application.
Ans.Presentation (UI), Business (logic and underlying
code) and Data (from storage or other sources)
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.

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

Using inhertance, we may assign different traits to different


classes. Yet, the child classes will inherit some common
traits from the base class. As in the figure above, the
classes for "Permanent" and "Wage Worker" will inherit
some common traits from the class of "Employee".

A class may contain class members like fields, properties,


events & methods with different types of access modifiers
like private, public, protected or friend, to process the
way they are accessed. In VB.NET, a class may be declared
as below...

Public Class SampleClass


'define class members
End Class

Key Concepts of .NET - To work with classes and modules,


the key concepts to know are definition, access, inheritance,
constructors, destructors, delegates, abstract classes & interfaces..

Class members - The different types of entities in a class,


like fields, properties, events & methods.
Object - An object is an instance of a class. This instance
may be used to access the members of the class. It is pretty
easy to define an object. See sample code below...

Dim objSampleObject as SampleClass

Structure - It is a bit similar to a class. Semantically,


structures are known as value types, while classes as reference types. We do'nt instantiate an
object using the New keyword while working with a structure. We can not inherit from a
structure.

Public Structure Student


Public RollNo as Integer
Public Name as String
End Structure

Dim objStud as Student


objStud.RollNo=31
objStud.Name="Monu"

Here, note that the object objStud is not exactly an instance,


it is a simple object (object of a structure) that is used to
access the members of this structure. It would have behaved
differently had it been an object of a class, as it would have
invoked the constructor associated with the class.

Public Class ClassCalc


Public Function FnAdd(ByVal dblA as double, ByVal dblB _

as double) as Double
FnAdd = dblA + dblB
End Function
End Class

Now, lets make use of the method FnAdd defined in the class
above. To use it, first create an object of this class, say
objX. Using this object, we can invoke the methods of this
class. See code below...

Dim objX as ClassCalc


Dim dblResult as Double
dblResult = objX.FnAdd(4.56,2.35)

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 that
definition, you might think you could declare a public variable in a class and call it a property.
While this assumption is somewhat valid, the true technical term for a public variable in a class
is a field. The key 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.

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.

Access Modifiers - Keywords used to vary the way members of a class are used. Following are
different types...

1) Public - These classes can be used anywhere in the code.


There are no restrictions.

Available only to code outside our class

2) Private - These classes are accessible only within their


declaration contexts. This includes nested procedures. When a variable is declared Public inside
a Private class, it is
accessible only from inside that class.

Available only to code inside our class

3) Protected - These classes extend the accessibility of their


members to their child classes (means, to the classes that derive from them). They extend their
members to both themselves & their child classes.

Available only to classes that inherit from our class

4) Friend - Friend access means that elements are accessible only within the program. Friend is
the default access modifer for any class that does not have a modifier.
Available only to code within our project/component

5) Protected Friend - Available only to classes that inherit from our class (in any project) or to
code within our project/component. This is a combination of Protected and Friend.

Default - A Default property is a single property of a class that can be set as the default. This
allows developers that use your class to work more easily with your default property because
they do not need to make a direct reference to the property. Default properties cannot be
initialized as Shared or Private and all must be accepted at least on argument or parameter.
Default properties do not promote good code readability, so use this option sparingly.

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

Shared -The Shared keyword is used in an inherited or base class to define a property or method
as being shared among all instances of a given class. If multiple instances of a class with shared
properties or methods are loaded, the shared properties or methods will provide the same data
across each instance of the class. When one class alters the value for a shared property, all
instances of that class will reflect the change. Shared properties of all instances of the class
point to the same memory location.

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.

Shadows - The Shadows keyword will effectively hide all of the other methods in the baseclass.
It is like forcefully getting rid of the overloading that has been done on the methods of the base
class.
The Shadows keyword works like the Overloads keyword except that with shadows we do not
have to follow rules such as implementing the same signature. The Shadows keyword does not
require the consent (override ability) of the inherited class to replace the property or method's
implementation code. A method does not have to be defined as overridable for the Shadows
keyword to work. Read the example...
'This is the Base Class
Public Class Parent
Public Sub MyProc(ByVal num As Integer)
MsgBox("Number in Parent is " & num)
End Sub

Public Sub MyProc(ByVal st As String)


MsgBox("String in Parent is " & st)
End Sub
End Class

'This is the Child Class


Public Class Child
Inherits Parent
Overloads Sub MyProc(ByVal num As Integer)
'overloads the method with the same parameter list
MsgBox("Number in Child is " & num)
End Sub

Overloads Sub MyProc(ByVal ch As Char)


' overloads the method
MsgBox("Character in Child is " & ch)
End Sub
End Class

When we execute the following code...


Dim c As New Child()

' prints out "String in Parent is Hello Wazzup!"


c.MyProc("Hello Wazzup!")

' prints out "Number in Child is 12"


c.MyProc(12)

' prints out "Character in DerivedClass is B"


c.MyProc(Chr(66))

When we use Shadows keyword...


Public Class ChildNumber2
Inherits Parent
Shadows Sub MyProc(ByVal num As Integer)
' hides all the different argument list
MsgBox("Number in ChildNumber2 is " & num)
End Sub
End Class
Dim c2 As New DerivedClass2()
c2.MyProc(7) 'only one method is exposed, rest of the
'methods are hidden

Constructor - When a class instance is created in our code,


a special method of that class, called the constructor, is called. Similarly, when the class is
destroyed, the destructor
method is called. These are general terms and usually not the actual member names in most
object-oriented languages. It is initialized using the keyword New, and is destroyed using the
keyword Finalize. In .NET, we tend to forget using Finalize as
the instances(means the object) are automatically destroyed by the Garbage Collecter, when the
object is not in use by he CLR(Common Language Runtime).

Dim objSampleObject as New SampleClass


' write the code here...
objsampleobject.Finalize

We can add parameters to the constructors. This was'nt allowed in VB6. We can overload the
constructors, change the order of parameters, datatypes of parameters which ultimately change
the way the constructor works whenever an instance of that class is invoked.

Also note that a constructor can have any access modifier. If


no argument is added in a constructor, VB.NET adds a no-argument constructor during compile
time. It adds the Public Sub New( ) with the class declared, if no argument is passed in the
constructor. The following code is added...

Public Class ClassA


Public Sub New( )
End Sub

However, when the constructor is added with parameters, the following code is generated...

Public Class ClassA


Public Sub New(ByVal SomeString as String )
End Sub

When a child class' object is declared, the child class


constructor & its parent class constructor, both are invoked.
Read example below for more clarity...

Public Class Books


Public Sub New()
System.Console.WriteLine("Book's constructor.")
End Sub
Public Sub myProc()
System.Console.WriteLine("This is a book.")
End Sub
End Class

Public Class Authors : Inherits Books


Public Sub New()
System.Console.WriteLine("Author's constructor.")
End Sub
End Class

When the Authors class' constructor is invoked, like in the


following code, the Books class' no-argument constructor is also called.

Dim author As Authors


author = New Authors()

The result on the console will be...

Book's constructor.
Author's constructor.

If the base class does'nt have a no-argument constructor, then it would result in a compiler error.
Hence, we need to use the MyBase keyword with the constructor. Our child class will look like
this...

Public Class Authors : Inherits Books


Public Sub New(ByVal SomeString As String)
MyBase.New(SomeString)
System.Console.WriteLine("Authors's constructor.")
End Sub
End Class

If a class is not inheriting from any base class, then it will


call the base class constructor of System.Object if we are using MyBase.New( ). Summarizing
constructors, whenever we initiate a constructor, the following things happen...

Base class constructor is invoked.


Class level variables are initialized.
Code in the class constructor gets executed.
If the argument name passed in the constructor, is same as the variable name used in the
constructor, we use the Me keyword to refer to the constructor variable. For example if the
variable name is SomeString, and the parameter passed is also SomeString, then the variable is
referred as Me.SomeString.
Abstract Class - They are classes that cannot be instantiated. We cannot create an object from
such a class for use in our program. We can use an abstract class as a base class, creating new
classes that will inherit from it. Creating an abstract class with a certain minimum required level
of functionality gives us a defined starting point from which we can derive non-abstract classes.

An abstract class may contain abstract methods & non-abstract methods. When a class is derived
from an abstract class, the derived class must implement all the abstract methods declared in the
base class. We may use accessibility modifiers in an abstract class (unlike in Interfaces).

An abstract class can inherit from a non-abstract class. In C++, this concept is known as pure
virtual method.

Interface - its a kind of class, that has only methods, do not have code, just the definition of the
methods. Also, the interface can't be instantiated. Its an abstract class with public abstract
methods, all of which must be implemented in the inherited classes. All methods in an interface
are public, no other access modifier is used. It is public by default.

Classes can contain code, but interface dont. However, classes that implement an interface do
contain code. Keep in mind that there are no instances of interfaces in VB .NET. Every instance
is a type that implements an interface, but is itself not an instance of the interface. Also note, in
an interface, all methods must be abstract (which is not necessary in an abstract class).

'VB .NET Interface


Public Interface ISalary
Sub CreditSalary(ByVal Amount As Decimal)
ReadOnly Property Incentive() As Decimal
ReadOnly Property Attendance() As Integer
End Interface

To use members of an interface, we make use of the implements keyword.

Public Class Employee


Implements ISalary
Public Function Salary() As Decimal Implements ISalary.CreditSalary()
'code here ...
End Function
End Class

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.

Boxing & Unboxing - Value Types are stored on the stack and Reference types are stored on the
heap. The conversion of value type to reference type is known as Boxing. Converting reference
type back to value type
is known as Unboxing.

Value Types - Value types are primitive types that are mapped directly to the FCL. Like Int32
maps to System.Int32, double maps to System.double.
All value types are stored on stack and all the value types are derived from System.ValueType.
All structures and enumerated types that are derived from System.ValueType are created on
stack, hence known as ValueType.

Reference Types - Reference Types are different from value types in such a way that memory is
allocated to them from the heap. All the classes are of reference type. C# new operator returns
the memory address of the
object.

Partial Class - This concept has been introduced in .NET framework 2.0. They give you the
ability to split a single class into more than one source code (.cs or .vb) file. Here's what a partial
class looks like when it's split over two files...

// Stored in file MyClass1.cs


public partial class MyClass
{
public MethodA()
{...}
}

// Stored in file MyClass2.cs


public partial class MyClass
{
public MethodB()
{...}
}

When you build the application, Visual Studio .NET tracks down each piece of MyClass and
assembles it into a complete, compiled class with two methods, MethodA() and MethodB().

Partial classes don't offer much in the way of solving programming problems, but they can be
useful if you have extremely large, unwieldy classes. (Of course, this might be a sign that you
haven't properly factored your problem, in which case you should really break your class down
into separate classes.) The real purpose of partial classes in .NET is to hide automatically
generated designer code.
XML Documentation Questions
1.Is XML case-sensitive?
Ans. Yes.

2.What’s the difference between // comments,


/* */ comments and /// comments?
Ans. Single-line comments, multi-line comments,
and XML documentation comments.

3.How do you generate documentation from the C#


file commented properly with a command-line compiler?
Ans. Compile it with the /doc switch.

Debugging and Testing Questions


1.What debugging tools come with the .NET SDK?
Ans.
1. CorDBG – command-line debugger. To use
CorDbg, you must compile the original C# file
using the /debug switch.

2. DbgCLR – graphic debugger. Visual Studio


.NET uses the DbgCLR.

2.What does assert() method do?


Ans. In debug compilation, assert takes in a Boolean
condition as a parameter, and shows the error
dialog if the condition is false. The program proceeds
without any interruption if the condition is true.

3.What’s the difference between the Debug class


and Trace class?
Ans. Documentation looks the same. Use Debug class for
debug builds, use Trace class for both debug and release
builds.

4.Why are there five tracing levels in System.Diagnostics.TraceSwitcher?


Ans. The tracing dumps can be quite verbose. For
applications that are constantly running you run the
risk of overloading the machine and the hard drive.
Five levels range from None to Verbose, allowing you to
fine-tune the tracing activities.

5.Where is the output of TextWriterTraceListener


redirected?
Ans. To the Console or a text file depending on
the parameter passed to the constructor.
6.How do you debug an ASP.NET Web application?
Ans. Attach the aspnet_wp.exe process to the
DbgClr debugger.

7.What are three test cases you should go through


in unit testing?
Ans.
1. Positive test cases (correct data, correct
output).
2. Negative test cases (broken or missing data,
proper handling).
3. Exception test cases (exceptions are thrown
and caught properly).

8.Can you change the value of a variable while debugging


a C# application?
Ans. Yes. If you are debugging via Visual Studio.NET,
just go to Immediate window.

ADO.NET and Database Questions


1. What is the role of the DataReader class in
ADO.NET connections?
Ans. It returns a read-only, forward-only rowset from
the data source. A DataReader provides fast access
when a forward-only sequential read is needed.

2.What are advantages and disadvantages of Microsoft


provided data provider classes in ADO.NET?
Ans. SQLServer.NET data provider is high-speed and
robust, but requires SQL Server license purchased from
Microsoft.

OLE-DB.NET is universal for accessing other sources,


like Oracle, DB2, Microsoft Access and Informix.
OLE-DB.NET is a .NET layer on top of the OLE layer, so
it’s not as fastest and efficient as SqlServer.NET.

3.What is the wildcard character in SQL?


Ans. Let’s say you want to query database with LIKE for
all employees whose name starts with La. The wildcard
character is %, the proper query with LIKE would
involve ‘La%’.

4.Explain ACID rule of thumb for transactions.


Ans.
A transaction must be:
1.Atomic - it is one unit of work and does not dependent
on previous and following transactions.
2.Consistent - data is either committed or roll back, no
“in-between” case where something has been updated and
something hasn’t.
3.Isolated - no transaction sees the intermediate results
of the current transaction).
4.Durable - the values persist if the data had been
committed even if the system crashes right after.

5.What connections does Microsoft SQL Server support?


Ans. Windows Authentication (via Active Directory) and
SQL Server authentication (via Microsoft SQL Server
username and password).

6.Between Windows Authentication and SQL Server


Authentication, which one is trusted and which one is
untrusted?
Ans. Windows Authentication is trusted because the
username and password are checked with the Active
Directory, the SQL Server authentication is untrusted,
since SQL Server is the only verifier participating in the
transaction.

7.What does the Initial Catalog parameter define in the


connection string?
Ans. The database name to connect to.

8.What does the Dispose method do with the connection


object?
Ans. Deletes it from the memory.
To Do: answer better. The current answer is not entirely
correct.

9.What is a pre-requisite for connection pooling?


Ans. Multiple processes must agree that they will share
the same connection, where every parameter is the same,
including the security settings. The connection string
must be identical.

Assembly Questions
1.How is the DLL Hell problem solved in .NET?
Ans. Assembly versioning allows the application to specify
not only the library it needs to run (which was available
under Win32), but also the version of the assembly.
2.What are the ways to deploy an assembly?
Ans. An MSI installer, a CAB archive, and XCOPY command.

3.What is a satellite assembly?


Ans. When you write a multilingual or multi-cultural
application in .NET, and want to distribute the core
application separately from the localized modules, the
localized assemblies that modify the core application
are called satellite assemblies.

4.What namespaces are necessary to create a localized


application?
Ans.System.Globalization and System.Resources.

5.What is the smallest unit of execution in .NET?


Ans. an Assembly.

6.When should you call the garbage collector in .NET?


Ans. As a good rule, you should not call the garbage
collector. However, you could call the garbage collector
when you are done using a large object (or set of objects)
to force the garbage collector to dispose of those very
large objects from memory. However, this is usually not a
good practice.

7.How do you convert a value-type to a reference-type?


Ans. Use Boxing.

8.What happens in memory when you Box and Unbox a


value-type?
Ans. Boxing converts a value-type to a reference-type, thus
storing the object on the heap. Unboxing converts a

reference-type to a value-type, thus storing the value on


the stack.

Questions...

1. What is the difference between a Struct and a Class?


Ans.Structs are value-type variables and are thus saved
on the stack -> additional overhead but faster retrieval. Another difference is that structs
CANNOT inherit. Classes are reference types and structs are value types. Since classes are
reference type, a class variable can be assigned null.But we cannot assign null to a struct
variable, since structs are value type.

struct AStruct
{
int aField;
}

class AClass
{
int aField;
}

class MainClass
{
public static void Main()
{
AClass b = null; // No error.
AStruct s = null; // Error
/* [ Cannot convert null to 'AStruct' because it is
a value type ].*/
}
}

When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it
gets created on the stack. You will always be dealing with reference to an
object ( instance ) of a class. But you will not be dealing
with references to an instance of a struct ( but dealing directly with them ).

When passing a class to a method, it is passed by


reference. When passing a struct to a method, it's passed
by value instead of as a reference.

You cannot have instance Field initializers in structs.


But classes can have initializers.

class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; //syntax error
public void MyFun( )
{
// statements
}
}

Classes can have explicit parameterless constructors.


But structs cannot have explicit parameterless constructors.

class MyClass
{
int myVar = 10;
public MyClass( ) // no syntax error.
{
// statements
}
}

struct MyStruct
{
int myVar;
public MyStruct( ) // syntax error.
{
// statements
}
}

Classes must be instantiated using the new operator. But structs can be instantiated without using
the new operator.

MyClass aClassObj;
/* MyClass aClassObj=new MyClass(); is the correct
format.aClassObj.myVar=100;//NullReferenceException
(because aClassObj does not contain a reference to an object
of type myClass). */

MyStruct aStructObj;aStructObj.myVar=100;// no exception.

Classes support inheritance.But there is no inheritance for structs. ( structs don't support
inheritance polymorphism )

(1)
struct MyStruct
{
int aStructVar;
internal void aStructMethod()
{
// statements
}
}

class MyClass : MyStruct // Syntax error.


{
int aClassVar;
int aClassMethod()
{
// statements
}
}

(2)
class MyClass
{
int aClassVar;
int aClassMethod()
{
// statements
}
}

struct MyStruct : MyClass // Syntax error.


{
int aStructVar;
internal void aStructMethod()
{
// statements
}
}

Since struct does not support inheritance, access modifier


of a member of a struct cannot be protected or protected
internal. It is not mandatory to initialize all Fields inside
the constructor of a class. But all the Fields of a struct
must be fully initialized inside the constructor.

class MyClass //No error( No matter whether the Field


//'MyClass.myString' is initialized or not ).
{
int myInt;
string myString;
public MyClass( int aInt )
{
myInt = aInt;
}
}

struct MyStruct // Error ( Field ' MyStruct.myString ' must


//be fully assigned before it leaves the constructor ).
{
int myInt;
string myString;
public MyStruct( int aInt )
{ myInt = aInt;
}
}

A class is permitted to declare a destructor.But a struct is not permitted to declare a destructor.

struct MyStruct
{
int myInt;
public MyStruct( )
{ } ~MyStruct( ) //Error.
{
Console.WriteLine("Destructor of MyStruct object");
}
}

class MyClass
{
int myInt;
public MyClass( ) { } ~MyClass( ) // No Error.
{
Console.WriteLine("Destructor of MyClass object"); }
}

Classes are used for complex and large set data. structs are
simple to use. structs are useful whenever you need a type that will be used often and is mostly
just a piece of data.

2. What does the term immutable mean?


Ans. It means to create a view of data that is not
modifiable and is temporary of data that is
modifiable.

Immutable means you can't change the currrent data,


but if you perform some operation on that data, a
new copy is created. The operation doesn't change
the data itself. Like let's say you have a string
object having "hello" value. Now if you say

temp = temp + "new value"

a new object is created, and values is saved in that.


The temp object is immutable, and can't be changed.

An object qualifies as being called immutable if its value


cannot be modified once it has been created. For example,
methods that appear to modify a String actually return a new
String containing the modification. Developers are
modifying strings all the time in their code. This may
appear to the developer as mutable - but it is not. What
actually happens is your string variable/object has been
changed to reference a new string value containing the
results of your new string value. For this very reason
.NET has the System.Text.StringBuilder class. If you find
it necessary to modify the actual contents of a string-like object heavily, such as in a for or
foreach loop, use the System.Text.StringBuilder class.

3. Can we have private constructor? When can I


use them? When should we implement a private constructor?

Ans. Private constructors would be mainly used for singleton


patterns and for classes that are module-like
(only static/shared methods/attributes)

The idea of the singleton is that you don't have a public


constructor, specifically to prevent people from
instantiating more than one of them. You call a
non-constructor method to return the singleton instance.
If it doesn't exist, the method calls the private
constructor to create it. Then it returns a reference
to the singleton instance.

An example below...

// .NET Singleton
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}

Obviously you'd need to add some properties and methods to get something useful, but you get
the idea. Watch out for
thread safety issues.
This link may give more insight: ttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp

4.Explain the differences between Server-side and


Client-side code?
Ans. Server side code will execute at server end
all the business logic will execute at server end
where as client side code will execute at client side
at browser end. Usually, scripts like Javascript,
VBScript & JScript etc. take care of client side
funtions.

5. What type of code (server or client) is found in


a Code-Behind class?
Ans. Server side.

6.Should validation (Did the user enter a real date?)


occur server-side or client-side? Why?
Ans. Ideally it should occur client-side. It saves round-trip to server & thus saves time!!! It also avoids SQL
Injections from malicious users. SQL injection is a security vulnerability that occurs in the database layer of an
application. The vulnerability
is present when user input is either incorrectly filtered
for string literal escape characters embedded in SQL
statements or user input is not strongly typed and thereby
unexpectedly executed. It is in fact an instance of a more
general class of vulnerabilities that can occur whenever
one programming or scripting language is embedded inside another.

Validation is usually done using client-side script like


javascript, jscript, vbscript (javascript being the most
popular due to browser compatibility).

.NET provides 5 + 1 controls for validation


1- RequiredFieldValidator
2- RangeValidator
3- RegularExpressionValidator
4- CompareValidator
5- CustomValidator
and the ValidationSummary Control

7.What does the "EnableViewState" property do? Why


would I want it on or off?
Ans. It keeps the data of the control during post backs.
if we turn off, the values should not populate during
server round trip. Basically its used to sustain value
of control's attributes betwen postbacks.

When a form is submitted in classic ASP, all form values


are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error.
You will
have to go back to the form and correct the information. You click the back button, and what happens.......
ALL form values are CLEARED, and you will have to start all
over again! The site did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in


the browser window together with all form values. How come?
This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted
to the server.

The status is defined through a hidden field placed on each page


with a <form runat="server"> control.

Maintaining the ViewState is the default setting for ASP.NET


Web Forms. If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false"
%> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.

8. What is the difference between Server.Transfer and


Response.Redirect? Why would I choose one over the other?

Ans. Server.Transfer will prevent round trip. it will


redirect pages which or in the same directory. NO way to
pass the query strings . Thru http context we can able
to get the previous page control values.

Response.Redirect : There is a round trip to process the


request. We can redirect to any page external / internal
other than aspx. We can pass the query string thru which we
can manage sessions.

A common misconception is the difference between Server.Transfer and Response.Redirect in ASP.NET


applications. Redirect and Transfer both cause a new page to be processed, but the interaction between the client
(web browser) and server
(ASP.NET) is different in each situation.

Redirect: A redirect is just a suggestion – it’s like saying


to the client “Hey, you might want to look at this”. All you tell the client is the new URL to look at, and if they
comply,
they do a second request for the new URL.

If you want to pass state from the source page to the new
page, you have to pass it either on the URL (such as a database key, or message string), or you can store it in the
Session
object (caveat: there may be more than one browser window, and they’ll all use the same session object).

e.g. Redirect to the new.aspx page, passing an ID on the


query string. "true" stops processing the current page:
Response.Redirect("new.aspx?id=32", true);

Transfer: A transfer happens without the client knowing


– it’s the equivalent of a client requesting one page,
but being given another. As far as the client knows, they
are still visiting the original URL.

Sharing state between pages is much easier using


Server.Transfer – you can put values into the Context.Items
dictionary, which is similar to Session and Application,
except that it lasts only for the current request. (search
for HttpContext in MSDN). The page receiving postback can
process data, store values in the Context, and then Transfer
to a page that uses the values. e.g. Store a message in the context dictionary, and transfer to the default.aspx page
(which can then display the message):

Context.Items["Message"] = "Your password was changed successfully";


Server.Transfer("default.aspx");

Response.Redirect is more user-friendly, as the site visitor can


bookmark the page that they are redirected to. Transferred pages appear to the client as a different url than they
really are.
This means that things like relative links/image paths may not
work if you transfer to a page from a different directory.
Server.Transfer has an optional parameter to pass the form data
to the new page. Since the release version, this no longer works, because the Viewstate now has more security by
default (The
EnableViewStateMac defaults to true), so the new page isn’t able to access the form data. You can still access the
values of the original page in the new page, by requesting the original handler:

Page originalPage = (Page)Context.Handler;

TextBox textBox1 = (TextBox)originalPage.FindControl("textBox1");

9. Can you give an example of when it would be appropriate


to use a web service as opposed to a non-serviced .NET
component.
Ans. Web service is one of main component in Service Oriented
Architecture. You could use web services when your clients and servers are running on different networks and also
different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be
easy to use web service since it runs on port 80 (by default) instead of having some thing else in Service Oriented
Architecture applications.
What is the standard you use to wrap up a call to a Web service?
Ans. SOAP.

Web services are best suite for Hetrogenious


environment. Remoting is best suite for Homogenious environment where the system is under CLR.

10. Let's say I have an existing application written using


Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000 COM+ transaction services.
How would you approach migrating this application to .NET?
Ans. .NET has made excellent use of the existing COM+
Technology to provide component features like instance management, transactions, activity-based synchronization,
granular role-based security, disconnected asynchronous queued
components, and loosely coupled events. This integration is a
big leap forward, providing greater flexibility to developers
through code.

The .NET components, which make use of the COM+ Services, are termed as ServicedComponents. Must read this
link to learn more : http://msdn2.microsoft.com/en-us/library/ms973809.aspx

11. Can you explain the difference between an ADO.NET


Dataset and ADO Recordset?
Ans. In ADO, the in-memory representation of data is the
recordset. In ADO.NET, it is the dataset. There are important differences between them.

Number of Tables
A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a
JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a
dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are
DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple
DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this
way, a dataset can mimic the structure of the underlying database.

A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key
relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains
a table about investors and another table about each investor's stock purchases, it could also contain a relationship
connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can
hold multiple, separate tables and maintain information about relationships between them, it can hold much richer
data structures than a recordset, including self-relating tables and tables with many-to-many relationships.

Data Navigation and Cursors


In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET,
rows are represented as collections, so you can loop through a table as you would through any collection, or access
particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail
records and provide a method that allows you to get records related to the one you are working with. For example,
starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table
describing his purchases.

A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes
made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data
classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-
only cursor is available in the ADO.NET DataReader object. For more information about cursor unctionality, see
Data Access Technologies.

Minimized Open Connections


In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update.
You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the
recordset can provide disconnected access, but ADO is designed primarily for connected access.

There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you
communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the
database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter
object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The
important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are
transmitted to the database — by optimizing for performance, performing data validation checks, or adding any
other extra processing.

Note - Data adapters, data connections, data commands, and data readers are the components that make up a .NET
Framework data provider. Microsoft and third-party providers can make available other .NET Framework data
providers that can be integrated into Visual Studio. For information on the different .NET Data providers, see .NET
Data Providers.

Sharing Data Between Applications


Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected
recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling.
To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.

12. Can you give an example of what might be best suited to place in the Application_Start and Session_Start
subroutines?

Ans. The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a
good place to initialize global variables. For example, you might want to retrieve a list of products from a database
table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and
Session_End events.

13. If I'm developing an application that must accomodate


multiple security levels through secure login and my ASP.NET web appplication is spanned across three web-
servers (using round-robbin load balancing)
what would be the best approach to maintain login-in state
for the users?
Ans. Database Support OR through State Service

14. What are ASP.NET Web Forms? How is this technology


different than what is available though ASP (1.0-3.0)?
Ans. There are plenty of differences.
ASP Interpreter.. use the script engine.
ASP.Net is compiled as managed code within the CLR. It also
supports code-behind (unlike in ASP, where code=behind was
invoked through VB components).

15. How does VB.NET/C# achieve polymorphism?


Ans. We achieve it using Function overloading & Operator overloading.

Polymorphism by definition means taking many forms. In C# it means the ability for classes to share the same
methods (actions) but implement them differently. For instance, say we create a class called "Shape" and this class
has a method called .draw() which draws the shape onto the user interface. Then we create two subclasses, using
inheritance, of this Shape class. One called Square, the other called Circle. Now obviously a square and circle are
two entirely different shapes, yet both classes have the .draw() method. When the Square.draw() method is called it
will draw a square on the user interface. When the Circle.draw() method is called, it will draw a circle on the user
interface. So both classes can use the same methods but implement them differently.
16. Can you explain what inheritance is and an example
of when you might use it?
Ans. Inheriting a trait from a parent class!
Use the existing functionality along with its own
properities.

17. How would you implement inheritance using VB.NET/C#?


Ans. Derived Class : Baseclass
VB.NEt : Derived Class Inherits Baseclass

18. Whats an assembly ?


Ans. A Basic unit of executable code.

* It contains : Manifest - Meta data


* versioning , Culture , IL, Reference

19. Describe the difference between inline and code behind.

Ans. Inline function bind at compile time can write in aspx page with in <% %> .

The code-behind is in a CS or a VB file.

20. Explain what a diffgram is, and a good use for one.
Ans. A DiffGram is an XML format that is used to identify
current and original versions of data elements. The DataSet uses the DiffGram format to load and
persist its contents, and to serialize its contents for transport across a network connection. When
a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information
to accurately recreate the contents, though not the schema, of the DataSet, including
column values from both the Original and Current row versions, row error information, and row
order. When sending and retrieving a DataSet from an XML Web service, the DiffGram format is
implicitly used.
Additionally, when loading the contents of a DataSet from
XML using the ReadXml method, or when writing the
contents of a DataSet in XML using the WriteXml method,
you can select that the contents be read or written as a
DiffGram

DiffGram Format
The DiffGram format is divided into three sections: the
current data, the original (or "before") data, and an
errors section, as shown in the following example.

<?xml version="1.0"?>
<diffgr:diffgram
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<DataInstance>
</DataInstance>

<diffgr:before>
</diffgr:before>

<diffgr:errors>
</diffgr:errors>
</diffgr:diffgram>
The DiffGram format consists of the following blocks of data:

<DataInstance>
The name of this element, DataInstance, is used for
explanation purposes in this documentation. A DataInstance
element represents a DataSet or a row of a DataTable.
Instead of DataInstance, the element would contain the name
of the DataSet or DataTable. This block of the DiffGram format contains the current data,
whether it has been modified or not.
An element, or row, that has been modified is identified with
the diffgr:hasChanges annotation.

<diffgr:before>
This block of the DiffGram format contains the original
version of a row. Elements in this block are matched to
elements in the DataInstance block using the diffgr:id
annotation.
<diffgr:errors>
This block of the DiffGram format contains error information
for a particular row in the DataInstance block. Elements in
this block are matched to elements in the DataInstance block
using the diffgr:id annotation.

21. Where would you use an iHTTPModule, and what are


the limitations of any approach you might take in
implementing one?
Ans. It provides module initialization and disposal events
to the implementing class.

22. Compare Session State Vs. ViewState.


Ans. Session State is useful for storing values that must
be persisted across multiple pages by the same user. ViewState is useful for storing
serializable data that must be
persisisted across PostBacks by a single page. If you use
Session State, the value you insert will remain in memory
until (1) The Session times out, or (2) Your code removes it.
If you use ViewState, the value you insert will remain in
ViewState until the user requests a different page.
ViewState stores data betwen PostBacks by putting it into a
hidden form field on the client HTML doc. when the doc is
Posted Back, the values are read from the hidden form field
and stored in memory until the page has finished processing.
If ViewState is particularly large (and I'm talking KBs
here, not 6 bytes), it can negatively affect the speed at
which the HTML doc is downloaded by the browser.

24. Whats MSIL, and why should my developers need an appreciation of it if at all?
Ans. Microsoft Intermediate language. which is the out put
for all the .net supported languages after compilation will
produce. Appreciation is for cross language support.
Definition:Microsoft Intermediate Language (MSIL) is the
CPU-independent instruction set generated by .NET compilers
from .NET languages such as J#, C# or Visual Basic. MSIL is
compiled before or during execution of the program by a Virtual Execution System (VES), which
is part of the Common Language Runtime module (CLR).
25. In what order do the events of an ASPX page execute. As a developer is it important to
undertsand these events?
Ans.
Page request
The page request occurs before the page life cycle begins.
When the page is requested by a user, ASP.NET determines
whether the page needs to be parsed and compiled (therefore beginning the life of a page), or
whether a cached version
of the page can be sent in response without running the page.

Start
In the start step, page properties such as Request and
Response are set. At this stage, the page also determines
whether the request is a postback or a new request and sets
the IsPostBack property. Additionally, during the start step,
the page's UICulture property is set.

Page initialization
During page initialization, controls on the page are
available and each control's UniqueID property is set. Any
themes are also applied to the page. If the current request is
a postback, the postback data has not yet been loaded and
control property values have not been restored to the values
from view state.
Load
During load, if the current request is a postback, control
properties are loaded with information recovered from view
state and control state.

Validation
During validation, the Validate method of all validator
controls is called, which sets the IsValid property of
individual validator controls and of the page.

Postback event handling


If the request is a postback, any event handlers are called.
Rendering Before rendering, view state is saved for the page and all controls. During the
rendering phase, the page calls the Render method for each control, providing a text writer that
writes its output to the OutputStream of the page's Response property.

Unload
Unload is called after the page has been fully rendered, sent
to the client, and is ready to be discarded. At this point,
page properties such as Response and Request are unloaded and any cleanup is performed.

26. Which method do you invoke on the DataAdapter


control to load your generated dataset with data?
Ans. Fill()

27. Can you edit data in the Repeater control?


Ans. NO

28. Which template must you provide, in order to display


data in a Repeater control?
Ans. ITemtemplate

29. How can you provide an alternating color scheme in a Repeatercontrol?


Ans. AlternateItemTemplate

30. What property must you set, and what method must you call in your code, in order to
bind the data from some data source to the Repeatercontrol?
Ans. Datasource, DataBind

31. What base class do all Web Forms inherit from?


Ans. System.Web.UI.Page
32. What method do you use to explicitly kill a user's
session?
Ans. Abandon()

33. How do you turn off cookies for one page in your site?
Ans. Disablecookies.

34. Which two properties are on every validation control?


Ans. Control to validate, Error message

35. What tags do you need to add within the


asp:datagrid tags to bind columns manually?
Ans. autogenerated columns is set to false

36. How do you create a permanent cookie?


Ans. Setting a permanent cookie is no harder than setting a
Session cookie. It’s very similar, except you give the cookie
an expiration date as well. It is very common that you don’t
specify any arbitrary expiration date, but instead expire the
cookie relative to the current date, using the DateAdd()
function, built into ASP. If you want to create a permanent
cookie called Name with a value of Nigel, which expires in one
month, you’d use the following code

Response.Cookies("Name") = "Nigel"
Response.Cookies("Name").Expires = DateAdd("m", 1, Now())

It’s that easy! Nothing more to it. You have now set a permanent cookie on your computer. Also,
note that whenever the above code is called the expiration date of the cookie is renewed by one
month from now.
There are a few more options which you can set, like for example the Path option. You can limit
cookies to certain paths on your website, so you can set several cookies with the same name, as
long as they belong to different paths. To do this, you would use the following code (extending
the previous code):

Response.Cookies("Name").Path = "/foo/"
The above code would limit the cookie to the path foo. It is
also possible to assign multiple values to a particular cookie.
This is done using the so-called dictionary functionality of
a cookie. For example, if I’d want to store not only the first
name, but also the surname in my Name cookie, I’d be using
something like the following code:

Response.Cookies("Name")("First") = "Nigel"
Response.Cookies("Name")("Last") = "Pallett"
Response.Cookies("Name").Expires = DateAdd("m", 1, Now())
That’s all! Although there are a few more "advanced" options,
such as the Secure option and the Domain option, it is of no use now.

Retrieving Cookies
Retrieving the value of cookies is a very easy job, because
again everything is handled by the browser and your server.
All you have to use is ASP’s inbuilt functions.
There is no difference in retrieving a Session cookie or a
permanent cookie, and in both cases you use the following code:

Response.Write "Your Name: " & Request.Cookies("Name")

The above is for when you assigned only one value to a cookie. If you assigned multiple values
you a cookie, you use the following code:

Response.Write "Your First Name: " & _


Request.Cookies("Name")("First")
Response.Write "Your Surname: " & _
Request.Cookies("Name")("Last")

That’s all there is to it. It’s that easy, because everything


is done by your server and the ASP engine. Make sure you check out this handy function as well,
which shows your visitors all the cookies they have stored.

Checking if Cookies are enabled


Before using cookies, it is often useful to check whether your
visitor accepts cookies. Some may disable it in their browser;
others may be using browsers that don’t support cookies at all (although very few browsers do).
You should always keep the fact that your cookies might not work in the back of your mind,
meaning, do NOT rely on cookies to work. If your website does not work when cookies are
disabled, you must fix this.

37. What tag do you use to add a hyperlink column to


the DataGrid?
Ans.<asp:HyperLink id="some_Id_uDefine" runat="server">

38. What is the standard you use to wrap up a call to a


Web service?
Ans. SOAP - SOAP is a simple XML-based protocol to let
applications exchange information over HTTP.
SOAP (originally Simple Object Access Protocol) is a
protocol for exchanging XML-based messages over computer
network, normally using HTTP. SOAP forms the foundation
layer of the Web services stack, providing a basic messaging
framework that more abstract layers can build on. The original acronym was dropped with
Version 1.2 of the standard, which became a W3C Recommendation on June 24, 2003, as it was
considered to be misleading.

There are several different types of messaging patterns in


SOAP, but by far the most common is the Remote Procedure Call (RPC) pattern, in which one
network node (the client) sends a request message to another node (the server), and the server
immediately sends a response message to the client. SOAP is the successor of XML-RPC,
though it borrows its transport and interaction neutrality and the envelope/header/body from
elsewhere, probably from WDDX [citation needed]. Originally designed by Dave Winer, Don
Box, Bob Atkinson, and Mohsen Al-Ghosein in 1998 with backing from Microsoft (where
Atkinson and Al-Ghosein worked at the time) as an object-access protocol, the SOAP
specification is currently maintained by the XML Protocol Working Group of the World Wide
Web Consortium.

39. Which method do you use to redirect the user to


another page without performing a round trip to the client?
Ans. Server.transfer

40. What is the transport protocol you use to call a


Web service
Ans.
SOAP. Transport Protocols: It is essential for the acceptance of Web Services that they are based
on established Internet
infrastructure. This in fact imposes the usage of of the HTTP,
SMTP and FTP protocols based on the TCP/IP family of
transports. Messaging Protocol: The format of messages exchanged between Web Services
clients and Web Services should be vendor neutral and should not carry details about the
technology used to implement the service. Also, the message format should allow for extensions
and different bindings to specific transport protocols. SOAP and ebXML Transport are
specifications which fulfill these requirements. We expect that the W3C XML Protocol Working
Group defines a successor standard.

41. True or False: A Web service can only be written


in .NET
Ans. False
42. What does WSDL stand for?
Ans.Webservice description language. WSDL is an XML format for describing network services
as a set of endpoints
operating on messages containing either document-oriented or procedure-oriented information.
The operations and messages are described abstractly, and then bound to a concrete network
protocol and message format to define an endpoint. Related concrete endpoints are combined
into abstract endpoints (services). WSDL is extensible to allow description of endpoints and their
messages regardless of what message formats or network protocols are used to communicate,
however, the only bindings described in this document describe how to use WSDL in
conjunction with SOAP 1.1, HTTP GET/POST, and MIME.
43. What property do you have to set to tell the
grid which page to go to when using the Pager object?
Ans. Page Index.

44. Where on the Internet would you look for Web services?
Ans. UDDI
45. What tags do you need to add within the
asp:datagrid tags to bind columns manually.
Ans. Autogenerate columns

46. Which property on a Combo Box do you set with a column name, prior to setting the
DataSource, to display data in the combo box?
Ans. Datatext, Datavalue
47. How is a property designated as read-only?
Ans.
In VB.NET:
Public ReadOnly Property PropertyName As ReturnType
Get ‘Your Property Implementation goes in here
End Get
End Property
In C#
public returntype PropertyName
{
get{
//property implementation goes here
}
// Do not write the set implementation
}

48. Which control would you use if you needed to make sure the values in two different
controls matched?
Ans. Ideally we would tend to use Comparefield validator.

49. True or False: To test a Web service you must create a windows application or Web
application to consume this service?
Ans. False

50. How many classes can a single .NET DLL contain?


Ans. As many as u want!

51. Is ASP.NET a language?


Ans. No! Its a technology.
ASP.NET is not a platform independent language. As was
ASP.NET is more of a technology that provides a framework for building web applications.
ASP.NET provides the reources needed to dynamically deliver html content (pages) to the end
user. ASP.NET can leverage languages such as C#, VB.NET, and javascript to help provide a
reliable, high perfofmance, and secure web application.

.NET - is the Microsoft Web services strategy to connect information, people, systems, and
devices through software. Integrated across the Microsoft platform, .NET technology provides
the ability to quickly build, deploy, manage, and use connected, security-enhanced solutions with
Web services. .NET-connected solutions enable businesses to integrate their systems more
rapidly and in a more agile manner and help them realize the promise of information anytime,
anywhere, on any device. (Source: http://www.microsoft.com/net/Basics.mspx )

Size of a .NET object - Minimum 12 bytes. 4 bytes for the table pointer, 4 bytes for the sync
block, and 4 bytes or more for the datatypes in the class. Even if there is no data type in the class,
the object will take 12 bytes, as per the CLR's functionality.

Programming Languages in .NET - C#, VB.NET, JS.NET, C++.NET

Versions of .NET - The final version of the 1.0 SDK & runtime were made publically available
on 15 - Jan -2002. At the same time, the final version of Visual Studio.NET was made available
to MSDN subscribers. .NET 1.1 was released in April 2003, with bugs fixed. .NET 2.0 was
launched in October 2005 for MSDN subscribers, and officially released in Nov 2005. On - Jun -
2006, .NET 3.0 was launched. This version is called WinFX.

Operating systems support in .NET - The runtime supports Windows Server 2003,
Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported.
Some parts of the framework do not work on all platforms - for example, ASP.NET is only
supported on XP and Windows 2000/2003. Windows 98/ME cannot be used for development.

Update: All versions of Vista support .NET.

IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET.
However, the ASP.NET Web Matrix web server does run on XP Home.

.NET Compact Framework - is a version of .NET for mobile devices. They run Windows CE
or Widows Mobile.

Mono - This version of .NET runs on Linux. Still not popular.

Tools for developing .NET applications :

The .NET Framework SDK is free and includes command-line compilers for C++, C#, and
VB.NET and various other utilities to aid development.
SharpDevelop is a free IDE for C# and VB.NET.
Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or
novice developers. There are different versions for C#, VB, web development etc. Originally
the plan was to charge $49, but MS has decided to offer them as free downloads instead, at
least until November 2006. Microsoft Visual Studio Standard 2005 is around $300, or $200 for
the upgrade. Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade.
At the top end of the price range are the Microsoft Visual Studio Team Edition for Software
Developers 2005 with MSDN Premium and Team Suite editions. Visual Web Developer Express
is available as a free download.

CLI (Common Language Infrastructure) - is the definition of the fundamentals of the .NET
framework. It is documented through ECMA (http://msdn.microsoft.com/netframework/ecma/).
The fundamentals include the following:

*CTS (Common Type Specification)

*Metadata

* VES (Virtual Execution Environment)

* IL (Or MSIL) (Microsoft Intermediate Language)

* CLS (Common Language Specification)

CLR - Common Language Runtime - It is the implementation of CLI. The core runtime engine
in the Microsoft .NET Framework for executing applications. The common language runtime
supplies managed code with services such as cross-language integration, code access security,
object lifetime management, resouce management, type safety, pre-emptive threading, metadata
services (type reflection), and debugging and profiling support. The ASP.NET Framework and
Internet Explorer are examples of hosting CLR.

The CLR is a multi-language execution environment. There are currently over 15 compilers
being built by Microsoft and other companies that produce code that will execute in the CLR.

The CLR is described as the "execution engine" of .NET. It's this CLR that manages the
execution of programs. It provides the environment within which the programs run. The software
version of .NET is actually the CLR version.

When the .NET program is compiled, the output of the compiler is not an executable file but a
file that contains a special type of code called the Microsoft Intermediate Language (MSIL).
This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the
job of the CLR to translate this Intermediate code into a executable code when the program is
executed making the program to run in any environment for which the CLR is implemented.
And that's how the .NET Framework achieves Portability. This MSIL is turned into executable
code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are
executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native
code on a demand basis as each part of the program is needed. Thus the program executes as a
native code even though it is compiled into MSIL making the program to run as fast as it would
if it is compiled to native code but achieves the portability benefits of MSIL.

Class Libraries - Class library is the another major entity of the .NET Framework. This library
gives the program access to runtime environment. The class library consists of lots of prewritten
code that all the applications created in VB .NET and Visual Studio .NET will use. The code for
all the elements like forms, controls and the rest in VB .NET applications actually comes from
the class library.

Common Language Specification (CLS) - If we want the code which we write in a language to
be used by programs in other languages then it should adhere to the Common Language
Specification (CLS). The CLS describes a set of features that different languages have in
common. The CLS includes a subset of Common Type System (CTS) which define the rules
concerning data types and ensures that code is executed in a safe environment.

Common Type Specification(CTS) - The Common Type System (CTS) defines the rules
concerning data types and ensures that code is executed in a safe environment. Since all .NET
applications are converted to IL before execution all primitive data types are represented as .NET
types. This means that, a VB Integer and a C# int are both represented in IL code as
System.Int32. Because both the languages use a common and interconvertible type system, it is
possible to transfer data between components and avoid time-consuming conversions.

Microsoft Intermediate Language(MSIL) - When compiling to managed code, the compiler


translates your source code into Microsoft intermediate language (MSIL), which is a CPU-
independent set of instructions that can be efficiently converted to native code. MSIL includes
instructions for loading, storing, initializing, and calling methods on objects, as well as
instructions for arithmetic and logical operations, control flow, direct memory access, exception
handling, and other operations. Before code can be run, MSIL must be converted to CPU-
specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime
supplies one or more JIT compilers for each computer architecture it supports, the same set of
MSIL can be JIT-compiled and run on any supported architecture.

When a compiler produces MSIL, it also produces metadata. Metadata describes the types in
your code, including the definition of each type, the signatures of each type's members, the
members that your code references, and other data that the runtime uses at execution time. The
MSIL and metadata are contained in a portable executable (PE) file that is based on and extends
the published Microsoft PE and common object file format (COFF) used historically for
executable content. This file format, which accommodates MSIL or native code as well as
metadata, enables the operating system to recognize common language runtime images. The
presence of metadata in the file along with the MSIL enables your code to describe itself, which
means that there is no need for type libraries or Interface Definition Language (IDL). The
runtime locates and extracts the metadata from the file as needed during execution.
Managed Code - The .NET framework provides lots of core runtime services to the programs
that run within it. For example - security & exception handling. Such a code has a minimum
level of information. It has metadata associated with it. Such a code is called Managed Code.
VB.NET, C#, JS.NET code is managed by default. In order to make C++ code managed, we
make use of managed extensions, which is nothing but a postfix _gc after the class name.

Managed Data - Data that is allocated & freed by the .NET runtime's Garbage collecter.

Managed Class - A class whose objects are managed by the CLR's garbage collector. In
VC++.NET, classes are not managed. However, they can be managed using managed extentions.
This is done using an _gc postfix. A managed C++ class can inherit from VB.NET classes, C#
classes, JS.NET classes. A managed class can inherit from only one class. .NET does'nt allow
multiple inheritance in managed classes.

Reflection - The process of getting the metadata from modules/assemblies. When .NET code is
compiled, metadata about the types defined in the modules is produced. These modules are in
turn packaged as assemblied. The process of accessing this metadata in called Reflection.

The namespace System.Reflection contains classes that can be used for interrogating the types
for a module/assembly. We use reflection for examining data type sizes for marshalling across
process & machine boundaries.

Reflection is also used for:

1) To dynamically invoke methods (using System.Type.InvokeMember) 2) To dynamically


create types at runtime (using System.Reflection.Emit.TypeBuilder).

Assembly - An assembly may be an exe, a dll, an application having an entry point, or a library.
It may consist of one or more files. It represents a group of resources, type definitions, and
implementation of these types. They may contain references to other assemblies. These
resources, types & references are compacted in a block of data called manifest. The manifest is a
part of the assembly, which makes it self-describing. Assemblies also increase security of code in
.NET. An assembly maybe shared(public) or private.

An assembly may be created by building the class(the .vb or .cs file), thereby producing its DLL.

ILDASM - The contents of an assembly may be viewed using the ILDASM tool, that comes
with the .NET SDK or the Visual Studio.NET.

Private Assembly - This type of assembly is used by a single application. It is stored in the
application's directory or the applications sub-directory. There is no version constraint in a
private assembly.

Shared Assembly (or Public Assembly) - A shared assembly has version constraint. It is stored
in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by
the .NET runtime. The shared assemblies may be used by many applications. To make an
assembly a shared assembly, it has to be strongly named.

In order to share an assembly with many applications, it must have a strong name.

In order to convert a private assembly to a shared assembly, i.e. to create a strongly named
assembly, follow the steps below...

1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The
key pair that is generated by the Strong Name tool can be kept in a file or we can store it our
your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command
interpreter, and type the following...

sn -k C:\samplekey.snk

This will create a strong key and save it to the location C:\samplekey.snk

2) If the key is stored in a file, just like we have done above, we use the attribute
AssemblyKeyFileAttribute. This belongs to the namespace
System.Reflection.AssemblyKeyFileAttribute.

If the key was in the CSP, we would make use of


System.Reflection.AssemblyKeyNameAttribute.

Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this
file...

<assembly: assemblykeyfileattribute("C:\samplekey.snk")>

We may write this in our code as well, like this...

Imports System.Reflection
<assembly: assemblykeyfileattribute("C:\samplekey.snk")>

Namespace StrongName
Public class Sample
End Class
End Namespace

3) Build your project. Your assembly is now strongly named.

Installing the Shared assembly in GAC...

Go to .NET command interpreter, use the tool gacutil.exe

Type the following...


gacutil /i sampleclass.dll To uninstall it, use... gacutil /u sampleclass.dll Visual Studio.NET
provides a GUI tool for viewing all shared assemblies in the GAC.

Folder of GAC: C:\Windows\Assembly

Assembly Versioning - Each assembly (shared assembly) has a version. Its called the
compatibility version. There are 4 parts in the version, namely Major, Minor, Build, Version. If
the first two parts are same, then two assemblies are compatible. If they are different, they are
incompatible. If the third part is different, then the two assemblies may or may not be
compatible. If only the fourth part is different, then they are surely compatible. The version
policy may be applied using the application's configuration file(.config file). Application Domain
- An application domain is a process running on the .NET runtime. In a Win32 environment, the
application domain can host several instances known as processes on the machine. An
application domain may be destroyed, without affecting other processes, as each application
domain is a separate process. The host, which is the Windows shell, creates a new application
domain for every application. For example, several instances of Internet Explorer may be
running on a single PC. Garbage Collection - Garbage collection is a heap-management strategy
where a run-time component takes responsibility for managing the lifetime of the memory used
by objects. This concept is not new to .NET - Java and many other languages/runtimes have used
garbage collection for some time. The garbage collector runs periodically. It runs through a list of
objects that are currently being referenced by an application. All objects that it does not find
during this search are ready to be destroyed (using the finalize method) and hence free the
memory. However, the runtime gets notified of the object that has been destroyed, only in the
next round of the garbage collector's periodic cycle.

In the class System.GC, there is a method called collect( ). This forces the garbage collector to
collect all unreferenced objects immediately, thereby giving the developer some control over the
garbage collector.

There is a gcConcurrent setting that can be set through the applications's .config file. This
specifies whether or not the garbage collector performs its activities on a specified thread or not.

We can view the performance monitor to view the activities of the garbage collector.

IDisposable interface - We implement this interface to a class when we have to work with
unmanaged types. For example, an IntPtr member representing an operating system's file
handler is actually unmanaged, and in order to destroy it, we make use of the Dispose method
by implementing the IDisposable interface. In this case, we override the Finalize method.
Note that we make use of Dispose method on those objects which have an uncertain life
period, and thus the garbage collector does not finalize them automatically.

We also make use of Dispose method while working with managed code, for example, an object
os System.IO.FileStream may have an uncertain life, and in order to dispose it, we use the
dispose method. Such types of objects are not accessed by the Garbage Collector's Finalizer.
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 BinaryFormattercolArrayList = CType(


objBinaryFormatter.Deserialize( objFileStream ), ArrayList )

objFileStream.Close()

For Each strItem In colArrayList

Response.Write( "<li>" & 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.

Example below shows how we can serialize a class to a database table... Imports System

Namespace myComponents

<serializable()> Public Class UserInfo


Public Username As String
Public Password As String
Public Email As String
End Class
End Namespace The class above contains 3 public properties. Using the serializable attribute
with this class means we can serialize the class. To use this class, we have to compile it from the
command line (or VS.NET). We use the following command... vbc /t:Library UserInfo.vb
Next, copy the compiled class, UserInfo.dll, to our application /bin directory. Placing the
UserInfo.dll file in our /bin directory exposes the class to your ASP.NET application. Next, we
create a table in our SQL Server...

CREATE TABLE UserList (


user_id INT NOT NULL IDENTITY,
username VARCHAR( 50 ),
userinfo Image )
For further code CLICK HERE

Xml Serializer does not serialize instances of classes like Hashtable which implement the
IDictionary interface.

Attributes - Is a kind of property attached with a class. It allows some data to be attached to a
class or method. This data becomes part of the metadata for the class, and (like other class
metadata) can be accessed via reflection. An example of a metadata attribute is [serializable],
which can be attached to a class and means that instances of the class can be serialized.

[Serializable]

Public Class SampleClass

( ... )

Code Access Security (CAS) - CAS is the part of the .NET security model that determines
whether or not code is allowed to run, and what resources it can use when it is running. For
example, it is CAS that will prevent a .NET web applet from formatting your hard disk. The
CAS security policy revolves around two key concepts - code groups and permissions. Each
.NET assembly is a member of a particular code group, and each code group is granted the
permissions specified in a named permission set. For example, using the default security policy,
a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres
to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named
permission set represents a very restrictive range of permissions.) To view codegroups on our
system, use the following command on .NET command interpretor... caspol -lg Note the
hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then
sub-divided into several groups, each of which in turn can be sub-divided. Also note that
(somewhat counter-intuitively) a sub-group can be associated with a more permissive permission
set than its parent. If we want to trust a particular website giving it full rights to our system...Use
caspol. For example, suppose we trust code from www.mydomain.com and we want it have full
access to our system, but we want to keep the default restrictions for all other internet sites. To
achieve this, we would add a new code group as a sub-group of the 'Zone - Internet' group, like
this: caspol -ag 1.3 -site www.mydomain.com FullTrust To change the permission, we use the
-cg attribute.To turn off caspol, use caspol -s off
Threads - When we want to run one or more instances of a method, we make use of threading.
Suppose we have a method like this... Private Sub OnGoingProcess()

Dim i As Integer = 1

Do While True
ListBox1.Items.Add("Repeatitions: " + i)
i += 1
Loop
End Sub Dim t As Thread
t = New Thread(AddressOf Me.OnGoingProcess)
t.Start()
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate
within VB.NET is a type-safe, object-oriented function pointer. After the thread has been
instantiated, you begin the execution of the code by calling the Start() method of the thread. After
the thread is started, you have some control over the state of it by using methods of the Thread
object. You can pause a thread's execution by calling the Thread.Sleep method. This method
takes an integer value that determines how long the thread should sleep. If you wanted to slow
down the addition of items to the listbox in the example above, place a call to the sleep method
in this code:

Private Sub OnGoingProcess()


Dim i As Integer = 1

Do While True
ListBox1.Items.Add("Repeatitions: " + i)
i += 1
Thread.CurrentThread.Sleep(2000)
Loop
End Sub

You can also place a thread into the sleep state for an indeterminate amount of time by calling
Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the
Thread.Interrupt method. Similar to Sleep and Interrupt are Suspend and Resume. Suspend
allows you to block a thread until another thread calls Thread.Resume. The difference between
Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The
thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it.
Sleep will immediately place a thread in a wait state. Lastly, Thread.Abort stops a thread from
executing. In our simple example, we would want to add another button on the form that allows
us to stop the process. To do this all we would have to do is call the Thread.Abort method as
follows:

Private Sub Button2_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button2.Click
t.Abort()
End Sub
This is where the power of multithreading can be seen. The UI seems responsive to the user
because it is running in one thread and the background process is running in another thread. The
cancel button immediately responds to the user's click event and processing stops. The next
example shows a rather simple situation. Multithreading has many complications that we have to
work out when we program. One issue that we will run into is passing data to and from the
procedure passed to the constructor of the Thread class. That is to say, the procedure we want to
kick off on another thread cannot be passed any parameters and we cannot return data from that
procedure. This is because the procedure wepass to the thread constructor cannot have any
parameters or return value. To get around this, wrap our procedure in a class where the
parameters to the method are written as fields of the class. A simple example of this would be if
we had a procedure that calculated the square of a number:

Function Square(ByVal Value As Double) As Double


Return Value * Value
End Function To make this procedure available to be used in a new thread we would wrap
it in a class: Public Class SquareClass
Public Value As Double
Public Square As Double

Public Sub CalcSquare()


Square = Value * Value
End Sub
End Class

Use this code to start the CalcSquare procedure on a new thread. following code:

Private Sub Button1_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button1.Click

Dim oSquare As New SquareClass()

t = New Thread(AddressOf oSquare.CalcSquare)

oSquare.Value = 30

t.Start()
End Sub

Notice that after the thread is started, we do not inspect the square value of the class, because it
is not guaranteed to have executed once you call the start method of the thread. There are a few
ways to retrieve values back from another thread. The easiest way is to raise an event when the
thread is complete. We will examine another method in the next section on thread
synchronization. The following code adds the event declarations to the SquareClass.
Public Class SquareClass
Public Value As Double
Public Square As Double

Public Event ThreadComplete(ByVal Square As Double)

Public Sub CalcSquare()


Square = Value * Value
RaiseEvent ThreadComplete(Square)
End Sub
End Class

Catching the events in the calling code has not changed much from VB6, you still declare the
variables WithEvents and handle the event in a procedure. The part that has changed is that you
declare that a procedure handles the event using the Handles keyword and not through the
naming convention of Object_Event as in VB6. Dim WithEvents oSquare As SquareClass

Private Sub Button1_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button1.Click

oSquare = New SquareClass()

t = New Thread(AddressOf oSquare.CalcSquare)

oSquare.Value = 30
t.Start()
End Sub

Sub SquareEventHandler(ByVal Square As Double) _


Handles oSquare.ThreadComplete

MsgBox("The square is " & Square)

End Sub

The one thing to note with this method is that the procedure handling the event, in this case
SquareEventHandler, will run within the thread that raised the event. It does not run within the
thread from which the form is executing. (Source:
www.devx.com)

Trace and Debug - There are two main classes that deal with tracing - Debug and Trace. They
both work in a similar way - the difference is that tracing from the Debug class only works in
builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in
builds that have the TRACE symbol defined. Typically this means that you should use
System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release
builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in
debug builds.Tracing is actually the process of collecting information about the program's
execution.Debugging is the process of finding & fixing errors in our program. Tracing is the
ability of an application to generate information about its own execution. The idea is that
subsequent analysis of this information may help us understand why a part of the application is
not behaving as it should and allow identification of the source of the error.

We shall look at two different ways of implementing tracing in .NET via the
System.Web.TraceContext class via the System.Diagnostics.Trace and
System.Diagnostics.Debug classes Tracing can be thought of as a better (more featureful and
automated) alternative to the response.writes we used to put in our old ASP3.0 code to help
debug pages!

If we set the Tracing attribute of the Page Directive to True, then Tracing is enabled. The output
is appended in the web form output. Messeges can be displayed in the Trace output using
Trace.Warn & Trace.Write. The only difference between Trace.Warn & Trace.Write is that the
former has output in red color. If the trace is false, there is another way to enable tracing. This is
done through the application level. We can use the web.config file and set the trace attribute to
true. Here we can set <trace enabled=false .../>

Note that the Page Directive Trace attribute has precedence over th application level trace
attribute of web.config. While using application level tracing, we can view the trace output in the
trace.axd file of the project. For more information on Trace & Debug CLICK HERE

You might also like