Monday, January 14, 2013

Socket Program in c-sharp

Client and server implementation using socket programming:

Socket -- an End-Point of To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the same network.
Details:Two programs are needed for communicating a socket application in C# using TCP/IP Communication protocol.
A Server Socket Program ( Server ) and a Client Socket Program ( Client ) .
Server Socket Program running on a computer has a socket bound to a Port Number on the same computer and listening to the client's incoming requests.
 Client Socket Program have to know the IP Address ( Hostname ) of the computer that the C# Server Socket Program resides.
Once the connection is established between Server and Client , they can communicate (read or write ) through their own sockets.
Start the server and then make a connection to server by invoking the client..
Both client and server are on the same machine.
Two types of communication protocol can beused for Socket Programming in C#: 
  1.  TCP/IP ( Transmission Control Protocol/Internet protocol ) Communication
  2.  UDP/IP ( User Datagram Protocol/Internet protocol ) Communication .
 Server Implementation:Below is the source code for server implementation

using System.Net.Sockets:
namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {

            TcpListener serverSocket = new TcpListener(8888);
            int requestCount = 0;
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Console.WriteLine("...Server Started");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" ... Accept connection from client");
            requestCount = 0;

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[10025];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" ..... Data from client - " + dataFromClient);
                    string serverResponse = "Server response " + Convert.ToString(requestCount);
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" ... " + serverResponse);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" ....exit");
            Console.ReadLine();
        }
    }
}

Client Implementation:Drag textbox,label and button control and drop them on form.In the code behind paste the following code
using System.Net.Sockets;
namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        private void Form1_Load(object sender, EventArgs e)
        {
            msg("Client Started");
            clientSocket.Connect("127.0.0.1", 8888);
            label1.Text = "Client Socket Program - Server Connected ...";
        }
       

        public void msg(string mesg)
        {
            textBox1.Text = textBox1.Text + Environment.NewLine + " --> " + mesg;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            msg("Data from Server : " + returndata);
        }
    }
}
Images:
1. Form Design:
2.  Client server snapshot (running mode)


Enjoy coding!!!!!

Friday, January 11, 2013

String Searching:Knuth-Morris-Pratt Algorithm

Knuth, Morris and Pratt discovered first linear time string-matching algorithm by following a tight analysis of the naive algorithm.

The Problem 

The problem that we are trying to deal with, is of course, exactly the same as the naive problem. Given some pattern p, does it exist in some string s.


Example

Let’s say we have the following string and pattern,
  • s = “abra abracad abracadabra”
  • p = “abracadabra”
Now if this were the naive approach, we would need quite a lot of comparisons – 154 to be exact! Before we start, it would be best to note that we’ll be using zero-based arrays for this. So since s is really an array of characters, then s[0] would be referencing to the character ‘a’, and p[2] would be the character ‘r’.
We also need two more variables, name i and j. Here i will be the indexes into p, and j will be the indexes into s. Now, let’s start off with the first match-up,
  • j = 012345678901234567890123
  • s = abra abracad abracadabra
  • p = abracadabra
  • i = 01234567890
Here we can see that p[0] and s[0] are equal, but then we reach s[4] and p[4]. Here we have a space character and the character ‘c’. Clearly they don’t match up. So what we need to do now is slide the pattern along. But this is the part that isn’t like the naive approach. Instead of sliding the pattern across by one, we slide the pattern across by a special value. You see, behind the scenes there is in fact a table T. We’ll get to this later, but for now all you need to know is that we slide the pattern across to j=3 and reset i=0.
We get the value of j=3 from j = j+i-T[i] = 0+4–1 = 3. In this equation, j=0 because if you remember, j will be the starting point. i=4 because this is the point of failure – the position in p where we found our mismatch. And T[i]=1 because, well we’ll come to this later, for now take my word for it.
With these new values, we can now slide the pattern along:
  • j = 012345678901234567890123
  • s = abra abracad abracadabra
  • p =    abracadabra
  • i =    01234567890
Now we see that we find a mismatch at s[4] and p[1]. This is we slide the pattern along to j=4. If you wish to know why, it’s because j=3 and i=1 (which should be obvious) and T[i]=0, sticking them into that equation gives
j = j+i-T[i] = 3+1–0 = 4
Instead of drawing out all of the possible combinations, let’s jump ahead to:
  • j = 012345678901234567890123
  • s = abra abracad abracadabra
  • p =      abracadabra
  • i =      01234567890
Now this should be better to show off why this algorithm is better than the naive approach. Here we compare the characters again, and fail at s[12] and p[7]. But because of the way the algorithm works, we slide the pattern across by a huge amount,
  • j = 012345678901234567890123
  • s = abra abracad abracadabra
  • p =              abracadabra
  • i =              01234567890
I have actually skipped one step here, where we compare s[12] and p[0]. But as you can see the next step succeeds, and we find a match at j=13!
What’s more amazing is that we have only made 28 comparisons! A lot better than the naive approaches 154

So what’s this T table then!?

Well we had to get to this part sooner or later, so we may as well explain this now. Besides the obvious as to why KMP differs from the naive approach, there is another reason. You see, the KMP algorithm has a pre-processing stage, that is, that it does (or rather creates) something from the given pattern before the algorithm even starts searching for the pattern.
This pre-processing stage is the T table, and this is what it looked like for the above pattern:
i 0 1 2 3 4 5 6 7 8 9 10
p[i] a b r a c a d a b r a
T[i] -1 0 0 0 1 0 1 0 1 2 3
Now this may look rather complex, but it really isn’t that hard to understand. First things first, the values of T[0] and T[1] are always fixed, they never change. Therefore, T[0]=-1 and T[1]=0 all of the time. This means that the main program begins from i=2. There is also another variable that we need to use, and we shall call this variable sub, with initial value of sub=0.
And here is some pseudo-code to populate the T table.
Remember. i=2 and sub=0.

//whilst i doesn’t exceed the length of p
001    WHILE (i < length_of_p) DO:
//we have a continued substring in p from the start of p
002        IF (p[i-1] == p[sub]) THEN:
003            sub=sub+1
004            T[i] = sub
005            i=i+1
//if the substring stops, fall back to the start
006        ELSE IF (sub > 0) THEN:
007            sub = T[sub]
//we weren’t in a substring, so use default value
008        ELSE
009            T[i] = 0
010            i=i+1
011        ENDIF
012    ENDWHILE

I am not going to walk through the whole process. So let’s start at i=7 and sub=0.
Starting at line 002 we test to see if p[6] is equal to p[0]. Since ‘d’ is not equal to ‘a’ then we move onto the next statement. Here sub is not greater than 0, so we move onto the final statement. With this we make T[7]=0 and increment i to i=8.
Now, starting back at the first IF statement, we test to see if p[7] equals p[0], and by surprise it does since ‘a’ = ‘a’. This means that we increment sub to sub=1, we make T[8]=1 and increment i again to i=9.
Moving on again, we test p[8] to p[1] this time, since sub=1. This time we succeed again since ‘b’ = ‘b’. Therefore we increment sub and i to sub=2 and i=10. And obviously we set T[9]=2.
I’ll leave T[10] up to you, as well as the ones I missed, but it should be obvious by now how this works.
If you’re pondering why we need a –1 at the beginning, it’s so that if we fail on the very first character, we simply move along to the next character in the main string. As if this were just 0, we would not slide the pattern along.

The Main Algorithm

Now that we understand how the T table is created, the main algorithm for the KMP is very simple.
First of all, we have to remember that we have s which is the string to search through, and p which is the pattern to find. Then of course we have i which is the current index into p, and j which is the current index into s.
And here is the pseudo-code for the KMP,
       //while we don’t exceed the length of string s
001    WHILE (j+i < length_of_s) DO:
//character matching for parallel characters
002        IF (p[i] == s[j+i]) THEN:
//reached the end of the pattern, match found.
003            IF (i == length_of_p –1) THEN:
004                RETURN j
005            ENDIF
006            i=i+1
//parallel characters don’t match, slide pattern along
007        ELSE
008            j=j+i-T[i]
009            IF (T[i] > –1)
010                i = T[i]
011            ELSE
012                i = 0
013            ENDIF
014        ENDIF
015    ENDWHILE
016
//we reached the end of the string, match not found
017    RETURN length_of_s
This may look horribly daunting at first, but it really is very simple. Line 002 is simple the character by character matching process, matching parallel characters from the pattern and the string. If we reach the end of the pattern, return the position is s where is it (line 004), otherwise, we still have a character by character match, so increment to the next character in the pattern for testing (line 006).
The real fun beginnings inside of the ELSE statement. Now line 008 should look very familiar. Yep, we came across it earlier. This line simply sets the new start position in string s where we start matching the pattern against it again, and of course, you now know what the T table looks like.
The next part, from lines 009 to 013 are a little more tricky to grasp. Basically, when we slide the pattern along, we don’t always need to re-test some of the characters from the pattern. This is because of the way the T table works, and it’s called backtracking. For example, if we have the following s and p:
  • j = 01234567890
  • s = abcdab abcd
  • p = abcdabd
  • i = 0123456
We can see that the initial start point will fail at s[6] and p[6]. Now because of where is failed, T[6] is actually equal to the value 2. Therefore, we slide the pattern along to j = j + i + T[i] = 0 + 6 – 2 = 4:
  • j = 01234567890
  • s = abcdab abcd
  • p =     abcdabd
  • i =     0123456
But wait a second, we don’t need to compare the first 2 characters of p again, because we know that they already match up due to the T table. Therefore, like is says at line 010, we start at index i = T[6] = 2. This saves us a lot of time from doing none needed comparisons!
This backtracking only works if the value at T[i] is greater than 0. Otherwise, we just start at index i=0 in the pattern.

The Complexity

So, after all of this, what is the complexity of the KMP algorithm? Well the best part is that both the pre-processing phase and the main phase run in linear time. That is, the construction of the T table takes O(m) time, where m is the length of the pattern p. Then, the main program itself takes O(n) time where n is the length of the string s. Therefore the  overall time complexity is O(m+n).

Source:computersciencesource.wordpress.com/2011/01/03/string-searching-the-knuth-morris-pratt-algorithm/
Resources [1] http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
[2] University of Manchester, Advanced Algorithms 1 lecture notes by David Rydeheard
[3] Knuth-Morris-Pratt: An Analysis by Mireille Regnier
[4] Badgerati Tutorials – Knuth-Morris-Pratt Algorithm 




 

Friday, November 23, 2012

How to install an assembly in the Global Assembly Cache (GAC) in .NET

 What is a Shared Assembly?
A shared assembly is one that is used by multiple applications on the machine. A shared assembly must have a name that is globally unique. The .NET Framework supports these naming requirements through a technique called strong names.
Shared assemblies must have a "strong name" consisting of the name of the assembly, the version, a 64 bit hash of a public key (called a ´token´) and the culture.

To create a strong name for an assembly (that is, to generate a public/private key pair), you'll have to use another utility called sn.exe.

In this article, we will create a Visual C# 2010 class Library component called myGAC. We will also create a key file named mykeys.key. We will sign our component with this key file and place it in
To create a Component we have to create a Class Library project by using Visual Studio .NET.
Step 1 : Open Visual Studio .NET
Create a new Class Library project named myGAC in Visual Studio .NET or in Visual c# 2010.

Here is the code for the component. It just includes one method which returns a string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myGac
{
    public class Class1
    {

        public string GetName()
        {
            return "Syed Nisar Bukahri";
        }

    }
}

Step 2 : Generating Cryptographic Key Pair using the tool SN.Exe
Now, we will use the SN tool to generate the cryptographic key pair.


sn -k "C:\[DirectoryToPlaceKey]\[KeyName].key"
Next, create a directory named mykeys in C:\ so that you can easily locate the key and access the key from the visual studio command prompt.
Type the following at the command prompt.

sn -k "C:\mykeys\mykeys.key"
Step 3 : Sign the component with the key
A key is generated, but it is not yet associated with the project's assembly.
 To establish the association, open the AssemblyInfo.cs file in Visual Studio 2010 Solution Explorer.Add the following to the
list of assembly attributes that are included in this file by default when a project is created in Visual Studio .NET or in Visual Studio 2005:
[assembly: AssemblyKeyFile("C:\\mykeys\\mk.key")]

Note:Add this line just below the following line
[assembly: AssemblyTitle("ClassLibrary1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClassLibrary1")]
[assembly: AssemblyCopyright("Copyright ©  2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
...Add this line here.......
Now recompile/build the project and the assembly will be signed.
The next step is to install the assembly into the Global Assembly Cache.

Step 4 : Host the signed assembly in Global Assembly Cache
Using the Global Assembly Cache tool (Gacutil.exe)
You can use Gacutil.exe to add strong-named assemblies to the global assembly cache and to view the contents of the global assembly cache.
At the command prompt, type the following command:

gacutil ­I <assembly name>
In this command, assembly name is the name of the assembly to install in the global assembly cache.

The following example installs an assembly with the file name myGAC.dll into the global assembly cache.

gacutil -I "C:\[PathToBinDirectoryInVSProject]\myGAC.dll"

After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there.
Or if you are running windows 7 go to this location to locate the Assembly
C:\Windows\Microsoft.NET\assembly\GAC_MSIL
and here you will the folder in which is your signed assmbly
like myGac folder
In this will be another folder with name like
v4.0_1.0.0.0__e20b8219cca7baba
and in this folder will be your assemble stored with name as myGac.dll
Step 5 : Test the assembly
Once you've installed the assembly into the GAC, you can use it from other programs by creating a reference.

Now, we will create a sample client application which uses our shared assembly.

In our sample clientGACTest project, expand the project and then right-click on the References item. Select "Add Reference" from the popup menu, and the Add Reference dialog box is displayed.

To refer an assembly in the GAC, just click on the Browse button and browse to the directory (C:\Windows\Microsoft.NET\assembly\GAC_MSIL\v4.0_1.0.0.0__e20b8219cca7baba) that contains the assembly (myGAC.dll).
Locate the assembly, select it, and click OK.

Click on the myGAC reference in Solution Explorer and then examine the Properties pane. You'll see that the Copy Local property is set to False, Strong Name is true,Aliases is global and that the assembly version is 1.0.0.0
Just create a sample code as listed below :

You can now compile and run the clientGAC program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myGac;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c = new Class1();
            string str = c.GetName();
            Console.WriteLine(str);
            Console.Read();
        }
    }
}

And it will display the name "Syed Nisar Bukhari"

This article describes how to generate a strong name for an assembly and to install a .dll file in the Global Assembly Cache.
The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications.
 The GAC is automatically installed with the .NET runtime. Components are stored in C:\Windows\Microsoft.NET\assembly\GAC_MSIL\ or  C:\WINNT\Assembly.





Now time to practice!!!!


Thursday, November 22, 2012

How to Change the password for user sa of SQL Server

How to change the password of user sa of SQL Server

Make a login to SQL Server using windows authentication
Go to Security->Logins->right click on sa->properties->General tab and change the password
as
Password:
Confirm password:


Click on Ok   and you are done!!!!

Connect Sql Sever 2008 remotely

Open SQL Server Management studio

In the server name type the machine name  say HP-HP
 Set authentication to SQL Server authentication
Specify Login and password

Hope it helps....

Exception:Login failed for user 'IIS APPPOOL\ASP.NET v4.0

The fix to this exception is as:
Go to  IIS7->Application Pools -> Advanced Settings
Change the ApplicationPoolIdentity as
In Process Model section change the identity to Localsystem.This will make your application run under NT AUTHORITY\SYSTEM, which is an existing login for the database by default.

AdvancedSettings

Hope it helps.....

Sunday, October 14, 2012

SQL SERVER : Error 3154: The backup set holds a backup of a database other than the existing database


Error 3154: The backup set holds a backup of a database other than the existing database

Here is the fix to this error:


Steps:
1) Use WITH REPLACE while using the RESTORE command
2) Delete the older database which is conflicting and restore again using RESTORE command.
RESTORE DATABASE Inventory
FROM DISK = 'C:\BackupInventory.bak'WITH REPLACE
You are actually  trying to restore the database on another existing active database.

Enjoy..this is the efficient fix

Saturday, October 6, 2012

A potentially dangerous Request.Path value was detected from the client (:)

Sometimes you get the following exception when usually opening a page in web browser
A potentially dangerous Request.Path value was detected from the client (:)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client (:).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (:).]
   System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +8884233
   System.Web.PipelineStepManager.ValidateHelper(HttpContext context) +59



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 

Solution:
1.Check the url properly.Find out if there is any invalid character that has been accidently set as a part of the url.In my case when i got this exception,i did enough of google and all that....when  checked the url and i found that "colon :"  was getting appended to the url at the end.
like this http://localhost/myapp/index.aspx:
It is not always the case with colon...somtimes there may be some other unwanted character...This was the case with my problem...
I removed the colon and the problem was fixed......................and closed all the windows from google search :)


OR
These link may also be helpful
http://www.cryer.co.uk/brian/mswinswdev/ms_vbnet_server_error_potentially_dangerous.htm

http://stackoverflow.com/questions/5967103/a-potentially-dangerous-request-path-value-was-detected-from-the-client











Wednesday, October 3, 2012

SQL 2008 - "Saving changes is not permitted." error message.. Whenever any change is made to the table in SQL Server 2008,the following message is displayed Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

The fix to this warning is as:
Open SQL Server Management Studio (SSMS).
On the Tools menu, click Options.
In the navigation pane of the Options window, click Designers.
Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.
Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

To determine whether the Change Tracking feature is enabled for a table, follow these steps:
In SQL Server Management Studio, locate the table in Object Explorer.
Right-click the table, and then click Properties.
In the Table Properties dialog box, click Change Tracking.
If the value of the Change Tracking item is True, this option is enabled for the table. If the value is False, this option is disabled.

When the Change Tracking feature is enabled, use Transact-SQL statements to change the metadata structure of the table.

Steps to reproduce the problem

In SQL Server Management Studio, create a table that contains a primary key in the Table Designer tool.
Right-click the database that contains this table, and then click Properties.
In the Database Properties dialog box, click Change Tracking.
Set the value of the Change Tracking item to True, and then click OK.
Right-click the table, and then click Properties.
In the Table Properties dialog box, click Change Tracking.
Set the value of the Change Tracking item to True, and then click OK.
On the Tools menu, click Options.
In the Options dialog box, click Designers.
Click to select the Prevent saving changes that require table re-creation check box, and then click OK.
In the Table Designer tool, change the Allow Nulls setting on an existing column.
Try to save the change to the table.
[Source:Microsoft]


Thursday, September 20, 2012

SQL SERVER – FIX : ERROR : Cannot open database requested by the login. The login failed. Login failed for user ‘NT AUTHORITY\NETWORK SERVICE’.


This error occurs when you have configured your application with IIS, and IIS goes to SQL Server and tries to login with credentials that do not have proper permissions. This error can also occur when replication or mirroring is set up.
Here is the solution:
Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
In newly opened screen of Login Properties, go to the “User Mapping” tab. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed. On the lower screen, check the role db_owner. Click OK.
Hope this solves your issue

Thursday, September 13, 2012

Manually configure IIS webserver for asp.net 4.0

Hi folks if you are getting this error "Manually configure IIS webserver for asp.net 4.0" then do the following





1.Open visual studio command prompt in administrative mode.
2.Then run this command
       C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i

i.e., you have to reach to v4.0.30319 folder first,then run the command aspnet_regiis -i

Here is the screen shot


Hope this solves your problem

How to Install SQL SERVER – 2008 –A Step By Step Installation Guide


How to Install SQL SERVER – 2008 –A Step By Step Installation Guide 

SQL SERVER 2008 Release Candidate 0 has been released for some time and I have got numorous request about how to install SQL Server 2008. I have created this step by step guide Installation Guide. Images are used to explain the process easier.
[Click On Images to See Larger Image]
[Click On Images to See Larger Image]

Monday, December 19, 2011

C# Facade Design Pattern

In real world a facade or façade  is generally one exterior side of a building usually, but not always, the front...:)

The facade pattern is a software engineering design pattern commonly used with object oriented programming analogy to an architectural facade.A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make code that uses the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).
    • Facade defines a higher-level interface that makes the subsystem easier to use. Facade  is one of the common and easiest patterns. It wrap a complicated subsystem with a simpler interface. As a developer we often use this facade pattern. Even some of them don't recognise while using it that its a facade patterns. I have tried to explain facade pattern by building a blog system.
    • Facade design patterns  gives easier interface for common task. It provides simplified and uniform interface to a large subsystem of classes. For example in a shopping cart system  there could be many API’s related to register user, purchase,user detail, transactions etc so facade deals with all these interfaces and provide one simple modified interface to deals with them.
      A more simple non-software example can be if you want to play a game suppose Metal gear Solid on PS3 (Did i tell you that i love that game?). You Require PS3, HD TV, Controller etc.  So there are so many sub system could be involve if you want to play a game on ps3. But actually all you are doing in simpler term is playing a game. So facade can give you a simple interface with a operation call PlayGame() in this example.The Facade object should be a fairly simple advocate or facilitator. If the Facade is the only access point for the subsystem, it will limit the features and flexibility that “power users” may need.
      For example we have
      // Facade pattern -- Structural example

      using System;

      namespace DoFactory.GangOfFour.Facade.Structural
      {
        /// <summary>
        /// MainApp startup class for Structural
        /// Facade Design Pattern.
        /// </summary>
        class MainApp
        {
          /// <summary>
          /// Entry point into console application.
          /// </summary>
          public static void Main()
          {
            Facade facade = new Facade();

            facade.MethodA();
            facade.MethodB();

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

        /// <summary>
        /// The 'Subsystem ClassA' class
        /// </summary>
        class SubSystemOne
        {
          public void MethodOne()
          {
            Console.WriteLine(" SubSystemOne Method");
          }
        }

        /// <summary>
        /// The 'Subsystem ClassB' class
        /// </summary>
        class SubSystemTwo
        {
          public void MethodTwo()
          {
            Console.WriteLine(" SubSystemTwo Method");
          }
        }

        /// <summary>
        /// The 'Subsystem ClassC' class
        /// </summary>
        class SubSystemThree
        {
          public void MethodThree()
          {
            Console.WriteLine(" SubSystemThree Method");
          }
        }

        /// <summary>
        /// The 'Subsystem ClassD' class
        /// </summary>
        class SubSystemFour
        {
          public void MethodFour()
          {
            Console.WriteLine(" SubSystemFour Method");
          }
        }

        /// <summary>
        /// The 'Facade' class
        /// </summary>
        class Facade
        {
          private SubSystemOne _one;
          private SubSystemTwo _two;
          private SubSystemThree _three;
          private SubSystemFour _four;

          public Facade()
          {
            _one = new SubSystemOne();
            _two = new SubSystemTwo();
            _three = new SubSystemThree();
            _four = new SubSystemFour();
          }

          public void MethodA()
          {
            Console.WriteLine("\nMethodA() ---- ");
            _one.MethodOne();
            _two.MethodTwo();
            _four.MethodFour();
          }

          public void MethodB()
          {
            Console.WriteLine("\nMethodB() ---- ");
            _two.MethodTwo();
            _three.MethodThree();
          }
        }
      }

      Output
      MethodA() ----
      SubSystemOne Method
      SubSystemTwo Method
      SubSystemFour Method

      MethodB() ----
      SubSystemTwo Method
      SubSystemThree Method

Patterns in Practice..Cohesion And Coupling

Much of software design involves the ongoing question, where should this code go?
In particular, I would like to achieve three specific things with my code structure:
  1. Keep things that have to change together as close together in the code as possible.
  2. Allow unrelated things in the code to change independently (also known as orthogonality).
  3. Minimize duplication in the code.
To achieve these three goals, I need some tools to help me know where new code should go and some other tools to help me recognize when I've put code in the wrong place.
By and large, these goals are closely related to the classic code qualities of cohesion and coupling. I achieve these goals by moving toward higher cohesion and looser coupling. Of course, first we need to understand what these qualities mean and why coupling and cohesion are helpful concepts. Then I'd like to discuss some of what I'm going to call "design vectors" that help us move toward better structures and recognize when we need to move away from bad structures that have crept into our code.
Just as a note, I'm the primary developer of an open source inversion of control (IOC) tool called StructureMap. I'm going to be using some real-life examples from StructureMap to illustrate the design problems that these vectors address. In other words, don't make the same mistakes that I made.

Decrease Coupling
You can't help but hear the terms "loose coupling" or "tight coupling" in almost any discussion on software design. Coupling among classes or subsystems is a measure of how interconnected those classes or subsystems are. Tight coupling means that related classes have to know internal details of each other, changes ripple through the system, and the system is potentially harder to understand. Figure 1 shows a contrived sample of a business-processing module that is very tightly coupled to various other concerns besides the business logic.
public class BusinessLogicClass {
  public void DoSomething()  {
    // Go get some configuration
    int threshold = 
      int.Parse(ConfigurationManager.AppSettings["threshold"]);

    string connectionString = 
      ConfigurationManager.AppSettings["connectionString"];

    string sql = 
      @"select * from things 
        size > ";

    sql += threshold;

    using (SqlConnection connection = 
      new SqlConnection(connectionString)) {

      connection.Open();

      SqlCommand command = new SqlCommand(sql, connection);
      using (SqlDataReader reader = command.ExecuteReader()) {
        while (reader.Read()) {
          string name = reader["Name"].ToString();
          string destination = reader["destination"].ToString();

          // do some business logic in here
          doSomeBusinessLogic(name, destination, connection);
        }  
      }
    }
  }
}
Let's say that what we really care about is the actual business processing, but our business logic code is intertwined with data-access concerns and configuration settings. So what's potentially wrong with this style of code?
The first problem is that the code is somewhat hard to understand because of the way the different concerns are intertwined. I'll discuss this further in the next section on cohesion.
The second problem is that any changes in data-access strategy, database structure, or configuration strategies will ripple through the business logic code as well because it's all in one code file. This business logic knows too much about the underlying infrastructure.
Third, we can't reuse the business logic code independent of the specific database structure or without the existence of the AppSettings keys. We also can't reuse the data-access functionality embedded in the BusinessLogicClass. That coupling between data access and business logic might not be an issue, but what if we want to repurpose this business logic for usage against data entered directly into an Excel spreadsheet by analysts? What if we want to test or debug the business logic by itself? We can't do any of that because the business logic is tightly coupled to the data-access code. The business logic would be a lot easier to change if we could isolate it from the other concerns.
To summarize, the goals behind achieving loose coupling between classes and modules are to:
  1. Make the code easier to read.
  2. Make our classes easier to consume by other developers by hiding the ugly inner workings of our classes behind well-designed APIs.
  3. Isolate potential changes to a small area of code.
  4. Reuse classes in completely new contexts.
  5. Code Smells
    It's obviously good to know how to do the right things when designing new code, but it might be even more important to recognize when your existing code or design has developed problems. Like inappropriate intimacy, "code smell" (defined by Martin Fowler in the book Refactoring: Improving the Design of Existing Code) is a tool that you can utilize to spot potential problems in code.
    A code smell is a sign that something may be wrong in your code. It doesn't mean that you need to rip out your existing code and throw it away on the spot, but you definitely need to take a closer look at the code that gives off the offending "smell." A code smell can be spotted by simple inspection. Learning about code smells is a powerful tool to remove little problems in your code and class design before those problems become bigger issues.
    Many, if not most, of the commonly described code smells are signs of poor cohesion or harmful tight coupling. Here are some other examples:
    Divergent Changes A single class that has to be changed in different ways for different reasons. This smell is a sign that the class is not cohesive. You might refactor this class to extract distinct responsibilities into new classes.
    Feature Envy A method in ClassA seems way too interested in the workings and data fields of ClassB. The feature envy from ClassA to ClassB is an indication of tight coupling from ClassA to ClassB. The usual fix is to try moving the functionality of the interested method in ClassA to ClassB, which is already closer to most of the data involved in the task.
    Shotgun Surgery A certain type of change in the system repeatedly leads to making lots of small changes to a group of classes. Shotgun surgery generally implies that a single logical idea or function is spread out over multiple classes. Try to fix this by pulling all the parts of the code that have to change together into a single cohesive class.

    Increase Cohesion
    The academic definition of cohesion is that it is a measure of how closely related all the responsibilities, data, and methods of a class are to each other. I like to think of cohesion as a measure of whether a class has a well-defined role within the system. We generally consider high cohesion to be a good thing and repeat the words "highly cohesive" like a mantra. But why?
    Let's think of coding as having a conversation with the computer. More accurately, we're having several simultaneous conversations with the computer. We're having conversations about how security is carried out, how the infrastructure concerns are supposed to behave, and what the business rules are.
    When you're at a loud party with a lot of different conversations going on at once, it can be difficult to focus on the one conversation you're trying to have. It's much easier to have a conversation in a quiet setting where there's only one conversation going on.
    An easy test for cohesion is to look at a class and decide whether all the contents of the class are directly related to and described by the name of the class—vague class names, such as InvoiceManager, do not count. If the class has responsibilities that don't relate to its name, those responsibilities probably belong to a different class. If you find a subset of methods and fields that could easily be grouped separately under another class name, then maybe you should extract these methods and fields to a new class.
    To illustrate, if you find methods and data in your TrainStation, Train, and Conductor classes that seem to most accurately fit the theme of the TrainSchedule class, move those methods and data into the TrainSchedule. One of my favorite sayings about design is applicable here: put code where you'd expect to find it. It's most logical to me that functionality involving a train schedule would be in the TrainSchedule class.
    To stretch my earlier conversation analogy, a system consisting of cohesive classes and subsystems is like a well-designed online discussion group. Each area in the online group is narrowly focused on one specific topic so the discussion is easy to follow, and if you're looking for a dialog on a certain subject, there's only one room you have to visit.

    Eliminate Inappropriate Intimacy
    Inappropriate intimacy refers to a method in a class that has too much intimate knowledge of another class. Inappropriate intimacy is a sign of harmful, tight coupling between classes. Let's say that we have a business logic class that calls an instance of class DataServer1 to get the data it needs for its business-logic processing. Figure 2 shows an example. In this case, the Process method has to know a lot of the inner workings of DataServer1 and a bit about the SqlDataReader class.
    public void Process() {
      string connectionString = getConnectionString();
      SqlConnection connection = new SqlConnection(connectionString);
      DataServer1 server = new DataServer1(connection);
    
      int daysOld = 5;
      using (SqlDataReader reader = server.GetWorkItemData(daysOld)) {
        while (reader.Read()) {
          string name = reader.GetString(0);
          string location = reader.GetString(1);
    
          processItem(name, location); 
        }
      }
    }
    Now, let's rewrite the code in Figure 2 to remove the inappropriate intimacy:
    public void Process() {
      DataServer2 server = new DataServer2();
      foreach (DataItem item in server.GetWorkItemData(5)) {
        processItem(item);
      }
    }
    As you can see in this version of the code, I've encapsulated all the SqlConnection and SqlDataReader object manipulation inside the DataServer2 class. DataServer2 is also assumed to be taking care of its own configuration, so the new Process method doesn't have to know anything about setting up DataServer2. The DataItem objects returned from GetWorkItemData are also strongly typed objects.
    Now, let's analyze the two versions of Process method against some of the goals of loose coupling. First, what about making the code easier to read? The first and second versions of Process perform the same basic task, but which is easier to read and understand? Personally, I can more easily read and understand the business logic processing without wading through data-access code.
    How about making our classes easier to consume? Consumers of DataServer1 have to know how to create a SqlConnection object, understand the structure of the DataReader returned, and iterate through and clean up the DataReader. A consumer of DataServer2 only has to call a no-argument constructor and then call a single method that returns an array of strongly typed objects. DataServer2 is taking care of its own ADO.NET connection setup and cleaning up open DataReaders.
    And as for isolating potential changes to a small area of code? In the first version of the code, almost any change in the way DataServer works would impact the Process method. In the second, more encapsulated version of DataServer, you could switch the data store to an Oracle database or to an XML file without any effect on the Process method.

    The Law of Demeter
    The Law of Demeter is a design rule of thumb. The terse definition of the law is: only talk to your immediate friends. The Law of Demeter is a warning about the potential dangers of code, as in Figure 3.
    public interface DataService {
      InsuranceClaim[] FindClaims(Customer customer);
    }
    
    public class Repository {
      public DataService InnerService { get; set; }
    }
    
    public class ClassThatNeedsInsuranceClaim {
      private Repository _repository;
    
      public ClassThatNeedsInsuranceClaim(Repository repository) {
        _repository = repository;
      }
    
      public void TallyAllTheOutstandingClaims(Customer customer) {
        // This line of code violates the Law of Demeter
        InsuranceClaim[] claims = 
          _repository.InnerService.FindClaims(customer);
      }
    }
    The ClassThatNeedsInsuranceClaim class needs to get InsuranceClaim data. It has a reference to the Repository class, which itself has a DataService object. ClassThatNeedsInsuranceClaim reaches inside Repository to grab the inner DataService object, then calls Repository.FindClaims to get its data. Note that the call to _repository.InnerService.FindClaims(customer) is a clear violation of the Law of Demeter because ClassThatNeedsInsuranceClaim is directly calling a method on a property of its Repository field. Now please turn your attention to Figure 4, which shows another sample of the same code, but this time it is following the Law of Demeter.
    public class Repository2 {
      private DataService _service;
    
      public Repository2(DataService service) {
        _service = service;
      }
    
      public InsuranceClaim[] FindClaims(Customer customer) {
        // we're simply going to delegate to the inner
        // DataService for now, but who knows what 
        // we want to do in the future?
        return _service.FindClaims(customer);
      }
    }
    
    public class ClassThatNeedsInsuranceClaim2 {
      private Repository2 _repository;
    
      public ClassThatNeedsInsuranceClaim2(
        Repository2 repository) {
        _repository = repository;
      }
    
      public void TallyAllTheOutstandingClaims(
        Customer customer) {
        // This line of code now follows the Law of Demeter
        InsuranceClaim[] claims = _repository.FindClaims(customer);
      }
    }
    What did we accomplish? Repository2 is easier to use than Repository because you have a direct method to call for the InsuranceClaim information. When we were violating the Law of Demeter, the consumers of Repository were tightly coupled to the implementation of Repository. With the revised code, I have more ability to change the Repository implementation to add more caching or swap out the underlying DataService with something completely different.
    The Law of Demeter is a powerful tool to help you spot potential coupling problems, but don't follow the Law of Demeter blindly. Violating the Law of Demeter does add tighter coupling to your system, but in some cases you may judge that the potential cost of coupling to a stable element of your code is less expensive than writing a lot of delegation code to eliminate the Law of Demeter violations.

    Tell, Don't Ask
    The Tell, Don't Ask design principle urges you to tell objects what to do. What you don't want to do is ask an object about its internal state, make some decisions about that state, then tell that object what to do. Following the Tell, Don't Ask style of object interaction is a good way to ensure that responsibilities are put in the right places.
    Figure 5 illustrates a violation of Tell, Don't Ask. The code is taking a purchase of some sort, checking for the possibility of a discount for purchases of more than $10,000, and finally examining the account data to decide whether there are sufficient funds. The previous DumbPurchase and DumbAccount classes are, well, dumb. The account and purchase business rules are both encoded in ClassThatUsesDumbEntities.
    public class DumbPurchase {
      public double SubTotal { get; set; }
      public double Discount { get; set; }
      public double Total { get; set; }
    }
    
    public class DumbAccount {
      public double Balance { get; set;}
    }
    
    public class ClassThatUsesDumbEntities {
      public void MakePurchase(
        DumbPurchase purchase, DumbAccount account) {
        purchase.Discount = purchase.SubTotal > 10000 ? .10 : 0;
        purchase.Total = 
          purchase.SubTotal*(1 - purchase.Discount);
    
        if (purchase.Total < account.Balance) {
          account.Balance -= purchase.Total;
        }
        else {
          rejectPurchase(purchase, 
            "You don't have enough money.");
        }
      }
    } 
    This type of code can be problematic in a couple of ways. In a system like this, you potentially have duplication because the business rules for an entity are scattered in procedural code outside of the entities. You might duplicate logic unknowingly because it's not obvious where the previously written business logic would be.
    Figure 6 shows the same code, but this time following the Tell, Don't Ask pattern. In this code, I moved the business rules for purchasing and accounts into the Purchase and Account classes themselves. When we go to make a purchase, we just tell the Account class to deduct the purchase from itself. Account and Purchase know about themselves and their internal rules. All a consumer of Account has to know is to call the Account.Deduct(Purchase, PurchaseMessenger) method.
    public class Purchase {
      private readonly double _subTotal;
    
      public Purchase(double subTotal) {
        _subTotal = subTotal;
      }
    
      public double Total {
        get {
          double discount = _subTotal > 10000 ? .10 : 0;
          return _subTotal*(1 - discount);
        }
      }
    }
    
    public class Account {
      private double _balance;
    
      public void Deduct(
        Purchase purchase, PurchaseMessenger messenger) {
        if (purchase.Total < _balance) {
          _balance -= purchase.Total;
        }
        else {
          messenger.RejectPurchase(purchase, this);
        }
      }
    }
    
    public class ClassThatObeysTellDontAsk {
      public void MakePurchase(
        Purchase purchase, Account account) {
        PurchaseMessenger messenger = new PurchaseMessenger();
        account.Deduct(purchase, messenger);
      }
    }
    The Account and Purchase objects are easier to use because you don't have to know quite so much about these classes to execute our business logic. We've also potentially reduced duplication in the system. The business rules for Accounts and Purchases can be effortlessly reused throughout the system because those rules are inside the Account and Purchase classes instead of being buried inside the code that uses those classes. In addition, it should be easier to change the business rules for Purchases and Accounts as those rules are found in just one place in the system.
    Closely related to Tell, Don't Ask is the Information Expert pattern. If you have a new responsibility for your system, in what class should the new responsibility go? The Information Expert pattern asks, who knows the information necessary to fulfill this responsibility? In other words, your first candidate for any new responsibility is the class that already has the data fields affected by that responsibility. In the purchasing sample, the Purchase class knows the information about a purchase that you would use to determine any possible discount rates, so the Purchase class itself is the immediate candidate for calculating discount rates.