Pages

Tuesday, March 12, 2013

Singleton Design Pattern in C#

Design Patterns provide solutions to common recurring problems. Design patterns can be classified as creational, structural or behavioral .Singleton and Factory patterns are two of the creational pattern.Here we will discuss these two patterns .In the later posts we will discuss other design patterns.

Singleton Design Pattern

We use this design pattern when we want to restrict the number of instances of any object to one at max at any instant of time. The practical implementation of this design pattern can be seen in applications that we use daily. Take the example of Microsoft word .What happens when you open multiple word documents and navigate between them?. There is only one instance of the word application active at a time ,you can verify this by checking the active processes .So all the requests for handling the different word documents is handled by a single application instance.

Here is an implementation of the singleton design pattern in C#. We will use a console application for this example. We will create a class and define a private constructor in that class so that the instances of that class can be created from only within that class.

       private Singleton()
        {

        }

Since we declare our class constructor as shown above we can not access it from outside the class .The below statement will give compilation error 

     
Singleton obj = new Singleton();  

To access the single object of the Singleton class we will create a static variable of type Singleton and a property to access that private variable.

Here is the complete source code of the above example :

   class Singleton
    {
        
private Singleton()
        {

        }
        
//private static variable of Singleton type.
        private static Singleton objSingle = new Singleton();

        //declare a public static property that returns the
        //Singleton object as we can not call the private 
        //constructor from outside the class.
        public static Singleton ObjSingle
        {
            
get { return Singleton.objSingle; }
            
set { Singleton.objSingle = value; }
        }

        private string name;

        public string Name
        {
            
get { return name; }
            
set { name = value; }
        }
 
    }
    
class Program
    {

        static void Main(string[] args)
        {
            
//the below line create an object of singleton type
            Singleton objFirstObject = Singleton.ObjSingle;
            objFirstObject.Name = 
"ashish";
            
//if we access the objSingle property from another variable we will get the same object
            Singleton objSecondObject = Singleton.ObjSingle;
            
//We have assigned the name in first object,we will get the same value in second object since both points 
            //to the same instance
            Console.WriteLine("objFirstObject.Name={0} ,objSecondObject.Name={1}",objFirstObject.Name,objSecondObject.Name);
            
Console.ReadLine(); 
        }

    }

Factory Method Pattern

In the Factory method pattern there is Factory method which decides which subclass to instantiate depending on the information passed by the client. All the subclasses implement a common interface.

The client declares a variable of interface type and calls the Factory method that returns an instance of the subclass to the client code.So the client is decoupled from the implementation details of subclass creation.

Following is an example of factory method pattern.

        
interface IGreet
        {
            
string Hello();
        }
 
        
class WeekStart : IGreet
        {
            
public string Hello()
            {
                
return " Week Started";
            }
        }
 
        
class WeekEnd : IGreet
        {
            
public string Hello()
            {
                
return "Happy Weekend";
            }

        }
        
class Creator
        {
            
public IGreet FactoryMethod()
            {
                
if (DateTime.Now.DayOfWeek == DayOfWeek.Monday || DateTime.Now.DayOfWeek ==DayOfWeek.Tuesday
                || 
DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Thursday
                )
                    
return new WeekStart();
                
else
                    return new WeekEnd();
            }
        }

        class Program
        {
            
private DateTime dt = DateTime.Now;

            static void Main(string[] args)
            {
                
Creator ct = new Creator();
                
IGreet weekDayStatus = ct.FactoryMethod();
                
Console.WriteLine(weekDayStatus.Hello());
                
Console.ReadLine();

            }
        }

 

Digest Authentication

Digest authentication addresses the primary weaknesses of basic authentication: sending passwords in plain text. Digest authentication is a challenge/response mechanism, which sends a digest (also known as a hash) instead of a password over the network. A digest is a fixed-size result obtained by applying a mathematical function (called a hash function or digest algorithm) to an arbitrary amount of data. The fixed-size depends upon the level of encryption. For example, if a 128-bit digest consisted of 32 ASCII characters, a 40-bit digest would consist of 10 ASCII characters. When a client attempts to access a resource requiring Digest authentication, IIS send a challenge to the client to create a digest and send it to the server. The client concatenates the password with data known to both the server and the client. The client then applies a digest algorithm (specified by the server) to the combined data. The client sends the resulting digest to the server as the response to the challenge. The server uses the same process as the client to create a digest using a copy of the client's password it obtains from Active Directory, where the password is stored using reversible encryption. If the digest created by the server matches the digest created by the client, IIS authenticates the client. IIS uses a subauthentication DLL (iissuba.dll) to authenticate the user, resulting in a network logon. By itself, Digest authentication is only a slight improvement over Basic authentication. In the absence of SSL/TLS, an attacker could record communication between the client and server. Using this information, the attacker can then use that information to replay the transaction. For more information, see About Authentication in the IIS Documentation (http://www.microsoft.com/windows2000/en/server/iis/htm/core/iiabasc.htm).

 

Pros

  • Sends a digest over the network instead of a password.
  • Works with proxy servers and firewalls.
  • Does not require SSL/TLS for the sake of password protection.

Cons

  • Cannot delegate security credentials.
  • Is only supported by Internet Explorer 5.0 and later.
  • Is subject to replay attacks unless you use SSL/TLS.
  • Requires storing of passwords in cleartext using reversible encryption.
  • Requires the creation of domain accounts for each user in Active Directory.

Implementation

To use Digest authentication in Windows 2000, the server must have access to an Active Directory server that is set up for Digest authentication. For more information, see Enabling and Configuring Authentication in the IIS Documentation (http://www.microsoft.com/windows2000/en/server/iis/htm/core/iiauths.htm?id=76) and Knowledge Base article Q222028, Setting Up Digest Authentication for Use with Internet Information Services 5.0 (http://support.microsoft.com/support/kb/articles/Q222/0/28.asp).

Note   After configuring Active Directory to store passwords using reversible encryption, all users must change their passwords for Active Directory to store each password in this manner.

If you implement Digest authentication, you should also use SSL/TLS to defend against replay attacks. For more information, see Setting up SSL on Your Server in the IIS Documentation (http://www.microsoft.com/windows2000/en/server/iis/htm/core/iisslsc.htm) and Knowledge Base article Q298805, HOW TO: Enable SSL for All Customers Who Interact with Your Web Site (http://support.microsoft.com/support/kb/articles/Q298/8/05.asp).

If your ASP.NET application needs to run as the user authenticated by IIS Digest authentication, use the following Web.config configuration. For more information, see ASP.NET Authentication.

 
<!-- Web.config file -->
<system.web>
   <authentication mode="Windows" />
</system.web>
 

For more information about digest authentication, see the specification (RFC 2069) on the Internet Engineering Task Force (IETF) Web site (http://www.ietf.org/rfc/rfc2069.txt).

 

Thursday, March 7, 2013

UML Unified Modeling Language

Structure diagrams

Behavior diagrams

Structure diagrams emphasize the things that must be present in the system being modeled. Since structure diagrams represent the structure, they are used extensively in documenting the software architecture of software systems.

·         Class diagram: describes the structure of a system by showing the system's classes, their attributes, and the relationships among the classes.

·         Component diagram: describes how a software system is split up into components and shows the dependencies among these components.

·       structure diagram: describes the internal structure of a class and the collaborations that this structure makes possible.

·     Deployment diagram: describes the hardware used in system implementations and the execution environments and artifacts deployed on the hardware.

·         Object diagram: shows a complete or partial view of the structure of an example modeled system at a specific time.

·         Package diagram: describes how a system is split up into logical groupings by showing the dependencies among these groupings.


·        Profile diagram: operates at the metamodel level to show stereotypes as classes with the stereotype, and profiles as packages with the <<profile>> stereotype. The extension relation (solid line with closed, filled arrowhead) indicates what metamodel element a given stereotype is extending.

Behavior diagrams emphasize what must happen in the system being modeled. Since behavior diagrams illustrate the behavior of a system, they are used extensively to describe the functionality of software systems.
·         Activity diagram: describes the business and operational step-by-step workflows of components in a system. An activity diagram shows the overall flow of control.
·        UML state machine diagram: describes the states and state transitions of the system.
·        Use Case Diagram: describes the functionality provided by a system in terms of actors, their goals represented as use cases, and any dependencies among those use cases.

=============================================
Interaction diagrams

Interaction diagrams, a subset of behavior diagrams, emphasize the flow of control and data among the things in the system being modeled:

·     Communication diagram: shows the interactions between objects or parts in terms of sequenced messages. They represent a combination of information taken from Class, Sequence, and Use Case Diagrams describing both the static structure and dynamic behavior of a system.

·     Interaction overview diagram: provides an overview in which the nodes represent communication diagrams.

·        Sequence diagram: shows how objects communicate with each other in terms of a sequence of messages. Also indicates the lifespans of objects relative to those messages.

·        Timing diagrams: a specific type of interaction diagram where the focus is on timing constraints.