Friday, December 31, 2010

Difference Between Server.Transfer and Response.Redirect

Server.Transfer and Response.Redirect are used to transfer the control from one page to other. But there are some differences in both which are listed below.

Response.Redirect(..) :- Response.Redirect sends HTTP code 302 down to the users browser along with the new URL location of the wanted page.HTTP Code 302 actually means ' The requested resource resides temporarily under a different URI'.
After browser receives this code it send a request to server for that resource or page.
This actually causes two requests to the server, first one to the original URL, and second to the new URL that is suggested via 302 response.

Server.Transfer(..) :- In contrast to all this when we call Server.Transfer we do not initiate another request to the server, but the original request is simply rewritten and transferred to some other page on the same server.
(This off course means that we can use it only to transfer requests to the pages on the same server, not to some other servers and we can only transfer to .aspx pages and not other page types like HTML, php etc).

When Repsponse.Redirect("Temp.aspx") line execute server say to client browser to send a request for Temp.aspx. Than Client browser request for Temp.aspx.While in case of Server.Transfer("Temp.aspx") Server does not say anything to client browser just send Temp.aspx page.

1) In Response.Redirect previous page is not accessible while in Server.Transfer it is optional.

2) Server.Transfer use only within the server.But Response.Redirect can be use ouside the server.But it should be a full path like only will not work

3)Resonse.Redirect can be used both for aspx and html or php pages.But Server.Transfer is only used for .aspx pages it will not work for html pages.

4) Response.Redirect use only get method to post variables form one page to another means we need to give in query string if we want to pass some variables to next page. But in case of Response.Transfer you can use post method with the help of Context.Item[“Message”].

5)In Response.Redirect you see the full url with values in browser and in Server.Transfer you can not see it.

6)Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

8)In case of Server.Transfer you can use Context.Items["Message"] to store and get the values but in case of Response.Redirect you can not save values with this method.

9)One thing to be careful about when using the Server.Transfer is to clear the HttpResponse object with Response.Clear method on the transferred page to avoid any output from the first page to be shown on the second page.

10)In Server.Transfer url remain same there Bookmark can not be used while in case of Response .Redirect Bookmark can be use.

Server Transfer

1. Client Request Page HelloWorld.ASPX
2. Server.Transfer -> Server send a different page to the client
3. Client Receives Page still thinking it's HelloWorld.ASPX.
4. Client's URL (Address bar) remains HelloWorld.ASPX since the page was
sent on the server side and the client doesn't know a different page was


1. Client Requests Page HelloWorld.ASPX
2. Response.Redirect -> Server sends a HTTP header informing that the
user should redirect.
3. Client sees the redirect notice and requests
4. Server sends AnotherPage.ASPX
5. Client's URL (address bar) shows AnotherPage.ASPX

Don't confuse Server.Transfer with Server.Execute, which executes the page and returns the results. It was useful in the past, but, with ASP.NET, it's been replaced with fresher methods of development. Ignore it.

Friday, December 24, 2010

Interview Questions - 4

Questions Shared by Arvind Kumar Rathour
Coalesce function return not null value. It is more power full than ISNULL. ISNULL takes two parameters while coalesce can take n number of parameters. This function returns left most non null value. If all arguments are null than coalesce returns null. You can not pass single parameter in coalesce., this will give compile time error


Output : foo


Output : foo

SELECT ISNULL(NULL, 'foo',’fop’)

Error : The isnull function requires 2 argument(s).

ASP .Net
- Difference between asp and
- How do you do exception management?
- If you are using components in your application, how can you handle exceptions raised in a component?
- Can we throw exception from catch block?
- How do you relate an .aspx page with its code behind page?
- What are the types of assemblies and where can u store them and how?
- What is difference between value and reference types?
- Is array reference type / value type?
- Is string reference type / value type?
- What is web.config. How many web.config files can be allowed to use in an application?
- What is difference between machine.config and web.config?
- What is shared and private assembly?
- What are asynchronous callbacks?
- How to write unmanaged code and how to identify whether the code is managed / unmanaged?
- How to authenticate users using web.config?
- What is strong name and which tool is used for this?
- What is gacutil.exe. Where do we store assemblies?
- Should sn.exe be used before gacutil.exe?
- What does assemblyinfo.cs file consists of?
- What is boxing and unboxing?
- Types of authentications in ASP.NET?
- Difference between Trace and Debug?
- Difference between Dataset and DataReader.
- What is custom tag in web.config?
- How do you define authentication in web.Config?
- What is sequence of code in retrieving data from database?
- About DTS package.
- What provider use by default?
- Where does web.config info stored? Will this be stored in the registry?
- How do you register the dotnet component or assembly?
- What is stateless asp or
- Authentication mechanism in dotnet
- State management in
- Types of values mode can hold session state in web.config
- About WebService
- What are Http handler?
- What is view state and how this can be done and was this there in asp?
- Types of optimization and name a few and how do u do?
- About DataAdapters
- Features of a Dataset
- How do you do role based security?
- Difference between Response.Expires and Expires.Absolute?
- Types of object in asp.
- About duration in caching technique.
- Types of configuration files and the differences.
- Difference between ADO and
- About Postback.
- If you are calling three SPs from a window application how do u check for the performance of the SPS?


- What is normalization?
- What is an index and types of indexes. How many number of indexes can be used per table?
- What is a constraint. Types of constraints?
- What are code pages?
- What is referential integrity?
- What is a trigger?
- What are different types of joins?
- What is a self join?
- Authentication mechanisms in Sql Server.
- What are user defined stored procedures?
- What is INSTEAD OF trigger?
- Difference between SQL server 7.0 and 2000?
- How to optimize a query that retrieves data by joining 4 tables?
- Usage of DTS.
- How to disable an index using select query?
- Is non-clustered index faster than clustered index?
- Types of optimization in queries?
- Difference between ISQL and OSQL?
- How you log an exception directly into sql server what is used for this?
- About Replication in Database.
- What is the default optimization done in oracle and sql server?
- How can i make a column as unique?
- How many no of tables can be joined in same sql server?
- How many column can exist per table?
- About Sql Profiler usage?

• Technical

#61607; .NET-
- How do you handle session management in ASP.NET and how do you implement them. How do you handle in case of SQLServer mode.
- What are different authentication types. How do you retrieve user id in case of windows authentication
- For a server control, you need to have same properties like color maxlength, size, and allowed character throughout the application. How do you handle this.
- What is custom control. What is the difference between custom control and user control
- What is the syntax for datagrid and specifying columns
- How do you add a javascript function for a link button in a datagrid.
- Does C# supports multi-dimensional arrays
- How to transpose rows into columns and columns into rows in a multi-dimensional array
- What are object oriented concepts
- How do you create multiple inheritance in C#
-- Features and disadvantages of dataset
- What is the difference between and ActiveX dll and control
- How do you perform validations
- What is reflection and disadvantages of reflection
- What is boxing and how it is done internally
- Types of authentications in IIS
- What are the security issues if we send a query from the application
- Difference between ByVal and ByRef
- Disadvantages of COM components

- How do we invoke queries from the application
- What is the provider and namespaces being used to access oracle database
- How do you load XML document and perform validation of the document
- How do you access elements in XML document
- What is ODP.NET
- Types of session management in ASP.NET
- Difference between data reader and dataset
- What are the steps in connecting to database
- How do you register a .NET assembly
- Usage of web.config
- About remoting and web services. Difference between them
- Caching techniques in .NET
- About CLS and CTS
- Is overloading possible in web services
- Difference between .NET and previous version
- Types of caching. How to implement caching?
- Features in ASP.NET.
- How do you do validations. Whether client-side or server-side validations are better?
- How do you implement multiple inheritance in .NET?
- Difference between multi-level and multiple inheritance?
- What are runtime hosts?
- What is an application domain?
- What is viewstate?
- About CLR, reflection and assemblies?
- Difference between .NET components and COM components?
- What does assemblyinfo.cs consists?
- Types of objects in ASP?

Thanks Arvind.

Friday, December 17, 2010

Interview Questions-3

1) If you have two text boxes one is multi line and other is single line and both have MaxLength 10. What will be the difference in behavior of both?

In multi line text box Max Length property has been ignored. The reason is that multi line text box converted into textarea and text area does not support max length property.While in single line it consider max length and you can not type more than 10 characters in that. If any how you want to implement MaxLength in multi line text box you can use Validator control or java script validation for that.

2) Can we define Optional Parameter in Stored Procedure in SQL Server?
Yes, We can define optional parameter in a stored procedure following way.

CREATE Procedure sp_User
@Name as varchar(20),
@Age int = null
WHERE table1.Name= @Name
and (@Age is null or Age= @Age)

3) What is equivalent of Variant in VB .Net?
There is no "Variant" type in VB.NET. The closest you can get to that is type Object,which is the Mother Type from which all types descend.

If you define

Dim Var

than Var will work as a Variant also.

If you are calling a Com method which take 5 parameters 3 of them are optional. In VB .Net you can pass only three parameters but in C# it will give compile time error method not found with that signature. In C# you can use

object objVal = Type.Missing.

4) What is .Xap file ?
.xap file is the compressed output file for the Silverlight application. The .xap file includes AppManifest.xaml, compiled output assembly of the Silverlight project (.dll) and any other resource files referred by the Silverlight application.

Web pages like .aspx files and .html files use the Silverlight components by loading the .xap files using the <object> tag in the HTML or by using <asp:Silverlight> tag in the ASP.NET pages.

".xap" files (pronounced "zap") use the standard .zip compression algorithm to minimize client download size. A "hello world" .NET Silverlight application (built using VB or C#) is about 5KB in size.

5) How we define constructor and destructor in VB.Net?
In VB .Net we have Finalize method in place of destructor in C#. we can define it like :-

Protected Overrides Sub Finalize()
MyBase.Finalize() 'define the destructor
End Try
End Sub

And constructor can be define like :-

Public Sub New() ' define the constructor
End Sub

6) What is the Role of Set NoCount in SQL Server?
When SET NOCOUNT is ON, the count (indicating the number of rows affected by a Transact-SQL statement) is not returned. When SET NOCOUNT is OFF, the count is returned.

Actually when you fire any sql query it returns two things actual result and number of rows affected. Suppuse you have fired a select query. This query returns the rows as a result and in message part it will return number of rows return. It is an extra overhead we can suppress the second message with the use of NoCount.

7) Can we define our global variables in SQL Server?
SQL Server provides a wide range of global variable. But you can not define your own global variables in SQL Server.Some global variables are..

* @@SPID
8) What is Referential Integrity?
Referential integrity is a database concept that ensures that relationships between tables remain consistent. When one table has a foreign key to another table, the concept of referential integrity states that you may not add a record to the table that contains the foreign key unless there is a corresponding record in the linked table. It also includes the techniques known as cascading update and cascading delete, which ensure that changes made to the linked table are reflected in the primary table.

Friday, December 10, 2010

Why property is a better choice instead of public variables?

Property Vs. Public Variable
Properties are better than public variables There are two reasons.

1) Public variables are unsafe, as anyone can set any value and you have no control over them.While in case of property you can put a check that no one could set invalid value to them.

Suppose you have a property Salary..

private int m_iSalary=100;

property int Salary
return m_iSalary;

if(value > 0)
MessageBox.Show("You can not set Negative value in Salary.");

2) We can restrict any one, that he can only get the value but could not set from outside of class and vise versa.

property int Salary
return m_iSalary;

private set
if(value > 0)
MessageBox.Show("You can not set negative value in Salary.");

But inner access modifier should be more restrictive than main access modifier. We can not define access specifier for both(get and set) in one property, You can set only one at a time. And other will use main access specifier.

In set method value is a keyword you can not use any hard code value or any other variable instead of value keyword.

Monday, December 6, 2010

Use two tables in update statement

You can use more than one table in single update query but you can not update more than one table in single update query in Sql Server.

You have two tables on the base of them you want to fire update statement. Than you can do it like :-

Update Table1 set Field1 ='Name' from Table2 where Table1.ID=Table2.ID

Even you can use more than two tables in a single update query like..

Update Table1 set Field1 ='Name' from Table2,Table3 where and Table1.Id= Table3.Id

But you can not update two tables in one query in SQL Server.

In MYSQL it is possible to update two tables in Single Query..

update schoolsdata t1, schoolblog t2 set t1.state='A', t2.studentcomments='Z' where t1.collegeid = t2.collegeid and t1.collegeid=40

Saturday, December 4, 2010

IE8 compatibility Issue

If you have developed a website that is compatible with IE-7 or IE-6. And its designing is not good enough with IE-8 than you can force IE-8 to use IE-7 or IE-6 rendering mode until you fix the issue with IE-8.

This can be done with the help of meta tag :

<meta http-equiv="X-UA-Compatible" content="IE=7"/>

you can change here content attribute's value according to your requirement(IE-8,IE-7,IE-6,IE-5).

On the other hand if you have developed a windows application and used web browser control. Web Browser control by default gives IE-6 views for XP. But you want, it should use IE-8 rendering mode than also you can use above meta tag with the xslt you are using.

If don't want to change xslt than you can do the setting in registry also like:-

For IE-8 rendering mode
[(HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE)\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"ApplicationName.exe" = dword 8000 (Hex: 0x1F40)

and For IE-7 you can use "ApplicationName.exe" = dword 7000 (Hex: 0x1B58)

Or you can save following code as IE8.reg file(Simple create a notepad file and paste following code in that). And when you will double click on that file it will do the setting automatically. Following code is for IE-8 only.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]

Thursday, December 2, 2010

RPC Sever not available

Sometimes you get this error -> Error : RPC Sever not available. What is it mean?

What is RPC?Microsoft Remote Procedure Call is an inter process communication mechanism that enables two processes to communicate and exchange data. Processes may be on the same computer or on LAN or across the internet.

There is a service named RPC that should be always running on host computer to use RPC. Sometimes it stopped due to some malfunction, due to some anti virus or due to to some spy ware or by any other reason.

You can check it whether it is running or not.
Go to Control Panel/Administrative Tools/Services then double click on the Remote Procedure Call entry and either start the server, or set it to start automatically on system start up.

If it is not there you have to check registry entry for this service. If it is not present in registry than you will not find it in services.You can add it in registry.By exporting it from another system on which it is working fine.

Registry Path :- HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\RpcSs

If you don't another PC to export the correct registry file you can save following code as .reg file and when will double click on that file it will automatically import.

Windows Registry Editor Version 5.00

"Description"="Provides the endpoint mapper and other miscellaneous RPC services."
"DisplayName"="Remote Procedure Call (RPC)"
"Group"="COM Infrastructure"
"ObjectName"="NT Authority\\NetworkService"




Wednesday, December 1, 2010

Finally Block

How to work with finally?
Finally block guarantees to execute in each and every condition whether it is successful completion of a function or any error has been occurred not matter finally block would execute definitely.But control should come in try block if it did not come in try block and return before try block than finally will not execute.

Example 1

private void Show()
Console.Writeline("In try");
catch(Exception ex)
throw ex;


Output :- In try Finally
Example 2

private void Show()
Console.Writeline("In Function");
Console.Writeline("In try");

catch(Exception ex)
throw ex;


Output :- In Function In try Finally

Finally block used for to close any open file or connection or to null the reference type variables or for all type of work that you want to do in each and every condition.

There is some limitation of finally block you can not write return statement there since there is a chance that it may override the actual return statement.

If you write return statement there it will throw a compile time error.

"Control cannot leave the body of a finally clause."

Even you can not modify the return value inside finally block. Though it will not give any error but will not affect output.Since return value already decided before it goes to finally block,

public class ReturnExample
private String normalExecution()
String result = "";
result = "Entered try block.";
return result;

catch(Exception e)
result = result + "Entered Catch block.";
return result;

result = result + "Entered finally block.";

public static void main(String[] args)
ReturnExample example = new ReturnExample();
String result = example.normalExecution();

Output :- Entered Try block.

Finally block is not like if or for means in case of if or for there is no need of braces if we have only one line but same is not true for finally. Braces are compulsory for finally.Although you can write only try and catch or try and finally.

These are all correct


Tuesday, November 30, 2010

Interview Questions on Remoting/Web Services

What are the properties of a [WebMethod ] attribute?
1. Description
2. MessageName
3. EnableSession
4. CacheDuration
5. TransactionOption
6. BufferResponse

Name the layers of the WebServices protocol stack?
Layer 1 --> Transport Layer (HTTP, SMTP,FTP)
Layer 2 --> XML Messaging Layer (XML,SOAP)
Layer 3 --> WSDL Layer
Layer 4 --> UDDI Layer

Is overloading possible in web services?
Yes, We can overload webmethods in a webservice.

There is the MessageName property of a WebMethod attribute! The MessageName property enables the XML Web Service to uniquely identify overloaded methods using an alias. The default value of this property is the method name, but you can change it to distinguish this overloaded method
implementation from others. When specifying the method name, the resulting SOAP messages will reflect this name instead of an actual method name.

What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

How do you define the lease of the object?
By implementing ILease interface when writing the class code.

How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.

What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.

Explain what relationship is between a Process, Application Domain, and Application?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.

Name the distributed systems available apart from .Net Remoting.
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC),
Microsoft Distributed Component Object Model (DCOM),
Common Object Request Broker Architecture (CORBA), and
Java Remote Method Invocation (RMI).

Define remotable objects in .NET Remoting.
Remotable objects are the objects that can be marshaled across the application domains.You can marshal by value, where a copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

Advantage of Remoting over Web Services.

.Net Remoting can work with both internet and interanet.
WebService Support only SOAP/HTTP while .Net Remoting support TCP/HTTP.
.Net Remoting best for interanet while web service best for inernet.
.Net Remoting best for homogeneous platform while Web Services best for hetrogeneous platform.
TCP is fast than HTTP.
.Net type system and can expose any object to the client. .Net Web Service supports on those types that can be expressed with XSD.
When to use .Net Remoting over Web services
.Net Remoting provides distributed solution for a corporate use. So, if you need distributed environment to be implemented for internal use, .Net remoting is the best choice. If you require a faster distributed solution, .Net Remoting with TCP protocol using binary format is faster than Web services. .Net Remoting is better solution when large transfer of data is required. Web Services are best when you need to communicate with an external organization or non .NET technology.

What is an application domain?
Previously "PROCESS" were used as security boundaries. One process has its own virtual memory and does not over lap the other process virtual memory; Due to this one process can not crash the other process. So any problem or error in one process does not affect the other process. In .NET they went one step ahead introducing application domains. In application domains multiple applications can run in same process with out influencing each other. If one of the application domains throws error it does not affect the other application domains. To invoke method in a object running in different application domain .NET remoting is used.

What are two different types of remote object creation mode in .NET?
There are two different ways in which object can be created using Remoting:

o SAO (Server Activated Objects) also called as Well-Known call mode.
o CAO (Client Activated Objects).
* SAO has two modes "Single Call" and "Singleton". With Single Call object the object is created with every method call thus making the object stateless. With Singleton the object is created only once and the object is shared with all clients.
* CAO are stateful as compared to SAO. In CAO the creation request is sent from client side. Client holds a proxy to the server object created on server. It is stateful for client bases.

What is fundamental of published or precreated objects in Remoting?
In scenarios of singleton or single call the objects are created dynamically. But in situations where you want to precreate object and publish it you will use published object scenarios.

Dim obj as new objRemote
obj.Initvalue = 100
As shown in above sample following changes will be needed on server side.
RemotingConfiguration.RegisterWellKnownServiceType is replaced by RemotingServices.Marshal(obj,"RemoteObject") where "obj" is the precreated object on the server whose value is initialized to 100

What are the ways in which client can create object on server in CAO model?
There are two ways by which you can create Client objects on remoting server :
By Keyword "New".

And Singleton and SingleCall
"RemoteObject", WellKnownObjectMode.Singleton)

Can Non-Default constructors be used with Single Call SAO?
Non-Default constructors can not be used with single call objects as object is created with every method call, there is no way to define Non-default constructors in method calls. It’s possible to use Non-Default constructor with Client activated objects as both methods "NEW" keyword and "Activator.CreateInstance()" provide a way to specify Non-Default constructors.

What is Asynchronous One-Way Calls?
One-way calls are a different from asynchronous calls from execution angle.In one way call .NET Framework does not guarantee their execution. In addition, the methods used in this kind of call cannot have return values or out parameters. One-way calls are defined by using [OneWay()] attribute in class.

What is marshalling and what are different kinds of marshalling?
Marshaling is used when an object is converted so that it can be sent across the network or across application domains. Unmarshaling creates an object from the marshaled data. There are two ways to do marshalling:
+ Marshal-by-value (MBV): In this the object is serialized into the channel, and a copy of the object is created on the other side of the network. The object to marshal is stored into a stream, and the stream is used to build a copy of the object on the other side with the unmarshalling sequence.
Marshaling-by-reference (MBR): Here it creates a proxy on the client that is used to communicate with the remote object. The marshaling sequence of a remote object creates an ObjRef instance that itself can be serialized across the network.

What is UDDI?
Full form of UDDI is Universal Description, Discovery and Integration. It is a directory that can be used to publish and discover public Web Services. If you want to see more details you can visit the .

What is ObjRef object in remoting?
All Marshal() methods return ObjRef object.The ObjRef is serializable because it implements the interface ISerializable, and can be marshaled by value. The ObjRef knows about location of the remote object, host name, port number and object name.

What is DISCO?
DISCO is the abbreviated form of Discovery. It is basically used to club or group common services together on a server and provides links to the schema documents of the services it describes may require.

What happens when a client activates a remote object?
When a client activates a remote object, it receives a proxy to the remote object. All operations on this proxy are appropriately indirected to enable the remoting infrastructure to intercept and forward the calls appropriately.

What is considered as Remote Object?
Any object outside the application domain of the calling application is considered remote object, even if the objects are executing on the same machine.

Can you treat every object as a remote object?
Objects that cannot be serialized cannot be passed to a different application domain and are therefore nonremotable.

What are the ways in which an object can be serialized?
1. Mark your class with serializable attribute.
2. Make your class implement ISerializable interface.

Monday, November 29, 2010

DCOM vs .Net Remoting

DCOM vs .Net Remoting

.Net Remoting is the successor of Distributed component object Model(DCOM). Both these technology are introduced by Microsoft that enable inter-process communication across application domains. DCOM was very successful technology. But it is never treated as best technology for inter-process communication because of lack of its support for interoperability across platform.

.Net Remoting is a new technology that ship with .Net Framework. It has all those features which are missing in DCOM. There are other pain involve with DCOM such as difficult to control format or channels, message trace is painful, change in configuration setting such as channels or port is not easy. DCOM is hard to learn and complicated to deploy and to maintain.

Differences between these two technologies are as follows.

DCOM technology is based on the COM architecture whereas .NET Remoting is primarily based on .NET Frameworks.

DCOM is based on proprietary binary protocol which is not supported by all object model, thus has big drawbacks in the internet world.

DCOM is based on RPC protocol whereas .Net Remoting can use TCP or HTTP protocol which is stardard protocal in the market.

DCOM is not firewall friendly, can't choose port. .Net Remoting, on the other hand, works easily across firewalls.

.Net Remoting supports cross platform communication which is not possible with DCOM (only for windows platform).

Components created DCOM involves complex deployment in windows registries whereas .Net Remoting involves easy deployment using either xml based configuration file or programmatically in the code.
DCOM uses windows security features whereas .Net Remoting can use security features of IIS if hosted with ASP.NET. .Net Remoting, if hosted other than ASP worker process, allows to create own security mechanism for the application.

In DCOM, server is started by Service Control Manager (SCM) upon receiving the activation request from the client whereas in .Net Remoting, IIS is responsible to start server service. If not hosted with IIS then client request if the Remoting server is not already started.

DCOM manages remote object lifetime by frequent pinging of clients whereas .Net Remoting has more efficient leasing mechanisms to maintain object lifetime.

Sunday, November 28, 2010

Derive an Abstract class from an Abstract class

Question : What happen when you derive a abstract class from another abstract class? Is it mandatory to implement all the methods of abstract base class in abstract derive class?

Answer : No, it is not mandatory to implement all the methods of abstract base class in abstract derive class.

All abstract method of an abstract class should be public. You can not override any method if it is not abstract or virtual.
You can not define an abstract method as a private in abstract class will give compile time error.

abstract class Base
public abstract void BaseMethod();

abstract class Child:Base
public abstract void ChildMethod();

//If any class derived from that abstract child class than it must implement all the methods of both classes.

class Client: Child
public override void BaseMethod()
Console.Writeline("Base Method");

public override void ChildMethod()
Console.Writeline("Child Method");


If you have implemented the abstract method of abstract Base class in abstract Child class than there is no need to implement that method in Client class. But if you want you can override it in Client too.

Thursday, November 25, 2010

How to get Parent Process Path

using System.Management;

private String GetParentProcessPath(int CurrentProcessId)
int iParentPid = 0;
using (ManagementObject objMgmt= new ManagementObject("win32_process.handle='"+ Id.ToString() + "'"))
iParentPid = Convert.ToInt32(mo["ParentProcessId"]);

Process objPrc = Process.GetProcessById(iParentPid);

String sParentDirPath = Path.GetDirectoryName(objPrc.Modules[0].FileName);
return sParentDirPath;

Sunday, November 14, 2010

Interview Questions

What is .Net framework?
.Net framework is a set of technologies that form an integral part of .Net. platform. .Net framework provide you a environment to write managed code. It has two main components.
CLR and FCL(Framework Class Library)

What is CLR ?
Common Language Run Time provides the common services to manage code like memory management,Exception Handling and Security.

.Net compiler(Different for different languages) convert source code to CIL(Common Intermediate Language). At run time CLR’s JIT convert CIL to machine code.

What is FCL?
FCL(Framework Class Library) is a set of common classes that is used to access common functionality.

What is CTS?
CTS is a component of CLS.CTS describes the common types used by managed code. It facilitates cross-language integration, type safety and high performance code execution.

What is CLS?
Common Language Specification defines the guidelines for languages to communicate to each other.

What is Manage Code?
To get the facilities of CLR every code should provide a minimum information to CLR. That code provide that information it is called managed code.

What is an Application Domain?
An Application domain is a boundary for a process. A process can contains multiple application domain. It is an isolation for process. An application domain can not communicate directly to other application domain. For that we need proxy.

What is Assembly?
An assembly is a collection of one or more exe or dll. An assembly contains a collection of types and resources that are built to work together and form a logical unit of functionality.

What an assembly contains?
A static assembly can contains four parts.
1) Manifest
2) Type Metadata- Binary information that describes a program
3) IL
4) A set of resources.

What is manifest?
Manifest describes the assembly itself.
Manifest contains the assembly metadata. An assembly manifest contains the information about the identity and version of the assembly. It also contains the information required to resolve references to type and resources.

What is Strong Name?
To place an assembly in GAC we need to assign a strong name to that assembly. Strong Name Include text name, version and culture information, a public and a digital signature signature generated over that assembly. There is a tool Sn.exe verification and key pair and signature generation.

Satellite Assembly
An assembly that contains only resources is called satellite assembly. It is used often to deploy language specific resources for an application.

Sleep,Suspend and Resume
Suspend allows you to block a thread until another thread call Thread.Resume.
Sleep allow you to block a thread for a specific time or for inifinite time.

.Net framework does not suspend a thread until it determine that it is in a safe place to suspend, while Sleep immediately put a thread into wait state.

Join wait for a previous thread to complete and after the completion of previous thread it is started.

Daemon Thread
A background thread is called daemon thread. we can do it by setting the property IsBackground=true. GC is an example of Daemon thread.

Can we use events with threads?
Yes events can be used with thread. This is one of the technique to synchronize one thread with other.

How can we know thread state?
ThreadState property can be used to determine the state of thread. It is an enumeration.

How to stop a long running thread?
Thread.Stop() method can be called for that.

How do you implement synchronization ?
lock and Synclock
Two thread can try to access the same variable at same time. This can create the problem.To avoid it you can use lock to lock a variable but if two threads lock a variable at same time it can be cause a deadlock problem.
Synclock x
//Do something
End Synclock

What is use of Interlocked class?
Interlocked class provides methods by which you can achieve following functionality?
1) Increment Value
2) Decrement Value
3) Exchange Value between variables
4) Compare Values from any thread in synchronize mode.

Monitor object
Monitor object are used to ensure that a block of code runs without interruption of other thread. This is a way of synchronization, code from other thread can not run until code written in synch block has finished.

What are wait handles?
1) WaitOne
2) WaitAny
3) WaitAll

When a thread wants to release a wait handle it can call set method.

Mutex Object
Mutex object is a synchronized object that can be used by only one thread at a time. If it is owned by a thread its state is signaled and if it is not owned by any thread its state is non signaled. Exapmle :- If you want that at a time only single instance of an application should run than you can use Mutex object

What is ManualResetEvent and AutoResetEvent?
Thread that called wait method of synchronize event must wait until another thread signal the event by calling Set method.

In case of ManualReset event we use Set method to signaled. Threads set the status of ManualResetEvent instances to non signaled using the Reset method or when control returns to waiting Waitone call.

Instances of AutoResetEvent class can also be set to Signaled using set, But they automatically return to non signaled as soon as a waiting thread is notified that the event become signaled.

Indexes are created on columns of table or views. The index provides a fast way to look up data based on the values within these columns.
For example if you create an index on the primary key and search a row based on that primary key, SQL server first find that values in the index and then uses that index to find the entire row.
Without the index, a table scan would have to be performed in order to locate the data.
You can not create index on large data type like image,text,varchar(max).

Clustered Index :-
Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index.

Non Clustered Index :-
Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db(max 249).

Saturday, November 13, 2010


A transaction is a sequence of operations performed as single logical unit or work. Means all the statement written within Transaction block should execute successfully or none.

A transaction must follow ACID rule.

Automoicity :- A transaction must be Atomic. Either all of its data modification should performed or none.

Consistency :- A transaction must leave a database into consistent state whether it complete successfully or not. It should not be the case that we have transferred 1000 Rs. from account A to account B. A has credited 1000 but B has not due to electricity failure or any other reason.

Isolation :- A transaction will never affect another transaction running at same time. Means a transaction should not find the database in intermediate state because of another transaction. It should find it before the other transaction completion or after the completion.

Durability :- After the completion of transaction its effect should be permanent. Even in case of System Failure or database crash. Transaction log are maintained so that the database can be restored in its original position before failure takes place.

You can do it in .Net and SQL both.
There are three main function in transaction BeginTransaction, Rollback and Commit

string connectionString = ".........";
SqlConnection objConnection = new SqlConnection(connectionString);

// Start transaction.
SqlTransaction objTransaction = objConnection.BeginTransaction();
// Assign command in the current transaction.

SqlCommand objCommand = new SqlCommand();
myCommand.Transaction = objTransaction;
//.........................Begin Database operations........................//

//.........................End Database operations........................//

Console.WriteLine("Records are modified in the database.");
catch(Exception e)



Console.WriteLine("Neither record was written to database.");

In Sql Server we can do it like this

@DepartmentID int

-- This sproc performs deletes all of the department's associated employees.

-- STEP 1: Start the transaction

-- STEP 2 & 3: Issue the DELETE statements, checking @@ERROR after each statement
WHERE DepartmentID = @DepartmentID

-- Rollback the transaction if there were any errors
IF @@ERROR <> 0
-- Rollback the transaction
-- Raise an error and return
RAISERROR ('Error in deleting employees in DeleteDepartment.', 16, 1)

-- Commit the transaction....

Sweet Story of Imam Abu Hanifa(R.A)

Many years ago, during the time of the Taabi'een, Baghdad was a great city of Islam. There were many muslim scholars hence it was the center of Islamic knowledge. 1 day, a Roman came 2 this city with 3 challenges for the Muslims. He informed the Khalifah that he had 3 questions which he challenged the Muslims to answer.

The Khalifah gathered together all the scholars of the city & the Roman messenger climbed upon a HIGH PLATFORM & said, "I have come with 3 questions. 'Wat was there before Allah?' 'In which direction does Allah face?' 'What is Allah doing at this moment?'"

Everybody remained silent and confused. In the gathering of these brilliant scholars & students of Islam, there was a young boy who wanted 2 answer the unbeliever's questions. So the boy was given the permission 2 answer by Khalifah.

The Roman addressed the young Muslim and repeated his first question, "What was there before Allah?"

The boy asked, "Do you know how to count?" "Yes," said the man. "Then count down from ten!" So the Roman counted down, "10,9,8 ..." until he reached 1 & stopped counting. "But what comes before '1'?" asked the boy. "There is nothing before 1 tat is it!" said the man. "Well then, if there obviously is nothing before the arithmetic 'one', then how do u expect tat there shoud b anything before the '1' who is Absolute truth, All Eternal, Everlasting the First, the Last, the Manifest, the Hidden?"
Now the man was surprised by this direct answer which he could not dispute.So he asked, "Then tell me, in which direction is Allah facing?"

"Bring a candle & light it," said the boy, "& tell me in which direction the flame is facing." "But the flame is just light- it spreads in each of the 4 directions, North, South, East and West. It does not face any 1 direction only," said the man in wonderment. The boy cried, "Then if this physical light spreads in all 4 directions such tat u can't tell me which way it faces, then what do u expect of the Nur-us-Samawati-wal-'Ard: Allah - the Light of the Heavens & the Earth!? Allah faces all directions at all times". The Roman was astounded tat a young child was answering his challenges in such a way tat he cud not argue against the proofs. So, he desperately wanted to try his final question.

But before doing so, the boy said, "Wait! U r the 1 who is asking the questions & I am the 1 who is giving the answers . It is only fair tat u should cum down 2 where I am standing & I should go up where u r right now, so tat the answers may b heard as clearly as the questions". This seemed reasonable 2 the Roman, so he came down from where he was standing & the boy ascended the platform. Then the man repeated his final challenge, "Tell me, what Allah is doing at this moment?" The boy proudly answered, "At this moment, Allah found tat a non-muslim & mocker of Islam is standing on a high platform, so he brought him down(referring to roman challenger) & raised the status of a muslim (referring himself) by making him stand on a high platform ".The Roman had nothing to say and he accepted Islam immediately . This young boy grew up 2 become 1 of the most famous scholars of Islam. Allah, the Exalted, blessed him with special wisdom & knowledge of the Deen .His name was Abu Hanifah (r.a.) .He is known today as Imam Abu Hanifah (Imam-e-Azam), the Great Imam and scholar of Islam.

Difference Between XmlTextReader and XmlDocument

XmlDocument represents the contents of an xml file. When loading it from a file, you read the entire file into memory.
XmlReader is an abstract class able to read from xml data. It can read from a file, from an internet location, or from any other stream of data. When reading from a file, you don't load the entire document at once.
XmlTextReader is an implementation of XmlReader able to read xml from a file. It's recommended to use XmlReader.Create(file) instead of instantiating an XmlTextReader.

XmlTextReader is forward only stream, while XmlDocument is both forward and backward.

We use XMLTextReader to read XML streams. XMLdocument can be used to edit and navigate the document.

Difference Between Inner Join,Outer Join, Self Join and Cartesian Product

Joins :- If you see in general term join is to combine two or more tables in a manner that you can get your desired output. It is called join.

There are only three types of joins

1) Equi Join
2) Non Equi Join
3) Cross Jon or Cartesian Product.

Equi Join :-
When you use equal to(=) operator in where clause it is called Equi join

Select EmpName,Salary from Employee, SalaryRange where Employee.Salary =SalaryRange.MinSalary.

Non Equi Join :-
When you use any operator(!=,>,<,Between) other than equal to, it is called Non-Equi join. Ex select EmpName,Salary from Employee, SalaryRange where Employee.Salary between SalaryRange.MinSalary and SalaryRange.MaxSalary Cartesian Product :- If do not use any where condition in the join query than it is called Cartesian Product or Cross Join.

Further Equi join and Non Equi Join can be divided into following categories.

1)Inner Join
2)Outer Join
3)Self Join

Inner join :- An inner join (sometimes called a simple join ) is a
join of two or more tables that returns only those rows that satisfy the join condition.

Outer Joins :- An outer join extends the result of a simple join. An
outer join returns all rows that satisfy the join condition and also returns non matching rows based on Outer join type.

Further Outer Join can be divided into following categories

1) Left Outer Join :- All Matching Records + All Non Matching Records from Left Table
2) Right Outer Join :- All Matching Records + All Non Matching Records from Right Table
3) Full Outer Join :- All Matching Records + All Non Matching Records from both Tables

Self Join :- When we join a table to itself it is called Self Join.

Examples :-

Suppose we have two tables Employee and Manager with following data
Id     Name
1      Aslam
2      Ammar
3      Azam

Id     Name
1      Amir
2      Asim
4      Arif

Inner Join
All Matching Records
select a.Id,a.Name from Employee a INNER JOIN Manager b on a.Id = b.Id;
Output :
Id     Name
1      Aslam
2      Ammar

Left Outer Join
All Matching Records + All Non Matching Records from Left Table

Select a.Id,a.Name from Employee a LEFT OUTER JOIN Manager b on a.Id = b.Id;

Output :
Id     Name
1      Aslam
2      Ammar
3      Azam

Right Outer Join
All Matching Records + All Non Matching Records from Right Table
select b.Id,b.Name from Employee a RIGHT OUTER JOIN Manager b on a.a = b.b;

Output :
Id     Name
1         Aslam
2         Ammar
3         Azam
4         Arif

Full Outer Join
All Matching Records + All Non Matching Records from Both Table
Select * from Employee a FULL OUTER JOIN Manager b on a.I = b.Id;

Output :
Id     Name         Id      Name
1        Aslam         1       Amir
2        Ammar         2       Asim
3        Azam          NULL    NULL
NULL     NULL          4       Arif

Self Join
A join from a table to itself is called self join.
Suppose you have a table Name Employee which contain following data
Id      Name         ManagerId   
1       Asim          3
2       Arif          3
3       Asif          0

In this table every employee has a Manager But top one has no Manager so its manager id is zero

We want all Employee name and their Manager Name

Select a.Name as EmpName,b.Name as ManagerName from Employee a, Employee b where a.ManagerId= b.Id and b.ManagerId !=0

 Output :
EmpName       ManagerName
Asmim           Asif
Arif            Asif

Cartesian Product
When you join two or more tables without any condition, it is called Cartesian product or Cross Join.

Select a.Id,b.Id from Employee a,Manager b
Employee    Manager  
-            -
1            1
1            2
1            4
2            1
2            2
2            4
3            1
3            2
3            4

Worker Thread

If we are writing a program to check prime number through a list which has more than 10 Lac number. This process will take time and in the mean time if user want to exit the application he can’t do that since interface would not be visible to him.

In that case if want that user can close the application in the middle if want than we have to call Application.DoEvents() or we to have use a separate thread to check the prime number in that case interface would be visible to user and responsive.

In this scenario if user click on cancel button we have to use ManualResetEvent to signal the first thread to stop.

The very first thread that is checking for prime number it is called worker thread.

Connection Pooling

When we open a new connection it takes time this way it affects application performance. So by default .Net use connection pooling, while needed it get the database connection from there and while finishing the work it back place it to the pool.

We no need to worry about that SQl Server provide this facility through connection pool manager which provide the same facility to us.

String ConString = "integrated security=SSPI;SERVER=YOUR_SERVER;Pooling=true;DATABASE=YOUR_DB_NAME;Min Pool Size=5;Max Pool Size=60;Connect Timeout=2;Connection Lifetime=10";

Min Pool Size :- When we start application pool manager 5 connection opened. if needed more it can go up to max size. By default its value is 0.

Max Pool Size :- How many maximum connection can reside in pool it. By default value is 100.

Connect Timeout :- If we request a new connection and there is no connection available in the connection than it creates a new connection and add it in pool, if number of pools has reached Max than Pool Size than it waits for 2 second to release any connection, if there is available a connection within that time period it use else through an exception “System.InvalidOperationException Message: Timeout expired”. By default value is 15 Seconds.

Pooling :- The Data Providers in ADO.NET have Connection Pooling turned on by default; if you need to turn it off, specify Pooling = false in the connection string being used. Recognized values are true, false, yes, and no.

Connection Lifetime :- When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime.
A value of zero (0) causes pooled connections to have the maximum connection timeout. By default value is zero.

Incr Pool Size :- Controls the number of connections that are established when all the connections are used.By default value is five.

Decr Pool Size :- Controls the number of connections that are closed when an excessive amount of established connections are unused. By default value is one.

Enlist :- When true,the pooler automatically enlists the connection in the creation thread's current transaction context. Recognized values are true, false, yes, and no. Set Enlist = "false" to ensure that connection is not context specific.By default value is true.

The basic advantage of using Connection Pooling is an improvement of performance and scalability while the main disadvantage is that one or more database connections, even if they are currently not being used, are kept open.

Difference Between STA and MTA

Single Threaded Apartment :- There may be multiple apartment.But only single thread can be executed in a apartment. If there is a need to communicate between threads you need a proxy, they can not do it directly. The application defines when and for how long the thread in each apartment should execute. All requests are serialized through a window message queue such that only one thread can execute at a time. In Vb we have STA only but in ,Net we have both.

Multiple Threaded Apartment :- In multiple threaded apartment only one apartment will be there and all threads will execute within that single apartment. So that they communicate directly to each other without a proxy.

Design Pattern .......................

Design Pattern are recognized solutions to common problems defined by Gang of Four Programmer.
Design Pattern are about design, interaction of objects, as well as providing a communication platform for objects and reusable solutions to common problems.

Design Pattern are important to understand for the following reasons:

1) They give us reuse.
2) Design Pattern allow one refer to a design concept without explaining the full detail.
3) They give us a common taxonomy(classification) allowing for better communication.

There are three type of pattern :-

1) Creational Pattern :- Based on how to create an object
2) Structural Pattern :- Based on how to define the structure using interface and abstract classes
3) Behavioral Pattern :- Based on communication of the object how do they communicate.

..........Singleton Pattern [CD]

Singleton pattern ensure that a class should have only one instance and provide a global access to that instance.

Example 1 Not thread safe

public sealed class Singleton
private static Singleton instance=null;

private Singleton()

public static Singleton Instance

if (instance==null)
instance = new Singleton();
return instance;

Example 2 Thread safe

public sealed class Singleton
private static Singleton instance=null;
priavte readonly object objPadlock = new Object();

private Singleton()

public static SingletonInstance
//Otherwise Lock will execute each time even object already created, this is called double null
check condition.

if(instance ==null)
lock (padlock)
if (instance==null)
instance = new Singleton();
}//End of lock (padlock)
}//End of if(instance ==null)
return instance;

3. Thread safe without lock statement  using Nested class (Lazy Loading)

It is guaranteed that a static constructor in a C# class is called only once at most. If it only creates an
instance in the static constructor, there is one instance at most. A concise solution for the singleton

pattern with a static constructor is

public sealed class Singleton
    private Singleton()

    public static Singleton Instance { get { return Nested.instance; } }
    private class Nested
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()

        internal static readonly Singleton instance = new Singleton();

It is thread safe because of lazy loading.

5. Thread safe in .Net 4.0+

public sealed class Singleton
    private static readonly Lazy lazy =
        new Lazy(() =new Lazy(() => new Singleton());
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()

6. Not quite as lazy, but thread-safe without using locks using Static Constructor

It is guaranteed that a static constructor in a C# class is called only once at most. If it only creates an
instance in the static constructor, there is one instance at most. A concise solution for the singleton

pattern with a static constructor is

public sealed class Singleton
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()

    private Singleton()

    public static Singleton Instance
            return instance;

7. Another way for singleton pattern

/// Sample singleton object.

public sealed class SiteStructure

/// This is an expensive resource we need to only store in one place.

object[] _data = new object[10];

/// Allocate ourselves. We have a private constructor, so no one else can.

static readonly SiteStructure _instance = new SiteStructure();

/// Access SiteStructure.Instance to get the singleton object.
/// Then call methods on that instance.

public static SiteStructure Instance
get { return _instance; }

/// This is a private constructor, meaning no outsiders have access.

private SiteStructure()
// Initialize members, etc. here.

8.  Using readonly

public sealed clas Sinhgleton

private static readonly Singleton instance = new Singleton();

private Singleton()

public static Singleton Instance

return instance;


  • Abstract Factory, Builder and Prototype can use singleton in their implementation.
  • Facade object are often singleton because only one object required.
  • They don't pollute the global namspace with unnecessary variables.
  • They permit lazy allocation and initialization where global variable in many languages consume resources.
  • HttpContext class in ASP .net implements singleton, object can be retried using HttpContext.Current
  • OperationContext Class in WCF implement singleton
  • Dispatcher class implements singleton

..........Builder Pattern[CD]

The Builder Design Pattern separates the creation of an instance of a class from its representation so that the same creation pattern can be used for creating different representations of the object.

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. - Gof

A Builder can be one of implementations of the AbstractFactory. Of course it can use other factories to build the parts of its product.

The idea behind the builder pattern is to create a complex or multipart object on behalf of a client which knows the object to be created but does not know how it is being put together. It is applicable when the object cannot be created in an arbitrary manner. It helps the construction process to meet these requirements:

* There are several steps used to create the parts which make up the complex object
* These steps need to be carried out in a particular sequence.
* The product instantiation process must be hidden from the client.

The BuilderPattern is similar to FactoryPattern, but creates a complex object using a number of steps.

Example: DocumentBuilderFactory, StringBuffer, StringBuilder are some examples of builder pattern.


Build a complex object step by step:-

class Figure
public abstract DrawFigure();
public abstract DrawShade();
public abstract FillColor();

public Circle : Figure
private override DrawFigure()
Console.Writeline(“Draw Circle”);

private override DrawShade()
Console.Writeline(“Draw Shade”);

private override FillColor()
Console.Writeline(“Fill Red Color ”);

public Rectangle : Figure
private override DrawFigure()
Console.Writeline(“Draw Rectangle”);

private override DrawShade()
Console.Writeline(“Draw Shade”);

private override FillColor()
Console.Writeline(“Fill Green Color ”);

class Shape
public void CreateFigure(Figure objFigure)

public static void main(String[] args)

Figure objFigure=null;
Shape objShape=null;
objShape = new Shape();

objFigure = new Circle();

objFigure = new Rectalge();

.....Creational Pattern

Creational design pattern deals with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Abstract Factory :- When we want to create object using super class and want to hide subclass than we use Abstract method. In this pattern we use a method to create the object. Ex, XmlReader and XmlTextReader are the best example where we use XmlReader.Create(..) method to create the object of XmlTextReader,ASP .Net use AbstractFactory pattern in Handler implementation through IHTTPHandlerFactory interface.

Builder Patter :- Separate the construction of a complex object from its representation so that the same construction process can create different representations.In this pattern we create the object step by step. Example StringBuilde

Factory Pattern :- A Factory Pattern is one that returns an instance of class depending on parameter passed. Means which class object should be created it decide on run time.

Prototype Pattern :- When creating an object is very time consuming or complex in some way than we can just make the clone of existing object. This is called Prototype pattern.
Example : When we create shallow and deep it is an example of Prototype.

Singleton Pattern :- Singleton pattern ensure that a class should have only one instance and provide a global access to that instance.

.....Structural Pattern

Structural Patterns describe how objects and classes can be combined to form larger structures. The difference between class patterns and object patterns is that class patterns describe abstraction with the help of inheritance and how it can be used to provide more useful program interface. Object patterns, on other hand, describe how objects can be associated and composed to form larger, more complex structures.

There are seven structural patterns.

1) Adapter :- Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

2) Bridge Patter :- The Bridge pattern is used to separate the interface of class from its implementation, so that either can be varied separately.We can do it by using abstract class instead of interface.

3)Composite Pattern :- The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object.
i.e The Composite pattern allows you to create a tree like structure for simple and complex objects so they appear the same to the client. An XmlDocument,TreeView are example of composite pattern.

4) Decorator Pattern :- A Decorator design pattern is a design pattern that allows new/additional behavior to be added to an existing object dynamically.

5) Facade :- Facade - The front(face) of a building,In Facade pattern a single class represent the entire system and hide the complexity of the system.

6) Flyweight Pattern :- When we need to share information between many objects than we use Flyweight pattern. If an information is shared between many objects than we can remove it from each object and referenced. This eliminates the redundancy and we can save memory. So instead of storing the same information n times for n object, it is only stored once. This object that contains all of the intrinsic(basic) information is called a flyweight object.

7) Proxy :- The Proxy pattern is used when you need to represent a complex object by a simpler one. If creating an object is expensive in time or computer resources, Proxy allows you to postpone this creation until you need the actual object. A Proxy usually has the same methods as the object it represents, and once the object is loaded, it passes on the method calls from the Proxy to the actual object.

..........Abstract Factory Pattern[CD]

Abstract Factory Pattern : Term “Factory” refer to the location in code where object has been created.Here object is created without knowing its class. Means object is created by a method of class not by the class’s constructor. So basically Abstract Factory Pattern is used wherever subclasses given the privilege of instantiating a method that can create an object.

The benefit of this is if in the future the implementation of the object that implements the interface changes, the consuming client is not affected as long as the interface remains the same.

An Abstract Factory class is a class which exist to create instances of another class.

If you want to create an instance of class at runtime (Means class should be selected at runtime).

1) Create an AbstractFactory class for each class you wish to create.
2) In each AbstractFactory class there should have a polymorphic “created instance” method, conforming to a method signature, used to create instances of the corresponding classes.

Suppose an Abstact class wants to hide its subclass name and instantiation.

abstract class BaseClass
static BaseClass GetInstance()

return new ChildClass();

class ChildClass extends BaseClass


void main()

BaseClass objBase = BaseClass.GetInstance();


..........Factory Pattern[CD]

Factory Pattern :- A Factory Pattern is one that returns an instance of class depending on parameter passed. Means which class object should be created it decide on run time.

Example : We have a base class Shape and two child classes named Circle and Square.

public class Shape
public abstract Draw(String Type);

public void Square:Shape
private override Draw()
System.Console.Writeline(“Draw Square”);

public void Circle:Shape
private override Draw()
System.Console.Writeline(“Draw Circle”);

public void Client

private void CreateObject(String Type)
return new Circle();
else if(Type==”Square”)
return new Square();
return null;

public static void main(String[] args)
Client objClient =null;
Shape objShape =null;

objClient = new Client();
objShape= objClient.CretaeObject(“Circle”);

objShape= objClient.CretaeObject(“Square”);

..........Prototype Pattern[CD]

When creating an object is very time consuming or complex in some way than we can just make the clone of existing object. This is called Prototype pattern.

public class PersonData : ICloneable

public Object clone()

return this.MemberwiseClone();
catch(Exception e)
return null;

..........Adaptor Pattern[SD]

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

During object-oriented developments, some times we have to use an unrelated class along with our existing class hierarchy. The simplest solution is to make a wrapper or adaptor around the foreign class, which is acceptable by the existing class hierarchy. This is what known as the ADAPTOR PATTERN or WRAPPER PATTERN.

Suppose we have a class CClient and COldClass

class CClient

public void ClientMethod(IExisting objIExisting)


class COldClass : IExisting
public void Method()

And we are using them like that
public void main()
CClient objCClient = new CClient();
objCClient.ClientMethod(new COldClass());

We were using that classes in our code, In future we have given another class called CAdoptee. which has it’s own method.

private class CAdaptee

public void ForeignMethod()
Console.WriteLine("Foreign Adapted Method");


And we have to use that CAdoptee class with client class and we have to call that method ClientMethod. So how we can do that while ClientMethod except a parameter of type IExisting.
There is a way to do that by introducing a CAdopter class.

priavte class CAdopter: IExisitng

private CAdoptee objCAdoptee = new CAdoptee();

public void Method()

public void main()
CClient objCClient = new CClient();
objCClient.ClientMethod(new CAdopter());

..........Composite Pattern[SD]

The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object.

The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly. An XmlDocument,TreeView are example of composite pattern.

public class TreeNode

priavte String m_sName = null;
priavte Arraylist m_arlstChilds = null;

public TreeNode()
m_arlstChilds=new Arraylist();

public String Name

return m_sName;



private String m_sValue = null;

public String Value

return m_sValue;


public void AddNode(TreeNode objTreeNode)

public class CreateTree
TreeNode BookNode = new TreeNode(“Bible”,”Book”);
TreeNode ChapterNode1 = new TreeNode(“Chapter1”,”Chapter1”);
TreeNode ChapterNode2 = new TreeNode(“Chapter2”,”Chapter2”);
TreeNode ChapterNode3 = new TreeNode(“Chapter3”,”Chapter3”);

TreeNode SectionNode1 = new TreeNode(“Section1”,”Section1”);
TreeNode SectionNode2 = new TreeNode(“Section2”,”Section2”);




Thus the Composite pattern allows you to create a tree like structure for simple and complex objects so they appear the same to the client.

..........Bridge Pattern[SD]

The Bridge pattern is used to separate the interface of class from its implementation, so that either can be varied separately.

suppose we have an interface

public interface ISwitch
public void SwitchOn();

public void SwitchOff();

And we have class CFan

public class CFan : ISwitch
public void SwitchOn()
System.Console.Writeline(“Switch On”);

public void SwitchOff()
System.Console.Writeline(“Switch Off”);

Suppose two classes are derived from this interface Bulb and Fan.

In future if we require to add one or more function in Switch for Bulb than we have to add that function in Fan also But we don’t want it, This problem can be solved by converting this interface into abstract class. But this decision should be made earlier to implementation whether the interface should be interface or abstract class.

Difference Between Adoptor and Bridge
The adaptor is a thing that sits between the two interfaces. In a bridge, there isn't a thing that sits between two interfaces. The interfaces connect directly in a Bridge. It's a tight coupling. No adaptors sitting between the two halves.

A bridge is by design. An adaptor is not. An adaptor is a patch. A bridge is put in place on purpose.

An adaptor is just something for working one interface to fit another interface. The two interfaces "mean" the same thing, (or roughly the same thing,) they just do it in a different shape. So you put an adaptor between them.

..........Flyweight Pattern[SD]

When we need to share information between many objects than we use Flyweight pattern. If an information is shared between many objects than we can remove it from each object and referenced. This eliminates the redundancy and we can save memory. So instead of storing the same information n times for n object, it is only stored once. This object that contains all of the intrinsic(Moolbhoot) information is called a flyweight object.

Different Component involved in flyweight Pattern are:-

Flyweight is the set of intrinsic information that a set of objects share in common. It is a abstract class.

The ConcreateFlyweight is a subclass of Flyweight, and contains all of its information as well as how to calculate extrinsic information for a particular object. It is shared among more than one object.

The FlyweightFactory serves to dispense particular Flyweight requested. When a Flyweight with certain properties requested it check to see if it exist, If it exist it return else create a new one store it and return.

The Client, in creating a new object, must assign a Flyweight to it. So it ask the Flyweight Factory for a particular flyweight, receives that flyweight and create a reference to it, in the object it is creating.

abstract class Company
protected String m_sCompanyName = “ABC”
public abstract void GetEmployeeDetails();

private class Engineering:Company
Console.WriteLine(“Company Name “ + m_sCompanyName);
private void GetEmployeeDetails()
{ Consloe.WriteLine(“Engineering Employees Detail”);

private class RND:Company
Console.WriteLine(“Company Name “ + m_sCompanyName);
private void GetEmployeeDetails()
{ Consloe.WriteLine(“RND Employees Detail”);

..........Facade Pattern

Facade - The front(face) of a building,In Facade pattern a single class represent the entire system and hide the complexity of the system.

class CPU {

public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }


class Memory {

public void load(long position, byte[] data) { ... }


class HardDrive {

public byte[] read(long lba, int size) { ... }


/* Facade */

class Computer {

private CPU cpu;
private Memory memory;
private HardDrive hardDrive;

public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();

public void startComputer() {


/* Client */

class You {

public static void main(String[] args) {
Computer facade = new Computer();


We do not know anything about Computer we know only one function startComputer what is happening inside startComputer no need to worry about that.

..........Decorator Pattern

A Decorator design pattern is a design pattern that allows new/additional behavior to be added to an existing object dynamically.

The decorator pattern can be used to extend the functionality of certain object at runtime, independently of other instances of the same class. This is achieved by designing a new decorator class that wraps the original class.

We have to follow following steps for that :-
1) Subclass the original “Component” class or interface into a decorator class(Window is Component interface in below example).
2) In the decorator class add a component pointer as a field( CWindowDecorator is an added class here to add more functionality.)
3) Pass a component to the decorator constructor to initialize the component pointer.
4) In the Decorator class, redirect all Component methods to the component pointer.
5) In the Decorator class override any component methods whose behaviour need to be modified.

Suppose we have a window interface :-

// the Window interface
interface IWindow
public void draw(); // draws the Window
public String getDescription(); // returns a description of the Window

And a Simple Window class

// implementation of a simple Window without any scrollbars
class CSimpleWindow : Window
public void draw()
// draw window
public String getDescription()
return "simple window";

Suppose we want to add Vertical Scroll Bar into it.

//abstract decorator class - note that it implements Window
abstract class CWindowDecorator : IWindow
protected IWindow decoratedWindow; // the Window being decorated

public CWindowDecorator (IWindow decoratedWindow)
this.decoratedWindow = decoratedWindow;

public void draw()

public void getDescription()

Now we can add new functionality to the methods in new subclass of WindowDecorator.

// the first concrete decorator which adds vertical scrollbar functionality
class CVerticalScrollBarDecorator : CWindowDecorator
public CVerticalScrollBarDecorator (IWindow decoratedWindow)

public void draw()

private void drawVerticalScrollBar()
// draw the vertical scrollbar

public String getDescription()
return decoratedWindow.getDescription() + ", including vertical scrollbars";

How to use there classes.

public class CDecoratedWindowTest
public static void main(String[] args)
// create a decorated Window with horizontal and vertical scrollbars
IWindow decoratedWindow = new CVerticalScrollBarDecorator(new CSimpleWindow()));

// print the Window's description

.Output : Simple Window Including Vertical ScrollBar

.....Behavioral Pattern

Behavioral patterns are those patterns that are most specifically concerned with communication between objects.

The interactions between the objects should be such that they are talking to each other and still are loosely coupled. The loose coupling is the key to n-tier architectures. In this, the implementation and the client should be loosely coupled in order to avoid hard-coding and dependencies.

There are eleven patterns under this category:-

Chain of Responsibility :- The chain of responsibility pattern is a design pattern that defines a linked list of handlers, each of which is able to process requests. When a request is submitted to the chain, it is passed to the first handler in the list that is able to process it. Ex. Exception Handling is an example of this pattern.

Command Pattern :- The Command design pattern encapsulates the concept of the command into an object.The issuer holds a reference to the command object rather than to the recipient.The issuer sends the command to the command object by executing a specific method on it.The command object is then responsible for dispatching the command to a specific recipient to get the job done. Delegate -Event an example of command pattern.

Interpreter Pattern :- The Interpreter Pattern defines a grammatical representation for a language and an interpreter to interpret the grammar. The best example you can get for this is Java itself which is an interpreted language. It converts the code written in English to a byte code format so as to make possible for all the operating systems to understand it. This quality of it makes it platform independent.

Iterator Pattern :- The Iterator pattern allows you to move through a list or collection of data using a standard interface without having to know the details of the internal representations of that data. Ex. Enumerator

Mediator Pattern :- Mediator pattern, used to handle complex communications between related objects, helping with decoupling of those objects.Ex. Just like all airplanes contact to airplane control Tower to confirm whether they should land or not, they do not communicate to each other.

Momento Pattern :- The memento design pattern is a pattern that helps to save the object's internal state in an external place enabling us to restore the state later when needed. The memento pattern doesn’t violate encapsulation of the internal state. The pattern is rarely used but it’s very helpful in scientific computing or in computer games (saving of check points in the game for example).

Observer :- Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.When we call AcceptChanges method of dataset all its row's status has been changed, this is the best example of Observer pattern. MVVM Pattern is an example of Observer pattern where when properties changes than the control bind with them are changes as well.

State :- Allow an object to alter its behavior when its internal state changes.

Strategy :- Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Template Pattern :- It is used to set up the outline or skeleton of an algorithm, leaving the details to specific implementations later. This way, subclasses can override parts of the algorithm without changing its overall structure.Ex.. When we use interface or abstract class simply actually at that way we are using Template pattern.

Visitor Pattern :- The visitor design pattern is a way of separating an algorithm from an object structure it operates on. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.

If a Collection contains different classes objects. And we have to iterate the collection than we have to typecast each object to its proper type means we have to use if-else ladder. The best solution for this problem is used Visitor Pattern. Implements all classes with a common interface and again when you will iterate the collection you have to typecast only once in interface type.