Monday, June 30, 2008

.NET Architecture

Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns
√ Mediator:-Defines simplified communication between classes.
√ Memento:-Capture and restore an object's internal state.
√ Interpreter:-A way to include language elements in a program.
√ Iterator:-Sequentially access the elements of a collection.
√ Chain of Resp:-A way of passing a request between a chain of objects.
√ Command:-Encapsulate a command request as an object.
√ State:-Alter an object's behavior when its state changes.
√ Strategy:-Encapsulates an algorithm inside a class.
√ Observer:-A way of notifying change to a number of classes.
√ Template Method:-Defer the exact steps of an algorithm to a subclass.
√ Visitor:-Defines a new operation to a class without change.
Note :- Just remember Music....... 2 MICS On TV (MMIICCSSOTV).
Note:- No source code is provided for architecture section. As much of the things can be
clear from good UML diagrams.
(A)What’s difference between Factory and Abstract Factory Pattern’s?
Note: - This is quiet a confusing architect question especially in design pattern section.
Interviewer can take you for a nice ride …. So get the difference’s in your heart.
First read the definition provided in the first question about both these patterns. The
common thing they have is that they belong to creational patterns. In short they hide the
complexity of creating objects.
The main difference between factory and Abstract factory is factory method uses
inheritance to decide which object has to be instantiated. While abstract factory uses
delegation to decide instantiation of object. We can say Abstract factory uses factory
method to complete the architecture. Abstract Factory is one level higher in abstraction
over Factory.
The below two class diagrams will provide overview of what the actual difference is.
First figure shows a sample implementation of Factory Patterns. In this figure there are
two basic sections:-
√ The actual product section i.e. Class “Product” it inherits from a abstract
class “AbstractProduct”.
√ The creational aspect section that’s “ConcreteCreator” class which inherits
from class “Creator”.
√ Now there are some rules the client who will need the “Product” object will
have to follow. He will never refer directly to the actual “Product” object he
will refer the “Product” object using “AbstractProduct”.
√ Second client will never use “New” keyword to create the “Product” object
but will use the “Creator” class which in turn will use the “ConcreteCreator”
class to create the actual “Product” object.
Figure: - 8.1 Class diagram of a factory Pattern
So what are benefits from this architecture? All creational and initializing aspects are
now detached from the actual client. As your creational aspect is now been handled in
“ConcreteCreator” and the client has reference to only “Creator”, so any implementation
change in “CreateProduct” will not affect the client code. In short now your creational
aspect of object is completely encapsulated from the client’s logic.
Now let’s look at the second class diagram which provides an overview of what actually
“Abstract factory” pattern is. It creates objects for families of classes. In short it describes
collection of factor methods from various different families. In short it groups related
factory methods. Example in this the class “Creator” is implemented using the “Abstract”
factory pattern. It now creates objects from multiple families rather one product.
Note :- Just stick up to this definition that Abstract factory classifies factory methods or
groups logically related factory method together..
Figure:- 8.2 Class Diagram of Abstract Factory
(I)What’s MVC pattern?
Twist: - How can you implement MVC pattern in ASP.NET?
The main purpose using MVC pattern is to decouple the GUI from the Data. It also gives
the ability to provide multiple views for the same Data. MVC pattern separates objects in
to three important sections:-
√ Model: - This section is specially for maintaining data. It is actually where your
business logic, querying database, database connection etc. is actually
√ Views: - Displaying all or some portion of data, or probably different view of
data. View is responsible for look and feel, Sorting, formatting etc.
√ Controller: - They are event handling section which affects either the model or
the view. Controller responds to the mouse or keyboard input to command
model and view to change. Controllers are associated with views. User
interaction triggers the events to change the model, which in turn calls some
methods of model to update its state to notify other registered views to refresh
their display.
Ok now this was all in theory. Let’s look at how in actually ASP.NET can we implement
MVC pattern. During interview with theory they will be looking at more have you really
implemented MVC or its just talks. Following are the various sections of ASP.NET which
maps to MVC sections:-
√ Model: - This section is represented by Data view, Dataset, Typed Dataset,
Business components, business entity models etc. Now this section can then
be tied up to either windows application or web UI.
√ View: - ASPX, ASCX, or windows application UI like data grid etc. form the
view part of it.
√ Controller: - In ASP.NET the behind code is the controller. As the events are
handled by that part. Controller communicates both with Model as well as
I hope I was able to map you imagination of ASP.NET with the diagram given below.
Figure: - 8. 3 Data flow between MVC architectures.
(A)How can we implement singleton pattern in .NET?
Singleton pattern mainly focuses on having one and only one instance of the object running.
Example a windows directory service which has multiple entries but you can only have
single instance of it through out the network.
Note:- May of developers would jump to a conclusion saying using the “STATIC” keyword
we can have a single instance of object. But that’s not the real case there is something more
that has to be done. But please note we can not define a class as STATIC, so this will not
serve our actual purpose of implementing singleton pattern.
Following are the three steps needed to implement singleton pattern in .NET:-
√ First create your class with static members.
Public class ClsStaticClass
Private shared objCustomer as clsCustomer
End class
This ensures that there is actually only one Customer object through out the project.
√ Second define a private constructor to your class.
Note: - defining a private constructor to class does not allow a client to create objects directly.
√ Finally provide a static method to get access to your singleton object.
(A)How do you implement prototype pattern in .NET?
Twist: - How to implement cloning in .NET ? , What is shallow copy and deep copy ?
Cloning is achieved by using ICloneable of the System namespace. It has a “Clone” method
which actually returns the reference of the same copy. Clone method allows a Shallow
copy and not a deep copy. In Shallow copy if you make changes to the cloned object it
actually does change on the main object itself. So how is deep copy achieved, by using
“ISerializable” interface? So what you do is first serialize the object then deserialize back
to a complete new copy. Now any changes to this new copy do not reflect on the original
copy of the object, this is called as Deep copy.
(I)What are the situations you will use a Web Service and Remoting in
Well “Web services” uses “remoting” concepts internally. But the major difference between
“web service” and “remoting” is that “web service” can be consumed by clients who are
not .NET platform. While remoting you need the client to be .NET compliant. Regarding
the speed issue “Remoting” is faster than “Web Services”. So I think when deciding the
architecture side of choosing between “Web services” and “Remoting” keep the cross
platform issue and the speed issue in mind.
(A)Can you give a practical implementation of FAÇADE patterns?
Façade pattern sits on the top of lot of subsystems and makes access easy to interfaces
of these subsystems. Basic purpose of Façade is to make interfacing between many
modules and classes manageable.
Figure: - 8.4 Façade in action
Above is a simple live application of a Façade class. In this we have four subsystems :-
√ Customer
√ Product
√ Payment
√ Invoicing
All the four modules when built at initial stage where built completely independent. The
main interaction between all these subsystems is customer placing order. This functionality
can be attained by using all these subsystems, which involves complex interaction between
There’s where FAÇADE comes in to action. We have built a FAÇADE called as
“FACADEORDER” which sits on the top of all these subsystem and fulfills our
(I) How can we implement observer pattern in .NET?
Observer patterns can be implemented using “Delegates” and “Events”. I leave this to
the readers to implement one sample code for observer patterns.
(B)What is three tier architecture?
The three tier software architecture emerged in the 1990s to overcome the limitations of
the two tier architecture.
There are three layers in when we talk about three tier architecture:-
User Interface (Client) :- This is mostly the windows user interface or the Web interface.
But this has only the UI part.
Mid layer: - Middle tier provides process management where business logic and rules are
executed and can accommodate hundreds of users (as compared to only 100 users with
the two tier architecture) by providing functions such as queuing, application execution,
and database staging.
Data Access Layer: - This is also called by the famous acronym "DAL" component. It has
mainly the SQL statement which do the database operation part of the job.
The three tier architecture is used when an effective distributed client/server design is
needed that provides (when compared to the two tier) increased performance, flexibility,
maintainability, reusability, and scalability, while hiding the complexity of distributed
processing from the user.
(I)Have you ever worked with Microsoft Application Blocks, if yes then
Application Blocks are C# and VB.NET classes distributed as Visual Studio projects
that can be downloaded from Microsoft's Web site and used in any .NET application,
including ASP.NET Web applications. They are useful and powerful tools that can make
applications more maintainable, scalable and efficient
The second question which of the application blocks has been used depends on really
what you have implemented. But there are two famous MAB which is making buzz around
the industry:-
√ data access block
The Data Access Block provides static methods located in the SqlHelper class
that encapsulates the most common data access tasks performed with Microsoft
SQL server. If the term "static method" is new to you, it means that the class
methods can be called without instantiating an instance of the class. For
example, the method ExecuteReader () within the SqlHelper class can be called
by simply using the statement SqlHelper.ExecuteReader () -- no object
instantiation of the SqlHelper class is required.
√ Exception management block.
The Exception Management Application Block provides a simple yet extensible
framework for handling exceptions. With a single line of application code you
can easily log exception information to the Event Log or extend it by creating
your own components that log exception details to other data sources or notify
operators, without affecting your application code. The Exception Management
Application Block can easily be used as a building block in your own .NET
Note: - It’s beyond the scope the book to look in to details of application block. Best is go to and search for these application block. Try to compile one or two
programs using there given classes and documentation.
(A)What is Service Oriented architecture?
“Services” are components which expose well defined interfaces and these interfaces
communicate through XML messages. Using SOA you can build workflow, which uses
interfaces of these components. SOA is typically useful when you are crossing
heterogeneous technical boundaries, organizations, domain etc.
In .NET SOA technically uses Web services to communicate with each service which is
crossing boundaries. You can look SOA which sits on TOP of web services and provides
a workflow.
SOA uses service components which operate in there own domain boundary. Let’s note
some points of service :-
√ They are independent components and operate in there own boundary and
own technology.
√ They have well defined interfaces which use XML and WSDL to describe
√ Services have URL where any one can find them and clients can bind to these
URL to avail for the service.
√ Services have very loosely coupled architecture. In order to communicate to
service you only have to know the WSDL. Your client can then generate proxy
from the WSDL of the service.
Figure: - 8.5 SOA basic architecture
Above figure describes a broader picture of what service oriented architecture will look
like. The basic fundamental of SOA is a web service. In above diagram you can see there
are two services available. One is the “Credit Card” service and other is “Address Check”
web service. Both these services are provided by different company. Now we want to
build a functionality which needs to validate a credit card and also check that addresses
are proper. In short we will need functionalities of both the “CreditCard” and
“AddressCheck” service. Also note the “CreditCard” service has its own business layer
and DAL components, which can be in a proprietary language. It’s very much possible
that the whole Credit card service is made in .NET and the Address check is SAP
implementation or JAVA implementation. But because both the systems provide there
functionality using Web services which is nothing but basically XML message
communication. So we have made new service which sits like a FAÇADE on top of both
the web service and performs both functionalities in one common service. You will see I
have made a third service which sits on top of both the webservice and consumes them.
Also you can see that the UI part of the systems have access to Buisness layer and Web
service of there system. But the service which does both these check has only access to
the Web service.
Note:- It’s beyond the scope of this book to discuss about SOA. But just to keep you safe
during interview this book has tried to clear some basics of SOA.
(I)What are different ways you can pass data between tiers?
There are many ways you can pass data between tiers :-
√ Dataset the most preferred one as they maintain data in XML format.
√ Datareader
√ Custom classes.
(A)What is Windows DNA architecture?
Note :- If you have worked with classic ASP this question can come to you.
The Windows Distributed interNet Applications Architecture (DNA) is a Microsoft
blueprint for robust, scalable, distributed business software. Windows DNA has evolved
over time and was not preplanned. It gives all combined advantages of Centralized
mainframe, application servers, internet technologies and Personal computers. Windows
DNA is a evolution which started from mainframes (Where all logic was centralized) ,
Fox pro ages ( Where we talked in terms of two tier systems) , VB6 / SQL SERVER
(Three tier where we talked in terms of having one more tier which was mainly COM
where business logic resided) , COM+ ( looking in terms of transactions and fulfilling
ACID rules) and finally the DNA.
Figure :- 8.6 Windows DNA sections
Above shown is a Windows DNA model which is a blue print which Microsoft has
proposed. So if interviewer is asking you have you worked with Windows DNA , then
answer is yes. You will see that you always use these sections in project. Do not get
confused with the terminology DNA.
(A)What is aspect oriented programming?
Note :- This is something which is catching up the market so interviewer can ask you to see
how you are in touch with the market.So probably this explanation can be quiet long but
bear with me it is worth of it
I will try to be as short as possible as this book is not a reference book. Just to save you
from interviewer I will give a short description of aspect oriented programming in .NET.
First let's try to define it which can probably save you during interview
Aspect-oriented software development is a new technology for separation of concerns (SOC)
in software development. The techniques of AOSD make it possible to modularize
crosscutting aspects of a system.
Ok that statement’s can save you for the first stage let’s get down actually what is it. Let’s
revisit back how software development cycle evolved.
When we look back at times of Cobol where we used to break the modules in small
functionalities and use reusability to its maximum.
Then came the time when we talked in terms of Objects where things where clearer as
software was modeled in terms of real life examples. It worked fine and till today is the
most accepted way of implementing and organizing project. So why AOP ?
Aspect oriented programming does not oppose OOP’s but rather supports it and make’s
it more maintainable. So remove the logic from head the AOP is replacement of OOP.
No its brother of OOP helping him to be better.
When we talk in terms of object’s it’s an entity which maps to real world domain. Object
has attributes which represent the state of object and also define its behavior. By rule of
object oriented programming object should be stand alone and communicate with other
object’s using messages or defined interface.
One object should not communicate with other object directly rather communicate through
defined interfaces. Every object satisfies some “Concern” in relation to the system.
Twist: - What is Concern in AOP?
“A concern is a particular goal, concept, or area of interest”
There are mainly two types of concern from an object perspective:-
√ Core / Main concerns which it should satisfy and is his work.
I hope in my second edition i will come out with a seperate chapter on AOP
√ System concerns which are not related to business functionalities but software
related concerns example audit trail, Error handling, Security etc.
Ok let’s try to understand this principle by some actual example.
Figure :- 8.7 Customer and Audit trail relationships
Above is a class diagram which shows relationshipbetween two classes “ClsCustomer”
and “ClsAuditTrail”. “ClsCustomer” class does inserting of new customer’s in to database
and “ClsAuditTrail” does the auditing of what is changed in the customer class.
Now there are two concerns in this project :-
√ Customer code should not exceed greater than 10 length (Business level
√ All customer data which is updated should be audited. (System level concern)
Here goes the class code. If you see the ClsCustomer implementation in the update method
I have called the Audit trail implementation. If you really look from object oriented point
of view we are doing something in customer class which is supposed to be not his
implementation: - Audit Trail logging. Thus we have also broken down the rule of
encapsulation. In short the class not only handles his work but also some other work
which is not his concern.
Ok now lets define crosscutting which is one of important aspect’s of AOP.
Twist :- What is cross cutting in AOP ?
When one or many concerns span across module its called as cross cutting.Example in
our audit trail example we will probably need to audit trail for customer as well as supplier.So
Audit trail can span across other objects also that is termed as cross cutting.
Below are both the classes actually implemented as per class diagram 8.7. If you see the
“Update” method of the customer class , its doing both of the concerns that is checking
for customer code length and also maintaining the audit trail using the audit trail class.
Public Class ClsCustomer
Private pstrCustcode As String
Private pstrCustName As String
Public Property Code() As String
Return pstrCustcode
End Get
Set(ByVal Value As String)
pstrCustcode = Value
End Set
End Property
Public Property CustomerName() As String
Return pstrCustName
End Get
Set(ByVal Value As String)
pstrCustName = Value
End Set
End Property
Public Function Update() As Boolean
‘ first / core concern
If pstrCustcode.Length() > 10 Then
Throw New Exception("Value can not be greater than 10")
End If
' usingthe customer audit trail to do auditing
‘ second concern / system concern
Dim pobjClsAuditTrail As New ClsAuditTrail
With pobjClsAuditTrail
.NewValue = "1001"
.OldValue = "1003"
.UserName = "shiv"
End With
' then inserting the customer in database
End Function
End Class
Public Class ClsAuditTrail
Private pstrUserName As String
Private pstrOldValue As String
Private pstrNewValue As String
Private pdblLogTime As Double
Public Property UserName() As String
Return pstrUserName
End Get
Set(ByVal Value As String)
pstrUserName = Value
End Set
End Property
Public Property OldValue() As String
Return pstrOldValue
End Get
Set(ByVal Value As String)
pstrOldValue = Value
End Set
End Property
Public Property NewValue() As String
Return pstrNewValue
End Get
Set(ByVal Value As String)
pstrNewValue = Value
End Set
End Property
Public Property LogTime() As Double
Return pdblLogTime
End Get
Set(ByVal Value As Double)
pdblLogTime = Value
End Set
End Property
Public Sub Update()
' do the logging activity here
End Sub
End Class
In short the customer class is doing lot of activity. There is lot of tangling of code. So
how do we overcome this problem… Simple separate the System level concern (Audit
Trail) from the core level concern ( Customer code check). This is achieved at this
moment in .NET using attribute programming.
Here is the change to the customer class
Imports System.Reflection
Public Class ClsCustomer
Private pstrCustcode As String
Private pstrCustName As String
Public Property Code() As String
Return pstrCustcode
End Get
Set(ByVal Value As String)
pstrCustcode = Value
End Set
End Property
Public Property CustomerName() As String
Return pstrCustName
End Get
Set(ByVal Value As String)
pstrCustName = Value
End Set
End Property
Public Function Update() As Boolean
If pstrCustcode.Length() > 10 Then
Throw New Exception("Value can not be greater than 10")
End If
' usingthe customer audit trail to do auditing
' then inserting the customer in database
End Function
End Class
And here is the change to the audit trail class
Imports System.Reflection
Public Class ClsAuditTrail
Inherits Attribute
Private pstrUserName As String
Private pstrOldValue As String
Private pstrNewValue As String
Private pdblLogTime As Double
Public Property UserName() As String
Return pstrUserName
End Get
Set(ByVal Value As String)
pstrUserName = Value
End Set
End Property
Public Property OldValue() As String
Return pstrOldValue
End Get
Set(ByVal Value As String)
pstrOldValue = Value
End Set
End Property
Public Property NewValue() As String
Return pstrNewValue
End Get
Set(ByVal Value As String)
pstrNewValue = Value
End Set
End Property
Public Property LogTime() As Double
Return pdblLogTime
End Get
Set(ByVal Value As Double)
pdblLogTime = Value
End Set
End Property
Public Sub New(ByVal pstrUserName As String, _
ByVal pstrOldValue As String, _
ByVal pstrnewValue As String, _
ByVal plng As Long)
End Sub
Public Sub Update()
' do the logging activity here
End Sub
End Class
The fun part of the code is below , you can see that the code audit trail is now seperate
and the code check belongs to the customer code.
Public Function Update() As Boolean
If pstrCustcode.Length() > 10 Then
Throw New Exception("Value can not be greater than 10")
End If
' usingthe customer audit trail to do auditing
' then inserting the customer in database
End Function
Note:- Architecture is everybodys favorite and the wide combination is difficult to be covered
in this book. Many of the things can only come by live experience.

.NET Interoperability

√ Using Type library import tool. Tlbimp.exe yourname.dll.
√ Using interopservices.System.runtime.Interopservices namespace contains class
TypeLib Converter which provides methods to convert COM classes and interface in
to assembly metadata.
√ Make your custom wrappers.If your COM component does not have type library
then the only way to communicate is writing custom wrappers. That means
communicating directly with COM components.
(I) Once i have developed the COM wrapper do i have to still register the
COM in registry?
(A)How can we use .NET components in COM?
Twist :- What is CCW (COM callable wrapper) ?, What caution needs to be taken in
order that .NET components is compatible with COM ?
.NET components can not be used in straight forward way with COM.You will need to create
CCW in order that COM components communicate with .NET assemblies.Following are the
different approaches to implement it :-
√ Explicitly declare interfaces..
Public Interface ICustomer
Property CustomerName() As String
Property CustomerCode() As String
Sub AddCustomer()
End Interface
Public Class Customer
Implements ICustomer
Private PstrCustomerName As String
Private PstrCustomerCode As String
Public Sub AddCustomer() Implements ICustomer.AddCustomer
‘ addin of database code can go here
Catch ex As Exception
Throw ex
End Try
End Sub
Public Property CustomerCode() As String Implements
Return PstrCustomerCode
End Get
Set(ByVal value As String)
PstrCustomerCode = value
End Set
End Property
Public Property CustomerName() As String Implements
Return PstrCustomerName
End Get
Set(ByVal value As String)
PstrCustomerName = value
End Set
End Property
Public Sub New()
End Sub
End Class
Note :- Source code of this is provided in CD in CODE folder in
The above customer class is going to be used by COM components so all the properties and
methods are declared in interface and implemented in the customer class.Customer Name.Customer
Code and AddCustomer are first declared in ICustomer and then implemented in Customer
Class.Note also the class must have a default constructor.
Note :- All source code in this book is provided in VB.NET that does not mean that
author of the book does not like C#. In fact the main programming language of author is
C#.In order to keep things small i have only used one language.But the conversion is so
seamless its of least matter.
√ The second way to create CCW using InteropServices attributes.Here interfaces are
created automatically.
Following are different type of class attributes :
None :No class interface is generated for the class.This is default setting when you do not specify
AutoDispatch :- Interface that supports IDispatch is created for the class. However, no type
information is produced.
AutoDual :- A dual interface is created for the class. Typeinfo is produced and made available in
the type library.
In below source code we have used the third attribute.
Imports System.Runtime.InteropServices
Public Class ClsCompliant
End Class
Other than class attributes defined up there are other attributes with which you can govern other
part of assembly.Example “GuidAttribute” allows you to specify the GUID,”ComVisibleAttribute
“ can be used to hide .NET types from COM etc.All attributes are not in scope of the book as
this is a interview questions book refer MSDN for more details.
√ Once .NET assembly is created using either interface or using interopservices method
we need to create a COM type library using Type library export tool.
Tlbexp (AssemblyName)
√ The final thing is registering the CCW in registry using regasm tool.
regasm AssemblyName [Options]
√ Finally refer the TLB in your COM IDE Below is figure showing VB6 IDE referencing
the DLL
Note :- DLL and TLB should be in same directory where the application is executed.
Figure :- 2.2 VB6 IDE referencing the CCW
(A)How can we make Windows API calls in .NET?
Windows API call are not COM based and are invoked through Platform Invoke Services.
Declare StringConversionType (Function | Sub) MethodName Lib "DllName" ([Args])
As Type
√ StringConversionType is for what type of conversion should take place.Either we
can specify Unicode to convert all strings to Unicode values, or Auto to convert
strings according to the .NET runtime rules.
√ MethodName is the name of the API to call.
√ DllName is the name of the DLL.
√ Args are any arguments to the API call.
√ Type is the return type of the API call.
Below is a sample code for VB.NET which uses Sleep windows API for delaying.
Public Class Form1
Declare Auto Sub Sleep Lib “kernel32.dll” (ByVal dwMilliseconds
As Long)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
MessageBox.Show(“ start sleeping for 5000 Milli
MessageBox.Show(“ end of sleeping.....”)
End Sub
End Class
In VB.NET we use declare keyword but in C# it goes little bit different we use DLLIMPORT
Note :- We have interopservices in this and EXTERN keyword.
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CSharpCode
partial class Form1 : Form
static extern int Sleep(long dwMilliseconds);
public Form1()
private void Form1_Load(object sender, EventArgs e)
MessageBox.Show(“Starting of 5000 ms...”);
MessageBox.Show(“End of 5000 ms...”);
(B)When we use windows API in .NET is it managed or unmanaged code
Windows API in .NET is unmanaged code.
Note:- Even though VB6 and V C++ has gone off still many people do ask these old
questions again and again.Still there are decent old application which are working with
COM very much fine.So interviewer still asks you these questions so that those application’s
can be ported to .NET.So let’s play some old music..... By the way my favourite music is
Kishore what’s yours????
(I)What is COM ?
Microsoft’s COM is a technology for component software development. It is a binary standard
which is language independent. DCOM is a distributed extension of COM.
(A) What is Reference counting in COM ?
Reference counting is a memory management technique used to count how many times an object
has a pointer referring to it. The first time it is created, the reference count is set to one. When the
last reference to the object is nulled, the reference count is set to zero and the object is deleted.
Care must be exercised to prevent a context switch from changing the reference count at the time
of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion
brief and manageable.
(A) Can you describe IUKNOWN interface in short ?
Every COM object supports at least one interface, the IUnknown interface. All interfaces are
classes derived from the base class IUnknown. Each interface supports methods access data and
perform operations transparently to the programmer. For example, IUnknown supports three
methods, AddRef, Release(), and QueryInterface(). Suppose that pinterf is a pointer to an IUnknown.
pinterf->AddRef() increments the reference count. pinterf->Release() decrements the reference
count, deleting the object when the reference count reaches zero. pinterf->QueryInterface( IDesired,
pDesired) checks to see if the current interface (IUnknown) supports another interface, IDesired,
creates an instance (via a call to CoCreateInstance()) of the object if the reference count is zero (the
object does not yet exist), and then calls pDesired->AddRef() to increment the reference count
(where pDesired is a pointer to IDesired) and returns the pointer to the caller.
(I)Can you explain what is DCOM ?
DCOM differs from COM in that it allows for creating objects distributed across a network, a
protocol for invoking that object’s methods, and secure access to the object. DCOM provides a
wrapper around COM, hence it is a backwards compatible extension. DCOM uses Remote
Procedural Calls (RPC) using Open Software Foundation’s Distributed Computing Environment.
These RPC are implemented over TCP/IP and named pipes. The protocol which is actually being
used is registered just prior to use, as opposed to being registered at initialization time. The reason
for this is that if a protocol is not being used, it will not be loaded.
In order to inform an object that the client is still alive, periodic pinging is used. Hence, when the
client has died and no ping has been received (to refresh it) before the expiration time, the server
object will perform some clean up tasks (including decrementing its reference count).
Since RPC across a network are typically slow (compared to processes residing on the same
machine), DCOM sends multiple requests in the same call. For example, in COM, the program
performs a QueryInterface, one interface at a time. In DCOM, multiple QueryInterfaces are all
clustered into one call.
This clustering optimization trick is also used when creating an instance of the object and serializing
it with data. Since these two operations usually occur together, DCOM allows one method which
will perform both operations in one call without waiting for an acknowledgment from the first
task before performing the second one.
Similarly, when a client pings its server object, he can do it in one call. Moreover, if there are
multiple clients sending pings to multiple servers, an optimization is made where the multiple
pings going to the same object are consolidated into just one ping. This is to cut down on the use
of precious bandwidth used only for pinging.
The client has the control to set the computer which will be responsible for the lifetime of the
object. That is to say, these objects are not created just somewhere where the system resources and
access privileges allow for it.
Call security is implemented in all four ways: authentication (to prevent false clients from
impersonating the true client), authorization (to insure that a client only does what it is authorized
to do), data integrity (to insure that data was not tampered with during transit) and data privacy (to
insure that only designated sources can read it). The security issues are handled as they are on
operating systems. The client gives the server various access privileges to access memory or disk
(B)How do we create DCOM object in VB6?
Using the CreateObject method you can create a DCOM object. You have to put the server
name in the registry.
(A)How to implement DTC in .NET ?
DTC is implemented using COM+ .
Following are the steps to implement COM + in .NET :-
√ “EnterpriseService” namespace has all the classes by which we can implement DTC
in .NET. You have to add reference “EnterpriseService” namespace.
Figure :- 2.3 Add reference to EnterpriseServices.
√ You class must derive from “Serviced Component” object.
√ Then you have to define your class with the transaction attribute
(For all transaction attribute look the down question)
[ Transaction(TransactionOption.RequiresNew) ]
√ After the class level transaction type is defined.Its time to define at the method level
the AutoComplete attribute. Autocomplete attribute says that if no exception is thrown
then mark its part of the transaction as being okay. This helps cut down on the
amount of code required. If the implementation sets AutoComplete to false, or
omits it all together, then we would need to manage the transaction manually. To
manually control the transaction you will need to use the ContextUtil class and its static
members.Following is small snippet of ContextUtil: -
public void SampleFunction()
// Do something to a database
// ...
// Everything okay so far Commit the transaction
// Something went wrong Abort and Rollback the Transaction.
√ Component derived from “ServicedComponent” should be strong named as they
run under COM+.
√ Once the classes are compiled using the string name.Register the Component in COM+
services using
regsvcs c:\DllPath\TransactionComponent.dll
√ You can see that the component is registered using the COM+ explorer.
(A)How many types of Transactions are there in COM + .NET ?
There are 5 transactions types that can be used with COM+. Whenever an object is registered with
COM+ it has to abide either to these 5 transaction types.
Disabled: - There is no transaction. COM+ does not provide transaction support for this
Not Supported: - Component does not support transactions. Hence even if the calling component
in the hierarchy is transaction enabled this component will not participate in the transaction.
Supported: - Components with transaction type supported will be a part of the transaction if the
calling component has an active transaction.If the calling component is not transaction enabled this
component will not start a new transaction.
Required: - Components with this attribute require a transaction i.e. either the calling should have
a transaction in place else this component will start a new transaction.
Required New: - Components enabled with this transaction type always require a new transaction.
Components with required new transaction type instantiate a new transaction for themselves every
(A)How do you do object pooling in .NET ?
COM+ reduces overhead by creating object from scratch. So in COM+ when object is activated
its activated from pool and when its deactivated it’s pushed back to the pool. Object pooling is
configures by using the “ObjectPoolingAttribute” to the class.
Note:- When a class is marked with objectpooling attribute it can not be inherited.
ObjectPooling(MinPoolSize := 2, MaxPoolSize := 5, CreationTimeout := 20000)> _
Public Class testingclass
Inherits ServicedComponent
Public Sub DoWork()
' Method contents go here.
End Sub
End Class
Above is a sample code which has the “ObjectPooling” attribute defined. Below is a sample code
which uses the class.
Public Class App
Overloads Public Shared Sub Main(args() As String)
Dim xyz As New TestObjectPooling()
ServicedComponent.DisposeObject (xyz)
End Sub
End Class
Above is a sample code which uses the object pooled object. Note the DisposeObject() This
ensures its safe return to the object pool.
(A)What are types of compatibility in VB6?
There are three possible project compatibility settings:
√ No Compatibility
√ Project Compatibility
√ Binary Compatibility
No Compatibility
With this setting, new class ID’s, new interface ID’s and a new type library ID will be generated by
VB each time the ActiveX component project is compiled. This will cause any compiled client
components to fail (with error 429!) and report a missing reference to the 'VB ActiveX Test
Component' when a client project is loaded in the VB IDE.
Note :- Use this setting to compile the initial release of a component to other developers.
Project Compatibility
With this setting, VB will generate new interface ID’s for classes whose interfaces have changed,
but will not change the class ID’s or the type library ID. This will still cause any compiled client
components to fail (with error 429!) but will not report a missing reference to the 'VB ActiveX
Test Component' when a client project is loaded in the VB IDE. Recompilation of client
components will restore them to working order again.
Note:- Use this setting during the initial development and testing of a component within
the IDE and before the component is released to other developers.
Binary Compatibility
VB makes it possible to extend an existing class or interface by adding new methods and properties
etc. and yet still retain binary compatibility. It can do this, because it silently creates a new interface
ID for the extended interface and adds registration code to register the original interface ID but
with a new Forward key containing the value of this new interface ID. COM will then substitute
calls having the old ID with the new ID and hence applications built against the old interface will
continue to work (assuming the inner workings of the component remain backward compatible!).
With this setting, VB will not change any of the existing class, interface or type library ID’s, however
in order that it can do so, VB requires the project to specify an existing compiled version that it can
compare against to ensure that existing interfaces have not been broken
(A)What is equivalent for regsvr32 exe in .NET ?

Basic .NET Framework

*How much do you rate yourself in .NET in one out of ten ?

Microsoft introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype in
C++ will convert it to System.int32 which is datatype of CTS.CLS which is covered in the coming
question is subset of CTS.
If you have undergone COM programming period interfacing VB6 application with
VC++ application was a real pain as the datatype of both languages did not have a
common ground where they can come and interface , by having CTS interfacing is smooth.
(B)What is a CLS(Common Language Specification)?
This is a subset of the CTS which all .NET languages are expected to support.It was always a
dream of microsoft to unite all different languages in to one umbrella and CLS is one step
towards that.Microsoft has defined CLS which are nothing but guidelines that language to follow
so that it can communicate with other .NET languages in a seamless manner.
(B)What is a Managed Code?
Managed code runs inside the environment of CLR i.e. .NET runtime.In short all IL are managed
code.But if you are using some third party software example VB6 or VC++ component they are
unmanaged code as .NET runtime (CLR) does not have control over the source code execution
of the language.
(B)What is a Assembly ?
√ Assembly is unit of deployment like EXE or a DLL.
√ An assembly consists of one or more files (dlls, exe’s, html files etc.), and
represents a group of resources, type definitions, and implementations of those
types. An assembly may also contain references to other assemblies. These
resources, types and references are described in a block of data called a manifest.
The manifest is part of the assembly, thus making the assembly self-describing.
√ An assembly is completely self-describing.An assembly contains metadata
information, which is used by the CLR for everything from type checking and
security to actually invoking the components methods.As all information is in
assembly itself it is independent of registry.This is the basic advantage as
compared to COM where the version was stored in registry.
√ Multiple versions can be deployed side by side in different folders. These
different versions can execute at the same time without interfering with each
other.Assemblies can be private or shared. For private assembly deployment,the
assembly is copied to the same directory as the client program that references
it.No registration is needed, and no fancy installation program is required.
* Never talk for more than 1 minutes straight during interview.
*Do not memorize each and every answer of this book.Just get the fundamentals straight and say in your own words.
When the component is removed, no registry cleanup is needed,and no uninstall
program is required. Just delete it from the hard drive.
√ In shared assembly deployment, an assembly is installed in the Global Assembly
Cache (or GAC). The GAC contains shared assemblies that are
globally accessible to all .NET applications on the machine.
(A) What are different types of Assembly?
There are two types of assembly Private and Public assembly.A private assembly is normally used
by a single application, and is stored in the application's directory, or a sub-directory beneath. A
shared assembly is normally stored in the global assembly cache, which is a repository of assemblies
maintained by the .NET runtime. Shared assemblies are usually libraries of code which many
applications will find useful, e.g. Crystal report classes which will be used by all application for
(B) What is NameSpace?
Namespace has two basic functionality :-
√ NameSpace Logically group types.Example System.Web.UI logically groups
our UI related features.
√ In Object Oriented world may times its possible that programmers will use the
same class name.By qualifying NameSpace with classname this collision can
be removed.
(B) What is Difference between NameSpace and Assembly?
Following are the differences between namespace and assembly :
√ Assembly is physical grouping of logical units. Namespace logically groups
√ Namespace can span multiple assembly.
(A)If you want to view a Assembly how to you go about it ?
Twist : What is ILDASM ?
When it comes to understanding of internals nothing can beat ILDASM.ILDASM basically converts
the whole exe or dll in to IL code.To run ILDASM you have to go to "C:\Program Files\Microsoft
*Is your experience fully in .NET , or do you have any prior experience in other
microsoft technology like VB6,VC++ etc
*Can you give me two references of your previous company whom i can contact ?
Visual Studio .NET 2003\SDK\v1.1\Bin". Note that i had v1.1 you have to probably change it
depending on the type of framework version you have.
If you run IDASM.EXE from the path you will be popped with the IDASM exe program as
shown in figure ILDASM.Click on file and browse to the respective directory for the DLL whose
assembly you want to view.After you select the DLL you will be popped with a tree view details
of the DLL as shown in figure ILDASM.On double clicking on manifest you will be able to view
details of assembly , internal IL code etc as shown in Figure Manifest View.
Note : The version number are in the manifest itself which is defined with the DLL or
EXE thus making deployment much easier as compared to COM where the information
was stored in registry.Note the version information in Figure Manifest view.
You can expand the tree for detail information regarding the DLL like methods etc.
* Do not mention client name’s in resume.If asked say that it’s confidential which brings
ahead qualities like honesty.
*When you make your resume keep you recent projects at the top.
*It must be hard to leave the previous company , as you have spend quiet a lot time
with them ?
Figure:- 1.1 ILDASM
Note :- * Find out what the employer is looking for by asking him questions at the start of
interview and best is before going to interview.Example if a company has projects on server
products employer will be looking for Biztalk , CS CMS experts.
* What’s your family background ?
* If you are fresher this is a common question.You do not have experience in .NET so why do you think you are suitable for this
job ?
Figure :- 1.2 Manifest View
(A) What is Manifest?
Assembly metadata is stored in Manifest.Manifest contains all the metadata needed to do the
following things( See Figure Manifest View for more details) :
√ Version of assembly
√ Security identity
√ Scope of the assembly
√ resolve references to resources and classes.
√ The assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a stand-alone PE file that
contains only assembly manifest information.
* Have you heard about our company ? Say five points about our company ? Just read atleast
once what company you are going for ?
* Which is the best project you have done till now ? and in what sense the project was the best ?
(B)Where is version information stored of a assembly ?
Version information is stored in assembly in manifest.
(I)Is versioning applicable to private assemblies?
Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
there individual folders.
(B) What is GAC ?
Twist :- What are situations when you register .NET assembly in GAC ?
GAC (Global Assembly Cache) is used where shared .NET assembly reside.GAC is used in the
following situations :-
√ If the application has to be shared among several application.
√ If the assembly has some special security requirements like only administrators
can remove the assembly.If the assembly is private then a simple delete of
assembly the assembly file will remove the assembly.
Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell.
Where COM version was stored in central registry.So GAC should be used when
absolutely necessary.
(I) What is concept of strong names ?
Twist :- How do we generate strong names or what is the process of generating strong names
, What is use of SN.EXE , How do we apply strong names to assembly ? , How do you
sign an assembly ?
Strong name is similar to GUID(It is supposed to be unique in space and time) in COM
components.Strong Name is only needed when we need to deploy assembly in GAC.Strong
Names helps GAC to differentiate between two versions.Strong names use public key cryptography
(PKC) to ensure that no one can spoof it.PKC use public key and private key concept.
Following are the step to generate a strong name and sign a assembly :-
* Which is the biggest size of team you have worked with and was there any lead
involved from your side ?
* Do you work on staurday’ and sunday’s ?
√ Go to “Visual Studio Command Prompt”.See below figure to “Visual studio
Command Prompt”.Note the samples are compiled in 2005 but 2003 users do
not have to worry about it.Same type of command prompt will be seen in
2003 also.
Figure :- 1.3 Visual Studio Command Prompt
√ After you are in command prompt type sn.exe -k “c:\test.snk”.
Figure :- 1.4 Running SN.EXE
* Have you done any kind of certification ?
* What’s the notice period for your previous company ?
Figure :- 1.5 Successful output of SN.EXE
Figure :- 1.6 Sample view of test.snk file
√ After generation of the file you can view the SNK file in a simple notepad.
√ After the SNK file is generated its time to sign the project with this SNK file.
* Do you have passport size photos , passport , final year graduation certificate etc. etc.Be sure to take these documents
with you.Do not know for these small things some companies do eliminate candidates.
* Have you worked with any server products like Biztalk,CMS , CS etc.
Figure:- 1.7 Click on project and then click on “classlibrary1 properties” menu to sign the assembly
√ Click on project -- properties and the browse the SNK file to the respective
folder and compile the project.
*Which is your favorite VB6 or VB.NET.....Just do not get in to arguments ?
* What’s your favorite VB.NET or C#....Prepare a diplomatic answer.... Do not get in to arguments.
Figure :- 1.8 Click on Use a key file to sign the assembly with strong name
(I)How to add and remove a assembly from GAC?
There are two ways to install .NET assembly in GAC:-
√ Using Microsoft Installer Package.You can get download of installer from
√ Using Gacutil. Goto “Visual Studio Command Prompt” and type “gacutil –i
(assembly_name)”.Where (assembly_name) is the DLL name of the project.
* If you fail in one interview does not mean you have to disappointed.Keep trying IT
industry has lot in store.
* As a interviewer always remember that you will also be sitting sometimes at the other end.So do not ask any psyche
question which does not judge anything of a candidate.
(B) What is Delay signing ?
During development process you will need strong name keys to be exposed to developer which
will is not a good practice from security aspect point of view.In such situations you can assign the
key later on and during development you an use delay signing
Following is process to delay sign a assembly:
√ First obtain your string name keys using SN.EXE.
√ Annotate the source code for the assembly with two custom attributes from
System.Reflection: AssemblyKeyFileAttribute, which passes the name of the file
containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute,
which indicates that delay signing is being used by passing true as a parameter to its
constructor. For example as shown below:
[Visual Basic]

The compiler inserts the public key into the assembly manifest and reserves space in the PE file for
the full strong name signature. The real public key must be stored while the assembly is built so
that other assemblies that reference this assembly can obtain the key to store in their own assembly
√ Because the assembly does not have a valid strong name signature, the verification of
that signature must be turned off. You can do this by using the –Vr option with the
Strong Name tool.The following example turns off verification for an assembly called
Sn –Vr myAssembly.dll
√ Just before shipping, you submit the assembly to your organization's signing authority
for the actual strong name signing using the –R option with the Strong Name tool.The
following example signs an assembly called myAssembly.dll with a strong name using
the sgKey.snk key pair.
Sn -R myAssembly.dll sgKey.snk
(B)What is garbage collection?
Garbage collection is a CLR feature which automatically manages memory. Programmers forget
to release the objects while coding ..... laziness ( Remember in VB6 where one of the good
practices is to set object to nothing).CLR automatically releases objects when they are no longer
referenced and in use.CLR runs on non-deterministic to see the unused objects and cleans them.
One side effect of this non-deterministic feature is that we cannot assume an object is destroyed
when it goes out of the scope of a function. Therefore, we should not put code into a class
destructor to release resources.
(I) Can we force garbage collector to run ?
System.GC.Collect() forces garbage collector to run.This is not recommended but can be used if
situations arises.
(B)What is reflection?
All .NET assemblies have metadata information stored about the types defined in modules.This
metadata information can be accessed by mechanism called as “Reflection”.System.Reflection can
be used to browse through the metadata information.
Using reflection you can also dynamically invoke methods using System.Type.Invokemember.Below
is sample source code if needed you can also get this code from CD provided , go to “Source
code” folder in “Reflection Sample” folder.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim Pobjtype As Type
Dim PobjObject As Object
Dim PobjButtons As New Windows.Forms.Button()
Pobjtype = PobjButtons.GetType()
For Each PobjObject In Pobjtype.GetMembers
End Sub
End Class
Note :- Sample source code are compiled using VB.NET 2005.
Figure:- 1.9 Sample reflection display
Sample source code uses reflection to browse through “Button” class of “Windows.Forms”.If
you compile and run the program following is output as shown in “Sample Reflection Display”.Using
reflection you can also dynamically invoke a method using “System.Type.InvokeMember”.
Note :- System.Type.InvokeMember is left as homework for readers.Believe me you will
enjoy doing it yourself and the concept of reflection will be more clearer.
(P)What are different type of JIT ?
Note :- This question can only be asked when the interviewer does not know what he
wants.It was asked to me in one of interview and for 15 minutes he was roaming around
the same question in order to get answer from me (requirement was for a simple database
project). Beware of such companies and interviewers you can land up no where.
JIT compiler is a part of the runtime execution environment.
In Microsoft .NET there are three types of JIT compilers:
√ Pre-JIT. Pre-JIT compiles complete source code into native code in a single compilation
cycle. This is done at the time of deployment of the application.
√ Econo-JIT. Econo-JIT compiles only those methods that are called at runtime.
However, these compiled methods are removed when they are not required.
√ Normal-JIT. Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in
cache. When the same methods are called again, the compiled code from cache is
used for execution.
(B) What are Value types and Reference types ?
Value types directly contain their data are either allocated on the stack or allocated in-line in a
Reference types store a reference to the value's memory address, and are allocated on the heap.
Reference types can be self-describing types, pointer types, or interface types.
Variables that are value types each have their own copy of the data, and therefore operations on
one variable do not affect other variables. Variables that are reference types can refer to the same
object; therefore, operations on one variable can affect the same object referred to by another
variable.All types derive from the System.Object base type.
(B) What is concept of Boxing and Unboxing ?
Boxing permits any value type to be implicitly converted to type object or to any interface type
implemented by value type.Boxing is process in which a object instances created and copying
value types value in to that instance.
Unboxing is vice versa of boxing operation where the value is copied from the instance in to
appropriate storage location.
Below is sample code of boxing and unboxing where integer data type is converted in to object
and then vice versa.
Dim x As Integer
Dim y As Object
x = 10
‘ boxing process
y = x
‘ unboxing process
x = y
(B) What’s difference between VB.NET and C# ?
Well this is the most debatable issue in .NET community and people treat there languages like
religion.Its a subjective matter which language is best.Some like VB.NET’s natural style and some
like professional and terse C# syntaxes.Both use the same framework and speed is also very much
equivalents . But still lets list down some major differences between them :-
Advantages VB.NET :-
√ Has support for optional parameters which makes COM interoperability much easy.
√ With Option Strict off late binding is supported.Legacy VB functionalities can be
used by using Microsoft.VisualBasic namespace.
√ Has the WITH construct which is not in C#.
√ The VB.NET part of Visual Studio .NET compiles your code in the background.
While this is considered an advantage for small projects, people creating very large
projects have found that the IDE slows down considerably as the project gets larger.
Advantages of C#
√ XML documentation is generated from source code but this is now been incorporated
in Whidbey.
√ Operator overloading which is not in current VB.NET but is been introduced in
√ The using statement, which makes unmanaged resource disposal simple.
√ Access to Unsafe code. This allows pointer arithmetic etc, and can improve
performance in some situations. However, it is not to be used lightly, as a lot of the
normal safety of C# is lost (as the name implies).This is the major difference that you
can access unmanaged code in C# and not in VB.NET.
* How much ever this book tries it can not match the huge variations of questions that's
been asked in.NET interviews.But note they will be variations and they will map to some
question of this book.
(I)What’s difference between System exceptions and Application
All exception derives from Exception Base class. Exceptions can be generated programmatically
or can be generated by system. Application Exception serves as the base class for all application36
specific exception classes. It derives from Exception but does not provide any extended functionality.
You should derive your custom application exceptions from Application Exception.
Application exception are used when we want to define user defined exception. While system
exception are all which are defined by .NET.
Figure :- 1.9 Exception Hierarchy
Note:- Frankly I have always relied on using Microsoft exception application blocks. As
such I have never used application exception; I think most of the work is done using System
exception classes.
(I)What is CODE Access security?
CAS is part of .NET security model that determines whether or not a piece of code is allowed to
run and what resources it can use while running. Example CAS will allow a application to read but
now write and delete rights are given to the application.
(I)What is a satellite assembly?
In multilingual application in .NET to support multilingual functionality you can have modules
which are customized for localization.These assemblies are called as satellite assemblies. You can
distribute these assemblies separately than the core modules.

Monday, June 23, 2008

What is .NET Framework 3.0 ?

.NET Framework 3.0 is a milestone for developing applications on the Windows operating system. Built on the top the .NET Framework 2.0, .NET Framework 3.0 is a set of managed APIs that provide enhanced functionality for messaging, workflow, and presentation.

Key components of .NET Framework 3.0 include:

❑ Windows Presentation Foundation (WPF)—The graphical subsystem for all things related to the UI.
❑ Windows Communication Foundation (WCF)—The messaging subsystem of .NET
Framework 3.0, securing program communication through a single API
❑ Windows Workflow Foundation (WF)—Provides workflow services for applications built to run on Windows

As the new programming model for Windows Vista, .NET Framework 3.0 fuses the Windows platform with applications developed using Visual Studio 2005. With direct access to low-level services of the operating system and hardware surface, .NET Framework 3.0 provides a compelling solution for creating applications with a rich UX.

Although WCF and WF are equally important components of .NET Framework 3.0, they are beyond the scope of this book. For more information on WCF and WF, visit the .NET Framework Developer Center
on MSDN (

Monday, June 16, 2008

IEnumerable with expensive resources

Often IEnumerable types allocate scarce resources in GetEnumerator(). For example, the IEnumerator returned from GetEnumerator may hold a reference to an expensive array of Disposable objects. Such IEnumerator types should implement the IDisposable interface to allow explicit cleanup.
internal class ExpensiveEnumerator: IEnumerator, IDisposable{


public class ExpensiveCollection: IEnumerable{
public IEnumerator GetEnumerator(){
return new ExpensiveEnumerator();


Some languages, for example C# and VB.NET, will call Dispose on enumerators that implement IDisposable when the foreach statement completes.
ExpensiveCollection expensive = new ExpensiveCollection();
foreach(ExpensiveItem in expensiveCollection){

} // Dispose will be called on the IEnumerator when the loop terminates

Resource Collector Pattern

There are scenarios in which the ownership of Disposable or Both objects is not well defined. For example, the reference to an object may be handed off to multiple clients. In such scenarios, it is very difficult, if not impossible, to dispose the scarce resource as soon as it is no longer needed. None of the clients knows when the other clients are done with the object.
One set of solutions to the problem relies on letting the finalizer collect the resources and just forcing the GC to collect more often than it normally would. We call such solutions Resource Collectors. Resource Collectors helps to minimize the time between when the resource is available for collection and the time when the finalizer actually runs and releases the resource. One drawback of such an approach is that forcing collection, if abused, may actually lead to performance loss. Good implementations of the pattern employ clever algorithms determining when forced collection should be executed.
One such implementation, a component called HandleCollector, can be downloaded from the GotDotNet site (http://GotDotNet). The collector maintains a counter of “live” resources. The counter is incremented when a resource is allocated and is decreased when the resource is released by the finalizer. When a new resource is about to be allocated and the counter is greater than an application specified threshold, collection is forced by a call to GC.Collect.
A degenerated version of a Resource Collector implementation uses a timer to force collection at specified intervals. Such an implementation is discouraged. The implementation described above is much better at forcing collection when needed and avoiding unnecessary collections which may significantly impair performance and scalability.

Disposable Types

Implement this variation for types that allocate, directly or indirectly, only managed resources, and for which most classes derived from the type will also allocate only managed resources. System.Web.UI.Control is an example. The Web Control base class has no unmanaged resources, and most classes derived from it won't either. This is why it does not need a finalizer. However, it is common for such controls to have other managed resources (SqlConnection, MessageQueue, etc.) that implement IDisposable interface, so it implements IDisposable as well to allow these to be cleaned up early.
public class DisposableOnly: IDisposable{
MessageQueue queue;
bool disposed = false;

public DisposableOnly(string path){
queue = new MessageQueue(path);

public virtual void Dispose(){
queue = null;
disposed = true;

public void SendMessage(string message){
throw new ObjectDisposedException(this.ToString());


After Dispose() is called, objects are free to throw ObjectDisposedException from any instance method except Dispose(). Dispose() can be called multiple times and should never throw ObjectDisposedException. An alternative is to allow an object to be resurrected by reacquiring resources when a method is called on already disposed object. For example:
public class DisposableResurrectableOnly: IDisposable{
MessageQueue queue;
bool disposed = false;

public DisposableOnly(string path){
queue = new MessageQueue(path);

public virtual void Dispose(){
queue = null;
disposed = true;

public void SendMessage(string message){


protected void Ressurect(){
queue = new MessageQueue();
disposed = false;

Some types may want to provide an additional cleanup method with a domain specific name. For example, SqlConnection class provides the method Close. Such method should just call Dispose().

Finalizable Types

This variation should be implemented carefully, only after fully considering all the ramifications. Types implementing this variation may cause system starvation if scarce resources are left allocated for longer than needed. In most cases the best coarse of action is to implement the full Disposable and Finalizable (Both) TypesDisposable and Finalizable (Both) Types variation described in section 3.4.
Only types that acquire unmanaged but not scarce resources and zero or more Simple types should implement this variation. For example, a type that allocates only a very small blob of unmanaged memory falls into this category. In such cases having a finalizer ensures that the memory is released but does not oblige clients to call Dispose. This is a rare case and should not be used in most implementations.
public class FinalizableOnly{
IntPtr nativeMemory = Marshal.AllocHGlobal(4);



Simple Types

This variation applies to types that hold references to only other managed objects that do not implement IDisposable and do not have Finalizers. This includes ensuring that no internal container, for example ArrayList, stores objects that require explicit resource cleanup. In such case, you don’t need to do anything special in terms of resource management.
public class SimpleType{
ArrayList names = new ArrayList();


Using IDisposable Types

Instances of types implementing the IDisposable interface need to be handled very carefully, especially in the presence of possible exceptions. For example, the following code may actually result in the resource not getting disposed
MessageQueue queue = new MessageQueue(“server\\queueName”);
queue.Send(“Hello World”);

If the Send operation throws an exception, the call to Dispose on the following line will not get executed.
A better way to implement the code is to dispose resources in a finally block, which always gets executed, even when an exception is thrown.
MessageQueue queue;
queue = new MessageQueue(“server\\queueName”);
queue.Send(“Hello World”);

The codes become more robust but also a bit less readable. The readability problem is even more pronounced in the case of two resources that need to be disposed, since such scenarios require nested try-finally blocks.
MessageQueue source;
MessageQueue destination;
source = new MessageQueue(“server\\sourceQueue”);
Message message = source.Receive();
destination = new MessageQueue(“server\\destinationQueue”);

Unfortunately, the code above lost a lot of its original simplicity. This is why some languages, including C#, introduced the using statement. The statement has semantics similar to the code above without sacrificing simplicity. It expands to multiple try-finally blocks and automatically calls Dispose() on IDisposable objects created inside the using clause.
MessageQueue source = new MessageQueue(“server\\sourceQueue”),
destination = new MessageQueue(“server\\destinationQueue”)
Message message = source.Receive();

If you work with languages that don’t provide support similar to like the using statement, you should implement the fully expanded code manually.

Releasing Unmanaged Resources

Any type allocating unmanaged resources, either directly or indirectly, has to provide a mechanism to release the resources. The simplest way of releasing an unmanaged resource is to release it in the Finalizer of the type owning the resource. This approach is perfectly fine for releasing resources that do not have limits on how many you can acquire and do not have a cost associated with keeping them acquired longer than absolutely necessary. Unfortunately, most unmanaged resources are not limitless and not free; rather they are scarce. Database connection is a perfect example of a scarce resource; you can open only a limited number them.
Finalizers are not very good at releasing scarce resources. They run too late. GC starts collection, and runs finalizers, when it detects memory allocation problems. It is not able to detect unmanaged resource allocation problems.
The solution is to provide clients of types that acquire scarce resources with a way to explicitly release the resources. This way the client can release the resources as soon as they are not needed anymore. For example:
MessageQueue queue = new MessageQueue(path);queue.Send(message);
queue.Dispose(); // explicitly release queue handle

To formalize and organize the process of releasing scarce resources, we have defined a couple of design guidelines and the IDisposable interface.
public interface IDisposable {
public void Dispose();

This defines a basic interface that declares the Dispose method, which is designed to be a common cleanup routine. When you implement this interface on a type, you are advertising that instances of that type allocate scarce resources. Some scenarios require clients to explicitly release the resources and some don’t. When in doubt, play it safe and always release the resource by making sure Dispose is called after the object is no longer needed.
For example, common implementations of server applications instantiate a new resource in every request, use the resource, and then release it. Such implementations will result in the cycle of allocate->use->release being repeated many times during the lifetime of the application. If the resource is scarce, it is desirable for the cycle to be as short as possible to maximize the number of requests that the application can process per unit of time. Calling Dispose() immediately after the resource is no longer needed will result in maximum throughput of the application.
Also, some multi-user client applications using resources that are shared among users should dispose the resources as soon as possible. This will prevent problems in which some users are denied access to a resource only because another user’s resource is waiting in the finalization queue. Holding a database connection open for longer than needed is a good example of such a programming mistake.
Single user applications, which don’t share scarce resources with other applications, don’t require such urgency in disposing resources. For example, a command line tool that creates a MessageQueue, sends a message, and terminates doesn’t need to explicitly dispose the MessageQueue instance. Please note that if the same code were executed in a server request, it would certainly cause a throughput problem.

Managing Scarce Resources

Managing Scarce Resources
2.1 Unmanaged Resources
As we have already mentioned, unmanaged resources are resources that cannot be released by the GC directly. Examples of unmanaged resources include file handles, database connection handles, message queue handles, and native memory allocated using Marshal.AllocHGlobal.
Releasing unmanaged resources requires an explicit call to a custom API, something along the lines of closing a “handle”.

2.2 Managed Resources
Managed resources are resources that can be released by the GC directly. Examples of managed resources include String, ArrayList, and TimeSpan. Code acquiring managed resources does need to be concerned with releasing them.
Instantiating and calling methods of managed types does not always allocate only managed resources, as it may seem. It may indirectly allocate unmanaged resources.

Controlling Finalization Queue

The runtime provides two methods to control objects’ eligibility for finalization, GC.SuppressFinalize and GC.ReRegisterForFinalize. GC.SuppressFinalize removes an object from the list of objects that will be finalized when they are no longer reachable, and GC.ReRegisterForFinalize takes an object that was previously suppressed, and adds it back to the list.
GC.SuppressFinalize is used to prevent unnecessary and costly finalization after the object has been cleaned up through other means, for example through IDisposable interface. GC.ReRegisterForFinalize is used to assure resource cleanup after an already cleaned up object reacquires resources that will need to be cleaned up.
In the .NET Framework Beta 2 release, there is a very expensive security check in GC.SuppressFinalize. This check has been removed in the final release, and should not be a source of performance problems.


For the majority of the objects that your application creates, you can rely on the CLR’s garbage collector to automatically perform all the necessary memory management tasks. However, some objects encapsulate unmanaged resources and those resources must be released explicitly. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. For these types of objects, the .NET Framework provides the Object.Finalize method, which allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object. By default, the Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object's memory, you must override the Finalize method in your class. You must use destructor syntax for your finalization code in the C# and the C++ with Managed Extensions.
The garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can reclaim their memory.
Implementing Finalize methods or destructors can have a negative impact on performance, so you should avoid using them unnecessarily. Reclaiming the memory used by objects with Finalize methods requires at least two garbage collections. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. A special runtime thread becomes active and calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list. In this future garbage collection, the objects' memory is actually reclaimed.
The following diagram shows the GC state transition that an object goes through during its lifetime.

Garbage Collection

The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you use the new operator to create an object, the runtime allocates memory for the object from the managed heap. As long as memory space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually, the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.

Describe the differences between the waterfall model and the spiral model, and describe how MSF uses both in the MSF Process Model.

The waterfall model is based on milestones. For a milestone to be achieved, all the tasks related to that phase must be completed. The next phase of development cannot be started until the milestone from the previous phase is completed. The clearly identifiable milestones of this model make it is easy to monitor the progress of the project and the schedule, and to assign responsibilities and accountability to the appropriate resources. The waterfall model is more applicable to projects that have clearly defined requirements and are not liable to modifications in the future.
The spiral model was created with the intention of being able to refine the product requirements and project estimates on a regular basis. Each time the project goes through an iteration of the spiral model, the development team can assess the project and plan for the next iteration. However, because the spiral model has no clear checkpoints, monitoring the progress of the project is difficult. The spiral model is suited best for rapid development of small projects.
The MSF Process Model incorporates the milestone approach of the waterfall model with the iterative approach of the spiral model. By using the process model, the development team takes an iterative approach to building a solution, while tracking the progress of each iteration by using milestones.

Friday, June 13, 2008

What are the types of assemblies?

There are four types of assemblies in .NET:

Static assemblies
These are the .NET PE files that you create at compile time.

Dynamic assemblies
These are PE-formatted, in-memory assemblies that you dynamically create at runtime using the classes in the System.Reflection.Emit namespace.

Private assemblies
These are static assemblies used by a specific application.

Public or shared assemblies
These are static assemblies that must have a unique shared name and can be used by any application.
An application uses a private assembly by referring to the assembly using a static path or through an XML-based application configuration file. While the CLR doesn't enforce versioning policies-checking whether the correct version is used-for private assemblies, it ensures that an
application uses the correct shared assemblies with which the application was built. Thus, an application uses a specific shared assembly by referring to the specific shared assembly, and the CLR ensures that the correct

• What meant of assembly & global assembly cache (gac) & Meta data

Assembly :-- An assembly is the primary building block of a .NET based application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or as accessible by code outside that unit. It overcomes the problem of 'dll Hell'.The .NET Framework uses assemblies as the fundamental unit for several purposes:
1. Security
2. Type Identity
3. Reference Scope
4. Versioning
5. Deployment
Global Assembly Cache :-- Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework. We can register the assembly to global assembly cache by using gacutil command.

We can Navigate to the GAC directory, C:\winnt\Assembly in explore. In the tools menu select the cache properties; in the windows displayed you can set the memory limit in MB used by the GAC

MetaData :--Assemblies have Manifests. This Manifest contains Metadata information of the Module/Assembly as well as it contains detailed Metadata of other assemblies/modules references (exported). It's the Assembly Manifest which differentiates between an Assembly and a Module.

What are the Main Features of .NET platform?

Common Language Runtime
Explains the features and benefits of the common language runtime, a run-time environment that manages the execution of code and provides services that simplify the development process.

Defines the concept of assemblies, which are collections of types and resources that form logical units of functionality. Assemblies are the fundamental units of deployment, version control, reuse, activation scoping, and security permissions.
Application Domains
Explains how to use application domains to provide isolation between applications.

Runtime Hosts
Describes the runtime hosts supported by the .NET Framework, including ASP.NET, Internet Explorer, and shell executables.

Common Type System
Identifies the types supported by the common language runtime.
Metadata and Self-Describing Components
Explains how the .NET Framework simplifies component interoperation by allowing compilers to emit additional declarative information, or metadata, into all modules and assemblies.

Cross-Language Interoperability
Explains how managed objects created in different programming languages can interact with one another.

.NET Framework Security
Describes mechanisms for protecting resources and code from unauthorized code and unauthorized users.

.NET Framework Class Library
Introduces the library of types provided by the .NET Framework, which expedites and optimizes the development process and gives you access to system functionality.