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
RemotingServices.Marshal(obj,"RemoteObject")
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 :
Activator.CreateInstance()
By Keyword "New".

And Singleton and SingleCall
RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
"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 http://www.UDDI.org .

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() + "'"))
{
objMgmt.Get();
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
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.

Index
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

Transaction

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);
objConnection.Open();

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

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

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

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

objTransaction.Rollback();

Console.WriteLine(e.ToString());

Console.WriteLine("Neither record was written to database.");
}
finally
{
objConnection.Close();
}

In Sql Server we can do it like this

CREATE PROCEDURE DeleteDepartment
(
@DepartmentID int
)
AS

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

-- STEP 1: Start the transaction
BEGIN TRANSACTION

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

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

-- Commit the transaction....
COMMIT

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

Ex.
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
Employee    
Id     Name
1      Aslam
2      Ammar
3      Azam


Manager    
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
{

get
{
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
{
get
{
//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
    {
        get
        {
            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 and Sealed class

public sealed clas Sinhgleton
{

private static readonly Singleton instance = new Singleton();

private Singleton()
{
}

public static Singleton Instance
{

get
{
return instance;
}

}

The benefit of using this approach(Using Sealed) that no one can create object even by inheritance, Otherwise anyone can create object  by inheritance like

public class Singleton
    {
        int counter = 0;
        private Singleton()
        {
            Console.WriteLine(counter++);
        }

        static Singleton singleton = null;

        public static Singleton GetSingleton()
        {
            if (singleton == null)
            {
                singleton = new Singleton();
                return singleton;
            }
            else
                return singleton;
        }
     

        public class SingletonChild : Singleton
        {           

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Singleton obj = new Singleton.SingletonChild();

            Singleton obj1 = new Singleton.SingletonChild();

            if (obj.Equals(obj1))
            {

            }
        }
    }

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


Example:

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)
{
objFigure.DrawFigure();
objFigure.DrawShade();
objFigure.FillColor();
}
}

public static void main(String[] args)
{

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

objFigure = new Circle();
objShape.CreateFigure(objFigure);

objFigure = new Rectalge();
objShape.CreateFigure(objFigure);
}

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

objBase.Method():
}

..........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)
{
if(Type==”Circle”)
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.Draw();.

objShape= objClient.CretaeObject(“Square”);
objShape.Draw();.
}

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

try
{
return this.MemberwiseClone();
}
catch(Exception e)
{
Console.Writeline(e.Message);
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)
{
objIExisting.Method();
}

}

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()
{
objCAdoptee.ForeignMethod();
}
}

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
{

get
{
return m_sName;
}

set
{
m_sName=value;
}

}


private String m_sValue = null;

public String Value
{

get
{
return m_sValue;
}

set
{
m_sValue=value;
}
}

public void AddNode(TreeNode objTreeNode)
{
m_arlsChilds.Add(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”);


BookNode.Add(ChapterNode1);
BookNode.Add(ChapterNode2);
BookNode.Add(ChapterNode3);

ChapterNode1.Add(SectionNode1);
ChapterNode1.Add(SectionNode2);

}


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() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}

}

/* Client */

class You {

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

}

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()
{
decoratedWindow.draw();
}

public void getDescription()
{
decoratedWindow.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)
{
base(decoratedWindow);
}

public void draw()
{
drawVerticalScrollBar();
base.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
Consloe.Writeline(decoratedWindow.getDescription());
}
}

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

..........Proxy Pattern

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.

There are several cases where a Proxy can be useful:
1. If an object, such as a large image, takes a long time to load.
2. If the object is on a remote machine and loading it over the network may be slow, especially during peak network load periods.
3. If the object has limited access rights, the proxy can validate the access permissions for that user.
4) In Remoting we use Proxy class that is a fake copy of server object that reside on client and call the real server object when we made a call to that proxy. this proxy help to compile client code as it is calling server method but server method are not present at compile time on client machine.


///
/// The 'Company' abstract class
///

abstract class Company
{
public abstract void GetDetail();
}

///
/// The 'MainClassEngineering' class
///

class MainClassEngineering: Company
{
public override void GetDetail()
{
Console.WriteLine("Called Main Class Method.");
}
}



///
/// The 'ProxyClass' class
///

class ProxyClass : Company
{
private MainClassEngineering _realObject;

public override void GetDetail()
{
// Use 'lazy initialization'
if (_realObject== null)
{
_realObject= new MainClassEngineering();
}

_realObject.GetDetail();
}
}

///
/// Entry point into console application.
///

static void Main()
{
// Create proxy and request a service
ProxyClass proxy = new ProxyClass();
proxy.GetDetail();
}

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

The responsibility of handling the request data is given to any of the members of the “chain”. If the first link of the chain cannot handle the responsibility, it passes the request data to the next level in the chain, i.e. to the next link. This is similar to what happens in an Exception Hierarchy. Suppose the code written throws an ArrayIndexOutOfBoundsException. Now, this exception is because of some bug in coding and so, it gets caught at the correct level. Suppose, we have an application specific exception in the catch block. This will not be caught by that. It will find for an Exception class and will be caught by that as both the application specific exceptions and the ArrayIndexOutOfBoundsException are sub-classes of the class Exception.

Once get caught by the exception, which is the base class, it will then not look for any other exception. This is precisely the reason why, we get an “Exception is unreachable” message when we try to add a catch block with the exception below the parent exception catch block.

So, in short, the request rises in hierarchy till some object takes responsibility to handle this request.

public abstract class CNumberHandler
{
protected Handler m_objSuccessor;

public void setSuccessor(Handler successor)
{
m_objSuccessor = successor;
}

public abstract void handleRequest(Request request);
}

public class NegativeHandler : CNumberHandler
{
public void handleRequest(int iNumber)
{
if (iNumber < 0) { //if request is eligible handle it Console.WriteLine("Negative values are handled by ConcreteHandlerOne:"); } // if not else m_objSuccessor.handleRequest(request); } } public class ZeroHandler : CNumberHandler { public void handleRequest(int iNumber { if (iNumber == 0) { //if request is eligible handle it Console.WriteLine("Zero values are handled by ConcreteHandlerThree:"); } // if not else m_objSuccessor.handleRequest(request); } } public class PositiveHandler : CNumberHandler { public void handleRequest(int iNumber) { if (iNumber > 0)
{ //if request is eligible handle it
Console.WriteLine("Positive values are handled by ConcreteHandlerTwo:");
}
// if not
else
m_objSuccessor.handleRequest(iNumber);
}
}
public class Main {

public static void main(String[] args)
{

// Setup Chain of Responsibility
CNumberHandler objCNegativeHandler = new NegaitveHandler();
CNumberHandler objCZeroHandler = new ZeroHandler();
CNumberHandler objCPositiveHandler = new PositiveHandler();

objCNegativeHandler .setSuccessor(objCZeroHandler );
h2.setSuccessor(objCPositiveHandler );

// Send requests to the chain
objCNegativeHandler .handleRequest(-1);
objCNegativeHandler .handleRequest(0);
objCNegativeHandler .handleRequest(1);
objCNegativeHandler .handleRequest(2);
objCNegativeHandler .handleRequest(-5);
}
}

..........Command Pattern

When two objects communicate, often one object is sending a command to the other object to perform a particular function.The most common way to accomplish this is for the first object (the "issuer") to hold a reference to the second (the "recipient"). The issuer executes a specific method on the recipient to send the command.
But what if the issuer is not aware of, or does not care who the recipient is? That is, the issuer simply wants to abstractly issue the command?
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.

Example. 1. When you use web browser there is mthod ExecCommand, When we call that method to execute various command like copy,color,find etc. It send a command to the COM class to execute those methods.
2. To use delegates and event in any program is an example of Command Pattern

Examlpe:-

public class Sender
{
public delegate void Done(int iValue);
public event Done OnDone ;

public void DoIt()
{
if(OnDone != null)
OnDone(10);
}
}


public class Receiver
{
priavte Sender m_objSender = null;

public void Action()
{
m_objSender.OnDone += new Done(OnDone);
}

private void OnDone(int iValue)
{
MessageBox.Show(“Work has been done for “ + iValue);
}
}

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

The development of languages can be done when you find different cases but, somewhat similar, it is advantageous to use a simple language which can be interpreted by the system and can deal with all these cases at the same time.

To make this interpreter clearer, let’s take an example. The “musical notes” is an “Interpreted Language”. The musicians read the notes, interpret them according to “Sa, Re, Ga, Ma…” or “Do, Re, Me… ” etc and play the instruments, what we get in output is musical sound waves. Think of a program which can take the Sa, Re, Ga, Ma etc and produce the sounds for the frequencies.

For Sa, the frequency is 256 Hz, similarly, for Re, it is 288Hz and for Ga, it is 320 Hz etc etc…

In this, case, we need these values set somewhere so, that when the system encounters any one of these messages, we can just send the related frequency to the instrument playing the frequency.

We can have it at one of the two places, one is a constants file, “token=value” and the other one being in a properties file. The properties file can give us more flexibility to change it later if required.

Ex. Java program is the best example for interpreter pattern. It interprets code written in English language in Byte Code.

This is how an interpreter pattern works in its most simple implementation. If you are using interpreter pattern, you need checks for grammatical mistakes etc. This can make it very complex. Also, care should be taken to make the interpreter as flexible as possible, so that the implementation can be changed at later stages without having tight coupling.

Other advantage of Interpreter is that you can have more than one interpreter for the same output and create the object of interpreter based on the input. E.g. “Sa” or “Do” can also be implemented as “Download” activity in some other language. In this case, you can use same input and different outputs by getting the proper interpreter from the Interpreter Factory.

..........Iteretor Pattern

The Iterator is one of the simplest and most frequently used of the design patterns. 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

Example :

public interface Iterator
{
public Object First();
public Object Next();
public boolean isDone();
public Object CurrentItem();
}

public interface Enumeration
{
public boolean hasMoreElements();
public Object nextElement();
}

..........Observer Pattern

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.


// Suppose you are working with a data set and you call AcceptChanges after deleting some row. Than all rows objects updated accordingly.This is the best example of Observer patterns

//Create Dataset
Dataset objDs = new Dataset();

//Read data from database in Dataset
//Fill data set here

MessageBox.Show( objDs.RowState.ToString());
// You will get Added.

objDs.Tables(0).Rows(0).Item(0)=”Hello”;

MessageBox.Show( objDs.RowState.ToString());
// You will get Modified.

objDs.AcceptChanges();

MessageBox.Show( objDs.RowState.ToString());
// You will get Unchanged.

..........Momento Pattern

In this design pattern we save the state of object into xml or in memory stream so that it can be restored 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).


Use Cases for the Memento Pattern
You should use the pattern in the following cases:

* You need to save object’s state and use the saved state later in order to
* restore the saved state.
* You don’t want to expose the internal state of your object.



public class CUser
{
// Get data from database in a dataset object
Dataset objDs =null;

//Write in xml
objDs.WriteXml(XmlPath);

//With this Xml file you can again create the same dataset.
objDs.ReadXml(XmlPath);
}

..........Mediator Pattern

Mediator pattern, used to handle complex communications between related objects, helping with decoupling of those objects.
Example :-
An airport control tower is an excellent example of the mediator pattern. The tower looks after who can take off and land - all communications are done from the airplane to control tower, rather than having plane-to-plane communication. This idea of a central controller is one of the key aspects to the mediator pattern.

private class AirPlane:ControllRoom
{
private String m_sAirPlaneNumber =null;

public AirPlane(String sAirPlaneNumber)
{
m_sAirPlaneNumber = sAirPlaneNumber;
}

public Register(Airplane objAirplane)
{
m_arlsAirplanes.Add(objAirplane);
}
}


private class ControllRoom
{
private Arraylist m_arlsAirplanes =null;
public Arraylist Airplanes
{
get
{
return m_arlsAirplanes;
}
}
public ControllRoom()
{
m_arlstAirplanes = new Arraylist();
}

private Arraylist m_arlstOnAirport =null;

public Arraylist OnAirport
{
get
{
return m_arlstOnAirPort;
}
}

public void AddOnAirPort(Airplane objAirplane)
{
m_arlstOnAirPort.Add(objAirplane);
}
public void RemoveFromAirPort(Airplane objAirplane)
{
m_arlstOnAirPort.Remove(objAirplane);
}

}
static void main()
{
Airplane objAirplaneA = new Airplane(“A100”);
objAirplaneA.Register(objAirplane);

if(objAirplaneA.OnAirport.Count <= 1)
objAirPlaneA.AddOnAirport(objAirplaneA);


Airplane objAirplaneB = new Airplane(“B100”);
objAirplaneB.Register(objAirplaneB);

if(objAirplaneB.OnAirport.Count <= 1)
objAirPlaneB.AddOnAirport(objAirplaneB);
}
}

..........State Pattern

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

static void Main()
{
CEmployee objCEmployee = new CManager();

objCEmployee = objCEmployee.Action();
objCEmployee = objCEmployee.Action();
objCEmployee = objCEmployee.Action();

// Wait for user
Console.ReadKey();
}


///
/// The 'CEmployee' abstract class
///

abstract class CEmployee
{
public abstract CEmployee Action();
}

class CManager: CEmployee
{
public override CEmployee Action()
{
Console.WriteLine(“This is Manager’s Work.”);
return new CDeveloper();
}
}

class CDeveloper : CEmployee
{
public override CEmployee Action()
{
Console.WriteLine(“This is Developer’s Work.”);
return new CManager();
}
}

..........Strategy Pattern

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

///
/// Entry point into console application.
///

static void Main()
{
CEmployee objCEmployee

objCEmployee = new CManager();
objCEmployee.DefineWork();

objCEmployee = new CDeveloper();
objCEmployee.DefineWork();
}

///
/// The 'Strategy' abstract class
///

abstract class CEmployee
{
public abstract void DefineWork();
}

///
/// A 'ConcreteStrategy' class
///

class CManager : CEmployee
{
public override void DefineWork()
{
Console.WriteLine("This is Manager Works.");
}
}

///
/// A 'ConcreteStrategy' class
///

class CDeveloper : CEmployee
{
public override void DefineWork()
{
Console.WriteLine( "This is Developer Work.");
}
}

..........Template Pattern

The Template Design Pattern is perhaps one of the most widely used and useful design 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.
This is particularly useful for separating the variant and the invariant behaviour, minimizing the amount of code to be written. The invariant behaviour is placed in the abstract class (template) and then any subclasses that inherit it can override the abstract methods and implement the specifics needed in that context. In the body of TemplateMethod() there are calls to operation1() and operation2(). What it is that operation1() and operation2() do are defined by the subclasses which override them.


public static void main()
{
TemplateClass aA = new ClassA();
aA.TemplateMethod();

TemplateClass aB = new ClassB();
aB.TemplateMethod();

// Wait for user
Console.ReadKey();
}


///
/// The 'TemplateClass' abstract class
///

abstract class TemplateClass
{
public abstract void Method1();
public abstract void Method2();

// The "Template method"
public void TemplateMethod()
{
Method1();
Method2();
}
}

///
///
///

class ClassA: TemplateClass
{
public override void Method1()
{
Console.WriteLine("Method1 in ClassA");
}
public override void Method2()
{
Console.WriteLine("Method2 in ClassA);
}
}

///
///
///

class ClassB : TemplateClass
{
public override void Method1()
{
Console.WriteLine("Method1 in ClassB");
}
public override void Method2()
{
Console.WriteLine("Method2 in ClassB");
}
}

..........Visitor Pattern

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.


The visitor pattern is used when:

* Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure).


Visitor lets you define a new operation without changing the classes of the elements on which it operates.

If you have a collection of objects and you have to perform some action for each object than you will do like this.

public void PrintObjectsType(Arraylist objArlst)
{
Iterator iterator = arlstCollection.iterator()
while (iterator.hasNext())
{
Object objIterator = iterator.next();

if (objIterator as CMale)
Console.WriteLine(“This is Male”);
else if (objIterator as Female)
Console.WriteLine(“This is Female”);
else
Console.WriteLine(“Other”);
}
}

But that is not a good programming practice to use if and else ladder. We can remove it using Visitor Pattern.

public interface IPerson
{
public void DoAction();
}

public class CMale:IPerosn
{
private void DoAction()
{
Console.WriteLine(“This is Male”);
}
}

public class CFemale:IPerosn
{
private void DoAction()
{
Console.WriteLine(“This is Female”);
}
}

public class CPrintPersonType
{
public void PrintPersonType(Arraylist objArlstPerosn)
{
Iterator objIterator = objArlstPerosn.iterator()
while (objIterator .hasNext())
{
IPerson objPerson = iterator.next();
objPerson.DoAction();
}
}
}

Difference Between Shallow Copy and Deep Copy

Similarity :- Both are used to copying data between objects.

Shallow Copy :- Create a new object copy all non static field to new object. If field is value type a bit by bit copy has been performed. If the field is reference type, the reference is copied but the referred object is not. Therefore original object and clone object will refer to the same object. If you will change one object’s ref value other object will be change accordingly. But in case of value type will refer different object. Means if you will change one value other will not change. .Net provides a method MemberwiseClone() for the shallow copy.

private void DoAction()
{

CPerson objCPerson = new CPerson();

objCPerson.Age = 20;
objCPerson.Name =”Mohammad”;
objCPerson.Salary = new CSlary(1000);

CPerson objShallowCPerson = CreateShallowCopy();

objShallowCPerson.Age =25;
objShallowPerson.Name =”Ahmad”;
objCShallow.Slalary = new Slary(2000);

//If you will check original object

Print(“Age= “ + objCPerson.Age);
Print(“Name = ” + objCPerson.Name);
Print(“Salary = ” + objCPerson.Salary);

In case of Shallow Copy Output will be

Age = 20;
Name = Mohammad;
Salary = 2000;

//In case of Deep copy output will be

Output

Age = 20;
Name = Mohammad;
Salary = 1000;
}

public class CPerson : ICloneable
{
public string Name;
public int Age;
pulic CSalary objSalary=null;
;
public object Clone()
{
return this.MemberwiseClone();
}

public CPerson CreateShallowCopy(CPerson objCPerson)
{
return (CPerson)objCPerson.MemberwiseClone();
}

}


Deep Copy Everything is same except in case of reference type. A new copy of the referred object is perforemed. Therefore original and clone object will refer to different object. If you will change one object’s ref value other object remain unchanged.

The classes to be cloned must be flagged as [Serializable].

There is no direct method for deep copy in .Net . But can do it following way.

Example 1

[Serializable]
public class Person : ICloneable
{
public string Name;
public Person Spouse;
public object Clone()
{
Person p = new Person();
p.Name = this.Name;
if (this.Spouse != null)
p.Spouse = (Person)this.Spouse.Clone();
return p;
}
}

Example 2

[Serializable]
// serialize the classes in case of deep copy
public class clsDeep
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;
public clsDeep CreateDeepCopy(clsDeep inputcls)
{
MemoryStream m = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(m, inputcls);
m.Position = 0;
return (clsDeep)b.Deserialize(m);
}
}

Deep Copy can be achieve by serialize the object.

Clone method is a method declared in ICloneable interface. and MemberwiseClone method is any objects inherit method that used for to create a shallow copy of an object.

Followers

Link