Wednesday, May 30, 2012

ViewStateMode in ASP.Net 4.0

ViewStateMode in ASP.Net 4.0

When asp.net introduced the concept of viewstate, it changed the way how developers maintain the state for the controls in a web page. Until then to keep the track of the control(in classic asp), it was the developer responsibility to manually assign the posted content before rendering the control again. Viewstate made allowed the developer to do it with ease. The developers are not bothered about how controls keep there state on post back.
Viewstate is rendered to the browser as a hidden variable __viewstate. Since viewstate stores the values of all controls, as the number of controls in the page increases, the content of viewstate grows large. It causes some websites to load slowly.
As developers we need viewstate, but actually we do not want this for all the controls in the page. Till asp.net 3.5, if viewstate is disabled from web.config (using ..), then you can not enable it from the control level/page level. Both <%@ Page EnableViewState=”true”…. and
Lot of developers demands for more control over viewstate. It will be useful if the developers are able to disable it for the entire page and enable it for only those controls that needed viewstate. With ASP.NET 4.0, this is possible, a happy news for the developers. This is achieved by introducing a new property called ViewStateMode.
Let us see, What is ViewStateMode – Is a new property in asp.net 4.0, that allows developers to enable viewstate for individual control even if the parent has disabled it. This ViewStateMode property can contain either of three values
  1. Enabled- Enable view state for the control even if the parent control has view state disabled.
  2. Disabled - Disable view state for this control even if the parent control has view state enabled
  3. Inherit - Inherit the value of ViewStateMode from the parent, this is the default value.
To disable view state for a page and to enable it for a specific control on the page, you can set the EnableViewState property of the page to true, then set the ViewStateMode property of the page to Disabled, and then set the ViewStateMode property of the control to Enabled.
Find the example below.
Page directive - <%@ Page Language="C#"  EnableViewState="True" ViewStateMode="Disabled" .......... %>
Code for the control  -

Now the viewstate will be disabled for the whole page, but enabled for the TextBox.
ViewStateMode gives developers more control over the viewstate.

Tuesday, May 29, 2012

Method Overriding in C#.NET

Method Overriding in C#.NET

Creating a method in derived class with same signature as a method in base class is called as method overriding.

Same signature means methods must have same name, same number of arguments and same type of arguments.

Method overriding is possible only in derived classes, but not within the same class.

When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.

To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods.



Monday, May 28, 2012

Improvements in C# 4.0

Improvements in C# 4.0


C# in .NET Framework 4.0 has some more things to offer. These are:
  • Dynamic lookup
  • Named
  • Optional parameters

Dynamic Lookup

There is a new static type named dynamic. We can use it as object of any type. If there is any error on its usage, we would get it on runtime only. For example:
dynamic integerValue = 1; 
dynamic stringValue = " a string"; 
dynamic Result = integerValue + stringValue;
Output of this would be: 1 a string.
But, if you change the last line to:
dynamic Result = integerValue & stringValue;
You will not get any compilation error, but the following error on runtime:
Operator '&' cannot be applied to operands of type 'int' and 'string'

Optional Parameters

To implement optional parameters, we used to create overloaded functions before ASP.NET 4, but now, optional parameters are no more a restriction in C#. Like VB, optional parameters must be mentioned last. For example:
public void FunctionOptionalParam(string Name, int Age, string Country = "") 
and we can call them without mentioning the value for the optional parameter.
FunctionOptionalParam("My Full Name",20);

Named Parameters

Named parameters allow you to ignore the parameter order and mention parameters with names in a different order. For example:
public void FunctionNamedParam(int x, int y , int z)
On function call, it would be:
FunctionNamedParam(x:1, z:3, y:2);
Although we are sending a value for the parameter z before its order in the function declaration, but these would be equal to x=1, y=2, z=3.

Friday, May 25, 2012

Tuesday, May 22, 2012

C# FAQ: abstract class & interface , private constructor

What is abstract class ?
Abstract class is a base class or a parent class. Abstract classes can  have empty abstract methods or it can have implemented methods which can be overridden by child classes.

The next question i expected was on interfaces and yes there it comes.

What are interfaces?
Interface is a contract class with empty methods , properties and functions. Any class which implements the interface has to compulsory implement all the empty methods , functions and properties of the interface.

Now the 1000% sure question was bound to come difference between them...

What's the difference between abstract class and interface?
There are many differences, below are some key two differences :-
  • Abstract class are base class or parent class while interfaces are contracts.
  • Abstract class can have some implemented methods and functions while interfaces methods and functions are completely empty.
  • Abstract classes are inherited while interfaces are implemented.
  • Abstract classes are used when we want to increase reusability in inheritance while interfaces are used to force a contract.

Can we create a object of abstract class or interface?
No we can not.
Now the practical question..

In what scenarios will you use a abstract class and in what scenarios will you use a  interface?
If you want to increase reusability in inheritance then abstract classes are good. If you want implement or force some methods across classes must be for uniformity you can use a interface. So to increase  reusability via inheritance use abstract class as it is nothing but a base class and to force methods use interfaces.

What is the use of private constructor ?

When we declare a class constructor as private , we can not do 2 things:-
-- We can not create a object of the class.
-- We can not inherit the class.
When to use private contstructor ==> when we have some classes like Utilty or Helper Classes Which we referer multiple places and we dont want to create instance of it all the time we call it. only one instance of such class will be used all over  the project.

Monday, May 21, 2012

Basic Concepts of OOPs in .Net

Introduction

.NET is fully object oriented platform that allow languages to take full advantage of these OO features. The features include:

Namespace
Classes
Abstract
Encapsulation
Overloading
New.
Overriding
Interfaces
Polymorphism

Let’s take a quick look at what each of this term means.

Namespace

Even though namespace is not really an OOPs feature, .NET use it extensively. Namespace is nothing but a logical container for various classes. Under given namespace class names must be unique. Namespace server two purposes – they provide logical organization of classes and they also avoid ambiguity.

Classes

Class is nothing but a template or blue-print for an entity. For example you may have a class that represents real life entity – Employee. The class will provide properties (Name, Age…) as well as actions (CalculateSalary, GoOnLeave…) of the entity.

Objects

Instances of classes are called as objects. For example there might be three instances of the Employee class mentioned above. They might represent individual employees – John, Bob and Tom.

Encapsulation

Each object typically deals with some kind of data or the other. Not all the data needs to be exposed to external systems. This can be controlled via data encapsulation.

Overloading

Overloading refers to the methods or functions having same name but varying parameters. The parameters should vary with respect to data types and order.
If no modifier is specified, the method is given private access.

Inheritance

Inheritance refers to extending functionality of existing class. Inheritance is useful when developing "object models" for your system. .NET supports only single inheritance.

Overriding

Overriding refers to the methods in the child class having the same signature (name as well as parameters) as of the parent class methods.

Interfaces

Interfaces are nothing but models of class properties and methods without any implementation. The class implements the interface. Once a class implements any interface it must implement all the properties and methods (although the implementation can be empty or null implementation).

Polymorphism

Polymorphism refers to the ability of the system to call correct implementation of methods with the same name. For example, Clerk as well as Manager class might have a method called CalculateSalary(). However, at runtime depending on whether the underlying object is of type Clerk or Manager correct version of the method is called.

Creating namespaces

Namespaces are created using keyword – Namespace (namespace in C#). Following example shows how to declare a namespace.

[VB.NET]
Namespace MyNamespace
End Namespace

[C#]
namespace MyNamespace
{
}

Note that one assembly can have one or more namespaces. Also, one namespace can span across multiple assemblies. You can create nested namespaces as follows:

[VB.NET]
Namespace MyNamespace
     Namespace MuSubNamespace
     …
     End Namespace
End Namespace

[C#]
     namespace MyNamespace
     {
         namespace MySubNamespace
         {
          …
         }
     } 

If you are using VS.NET then the project name acts as the default namespace name.

Creating classes

Creating classes is similar to creating namespaces.

[VB.NET]
    Public Class Class1
    …
    End Class

[C#]
    public class Class1
    {
      …
    }

Generally classes will be part of some of the namespace.

Creating Properties

Properties encapsulate data members of your class. Properties can be read-write, read only or write only. Here is how you create read-write properties:

[VB.NET]
      Public Class Employee

           private strName As String

           Public Property Name As String
           Get
               return strName;
           End Get

           Set(value As String)
              strName=value;
           End Set
           End Property
     End Class

[C#]
      public class Class1
      {
         public string Name
         {
           string strName;
           get
           {
               return strName;
           }
           set
           {
               strName=value;
           }
         }
     }

Here,

VB.NET uses Property keyword to declare properties. C# does not have this keyword
Property definition consists of two parts Get and Set. The get part returns the property value and set par sets some private variable.
The value in Set routine is received via implicit variable called value in C#. VB.NET allows you to change this.

Creating methods

Methods represent actions performed by the object. In VB.NET functions and sub routines are collectively called as methods. In C# everything is function.

[VB.NET]
      Public Sub CalculateSalary()
      …
      End Sub

[C#]
      public void CalculateSalary()
      {
        …
      }

Method overloading

Method overloading refers to methods with same name but different types or order of parameters. Following example make it clear:

[VB.NET]
      Public Sub CalculateSalary()
         …
      End Sub

      Public Sub CalculateSalary(month as Integer)
      …
      End Sub

[C#]
      public void CalculateSalary()
      {
       …
      }

      public void CalculateSalary(int month)
      {
      …
      }

In VB.NET you can also use optional parameters to achieve similar functionality. However, it is recommended to use overloading instead to make your code consistent across languages.

Inheritance

Inheritance is the ability to extend existing class further. Unlike languages like C++ that allow multiple inheritance .NET allows only single inheritance. This means that at a time you can inherit from a single class.

[VB.NET]
       Public Class Manager
           Inherits Employee
           …
       End Class

[C#]
       public class Manager : Employee
       {
         …
       }

In the above example, we create a class called Manager that inherits from Employee class. As you can guess Manager is specific implementation of generic Employee class. VB.NET uses Inherits keyword to indicate the parent class where as C# uses : operator to indicate that.

Method Overriding

In order to override method in child class they need to be marked as Overridable (VB.NET) or virtual (C#) in the parent class.

[VB.NET]
      Public Overridable Function CalculateSalary() As Integer
         …
      End Function

[C#]
      public virtual int CalculateSalary()
      {
       …
      }

Then in the child class you can create a method with the same signature and specify that it overrides the base class method.

[VB.NET]
      Public Overrides Function CalculateSalary() As Integer
        …
      End Function

[C#]
      public override int CalculateSalary()
      {
          …
      }

Note that if you do not provide the Overrides (VB.NET) or override (C#) keywords in the child class the compiler issues a warning that you are hiding a base class member. In this case you can either put the above keywords or use Shadows (VB.NET) or new (C#) keywords. Using these keywords ,however, will hide the base class members.

Creating Interfaces

Just like classes are templates for real life entities, interfaces can be thought of as templates for classes. They bring uniformity in your object model.

[VB.NET]
      Public Interface IEmployee
         Property EmployeeID() As Integer
         Property Name() As String
         Property Age() As Integer
         Function CalculateSalary() As Integer
      End Interface

[C#]
      public interface  IEmployee
      {
        int EmployeeID
      {
       get;
      }

          string Name
          {
             get;
             set;
          }

          int Age
          {
             get;
             set;
          }

          int CalculateSalary();
          }

As you can see VB.NET uses Interface keyword to define an interface. Similarly, C# uses interface keyword. Note, how they contain only property and method signatures and no code at all.

Implementing Interfaces

The main difference between inheritance based programming and interfaces based programming is that – interfaces just specify signatures of properties and methods for a class. Your class "implements" the interface by providing implementation for various properties and methods. Unlike inheritance there is no "code" inherited from interfaces. Your class can implement one or more interfaces.

[VB.NET]
        Public Class Manager
             Implements IEmployee
             …
             Public Function CalculateSalary() As Integer Implements IEmployee.CalculateSalary

             …
             End Function
End Class

[C#]
      public class Manager : IEmployee
      {
         …
         public int CalculateSalary()
         {
            …
         }

     }

Above example shows how VB.NET uses Implements keyword to implement an interface. Note how VB.NET also requires the use of Implements keyword for each property and method. You must have guessed from this that in VB.NET you can give different name to the implemented member than the interface. This feature is not available in C#. C# do not have a special keyword and uses the same : operator to implement the interface.

Polymorphism

Consider following lines of code:

[VB.NET]
        Dim emp As Employee
        emp = New Clerk()
        Console.WriteLine ("Clerk Salary :{0}", emp.CalculateSalary())
       
        emp = New Manager()
        Console.WriteLine ("Manager Salary :{0}", emp.CalculateSalary())
       

[C#]
       Employee emp;
       emp=new Clerk();
       Console.WriteLine ("Clerk Salary :{0}",emp.CalculateSalary());

       emp=new Manager();
       Console.WriteLine ("Manager Salary :{0}",emp.CalculateSalary());


Here, we have declared a variable of type Employee. A variable of parent class type can point to instance of any of its children. First, we point it to an instance of Clerk class. Then we point it to an instance of Manager class. Even though the variable is of type Employee, depending on which child type it is pointing to it calls the correct implementation of CalculateSalary() method. The underlying system does this via inheritance polymorphism. Similar thing can also be achieved in interface polymorphism.

[VB.NET]
        Dim emp As IEmployee
        emp = New Clerk()
        Console.WriteLine ("Clerk Salary :{0}", emp.CalculateSalary())

        emp = New Manager()
        Console.WriteLine ("Manager Salary :{0}", emp.CalculateSalary())


[C#]
      IEmployee emp;
      emp=new Clerk();
      Console.WriteLine ("Clerk Salary :{0}",emp.CalculateSalary());

      emp=new Manager();
      Console.WriteLine ("Manager Salary :{0}",emp.CalculateSalary());
  

SQL Tuning or SQL Optimization

Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.

SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.
For Example: Write the query as
SELECT id, first_name, last_name, age, subject FROM student_details;
Instead of:

SELECT * FROM student_details;

2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.

For Example: Write the query as
SELECT subject, count(subject)
FROM student_details
WHERE subject != 'Science'
AND subject != 'Maths'
GROUP BY subject; 


Instead of:

SELECT subject, count(subject)
FROM student_details
GROUP BY subject
HAVING subject!= 'Vancouver' AND subject!= 'Toronto';


3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as
SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';

Instead of:
SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';


4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.
For Example: Write the query as
Select * from product p
where EXISTS (select * from order_items o
where o.product_id = p.product_id)

Instead of:
Select * from product p
where product_id IN
(select product_id from order_items


5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as
SELECT d.dept_id, d.dept
FROM dept d
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);

Instead of:
SELECT DISTINCT d.dept_id, d.dept
FROM dept d,employee e
WHERE e.dept = e.dept;


6) Try to use UNION ALL in place of UNION.
For Example: Write the query as
SELECT id, first_name
FROM student_details_class10
UNION ALL
SELECT id, first_name
FROM sports_team;

Instead of:
SELECT id, first_name, subject
FROM student_details_class10
UNION
SELECT id, first_name
FROM sports_team;


7) Be careful while using conditions in WHERE clause.
For Example: Write the query as
SELECT id, first_name, age FROM student_details WHERE age > 10;
Instead of:
SELECT id, first_name, age FROM student_details WHERE age != 10;
Write the query as
SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE 'Chan%';

Instead of:
SELECT id, first_name, age
FROM student_details
WHERE SUBSTR(first_name,1,3) = 'Cha';

Write the query as
SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE NVL ( :name, '%');

Instead of:
SELECT id, first_name, age
FROM student_details
WHERE first_name = NVL ( :name, first_name);

Write the query as
SELECT product_id, product_name
FROM product
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)

Instead of:
SELECT product_id, product_name
FROM product
WHERE unit_price >= MAX(unit_price)
and unit_price <= MIN(unit_price)

Write the query as
SELECT id, name, salary
FROM employee
WHERE dept = 'Electronics'
AND location = 'Bangalore';

Instead of:
SELECT id, name, salary
FROM employee
WHERE dept || location= 'ElectronicsBangalore';

Use non-column expression on one side of the query because it will be processed earlier.
Write the query as
SELECT id, name, salary
FROM employee
WHERE salary < 25000;

Instead of:
SELECT id, name, salary
FROM employee
WHERE salary + 10000 < 35000;

Write the query as
SELECT id, first_name, age
FROM student_details
WHERE age > 10;

Instead of:
SELECT id, first_name, age
FROM student_details
WHERE age NOT = 10;

8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause.
For Example: Write the query as
SELECT id FROM employee
WHERE name LIKE 'Ramesh%'
and location = 'Bangalore';

Instead of:
SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee
WHERE name LIKE 'Ramesh%';

9) To store large binary objects, first place them in the file system and add the file path in the database.
10) To write queries which provide efficient performance follow the general SQL standard rules.
a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space
d) Right or left aligning verbs within the initial SQL verb

page events



 

Page Event


PreInit
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.
    NoteNote
    If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
Use this event to read or initialize control properties.
InitComplete
Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.
PreLoad
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
Load
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.
Control events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
NoteNote
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete
Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.
PreRender
Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
PreRenderComplete
Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
SaveStateComplete
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload
Raised for each control and then for the page.
In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
NoteNote
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Thursday, May 10, 2012

How IIS processes ASP.NET request




Before understanding the full flow, we have to go through following concepts:

IIS: IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it’s own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.

Worker Porcess (w3wp.exe): Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. In short, Worker process is the heart of ASP.NET Web Application which runs on IIS.

Application Pool: Application pool is the container of worker process. Application pools is used to separate the sets of IIS worker processes that share the same configuration. This makes sure that a particular web application doesn’t not impact other web application.

Note: One Application Pool can have one or many Worker Processes. An application pool with more than one worker process is called 'Web Garden'.

HTTP.SYS Process: HTTP.SYS resides in Kernel Layer of IIS. HTTP.SYS is responsible for pass the request to particular Application pool. It contains the ID of each Application Pool. (Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS).

WAS (Web Admin Services): WAS resides in User Layer of IIS. It takes the request from HTTP.SYS and pass it to the respective application pool.

ISAPI extensions: ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.

Note: Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.

Flow of ASP.NET Request:

1. Client Request hits the web server. Internally this request comes to Kernel Layer of IIS means at HTTP.SYS.

2. HTTP.SYS indentifies the name and ID of Application Pool for that ASP.NET Request.

3. Now Request comes to user level of IIS. WAS (Web Admin Service) puts the request from HTTP.SYS to Application Pool.

4. When Application pool receive the request, it simply pass the request to worker process (w3wp.exe).

5. The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension (aspnet_isapi.dll).

6. ISAPI creates an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder.HTTPRuntime is an entry point of the application.

Note: After these steps, After that the ASP.NET Page LifeCycle events starts.

Conclusion:

HTTP.SYS  (Kernel Layer) --> WAS (Web Admin Services) (User Layer) --> Application Pool --> Worker Process (w3wp.exe) --> ISAPI Process (aspnet_isapi.dll) -->  HTTPRuntime Process

Popular Posts

Recent Posts

Unordered List

Text Widget

Blog Archive