Buy Electronics

Thursday, May 20, 2010

Design Patterns

What is a Design Pattern?

Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. Further, it does not comprise of a complete solution that may be instantly converted to a code component, rather it provides a framework for how to solve a problem.

Design patterns consist of proven

Reusable architectural concepts,

Reliable and speed up software development process.
Design Patterns are in a continuous phase of evolution, which means that they keep on getting better & better as they are tested against time, reliability and subjected to continuous improvements.

Further, design patterns have evolved towards targeting specific domains.

For example,

> Windows-based banking applications are usually based on singleton patterns,

> E-commerce web applications are based on the MVC (Model-View-Controller) pattern.

Design Patterns are categorized into 3 types:
*
Creational Patterns
* Structural Patterns
*
Behavioral Patterns

Creational Patterns:

What are Creational Design Patterns?

The Creational Design Patterns focus on how objects are created and utilized in an application. They tackle the aspects of when and how objects are created, keeping in mind what’s the best way these objects should be created.

Listed below are some of the commonly known Creational Design Patterns:
>> Singleton Pattern

>> Abstract Factory Pattern
>> Factory Pattern
>> Builder Pattern
>> Lazy Pattern
>> Prototype Pattern

What is the Singleton Design Pattern?

The Singleton design pattern is based on the concept of restricting the instantiation of a class to one object. Say one object needs to perform the role of a coordinator between various instances of the application that depend on a common object; we may design an application using a Singleton. Usage of Singleton patterns is common in Banking, Financial (such as Banking tools or Car Loan tools etc.) and Travel based applications where the singleton object consists of the network related information.

A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case the object exists, a reference to the existing object is given. A singleton object has one global point of access to it.

An
asp.net Web Farm is also based on the Singleton pattern. In a Web Farm, the web application resides on several web servers. The session state is handled by a Singleton object in the form of the aspnet_state.exe, which interacts with the ASP.NET worker process running on each web server. Note that the worker process is the aspnet_wp.exe process. Imagine one of the web servers shutting down; the singleton object aspnet_state.exe still maintains the session state information across all web servers in the web farm.

In .NET, in order to create a singleton, a class is created with a private constructor, and a "static read-only" variable as the member that behaves as the instance.

What’s the difference between Abstract Factory Pattern and Factory Pattern?

In an abstract factory design, a framework is provided for creating sub-components that inherit from a common component. In .NET, this is achieved by creating classes that implement a common interface or a set of interfaces, where the interface comprises of the generic method declarations that are passed on to the sub-components. Note that not just interfaces, but even abstract classes can provide the platform of creating an application based on the abstract factory pattern.
Example, say a class called CentralGovernmentRules is the abstract factory class, comprised of methods like ShouldHavePolice () and ShouldHaveCourts (). There may be several sub-classes like State1Rules, State2Rules etc. created that inheriting the class CentralGovernmentRules, and thus deriving its methods as well.

Note that the term "Factory" refers to the location in the code where the code is created.

A Factory Pattern is again an Object creation pattern. Here objects are created without knowing the class of the object. Sounds strange? Well, actually this means that the object is created by a method of the class, and not by the class's constructor. So basically the Factory Pattern is used wherever sub classes are given the privileged of instantiating a method that can create an object.

Describe the Builder Design Pattern?

In a builder design pattern, an object creation process is separated from the object design construct. This is useful because the same method that deals with construction of the object can be used to construct different design constructs.

What is the Lazy Design Pattern?

The approach of the Lazy Design Pattern is not to create objects until a specific requirement matches, and when it matches, object creation is triggered. A simple example of this pattern is a Job Portal application. Say you register yourself in that site thus filling up the registration table, only when the registration table is filled, the other objects are created and invoked, that prompt you to fill in other details too, which will be saved in other tables.

What is the Prototype Design Pattern?

A prototype design pattern relies on creation of clones rather than objects. Here, we avoid using the keyword 'new' to prevent overheads.

Structural Design Patterns

What are Structural Design Patterns?

A structural design pattern establishes a relationship between entities. Thus making it easier for different components of an application to interact with each other. Following are some of the commonly known structural patterns:

>> Adapter Pattern - Interfaces of classes vary depending on the requirement.
>> Bridge Pattern - Class level abstraction is separated from its implementation.
>> Composite Pattern -
Individual objects & a group of objects are treated similarly in this approach.
>> Decorator Pattern - Functionality is assigned to an object.
>> Facade Pattern - A common interface is created for a group of interfaces sharing a similarity.
>> Flyweight Pattern - The concept of sharing a group of small sized objects.
>> Proxy Pattern - When an object is complex and needs to be shared, its copies are made.

These copies are called the proxy objects.

What are the different types of Proxy Patterns?

1 - Remote Proxy - A reference is given to a different object in a different memory location. This may be on a different or a same machine.
2 - Virtual Proxy - This kind of object is created only & only when really required because of its memory usage.
3 - Cache Proxy - An object that behaves as a temporary storage so that multiple applications may use it. For example, in ASP.NET when a page or a user control contains the OutputCache directive, that page/control is cached for some time on the ASP.NET web server.


Behavioral design pattern

What is a behavioral design pattern?

Behavioral design patterns focus on improving the communication between different objects. Following are different types of behavioral patterns:
>>> Chain Or Responsibilities Pattern - In this pattern, objects communicate with each other depending on logical decisions made by a class.
>>> Command Pattern - In this pattern, objects encapsulate methods and the parameters passed to them.
>>> Observer Pattern - Objects are created depending on an events results, for which there are event handlers created.

What is the MVC Pattern (Model View Controller Pattern)?

The MVC Pattern (Model View Controller Pattern) is based on the concept of designing an application by dividing its functionalities into 3 layers. Its like a triad of components. The Model component contains the business logic, or the other set of re-usable classes like classes pertaining to data access, custom control classes, application configuration classes etc. The Controller component interacts with the Model whenever required. The control contains events and methods inside it, which are raised from the UI which is the View component.

Consider an ASP.NET web application. Here, all aspx, ascx, master pages represent the View.
The code behind files (like aspx.cs, master.cs, ascx.cs) represents the Controller.
The classes contained in the App_Code folder, or rather any other class project being referenced from this application represent the Model component.

Advantages:

· Business logic can be easily modified, without affecting or any need to make changes in the UI.

· Any cosmetic change in the UI does not affect any other component.

When should design patterns be used?

While developing software applications, sound knowledge of industry proven design patterns make the development journey easy and successful. Whenever a requirement is recurring, a suitable design pattern should be identified. Usage of optimal design patterns enhances performance of the application. Though there are some caveats. Make sure that there are no overheads imposed on a simple requirement, which means that design patterns should not be unnecessarily be used.

How many design patterns can be created in .NET?

As many as one can think. Design patterns are not technology specific; rather their foundation relies on the concept of reusability, object creation and communication. Design patterns can be created in any language.

Describe the Ajax Design Pattern?

In an Ajax Design Pattern, partial postbacks are triggered asynchronously to a web server for getting live data. A web application would not flicker here, and the website user would not even come to know that a request is being sent to the web server for live data.

Such a design pattern is used in applications like Stock Market Websites to get live quotes, News Websites for live news, Sports websites for live scores etc.

Tuesday, May 18, 2010

Callback Function in C#

Definition:
-------------
       >> Functions that are triggered when an associated event happens.
 
Example :

------------
 
  > In C, function pointer is used as a callback functions.
 
  > In C++, virtual function is used as a callback function.
 
  > c#, delegate keyword is used to create a call back function.
 
Example in c#:
------------------

 
using System;
using System.Collections.Generic;
using System. Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        public delegate int execute(int a, int b); //declare a delegate method
 
        static void Main(string[] args)
        {
            Program p = new Program();     
                  
            execute ex = new execute(p.add);
            Console.WriteLine(ex(2,3));  //add method is executed
 
            ex = new execute(p.subtract);
            Console.WriteLine(ex(2, 3)); //subtract method is executed            
        }
 
        public int add(int a, int b)
        {
            return (a + b);
        }
 
        public int subtract(int a, int b)
        {
            return (a - b);
        }
    }
}

Monday, May 3, 2010

C# programming language

--- Arrays section (C#) ---
 
Create new array
 
Create new array to store values.
 
int[] cat = new int[5];
// cat = 0, 0, 0, 0, 0
 
string[] s = new string[10];
// s = null, null, ...
 
Initialize array
Create new int or string array with certain values.
 
int[] cat = {1, 4, 6};
string[] a = {"dog", "cat", "plant"};
 
Assign array
Set element in array to value.
 
cat[0] = 3;
cat[1] = 4;
cat[4] = 7;
 
Check array size
Use array's length property, then access elements.
 
if (cat.Length == 3)
{
    // 3 elements
}
 
Sort array
Sort an array alphabetically (A - Z).
 
string[] a = new string[]
{
    "z", "a", "b"
};
Array.Sort(a);
// "a", "b", "z"
 
Use 2D array
Use a two-dimensional array to store a grid of values.
 
int[,] i = new int[2, 2];
i[0, 0] = 0;
i[0, 1] = 1;
i[1, 0] = 2;
i[1, 1] = 3;
// 0, 1
// 2, 3
 
Convert List to array
Use instance method ToArray() to convert List to equivalent array.
 
List e = new List();
e.Add(1);
e.Add(2);
int[] a = e.ToArray();
// a = 1, 2
 
Loop through List
Iterate through each item in an array or list.
 
List e = new List();
e.Add(1);
e.Add(2);
foreach (int i in e)
{
    // 1, 2
}
 
Reverse array
Reorder elements in array backwards.
 
int[] a = {5, 6, 1};
Array.Reverse(a);
// 1, 6, 5
 
--- Methods section (C#) ---
 
Ref parameter
Allow another method to directly change value.
 
class C
{
    void Method()
    {
        int a = 4;
        Method2(ref a);
        // a = 5
    }
    void Method2(ref int p)
    {
        p = 5;
    }
}
 
Out parameter
Allow another method to directly change value.
With compile-time checking.
 
class C
{
    void Method()
    {
        int a;
        Method2(out a);
        // a = 5
    }
    void Method2(out int p)
    {
        p = 5;
    }
}
 
--- Strings section (C#) ---
 
Split string
Divide string into separate parts.
 
string c = "one,two";
string[] s = c.Split(',');
// s[0] = "one"
// s[1] = "two"
 
String new lines
Declare a string with newlines in it. Use "" for a quote.
 
string s = @"line 1
line 2
line 3";
 
Combine strings
Add strings together (also called concatenation).
Use overloaded + operator.
 
string s1 = "cat";
string s2 = "dog";
string c = s1 + " and " + s2;
// c = "cat and dog"
 
Compare strings
See if two strings have equal characters and lengths.
 
string s1 = "cat";
string s2 = "dog";
string s3 = "cat";
if (s1 == s2)
{
    // not true
}
if (s1 == s3)
{
    // success
}
 
Empty string check
See if string is empty or null (has no value).
 
string s1 = "";
string s2 = null;
string s3 = "cat";
if (string.IsNullOrEmpty(s1))
{
    // true
}
if (string.IsNullOrEmpty(s2))
{
    // true
}
if (string.IsNullOrEmpty(s3))
{
    // not true
}
 
Get string length
Find number of characters in string.
 
string c = "cat";
if (c.Length == 3)
{
    // true
}
 
Append strings quickly
Use StringBuilder and convert back to string.
 
StringBuilder b = new StringBuilder();
b.Append("Text");
b.Append(" more");
string r = b.ToString();
// r = "Text more"
 
Uppercase entire string
Uppercase each letter in string.
 
string s = "cat";
s = s.ToUpper();
// s = "CAT"
 
Uppercase first letter
Uppercase the first letter in string.
 
string s = "cat";
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
string u = new string(a);
// u = "Cat"
 
Convert string to int
Take string containing digits and convert it to int value.
 
 
string s = "105";
int i = int.Parse(s);
// i = 105
 
string s2 = "105.5";
double d = double.Parse(s2);
// d = 105.5
 
Substring of string
Get part of string based on indexes.
 
string s = "developer";
string b = s.Substring(0, 7);
// b = "develop"
 
Remove whitespace
Trim whitespace at beginning and ending of string.
 
string s = " cat  ";
string t = s.Trim();
// t = "cat"
 
Change string characters
Modify the letters in string in-place.
 
string s = "cat";
char[] a = s.ToCharArray();
    // a = 'c', 'a', 't'
a[0] = 'h';
    // a = 'h', 'a', 't'
string s2 = new string(a);
    // s2 = "hat"
 
 
--- Classes section (C#) ---
 
Declare constructor
Create new constructor for class.
 
class C
{
    public C(int a)
    {
        // initialize
    }
}
 
Cast safely
Use as operator or is operator.
Convert from one type to another.
 
void Method(object a)
{
    if (a is MyClass)
    {
        // correct type
    }
}
void Method2(object a)
{
    MyClass m = a as MyClass;
    if (m != null)
    {
        // correct type
    }
}
 
Null reference
Causes exception in programs. Null variable used.
 
 
string s = null;
if (s.Length == 0)
{
    // exception raised
}
 
New object
Create a new object of a kind.
 
class C
{
    // impl.
}
class Program
{
    void Main()
    {
        C name = new C();
    }
}
 
Singleton
Make a single object. One instance per AppDomain.
 
class S
{
    private static readonly _inst = new S();
    public static S Instance
    {
        get { return _inst; }
    }
    S()
    {
        // init
    }
}
 
Properties, Accessors, Getters, setters
Create properties to access fields of classes publicly.
 
class C
{
    public int P { get; set; }
}
void Method(C name)
{
    name.P = 4;
    int i = name.P;
    // i = 4
}
 
--- File/IO section (C#) ---
 
 
Read file lines
Read in each line of file into array.
 
string[] lines = File.ReadAllLines("file.txt");
// lines[0] = "..."
// lines[1] = "..."
 
 
Read text file
Read in entire file containing text.
 
string f = File.ReadAllText("file.txt");
// f = "..."
 
 
Read lines separately
Read file line-by-line with StreamReader.
Fastest and lowest memory.
 
using (StreamReader s = new StreamReader("file.txt"))
{
    string t;
    while ((t = s.ReadLine()) != null)
    {
        // t = "..."
    }
}
 
 
Append to file
Add text to end of file on disk.
 
File.AppendAllText("file.txt", "..." + Environment.NewLine);
 
Write file
Write text to file on disk, replacing any existing files.
 
File.WriteAllText("file.txt", "...");
 
Directory exists
See if folder exists on file system. Add using System.IO;
 
if (Directory.Exists("C:\\f"))
{
    // ...
}
 
File exists
See if file exists on disk at path.
 
if (File.Exists("file.txt"))
{
    // ...
}
 
--- Hashtables section (C#) ---
 
Use Dictionary
Use the generic Dictionary object with string keys.
 
 
Dictionary d = new Dictionary();
d.Add("cat", 2);
d.Add("dog", 4);
if (d.ContainsKey("cat"))
{
    // true
}
if (d.ContainsKey("hat"))
{
    // not true
}
 
Lookup Dictionary value
Get value from hashtable/Dictionary based on key.
 
 
Dictionary d = new Dictionary();
d.Add("cat", 2);
if (d.ContainsKey("cat"))
{
    int v = d["cat"];
    // v = 2
}
 
Scan Dictionary values
Use KeyValuePair on Dictionary to list each key/value combo.
Use this style to convert to string.
 
 
 
foreach (KeyValuePair p in d)
{
    // p.Key, p.Value
}
 
Use Hashtable
Implements older version of Dictionary, slower but required sometimes.
 
 
Hashtable h = new Hashtable();
h.Add(400, "Blazer");
 
string s = h[400] as string; // Cast
if (s != null) // True
{
    Console.WriteLine(s);
}
 
--- Language section (C#) ---
 
Namespaces
Put at top of file. 
 
using System;
using System.IO;
using System.Linq;
using System.Text;
 
Current time
Get current time using DateTime.
 
 
DateTime d = DateTime.Now;
string s = d.ToString();
// s = "8/20/2008 4:18:52 PM"
 
Debug message
Write diagnostics message to console.
 
 
using System.Diagnostics;
class C
{
    void Method()
    {
        Debug.WriteLine("...");
    }
}
 
Enums
Use enum type to assign names to numbers.
 
 
enum E
{
    None,
    Cat,
    Dog
};
void Method()
{
    E name = E.Cat;
    if (name == E.Dog)
    {
        // not true
    }
}
 
Loop through numbers
Use the for loop to loop through range of values.
 
 
 
for (int i = 0; i <>
{
    // 0, 1, 2, 3, ... 99
}
 
Catch exceptions
Detect errors and try to recover from them.
 
try
{
    int i = 1 / int.Parse("0");
}
catch (Exception)
{
    // log error
}
 
Switch statement
Compare value against constant values. Faster than if.
 
switch(v)
{
    case "cat":
    case "tiger":
        {
            // feline
            break;
        }
    case "dog":
    default:
        {
            // other
            break;
        }
}
 
 
 
 
 
--- Interfaces section (C#) ---
 
Interfaces, code contracts
Define required methods for classes so they can be swapped.
 
public interface IName
{
    void Method();
}
class C : IName
{
    public void Method()
    {
        // ...
    }
}
class D : IName
{
    public void Method()
    {
        // ...
    }
}
 
Use interfaces
Use classes by their common interfaces. Improves code reuse.
 
void Method()
{
    C name = new C();
    Method2((IName)name);
 
    D name2 = new D();
    Method2((IName)name2);
}
void Method2(IName i)
{
    // ...
}

Mobiles