Tuesday 17 September 2013

Different ways to achieve code re-usability in real time Asp.Net



Most of the people know inheritance is the major way for re-usability of code. Apart from that their are other ways of code re-usability. This article is very useful for the people who are preparing for interviews as well as the employees who are working in software industry.

This article describes  how people re-use the code in software Industry. This article is little big so don`t get hesitate to read this article. You will find very helpful information with an example.
  1. Using Master Pages. (Example .Master Pages in asp.net).
  2. Using User Controls. (Example: .ascx  Custom Controls ).
  3. Using Singleton Classes. (To prevent identical objects from being created)
  4. Using Entities. (Re-usability of Entities are very important in real time implementations).
  5. Inheritance and Shared Methods. (is-a Relationship and Has-a Relationship)
  6. Creating COM Components. (.dll class libraries interoperability between languages)

    Master Pages
    :
    • To create a set of controls that are common across all the web pages and attaching them to all the web pages.
    • A centralized way to change the above created set of controls which will effectively change all the web pages.
    • Changing the UI elements dynamically on master page from content pages based on user choice.
    • Nested Master Pages are also Possible. 

    Using of Master Pages: 
    • Whenever you create "Master pages" use content place holders inside master page where you can specify the controls to be rendered.
    • Use Same Content place holders id in the derived page and create your customized content in that content place holder.

    Normally in software industry Master Pages are placed in the below path
    Path= ~/Assets/masterpages/MasterPage.master

    In Any Real time development Must and should you master pages and it is recommended.
    MasterPagesMerge graphic


    User Controls: In addition to using Web server controls in your ASP.NET Web pages, you can create your own custom, reusable controls using the same techniques you use for creating ASP.NET Web pages. These controls are called user controls.
    • User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.
    •  Custom controls. A custom control is a class that you write that derives from control or web control.
      A user controls differs from an ASP.NET Web page in these ways:
      • The file name extension for the user control is .ascx.
      • Instead of an @page directive, the user control contains an @control directive that defines configuration and other properties.
      • User controls cannot run as stand-alone files. Instead, you must add them to ASP.NET pages, as you would any control.
      • The user control does not have html, body, or form elements in it. These elements must be in the hosting page.
     Use this tag in a page for registering the user control in a page:
    <%@ Register TagPrefix="Grid" TagName="RequestData" Src="~/Users/Controls/ConnectionControl.ascx" %> 
    Use this tag as many times you want to use this control in your page
     <Grid:RequestData ID="rgInbox" runat="server" />
     
    How to Access Page Methods from user controls and Vice Verse?
                 Page methods can be accessed from user control using Reflection and finding the control or value in user control can be accessed in page by using  Me.Parent.FindControl("controlname").                          
                                                           
    Singleton Classes: To Make sure to create only one instance and  there is a global access point to that object then singleton classes play an important role. This is one design pattern. Now i am just giving an idea how to create singleton class. Example:Garbage Collection.
    singleton Class
    Imports System
    Public Class Singleton
        Private Shared instance As Singleton
         Private Sub New()
           MyBase.New
         End Sub
    
         Public Shared ReadOnly Property GetInstance As Singleton
           Get
                If(instance Is Nothing) Then
                    instance = New Singleton
                End If
                Return instance
            End Get
         End Property
    
    End Class
    How to create an instance?
    Singleton.GetInstance()-----Use ClassName.MethodName

    Using Entities : Like Methods and Classes class entities can be reused.

    User.vb: This class consists of user properties with setter() and getter() methods.
    • user class properties: UserName,FirstName,LastName,Address,Mobile,DateOfBirth.

    Account.vb: This class consists of Account properties with setter() and getter() methods.
    • Account class properties: AccountId, AccountName, AccountType, AccountCreated, AccountUpdated.

    How to Re-use Entities?
    • Here to re-use User class entities in Account class as mentioned below
      public property AccountDetails as User
      For accessing in application you can use:  AccountDetails.UserName or AccountDetails.FirstName.

    Inheritance and Shared Methods:
    Inheritance is a process of inheriting properties and methods from parent class to child class. If an object is created to the child class then parent class constructor will be called first and  child class method will be executes.

    1. Single Inheritance
    2. Hierarchical Inheritance
    3. Multi Level Inheritance
    4. Hybrid Inheritance
    5. Multiple Inheritance

    All the types of inheritance can be achieved in Object Oriented Programming except Multiple Inheritance. Multiple inheritance can be implemented using Interfaces.

    Major People feel difficulty to explain the below question in interview
    Why Multiple inheritance is not possible?
                 
                  Reason 1: Problem around Diamond problem, consider a class A has run() method and then B and C derived from A and has there own run() implementation and now class D derive from B and C using multiple inheritance and if we refer just run() compiler will not be able to decide which run() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below
              A run()
            /      \
          /          \
       B run()     C run()
          \          /
            \     /
             D run()
               Even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

                Reason 2: Multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also .net avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn’t provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

    Shared Methods : Shared methods are majorly used in any application they re-use these methods many types in the application like making all the string safer while retrieving it from database and using common methods to bind controls like dropdown control.

    Example: Creating shared method for binding the drop down and re-use it whenever necessary to bind the different drop downs in the application. Concept of  "Write Once and use Many times."

    COM Components: Component Object Model is a method to facilitate communication between different applications and languages. The interesting thing in COM components and  widely accepted interoperability standard and explains the way the memory should be organized for all the objects.

    Creating COM Components
    • Create a new Class Library project.
    • Create a new interface, say IManagedInterface, and declare the methods required. Then provide the Guid (this is the IID) for the interface using the GuidAttribute defined in System.Runtime.InteropServices. The Guid can be created using the Guidgen.exe. [Guid("3B515E51-0860-48ae-B49C-05DF356CDF4B")]
    • Define a class that implements this interface. Again provide the Guid (this is the CLSID) for this class also.
    • Mark the assembly as ComVisible. For this go to AssemblyInfo.cs file and add the following statement [assembly: ComVisible (true)]. This gives the accessibility of all types within the assembly to COM.
    • Build the project. This will generate an assembly in the output path. Now register the assembly using regasm.exe (a tool provided with the .NET Framework)- regasm \bin\debug\ComInDotNet.dll \tlb:ComInDotNet.tlb This will create a TLB file after registration.
    • Alternatively this can be done in the Project properties -> Build -> check the Register for COM interop.
    Please share this helpful information with your friends.

    My next post will be on real time dropdown binding with an example and re-using the code to bind thousands of   dropdowns in web application.

No comments:

Post a Comment