Custom Control

http://www.beansoftware.com/ASP.NET-Tutorials/Custom-Server-Controls.aspx


Custom Server Controls In ASP.NET

When developer starts to learn ASP.NET, he or she plays with controls from the Visual Studio toolbox and build different user interfaces. Sooner or later, developer wants to encapsulate parts of web page to user controls, extend standard controls to add new features or even build custom web controls or components from scratch. On this way developer increases reusability, reduce repetitive code and ease maintenance.
In ASP.NET is possible to build two types of controls. That are custom server controls and user controls, which are pretty different. More about creating and using of user controls you can find in User Control In ASP.NET tutorial. This article will cover creating of custom server controls.
Unlike user controls, custom server controls are not placed in /App_Code folder but compiled to dll. You need to write complete control in code and there is no some visual designer (no markup code and no .ascx file). Because of that, custom controls are harder to create, but when created and compiled, they are easier to use. You can build installation package for custom controls and distribute them easy.

How to create web custom controls

In Visual Studio, create a new project. Choose the "ASP.NET Server Control" type, or "Web Custom Control" type if you use earlier version of Visual Studio. In any case, Visual Studio will create a class that inherits from WebControl class, which is located in System.Web.UI.WebControls interface.
If you use Visual Web Developer Express you'll see that there is no ASP.NET Server Control template, but you can download Visual C# Express or Visual Basic Express and create Class Library project. You can create your custom controls in Notepad too, just name text file with extension of .vb or .cs and write class that inherits System.UI.WebControls.WebControl, like in code bellow:
[ C# ]
public class ServerControl1 : WebControl
{

}
[ VB.NET ]
Public Class ServerControl1
   Inherits WebControl
 
End Class
In case that you don't want to build control from scratch, but only to add new feature to existing control, you can inherit that control directly instead of WebControl class and write additional code. All standard controls from Visual Studio toolbox are also inherited from WebControl or from a Control class. WebControl inherits Control class, so correct statement is that custom controls always intherit from System.Web.UI.Control class, directly or indirectly. You can check this in Object Browser (in Visual Studio menu go to View -> Object Browser or use Ctrl + Alt + J keyboard shortcut). It is better to use WebControl if your control will have visual interface. If there is no UI, inherit Control class.
Simple control written in code above can't do anything, but it is functional and it is possible to compile it to .dll file through Visual Studio IDE or command prompt.

Adding properties and methods to custom server control

Adding properties to custom server controls is similar to adding properties to other types of classes in .Net framework. Only difference is the way how we keep property values. Because http is stateless protocol, all variables and class are destroyed after web request is finished. To persist property value between post backs, you can use ViewState. Example property that use ViewState to save its value will look like this:
[ C# ]
public string Text
{
    get
    {
        // Read value from ViewState
        String s = (String)ViewState["Text"];
        // If ViewState is null return default value
        return ((s == null) ? "Some Default Value, could be local constant" : s);
    }
 
    set
    {
        // Save value to ViewState
        ViewState["Text"] = value;
    }
}
[ VB.NET ]
Property Text() As String
  Get
    ' Read value from ViewState
    Dim s As String = CStr(ViewState("Text"))
    ' If ViewState is null return default value
    If s Is Nothing Then
      Return "Some Default Value, could be local constant"
    Else
      Return s
    End If
  End Get
 
  Set(ByVal Value As String)
    ' Save value to ViewState
    ViewState("Text") = Value
  End Set
End Property
Web control uses ViewState to remember values between post backs. ViewState works nice, but there is a problem because it could be disabled on web page level. In some scenarios, property value is critical and control must get it to work properly. ASP.NET have ControlState which is not affected if ViewState is turned off. You should avoid using of ControlState if possible and use it only when necessary. More about how to use ControlState you can read on ControlState Property Demystified tutorial.
Adding methods for custom server controls is the same as for the other types of .Net classes. You can build your own method or override existing. Just take care if you need to keep functionality of base method, to execute method of base class, use base keyword in C# or MyBase keyword in VB.NET.

How to place custom server control to web page

First, your custom server control's dll must be in web application /bin folder, or installed in GAC (Global Assembly Cache).
After that, you can add custom controls to web page in two simple steps:
First, you need to register custom controls at the top of the markup code (.aspx file) by using Register directive. You can do this with markup code like this:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Namespace="BeanSoftware" Assembly="MyAssembly" TagPrefix="cc" %>
Second, on the place where you want to add custom control, use TagPrefix property value and class name of your custom control to build a tag, like this
<cc:MyClassName runat="server" ID="MyControl1" />
So, tag is built in this form TagPrefix:CustomControlClassName. Except this, you should add at least runat="server" and specify ID of control. In this example TagPrefix = "cc". There is no big reason for this, it is simply abbreviation for Custom Control. You can put practically anything here.
If the same server control will be used on many web pages, then you can register it in <controls> section in web.config:
<configuration>
  <system.web>
    <pages>
      <controls>
        <add namespace="MyNameSpaceName.SubNameSpace.MyControlClassName" tagPrefix="bs" assembly="MyAssembly" />
      </controls >
    </pages >
  </system.web>
</configuration>
When registered in web.config, you don't need to write Register directives on every web page.
It is possible to build three types of web custom server controls in ASP.NET:
- Derived custom controls
- Composite controls
- Custom rendered controls

Derived custom server controls

If you want to extend existing control and add some new features, you can build derived custom control. When you create new server control, Visual Studio by default creates class that inherits from WebControl class. You can change this and inherit any other control. For example, to create server control inherited from TextBox, you should use code like this:
[ C# ]
public class ServerControl1 : TextBox
{

}
[ VB.NET ]
Public Class ServerControl1
  Inherits TextBox

End Class
 
Control created on this way will have all functionality of based control. In this example, we'll get a complete TextBox control and now we need to add just code for additional features. It is possible to create new properties, methods and events or to override existing.

Composite server controls

Composite control is a control that are built from other controls. To build composite control you need to inherit WebControl class and implement INamingContainer interface. This interface have not any implementation, but it is needed to subcontrols get unique names on web page. After that, override ControlCollection property and CreateChildControls method. In ControlCollection property just call EnsureChildControls() method. EnsureChildControls method checks if CreateChildControls is already called, and call it if not. In CreateChildControls method we define the look of composite control and subcontrols are added by using of Controls.Add method.
This sounds complicated, but let see how it looks on simple example. We'll build composite control of one TextBox named "txtName", one Button contro "btnSayHi", and one Label "lblMessage". User will type her name in txtName and on button's click event we'll show welcoming message in label control.
[ C# ]
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace BeanSoftware
{
    [ToolboxData("<{0}:WelcomeCompositeControl runat=server></{0}:WelcomeCompositeControl>")]
    public class WelcomeCompositeControl : System.Web.UI.WebControls.WebControl, INamingContainer
    {
        // Declare subcontrols
        protected TextBox txtName = new TextBox();
        protected Label lblMessage = new Label();
        protected Button btnHi = new Button();
 
        public override ControlCollection Controls
        {
            get
            {
                EnsureChildControls();
                return base.Controls;
            }
        }
 
        protected override void CreateChildControls()
        {
            Controls.Clear();
 
            // Set subcontrols behavior
            txtName.ToolTip = "Write your name here and click a button.";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            btnHi.Text = "Say Hi!";
            btnHi.Click +=new EventHandler(btnHi_Click);
 
            // Create user interface by using Controls collection
            Controls.Add(txtName);
            Controls.Add(new LiteralControl("<br />"));
            Controls.Add(lblMessage);
            Controls.Add(new LiteralControl("<br />"));
            Controls.Add(btnHi);
        }
 
        // Handles btnHi button click event
        private void btnHi_Click(object sender, EventArgs e)
        {
            // Call this method first whenever do something
            // with subcontrols
            EnsureChildControls();
 
            // Show welcome message in label
            lblMessage.Text = "Hi " + txtName.Text;
        }
    }
}
[ VB.NET ]
Imports System
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls
 
Namespace BeanSoftware
    <ToolboxData("<{0}:WelcomeCompositeControl runat=server></{0}:WelcomeCompositeControl>")> _
    Public Class WelcomeCompositeControl
        Inherits TextBox
        Implements INamingContainer
 
        ' Declare subcontrols
        Protected txtName As TextBox = New TextBox()
        Protected lblMessage As Label = New Label()
        Protected WithEvents btnHi As Button = New Button()
 
        Public Overrides ReadOnly Property Controls() As ControlCollection
            Get
            EnsureChildControls()
                Return MyBase.Controls
            End Get
        End Property
 
        Protected Overrides Sub CreateChildControls()
            Controls.Clear()
 
            ' Set subcontrols behavior
            txtName.ToolTip = "Write your name here and click a button."
            lblMessage.ForeColor = System.Drawing.Color.Red
            btnHi.Text = "Say Hi!"
 
            ' Create user interface by using Controls collection
            Controls.Add(txtName)
            Controls.Add(New LiteralControl("<br />"))
            Controls.Add(lblMessage)
            Controls.Add(New LiteralControl("<br />"))
            Controls.Add(btnHi)
        End Sub
 
        ' Handles btnHi button click event
        Private Sub btnHi_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnHi.Click
            ' Call this method first whenever do something
            ' with subcontrols
            EnsureChildControls()
 
            ' Show welcome message in label
            lblMessage.Text = "Hi " & txtName.Text
        End Sub
    End Class
End Namespace

Custom rendered server controls

In custom rendered server controls you need to build complete output. First, you need to override RenderContents method. Then, use HtmlTextWriter object to create control's UI. In some basic example let output of control be text colored in red, RenderContents method could look like this:
[ C# ]
protected override void RenderContents(HtmlTextWriter output)
{
  output.AddStyleAttribute(HtmlTextWriterStyle.Color, "red");
  output.RenderBeginTag(HtmlTextWriterTag.Span);
  output.Write("This text will be red");
  output.RenderEndTag();
}
[ VB.NET ]
Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
   output.AddStyleAttribute(HtmlTextWriterStyle.Color, "red")
   output.RenderBeginTag(HtmlTextWriterTag.Span)
   output.Write("This text will be red")
   output.RenderEndTag()
End Sub
As you see, nothing visual here, you need to write every attribute and every tag manually. Also, since you have complete control, you need to pay attention to cross browser comaptibility. All this could be very confusing in complex projects. More about custom rendered controls you can find at Custom Rendered Controls In ASP.NET tutorial.

Adding client javascript to custom server control

To enable client side functionality, often we need to use some JavaScript code. Although you can write this code by using HtmlTextWriter, it is not recommended because the same JavaScript would be vritten for every instance of control on the web page. Because of this, it is better to use Page.RegisterClientScriptBlock method. To get better perfomance, call this method in overriden OnInit method instead of using RenderContents. Client side script registration could look like this:
[ C# ]
protected override void OnInit(EventArgs e)
{
    // Check first if script is already registered to
    // avoid multiple registrations of the same client code
    if (!Page.IsClientScriptBlockRegistered("MyClientScript"))
    {
        // client code to be registered
        string JavaScriptCode = @"<script>
        function SomeJavaScriptFunction()
        {
          // JavaScript code goes here
        }
        </script>";
        // Registering JavaScript code
        Page.RegisterClientScriptBlock("MyClientScript",
        JavaScriptCode);
    }
    // Keep functionality of base method 
    base.OnInit(e);
}
[ VB.NET ]
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
    ' Check first if script is already registered to
    ' avoid multiple registrations of the same client code
    If Not Page.IsClientScriptBlockRegistered("MyClientScript") Then
 
        ' client code to be registered
        Dim JavaScriptCode As String = "<script>" & vbCrLf & _
          "function SomeJavaScriptFunction()" & vbCrLf & _
          "{" & vbCrLf & _
          "// JavaScript code goes here" & vbCrLf & _
          "}" & vbCrLf & _
          "</script>"
        ' Registering JavaScript code
        Page.RegisterClientScriptBlock("MyClientScript", _
        JavaScriptCode)
    End If
    ' Keep functionality of base method  
    MyBase.OnInit(e)
End Sub
On this way, client side block will be registered only for first instance of custom server control on web form. For every next instance, checking of Page.IsClientScriptBlockRegistered will prevent repeated registration. Be aware that not every web browser supports JavaScript, especially those on mobile devices. Even if browser supporting JavaScript, some visitors could block it manually by using security settings of web browser.

Few custom server controls examples

Controls and components are on some way packaged knowledge. If you need to use the same functionality over and over again, you can place it to custom control instead of rewriting it. Let say you need to display different video file formats in web application. On client side, Flash Player and Windows Media Player objects are used. It is good idea to wrap client side logic to server side controls. Then, in web application you work with custom server controls that you can drag and drop from Visual Studio toolbox, easy manipulate with server side code etc.
To see how these examples are made check ASP.NET Media Player Control and ASP.NET JW FLV Flash Video Player Control. Both controls are free and include source code in C# and VB.NET.

Conclusion

As you see, like in many other parts of life, it is nothing hard in web control development if you know what are you doing :). Although main concepts are simple, it is broad area and you could experience a number difficulties if you try to build anything more useful than "Hello World" example. I strongly suggest you to obtain Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer) book. The writer is member of ASP.NET team and he already wrote many of ASP.NET standard web controls that are part of .Net Framework.

What are the difference between DDL, DML and DCL commands?

DDL

They are called Data Definition since they are used for defining the data. That is the structure of the data is known through these DDL commands.

Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

DML

Some of the DML commands insert,select,update,delete etc. Even though select is not exactly a DML language command oracle still recommends you to consider SELECT as an DML command.

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

DCL

Data Control Language is used for the control of data. That is a user can access any data based on the priveleges given to him. This is done through DATA CONTROL LANGUAGE. Some of the DCL Commands are:

Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

TCL

For revoking the transactions and to make the data commit to the database we use TCL. Some of the TCL commands are:

ROLLBACK is used for revoking the transactions until last commit.
COMMIT is used for commiting the transactions to the database.
Once we commit we cannot rollback. Once we rollback we cannot commit.
Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

WCF Create and consume

http://msdn.microsoft.com/en-us/library/bb386386.aspx

To create a WCF service

  1. On the File menu, point to New and then click Project.
  2. In the New Project dialog box, expand the Visual Basic or Visual C# node and click WCF, followed by WCF Service Library. Click OK to open the project.
    Note Note
    This creates a working service that can be tested and accessed. The following two steps demonstrate how you might modify the default method to use a different data type. In a real application, you would also add your own functions to the service.
  3. In Solution Explorer, double-click IService1.vb or IService1.cs and find the following line:
    [OperationContract]
    string GetData(int value);
    
    
    
    Change the type for the value parameter to String:
    [OperationContract]
    string GetData(string value);
    
    
    
    In the above code, note the <OperationContract()> or [OperationContract] attributes. These attributes are required for any method exposed by the service.
  4. In Solution Explorer, double-click Service1.vb or Service1.cs and find the following line:
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
    
    
    
    Change the type for the value parameter to String:
    public string GetData(string value)
    {
        return string.Format("You entered: {0}", value);
    } 
     

    To test a WCF service

    1. Press F5 to run the service. A WCF Test Client form will be displayed and it will load the service.
    2. In the WCF Test Client form, double-click the GetData() method under IService1. The GetData tab will be displayed.
    3. In the Request box, select the Value field and type Hello.
    4. Click the Invoke button. If a Security Warning dialog box is displayed, click OK. The result will be displayed in the Response box.
    5. On the File menu, click Exit to close the test form.

      To reference a WCF service

      1. On the File menu, point to Add and then click New Project.
      2. In the New Project dialog box, expand the Visual Basic or Visual C# node and select Windows, and then select Windows Forms Application. Click OK to open the project.
      3. Right-click WindowsApplication1 and click Add Service Reference. The Add Service Reference dialog box will appear.
      4. In the Add Service Reference dialog box, click Discover.
        Service1 will be displayed in the Services pane.
      5. Click OK to add the service reference.

      To build a client application

      1. In Solution Explorer, double-click Form1.vb or Form1.cs to open the Windows Forms Designer if it is not already open.
      2. From the Toolbox, drag a TextBox control, a Label control, and a Button control onto the form.
      3. Double-click the Button, and add the following code in the Click event handler:
        private void button1_Click(System.Object sender, System.EventArgs e)
        {
            ServiceReference1.Service1Client client = new
                ServiceReference1.Service1Client();
            string returnString;
        
            returnString = client.GetData(textBox1.Text);
            label1.Text = returnString;
        }
        
        
        
      4. In Solution Explorer, right-click WindowsApplication1 and click Set as StartUp Project.
      5. Press F5 to run the project. Enter some text and click the button. The label will display "You entered:" and the text that you entered.

Design Pattern Interview Questions - Part 1

 http://www.dotnetfunda.com/articles/article130.aspx

Design Pattern Interview questions, Factory, Abstract factory, prototype pattern

Software Architecture Interview Questions Part 1 - Design Pattern Interview Questions

(B) What are design patterns?

(A) Can you explain factory pattern?

(I) Can you explain abstract factory pattern?

(I)Can you explain builder pattern?

(I) Can you explain prototype pattern?

(A) Can you explain shallow copy and deep copy in prototype patterns?

(B) Can you explain singleton pattern?

(A) Can you explain command patterns?

Other Interview question PDF's

Introduction

Hi friends , Please do not think you get an architecture position by reading interview questions. But yes there should be some kind of reference which will help you quickly revise what are the definition. Just by reading these answers you get to a position where you are aware of the fundamentals. But if you have not really worked you will surely fail with scenario based questions. So use this as a quick revision rather than a short cut.
In case your are completely new to design patterns or you really do not want to read this complete  article do see our free design pattern Training and interview questions / answers videos.
My Other Design Pattern Articles
  1. Design pattern Interview Questions Part 2 :- Interpreter pattern, iterator pattern, mediator pattern, memento pattern and observer pattern

  2. Design pattern Interview Questions Part 3 :- state pattern, strategy pattern, visitor pattern, adapter pattern and fly weight pattern

  3. Design Patterb Interview Questions Part 4 :- bridge pattern, composite pattern, decorator pattern, Façade pattern, chain of responsibility(COR), proxy pattern and template pattern
Happy job hunting......

(B) What are design patterns?

Design patterns are documented tried and tested solutions for recurring problems in a given context. So basically you have a problem context and the proposed solution for the same. Design patterns existed in some or other form right from the inception stage of software development. Let’s say if you want to implement a sorting algorithm the first thing comes to mind is bubble sort. So the problem is sorting and solution is bubble sort. Same holds true for design patterns.

(I) Which are the three main categories of design patterns?

There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.
Creational Patterns
Abstract Factory:- Creates an instance of several families of classes
Builder: - Separates object construction from its representation
Factory Method:- Creates an instance of several derived classes
Prototype:- A fully initialized instance to be copied or cloned
Singleton:- A class in which only a single instance can exist
Note: - The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First President of States).
Structural Patterns
Adapter:-Match interfaces of different classes .
Bridge:-Separates an object’s abstraction from its implementation.
Composite:-A tree structure of simple and composite objects.
Decorator:-Add responsibilities to objects dynamically.
Façade:-A single class that represents an entire subsystem.
Flyweight:-A fine-grained instance used for efficient sharing.
Proxy:-An object representing another object.
Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns
Mediator:-Defines simplified communication between classes.
Memento:-Capture and restore an object's internal state.
Interpreter:- A way to include language elements in a program.
Iterator:-Sequentially access the elements of a collection.
Chain of Resp: - A way of passing a request between a chain of objects.
Command:-Encapsulate a command request as an object.
State:-Alter an object's behavior when its state changes.
Strategy:-Encapsulates an algorithm inside a class.
Observer: - A way of notifying change to a number of classes.
Template Method:-Defer the exact steps of an algorithm to a subclass.
Visitor:-Defines a new operation to a class without change.
Note: - Just remember Music....... 2 MICS On TV (MMIICCSSOTV).
Note :- In the further section we will be covering all the above design patterns in a more detail manner.

(A) Can you explain factory pattern?

  • Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it’s meant to construct and create something. In software architecture world factory pattern is meant to centralize creation of objects. Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice type specified by the client. There are two issues with the code below:-
  • First we have lots of ‘new’ keyword scattered in the client. In other ways the client is loaded with lot of object creational activities which can make the client logic very complicated.

    Second issue is that the client needs to be aware of all types of invoices. So if we are adding one more invoice class type called as ‘InvoiceWithFooter’ we need to reference the new class in the client and recompile the client also.




Figure: - Different types of invoice


Taking these issues as our base we will now look in to how factory pattern can help us solve the same. Below figure ‘Factory Pattern’ shows two concrete classes ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’.
The first issue was that these classes are in direct contact with client which leads to lot of ‘new’ keyword scattered in the client code. This is removed by introducing a new class ‘ClsFactoryInvoice’ which does all the creation of objects.
The second issue was that the client code is aware of both the concrete classes i.e. ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’. This leads to recompiling of the client code when we add new invoice types. For instance if we add ‘ClsInvoiceWithFooter’ client code needs to be changed and recompiled accordingly. To remove this issue we have introduced a common interface ‘IInvoice’. Both the concrete classes ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’ inherit and implement the ‘IInvoice’ interface.
The client references only the ‘IInvoice’ interface which results in zero connection between client and the concrete classes ( ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’). So now if we add new concrete invoice class we do not need to change any thing at the client side.

In one line the creation of objects is taken care by ‘ClsFactoryInvoice’ and the client disconnection from the concrete classes is taken care by ‘IInvoice’ interface.

Figure: - Factory pattern
Below are the code snippets of how actually factory pattern can be implemented in C#. In order to avoid recompiling the client we have introduced the invoice interface ‘IInvoice’. Both the concrete classes ‘ClsInvoiceWithOutHeaders’ and ‘ClsInvoiceWithHeader’ inherit and implement the ‘IInvoice’ interface.
InterfaceAndConcrete.jpg
Figure :- Interface and concrete classes
We have also introduced an extra class ‘ClsFactoryInvoice’ with a function ‘getInvoice()’ which will generate objects of both the invoices depending on ‘intInvoiceType’ value. In short we have centralized the logic of object creation in the ‘ClsFactoryInvoice’. The client calls the ‘getInvoice’ function to generate the invoice classes. One of the most important points to be noted is that client only refers to ‘IInvoice’ type and the factory class ‘ClsFactoryInvoice’ also gives the same type of reference. This helps the client to be complete detached from the concrete classes, so now when we add new classes and invoice types we do not need to recompile the client.
Figure: - Factory class which generates objects
Note :- The above example is given in C# . Even if you are from some other technology you can still map the concept accordingly. You can get source code from the CD in ‘FactoryPattern’ folder.

(I) Can you explain abstract factory pattern?

Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class. All other things related to factory pattern remain same as discussed in the previous question.

A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between related factory patterns which leads more simplified interface for the client.
Figure: - Abstract factory unifies related factory patterns
Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory (AbstractFactory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from common interface. For instance in figure ‘Implementation of abstract factory’ both the concrete classes ‘product1’ and ‘product2’ inherits from one interface i.e. ‘common’. The client who wants to use the concrete class will only interact with the abstract factory and the common interface from which the concrete classes inherit.
Figure: - Implementation of abstract factory

Now let’s have a look at how we can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes ‘ClsFactoryButton’ and ‘ClsFactoryText’. Both these classes inherit from common interface ‘InterfaceRender’. Both the factories ‘ClsFactoryButton’ and ‘ClsFactoryText’ inherits from the common factory ‘ClsAbstractFactory’. Figure ‘Example for AbstractFactory’ shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( ClsAbstractFactory ) and for calling the concrete class implementation it calls the methods via the interface ‘InterfaceRender’. So the ‘ClsAbstractFactory’ class provides a common interface for both factories ‘ClsFactoryButton’ and ‘ClsFactoryText’.
Figure: - Example for abstract factory


Note: - We have provided a code sample in C# in the ‘AbstractFactory’ folder. People who are from different technology can compare easily the implementation in their own language.
We will just run through the sample code for abstract factory. Below code snippet ‘Abstract factory and factory code snippet’ shows how the factory pattern classes inherit from abstract factory.


Figure: - Abstract factory and factory code snippet
Figure ‘Common Interface for concrete classes’ how the concrete classes inherits from a common interface ‘InterFaceRender’ which enforces the method ‘render’ in all the concrete classes.
Figure: - Common interface for concrete classes
The final thing is the client code which uses the interface ‘InterfaceRender’ and abstract factory ‘ClsAbstractFactory’ to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.
Figure: - Client, interface and abstract factory

(I)Can you explain builder pattern?



Builder falls under the type of creational pattern category. Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.
Figure: - Builder concept

To understand what we mean by construction and representation lets take the example of the below ‘Tea preparation’ sequence.

You can see from the figure ‘Tea preparation’ from the same preparation steps we can get three representation of tea’s (i.e. Tea with out sugar, tea with sugar / milk and tea with out milk).

Figure: - Tea preparation

Now let’s take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘EXCEL’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.

Figure: - Request a report
Now let’s take a different view of the problem as shown in figure ‘Different View’. The same flow defined in ‘Request a report’ is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.

Figure: - Different View

We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

Builder: - Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
Director: - Director takes those individual processes from the builder and defines the sequence to build the product.
Product: - Product is the final object which is produced from the builder and director coordination.

First let’s have a look at the builder class hierarchy. We have a abstract class called as ‘ReportBuilder’ from which custom builders like ‘ReportPDF’ builder and ‘ReportEXCEL’ builder will be built.

Figure: - Builder class hierarchy
Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘EXCEL’ (ReportExcel). These two custom builders define there own process according to the report type.

Figure: - Builder classes in actual code
Now let’s understand how director will work. Class ‘clsDirector’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or EXCEL.

Figure: - Director in action
The third component in the builder is the product which is nothing but the report class in this case.

Figure: - The report class
Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.
Figure: - Client, builder, director and product
The output is something like this. We can see two report types displayed with their headers according to the builder.

Figure: - Final output of builder

Note :- In CD we have provided the above code in C# in ‘BuilderPattern’ folder.

(I) Can you explain prototype pattern?

Prototype pattern falls in the section of creational pattern. It gives us a way to create new objects from the existing instance of the object. In one sentence we clone the existing object with its data. By cloning any changes to the cloned object does not affect the original object value. If you are thinking by just setting objects we can get a clone then you have mistaken it. By setting one object to other object we set the reference of object BYREF. So changing the new object also changed the original object. To understand the BYREF fundamental more clearly consider the figure ‘BYREF’ below. Following is the sequence of the below code:-
• In the first step we have created the first object i.e. obj1 from class1.
• In the second step we have created the second object i.e. obj2 from class1.
• In the third step we set the values of the old object i.e. obj1 to ‘old value’.
• In the fourth step we set the obj1 to obj2.
• In the fifth step we change the obj2 value.
• Now we display both the values and we have found that both the objects have the new value.

Figure :- BYREf
The conclusion of the above example is that objects when set to other objects are set BYREF. So changing new object values also changes the old object value.

There are many instances when we want the new copy object changes should not affect the old object. The answer to this is prototype patterns.

Lets look how we can achieve the same using C#. In the below figure ‘Prototype in action’ we have the customer class ‘ClsCustomer’ which needs to be cloned. This can be achieved in C# my using the ‘MemberWiseClone’ method. In JAVA we have the ‘Clone’ method to achieve the same. In the same code we have also shown the client code. We have created two objects of the customer class ‘obj1’ and ‘obj2’. Any changes to ‘obj2’ will not affect ‘obj1’ as it’s a complete cloned copy.


Figure: - Prototype in action

Note :- You can get the above sample in the CD in ‘Prototype’ folder. In C# we use the ‘MemberWiseClone’ function while in JAVA we have the ‘Clone’ function to achieve the same.

(A) Can you explain shallow copy and deep copy in prototype patterns?

There are two types of cloning for prototype patterns. One is the shallow cloning which you have just read in the first question. In shallow copy only that object is cloned, any objects containing in that object is not cloned. For instance consider the figure ‘Deep cloning in action’ we have a customer class and we have an address class aggregated inside the customer class. ‘MemberWiseClone’ will only clone the customer class ‘ClsCustomer’ but not the ‘ClsAddress’ class. So we added the ‘MemberWiseClone’ function in the address class also. Now when we call the ‘getClone’ function we call the parent cloning function and also the child cloning function, which leads to cloning of the complete object. When the parent objects are cloned with their containing objects it’s called as deep cloning and when only the parent is clones its termed as shallow cloning.

Figure: - Deep cloning in action

(B) Can you explain singleton pattern?

Punch :-  Create a single instance of object and provides access to this single instance via a central point.
There are situations in project where we want only one instance of the object to be created and shared between the clients. For instance let’s say we have the below two classes, currency and country.
These classes load master data which will be referred again and again in project. We would like to share a single instance of the class to get performance benefit by not hitting the database again and again.
public class Currency
    {
        List<string /> oCurrencies = new List<string />();
        public Currency()
        {
            oCurrencies.Add("INR");
            oCurrencies.Add("USD");
            oCurrencies.Add("NEP");
            oCurrencies.Add("GBP");
 
        }
        public IEnumerable<string /> getCurrencies()
        {
            return (IEnumerable<string />)oCurrencies;
        }
    }
public class Country
    {
        List<string /> oCountries = new List<string />();
        public Country()
        {
            oCountries.Add("India");
            oCountries.Add("Nepal");
            oCountries.Add("USA");
            oCountries.Add("UK");
 
        }
        public IEnumerable<string /> getCounties()
        {
            return (IEnumerable<string />) oCountries;
        }
    }
Implementing singleton pattern is a 4 step process.
Step 1: - Create a sealed class with a private constructor
The private constructor is important so that clients cannot create object of the class directly. If you remember the punch, the main intention of this pattern is to create a single instance of the object which can be shared globally, so we do not want to give client the control to create instances directly.
public sealed class GlobalSingleton
    {
private GlobalSingleton() { }
 
 ………..
 ……….
 }
Step 2: - Create aggregated objects of the classes (for this example it is currency and country) for which we want single instance.
public sealed class GlobalSingleton
    {
        // object which needs to be shared globally
        public Currency Currencies = new Currency();
        public Country Countries = new Country();
Step 3: - Create a static read-only object of t he class itself and expose the same via static property as shown below.
public sealed class GlobalSingleton
    {
 ….
 …
// use static variable to create a single instance of the object
static readonly GlobalSingleton INSTANCE = new GlobalSingleton();
 
public static GlobalSingleton Instance
        {
            get
            {
              
                return INSTANCE;
            }
        }       
    }
Step 4: - You can now consume the singleton object using the below code from the client.
GlobalSingleton oSingle = GlobalSingleton.Instance;
Country o = osingl1.Country;
Below goes the complete code for singleton pattern which we discussed above in pieces.
public sealed class GlobalSingleton
    {
        // object which needs to be shared globally
        public Currency Currencies = new Currency();
        public Country Countries = new Country();
 
        // use static variable to create a single instance of the object
        static readonly GlobalSingleton INSTANCE = new GlobalSingleton();
 
        /// This is a private constructor, meaning no outsides have access.
        private GlobalSingleton() 
        { }
        
public static GlobalSingleton Instance
        {
            get
            {
              
                return INSTANCE;
            }
        }       
    }

(A) Can you explain command patterns?

Command pattern allows a request to exist as an object. Ok let’s understand what it means. Consider the figure ‘Menu and Commands’ we have different actions depending on which menu is clicked. So depending on which menu is clicked we have passed a string which will have the action text in the action string. Depending on the action string we will execute the action. The bad thing about the code is it has lot of ‘IF’ condition which makes the coding more cryptic.
Figure: - Menu and Commands
Command pattern moves the above action in to objects. These objects when executed actually execute the command.
As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in ‘clsExecuteExit’ , open action is wrapped in ‘clsExecuteOpen’, print action is wrapped in ‘clsExecutePrint’ and so on. All these classes are inherited from a common interface ‘IExecute’.
Figure: - Objects and Command
Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes which have the action.
So we have added all the actions in one collection i.e. the arraylist. We have exposed a method ‘getCommand’ which takes a string and gives back the abstract object ‘IExecute’. The client code is now neat and clean. All the ‘IF’ conditions are now moved to the ‘clsInvoker’ class.

Figure: - Invoker and the clean client
Note: - You can find a sample code for C# code in command pattern in ‘Command’ folder.

boxing and unboxing time calcumate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000; i++)
            {
                box();
            }
            sw.Stop();
            Console.WriteLine("Box = " + sw.Elapsed.ToString());
            Stopwatch sw1 = new Stopwatch();
            sw1.Start();
            for (int j = 0; j < 10000; j++)
            {
                unbox();
            }
            sw1.Stop();
            Console.WriteLine("Box = " + sw1.Elapsed.ToString());
            Console.ReadLine();
        }
        private static void box()
        {
            int i = 123;
            object j = i;
        }
        private static void unbox()
        {
            int i = 123;
            int j = i;
        }
    }
}

Why C# doesn’t supports multiple inheritance?

Why C# doesn’t supports multiple inheritance?

Its good to know that  C# Supports Multiple Inheritance . But i  wrote  my  title that it  doesn’t. Yes  it doesn’t support by Implementation inheritance but supports using Interface  Implementation.  Sounds confused??  have a look at it…
Basic Inheritance

Two types of Inheritance:
1.    Implementation Inheritance: in which class inherits one class and implement/override its methods and properties for example Control object in which System.Windows.Forms.Textbox,System.Windows.Forms.Button both inherits their self from control class. But provides different functionality
2.    Interface inheritance: in which a class inherits from Interface. For example IDisposable. It just inherits definition not implementation. Any type which does interface inheritance it means that it will provide defined functionality called as “Contract”.
Multiple Inheritance:
A class derives from more than one class it is called Multiple inheritance
Multiple inheritance allows a class to take on functionality from multiple other classes, such as allowing a class named StudentMusician to inherit from a class named Person, a class named Musician, and a class named Worker. This can be abbreviated StudentMusician : Person, Musician, Worker.
Ambiguities arise in multiple inheritance, as in the example above, if for instance the class Musician inherited from Person and Worker and the class Worker inherited from Person. There would then be the following rules:
StudentMusician: Person, Musician, Worker
Musician : Person, Worker
Worker: Person
If a compiler is looking at the class StudentMusician it needs to know whether it should join identical features together, or whether they should be separate features. For instance, it would make sense to join the “Age” features of Person together for StudentMusician. A person’s age doesn’t change if you consider them a Person, a Worker, or a Musician. It would, however, make sense to separate the feature “Name” in Person and Musician if they use a different stage name than their given name. The options of joining and separating are both valid in their own context and only the programmer knows which option is correct for the class they are designing.
Debate
There is debate as to whether multiple inheritance can be implemented simply and without ambiguity. It is often criticized for increased complexity and ambiguity, as well as versioning and maintenance problems it can cause (often summarized as the diamond problem).[1] Detractors also point out multiple inheritance implementation problems such as not being able to explicitly inherit from multiple classes and the order of inheritance changing class semantics. There are languages that address all technical issues of multiple inheritance, but the main debate remains whether implementing and using multiple inheritance is easier than using single inheritance and software design patterns.

Multiple Inheritance arises Diamond Problem


programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override it), and B and C have overridden that method differently, then via which class does it inherit: B, or C?
For example, a class Button inherits from both classes Rectangle (for appearance) and Mouse (for mouse events), and classes Rectangle and Mouse both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an over-ridden equals method in both Rectangle and Mouse, which method should be called?
It is called the “diamond problem” because of the shape of the class inheritance diagram in this situation. Class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.
C# Supports Multiple Inheritances by Interfaces only
http://kiranpatils.wordpress.com/2008/03/10/why-c-doesn%E2%80%99t-supports-multiple-inheritance/ 
 
http://www.codeproject.com/KB/cs/cs_interfaces.aspx
NOTE: lots of help got from wikipedia
Happy Inheritance!!