Wednesday 29 April 2015

Access Modifiers in c# asp.net


Access modifiers are keywords used to specify the declared accessibility of a member or a type.

Why to use access modifiers?


Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features.


In C# here are 5 different types of Access Modifiers.













































public

The public keyword is an access modifier for types and type members. Public access is the most permissive access level.

There are no restrictions on accessing public members.

Accessibility: 
  1. Can be accessed by objects of the class
  2. Can be accessed by derived classes

 Example:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
using System.Data;


namespace AccessModifier
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine ("Please enter first number");
            int a = int.Parse(Console.ReadLine());
            Console.WriteLine ("Please enter second number");
            int b = int.Parse(Console.ReadLine());
            MyTestA ts = new MyTestA ();
            // access to public member
            int sum = ts.getSum(a,b);
   
            Console.WriteLine ("Entered numbers are : {0}, {1}\n", a, b);
            Console.WriteLine ("Sum of numbers is : {0}\n", sum);
            Console.Read();
        }
    }

    Public class MyTestA
    {
        Private int sum;
        //public member
        Public int getSum(int a, int b)
        {
            this.sum = a + b;
            Return this.sum;
        }
     
    }
}


Output:-















private

Private access is the least permissive access level.

Private members are accessible only within the body of the class or the struct in which they are declared.

Accessibility: 
  1. Cannot be accessed by object
  2. Cannot be accessed by derived classes

Here the private member  <<  ts.getMultiplication(a, b);  >> not accessable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
using System.Data;


namespace AccessModifier
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine ("Please enter first number");
            int a = int.Parse(Console.ReadLine());
            Console.WriteLine ("Please enter second number");
            int b = int.Parse(Console.ReadLine());
            MyTestA ts = new MyTestA();
            // access to public
            Int sum = ts.getSum(a,b);
            // Access to private member
            Int multi = ts.getMultiplication(a, b);
            Console.WriteLine ("Entered numbers are : {0}, {1}\n", a, b);
            Console.WriteLine ("Sum of numbers is : {0}\n", sum);
            Console.WriteLine ("multiplication of numbers is : {0}\n", multi);
            Console.Read ();
        }
    }

    Public class MyTestA
    {
        Private int sum;
        //public member
        Public int getSum (int a, int b)
        {
            this.sum = a + b;
            return this.sum;
        }
       //private member
        Private Int getMultiplication (int a, int b)
        {
            this.sum = a + b;
            Return this.sum;
        }
    }
}


See Error in Image below
The above program will give compilation error, as access to private is not permissible

























protected

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.

Accessibility: 
  1. Cannot be accessed by object
  2. By derived classes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
using System.Data;


namespace AccessModifier
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine ("Please enter first number");
            int a = int.Parse(Console.ReadLine());
            Console.WriteLine ("Please enter second number");
            int b = int.Parse(Console.ReadLine());
            Console.WriteLine ("Entered numbers are : {0}, {1}\n", a, b);
            MyTestB ts = new MyTestB();
            // access to public class MyTestB
            int sum = ts.getSum(a, b);
            Console.WriteLine ("sum of numbers are : {0}\n", sum);
            Console.ReadKey ();
        }
    }

    Public class MyTestA               
    {
        int sum;
       //protected member
        Protected int getMultiplication(int a, int b)
        {
            this.sum = a * b;
            Return this.sum;
        }
    }
    Public class MyTestB : MyTestA
    {
        Private int sum;
        //public member
        Public int getSum(int a, int b)
        {
            // Access to protected member of base class MyTestA
            int multi = this.getMultiplication(a,b);
            Console.WriteLine ("multiplication of numbers is : {0}\n", multi);

            // now retrun the sum
            this.sum = a + b;
            return this.sum;
           
        }
      
    }
}

Access of protected member in main it is not available

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
using System.Data;


namespace AccessModifier
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine ("Please enter first number");
            int a = int.Parse(Console.ReadLine());
            Console.WriteLine ("Please enter second number");
            int b = int.Parse(Console.ReadLine());
            Console.WriteLine ("Entered numbers are : {0}, {1}\n", a, b);
            MyTestB ts = new MyTestB ();
            // access to public class MyTestB
            int sum = ts.getSum(a, b);
            Console.WriteLine ("sum of numbers are : {0}\n", sum);

            // Access to protected member of class MyTestA in Main Function
    Error Line >>        int multi = ts.getMultiplication(a, b);
            Console.WriteLine ("sum of numbers are : {0}\n", sum);
            Console.ReadKey ();
        }
    }

    Public class MyTestA
    {
        int sum;
       //protected member
        Protected int getMultiplication (int a, int b)
        {
            this.sum = a * b;
            return this.sum;
        }
    }
    Public class MyTestB: MyTestA
    {
        Private int sum;
        //public member
        Public int getSum (int a, int b)
        {
            // Access to protected member of base class MyTestA
            int multi = this.getMultiplication(a,b);
            Console.WriteLine ("multiplication of numbers is: {0}\n", multi);

            // now retrun the sum
            this.sum = a + b;
            Return this.sum;
           
        }
      
    }
}

In the above program we try to access protected member in main it is not available as shown in the picture below that num1 is not listed in intellisense.




















Internal

The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll).

In other words, access is limited exclusively to classes defined within the current project assembly.

Accessibility:

In same assembly (public) 
  1. Can be accessed by objects of the class
  2. Can be accessed by derived classes
In other assembly (internal) 
  1. Cannot be accessed by object
  2. Cannot be accessed by derived classes
protected internal

The protected internal accessibility means protected OR internal, not protected AND internal.

In other words, a protected internal member is accessible from any class in the same assembly, including derived classes.

The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:  
  1. Inherited types, even though they belong to a different assembly, have access to the protected internal members.
  2. Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.
Default access

A default access level is used if no access modifier is specified in a member declaration. The following list defines the default access modifier for certain C# types:

enum: The default and only access modifier supported is public.

class: The default access for a class is private. It may be explicitly defined using any of the access modifiers.

interface: The default and only access modifier supported is public.

struct: The default access is private with public and internal supported as well.

The default access may suffice for a given situation, but you should specify the access modifier you want to use to ensure proper application behavior.

Note: Interface and enumeration members are always public and no access modifiers are allowed.

Conclusion

I hope that this article would have helped you in understanding accessibility modifiers. Your feedback and constructive contributions are welcome.





Tuesday 28 April 2015

Asp.net Page and Application life cycle

ASP.NET life cycle specifies, how:


When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the page life cycle, but the page raises more events for a control than are available for an ASP.NET page alone.)
1.      ASP.NET processes pages to produce dynamic output
2.      The application and its pages are instantiated and processed
3.      ASP.NET compiles the pages dynamically

The ASP.NET life cycle could be divided into two groups:

  1. Application Life Cycle
  2. Page Life Cycle

ASP.NET Application Life Cycle

The application life cycle has the following stages:
  1. User makes a request for accessing application resource, a page. Browser sends this request to the web server.
  2. A unified pipeline receives the first request and the following events take place:
2.1  An object of the class ApplicationManager is created.
2.2 An object of the class HostingEnvironment is created to provide information regarding the resources.
2.3 Top level items in the application are compiled.
  1. Response objects are created. The application objects such as HttpContext, HttpRequest and HttpResponse are created and initialized.
  2. An instance of the HttpApplication object is created and assigned to the request.
  3. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.NET Page Life Cycle

When a page is requested, it is loaded into the server memory, processed, and sent to the browser. Then it is unloaded from the memory. At each of these steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives, are part of this control tree. You can see the control tree by adding trace= "true" to the page directive. We will cover page directives and tracing under 'directives' and 'event handling'.
The page life cycle phases are:
  1. Initialization
  2. Instantiation of the controls on the page
  3. Restoration and maintenance of the state
  4. Execution of the event handler codes
  5. Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.
Following are the different stages of an ASP.NET page:
1.      Page request - When ASP.NET gets a page request, it decides whether to parse and compile the page, or there would be a cached version of the page; accordingly the response is sent.
2.      Starting of page life cycle - At this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
3.      Page initialization - At this stage, the controls on the page are assigned unique ID by setting the UniqueID property and the themes are applied. For a new request, postback data is loaded and the control properties are restored to the view-state values.
4.      Page load - At this stage, control properties are set using the view state and control state values.
5.      Validation - Validate method of the validation control is called and on its successful execution, the IsValid property of the page is set to true.
6.      Postback event handling - If the request is a postback (old request), the related event handler is invoked.
7.      Page rendering - At this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Response property of page.
8.      Unload - The rendered page is sent to the client and page properties, such as Response and Request, are unloaded and all cleanup done.

ASP.NET Page Life Cycle Events

       At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is      basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle.

Following are the page life cycle events:

  1. PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls, and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  2. Init - Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
  3. InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
  4. LoadViewState - LoadViewState event allows loading view state information into the controls.
  5. LoadPostData - During this phase, the contents of all the input fields are defined with the <form> tag are processed.
  6. PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
  7. Load - The Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
  8. LoadComplete - The loading process is completed, control event handlers are run, and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler
  9. PreRender - The PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
  10. PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
  11. SaveStateComplete - State of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
  12. UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.