Friday, 4 April 2014

Difference between HttpGet and HttpPost Method

 (HTTP) :- The Hypertext Transfer Protocol (HTTP) is a communication protocol that is designed to enable request-response between clients and servers. Here, a web browser is the client and an application on a computer that hosts a web site is the server.



Http GET method

Take an html form named "get_form.htm" and write the following code.
  1. <html>
  2. <head>
  3. <title>Using Http Get Method</title>
  4. </head>
  5. <body>
  6. <form id="frm_get" action=" Receiving_Get_Form.aspx" target="_blank" method="GET" >
  7. <table>
  8. <tr>
  9. <td>First Name : </td> <td><input type="text" id="txtF_Name" name="F_name" /></td>
  10. </tr> <tr>
  11. <td>Last Name : </td> <td><input type=" text" id="txtL_name" name="L_name" /></td>
  12. </tr> <tr>
  13. <td>Email-Id : </td> <td><input type="text" id="txtE_mail" name="E_mail" /></td>
  14. </tr> <tr>
  15. <td>Password: </td> <td><input type="password" id="txtP_word" name="P_word"/> </td>
  16. </tr> <tr>
  17. <td><input type="submit" value="Submit" /></td>
  18. </tr>
  19. </table>
  20. </form> </body>
  21. </html>
When we click submit button of this form, it will be redirected to "Receiving_Get_Form.aspx" in a new window.

Page.Request.QueryString["param_name"]

  1. <%@ page language="C#" AutoEventWireup="true" codeFile="Receiving_ Get_Form.aspx.cs" Inherits="Receiving_ Get_Form"% >
  2. <html>
  3. <head>
  4. <title>Data Received Here </title>
  5. </head>
  6. <body>
  7. <table border="1" cellpadding="6" cellspacing="3" >
  8. <tr>
  9. <td>First Name : </td> <td> <% Response.Write(Page.Request.QueryString["F_name"]); %> </td>
  10. </tr>
  11. <tr>
  12. <td>Last Name : </td> <td> <% Response.Write(Page.Request.QueryString["L_name"]); %> </td>
  13. </tr>
  14. <tr>
  15. <td>Email-Id : </td> <td> <% Response.Write(Page.Request.QueryString["E_mail"]); %> </td>
  16. </tr>
  17. <tr>
  18. <td>Password : </td> <td> <% Response.Write(Page.Request.QueryString["P_word"]); %> </td>
  19. </tr>
  20. </table>
  21. </body>
  22. </html>
The First Name, Last Name, Email-Id and Password text boxes of get_form.htm form will be sent as parameter of query string with the field name are F_name, F_name, E_mail and P_word respectively. The name of query string fields automatically taken from name attribute of each HTML element, so don’t forget to specify the name attribute So that values should be retrieving using Page.Request.QueryString ["param_name"] here in "Receiving_Get_Form.aspx" automatically.

Key points about data submitted by using HttpGet

  1. GET - Requests data from a specified resource
  2. An hyperlink or anchor tag that points to an action will ALWAYS be an HttpGet.
  3. Data is submitted as a part of url.
  4. Data is visible to the user as it posts as query string.
  5. It is not secure but fast and quick.
  6. It use Stack method for passing form variable.
  7. Data is limited to max length of query string.
  8. It is good when you want user to bookmark page.

HttpPost method

The POST request method is designed to request that a web server accepts the data enclosed in the request message's body for storage
Take an html form named “post_form.htm" and write the following code.
  1. </head>
  2. <body>
  3. <form id="frm_post" action=" Receiving_Post_Form.aspx" target="_blank" method=" POST" >
  4. <table>
  5. <tr>
  6. <td>First Name : </td> <td><input type="text" id="txtF_Name" name="F_name" /></td>
  7. </tr> <tr>
  8. <td>Last Name : </td> <td><input type=" text" id="txtL_name" name="L_name" /></td>
  9. </tr> <tr>
  10. <td>Email-Id : </td> <td><input type="text" id="txtE_mail" name="E_mail" /></td>
  11. </tr> <tr>
  12. <td>Password: </td> <td><input type="password" id="txtP_word" name="P_word"/> </td>
  13. </tr> <tr>
  14. <td><input type="submit" value="Submit" /></td>
  15. </tr>
  16. </table>
  17. </form> </body>
  18. </html>
When we click submit button of this form, it will be redirected to "Receiving_Post_Form.aspx" (opened in new window too). In ASP.NET, if data passed through HTTP Post method we need the following code to retrieve the data (as written in "Receiving_Post_Form.aspx").

Page.Request.Form["param_name"]

  1. <%@ page language="C#" AutoEventWireup="true" codeFile="Receiving_Post_Form.aspx.cs" Inherits=" Receiving_Post_Form"% >
  2. <html>
  3. <head>
  4. <title>Data Received Here </title>
  5. </head>
  6. <body>
  7. <table border="1" cellpadding="6" cellspacing="3" >
  8. <tr>
  9. <td>First Name : </td> <td> <% Response.Write(Page.Request.Form["F_name"]); %> </td>
  10. </tr>
  11. <tr>
  12. <td>Last Name : </td> <td> <% Response.Write(Page.Request.Form["L_name"]); %> </td>
  13. </tr>
  14. <tr>
  15. <td>Email-Id : </td> <td> <% Response.Write(Page.Request. Form["E_mail"]); %> </td>
  16. </tr>
  17. <tr>
  18. <td>Password : </td> <td> <% Response.Write(Page.Request. Form["P_word"]); %> </td>
  19. </tr>
  20. </table>
  21. </body>
  22. </html>
Values of "post_form.htm"(that used method="POST") form sent using POST method therefore, the URL still intact, we retrieve The First Name, Last Name, Email-Id and Password text using Page.Request.Form["param_name"] value taken from the name each of HTML element of second form (Once again don’t forget to specify name attribute for all textboxes so that we are able to get value automatically here in this page). When you click Submit button, values of "post_form.htm" passed to "Receiving_Post_Form.aspx".
Key points about data submitted using HttpPost
  1. POST - Submits data to be processed to a specified resource
  2. A Submit button will always initiate an HttpPost request.
  3. Data is submitted in http request body.
  4. Data is not visible in the url.
  5. It is more secured but slower as compared to GET.
  6. It use heap method for passing form variable
  7. It can post unlimited form variables.
  8. It is advisable for sending critical data which should not visible to users.


Friday, 28 March 2014

Polymorphism, Virtual Keyword,Sealed keyword

Polymorphism means one name many forms. Polymorphism means one object behaving as multiple forms. One function behaves in different forms. In other words, "Many forms of a single object is called Polymorphism."


With polymorphism, the same method or property can perform different actions depending on the run-time type of the instance that invokes it.

There are two types of polymorphism:

  • Static or compile time polymorphism
  • Dynamic or runtime polymorphism.




In static polymorphism, the decision is made at compile time.

Which method is to be called is decided at compile-time only.
Method overloading is an example of this.
Compile time polymorphism is method overloading, where the compiler knows which overloaded method it is going to call.
Method overloading is a concept where a class can have more than one method with the same name and different parameters.

Compiler checks the type and number of parameters passed on to the method and decides which method to call at compile time and it will give an error if there are no methods that match the method signature of the method that is called at compile time.

Example
namespace MethodOverloadingExample
{
    class Program
    {
        public class TestOverloading
        {

            public void Add(string a1, string a2)
            {
                Console.WriteLine("Adding Two String :" + a1 + a2);
            }

            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Two Integer :" +  a1 + a2);
            }

        }

        static void Main(string[] args)
        {
            TestOverloading obj = new TestOverloading();

            obj.Add("Manish " , "Agrahari");

            obj.Add(5, 10);

            Console.ReadLine();
        }
    }
}


Dynamic or Runtime Polymorphism

Run-time polymorphism is achieved by method overriding.

Method overriding allows us to have methods in the base and derived classes with the same name and the same parameters.

By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.

Through the reference variable of a base class, the determination of the method to be called is based on the object being referred to by reference variable.

Compiler would not be aware whether the method is available for overriding the functionality or not. So compiler would not give any error at compile time. At runtime, it will be decided which method to call and if there is no method at runtime, it will give an error.

See the following example:
namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase;
            objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            objBase = new Derived();
            objBase.Show();//Output--> Show From Derived Class.

            Console.ReadLine();
        }
    }
}
Compiler demands virtual Show() method and it compiles successfully. The right version of Show() method cannot be determined until run-time since only at that time Base objBase is initialized as Derived.

Virtual Keyword

According to MSDN, “The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.”

Virtual Method

Virtual method is a method whose behavior can be overridden in derived class. Virtual method allows declare a method in base class that can be redefined in each derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the static, abstract, private or override modifiers.
Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
It is an error to use the virtual modifier on a static property.
A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
Virtual method solves the following problem:

In OOP, when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class methods overridden by the derived class, the method call behavior is ambiguous.

In C#, polymorphism is explicit - you must have a virtual (or abstract) modifier on the base class method (member) and an override on the derived class method, which you probably already know.

If you don't put a modifier on a base class method, polymorphism can't ever happen. If you then add a non-modified method to the derived class with the same signature as the non-modified base class method, the compiler will generate a Warning message.

See the following example:


namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

            public void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            //Following line will Give an Warning
            /*
             'PolymorphismExample.Program.Derived.Show()'
  hides  inherited member
             'PolymorphismExample.Program.Base.Show()'.
              Use the new keyword if hiding was intended.
            */
            public void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            Derived objDerived = new Derived();
            objDerived.Show();//Output--> Show From Derived Class.


            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}
It means that you are hiding (re-defining) the base class method.

In other languages, take Java for instance, you have what is called "implicit" polymorphism where just putting the method in the derived class with the same signature as a base class method will enable polymorphism.

In Java, all methods of a class are virtual by default unless the developer decides to use the final keyword thus preventing subclasses from overriding that method. In contrast, C# adopts the strategy used by C++ where the developer has to use the virtual keyword for subclasses to override the method. Thus all methods in C# are non virtual by default.

The C# approach is more explicit for the purpose of making the code safer in versioning scenarios, i.e., you build your code based on a 3rd party library and use meaningful, but common, method names. The 3rd party library upgrades, using the same common method name. With implicit polymorphism the code would break, but with C#, you would receive a compiler warning so you can double check to see if polymorphism was something you wanted to do.

Difference between Method Overriding and Method Hiding

Method overriding allows a subclass to provide a specific implementation of a method that is already provided by base class. The implementation in the subclass overrides (replaces) the implementation in the base class.

The important thing to remember about overriding is that the method that is doing the overriding is related to the method in the base class.

When a virtual method is called on a reference, the actual type of the object to which the reference refers is used to determine which method implementation should be used. When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used. This is so even should the calling application be unaware that the object is an instance of the derived class.


namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
//the keyword "override" change the base class method.
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived .Show();//Output--> Show From Derived Class.

            Console.ReadLine();
        }
    }
}
Output--> Show From Derived Class

Method hiding does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.


namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived .Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}
Output is:? Show From Base Class.

In the preceding example, Derived.Show will be called; because, it overrides Base.Show.

The C# language specification states that "You cannot override a non-virtual method." See the following example:


namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

            public void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            //Following Line will give error.
            /*
             Error:- 'PolymorphismExample.Program.Derived.Show()'
cannot override inherited member  'PolymorphismExample.Program.Base.Show()'
             * because it is not marked virtual, abstract, or override
             */
            public override void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase = new Base();
            objBase.Show();//    Output ----> This is Base Class.

            Derived objDerived = new Derived();
            objDerived.Show();//Output--> This is Derived Class.

            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> This is Base Class.

            Console.ReadLine();
        }
    }
}
Error: 'PolymorphismExample.Program.Derived.Show()' cannot override inherited member 'PolymorphismExample.Program.Base.Show()' because it is not marked virtual, abstract, or override.

Sealed Keyword

Sealed keyword can be used to stop method overriding in a derived classes.

By default, all methods are sealed, which means you can't override them, so that "sealed" keyword is redundant in this case and compiler will show you an error when you'll try to make sealed already sealed method. But if your method was marked as virtual in a base class, by overriding and marking this method with "sealed" will prevent method overriding in derived classes.

See the following example:
namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

public sealed void Show()//This Line will give an error - "cannot
{                      //be sealed because it is not an override"

                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---------> This is Base Class.

            Console.ReadLine();
        }
    }
}
Error: 'PolymorphismExample.Program.Base.Show()' cannot be sealed because it is not an override.

To remove error from the above program, use the following:
namespace PolymorphismExample
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public override sealed void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }

        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---> This is Derived Class.

            Console.ReadLine();
        }
    }
}
Output ---> This is Derived Class.

Summary
It is not compulsory to mark the derived/child class function with override keyword while base/parent class contains a virtual method.
Virtual methods allow subclasses to provide their own implementation of that method using the override keyword.
Virtual methods can't be declared as private.
You are not required to declare a method as virtual. But, if you don't, and you derive from the class, and your derived class has a method by the same name and signature, you'll get a warning that you are hiding a parent's method.
A virtual property or method has an implementation in the base class, and can be overridden in the derived classes.
We will get a warning if we won't use Virtual/New keyword.
Instead of Virtual, we can use New keyword.

Interface & Abstract class


When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.


If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants No fields can be defined in interfaces.
An abstract class can have fields and constrants defined.



An interface is defined as a syntactical contract that all the classes inheriting the interface should follow.
The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.

Interfaces define properties, methods and events, which are the members of the interface. Interfaces contain only the declaration of the members.
It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure
that the deriving classes would follow.

Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by
the base class and the deriving class implements the functionalities.

Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default.
Following is an example of an interface declaration:

public interface ITransactions
{
   // interface members
   void showTransaction();
   double getAmount();
}
Example
The following example demonstrates implementation of the above interface:

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

namespace InterfaceApplication
{

   public interface ITransactions
   {
      // interface members
      void showTransaction();
      double getAmount();
   }
   public class Transaction : ITransactions
   {
      private string tCode;
      private string date;
      private double amount;
      public Transaction()
      {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }
      public Transaction(string c, string d, double a)
      {
         tCode = c;
         date = d;
         amount = a;
      }
      public double getAmount()
      {
         return amount;
      }
      public void showTransaction()
      {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());

      }

   }
   class Tester
   {
      static void Main(string[] args)
      {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result:

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
_________________________________________________________________________________

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Interface Requires more time to find the actual method in the corresponding classes.

Abstract is Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
-------------------------------------------------------------------------------------------
When to use Abstract class:-
Abstract Classes
–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.


Monday, 17 February 2014

Defination..

Class:-
A class Contains the member Variables(property) & member function (Function/methods).
Memory does not allocate untill object is not created.

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.Member variables are attributes of an object and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
We can say A class is the definition of an object.
Every instance of a class (except an abstract class) is an object?


abstract class:-
The purpose of abstract class is to provide default functionality to its sub classes.
When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.
An abstract class can also contain methods with complete implementation, besides abstract methods.
When a class contains at least one abstract method, then the class must be declared as abstract class.
It is mandatory to override abstract method in the derived class.
When a class is declared as abstract class,
then it is not possible to create an instance for that class. But it can be used as a parameter
in a method.

Access Modifier -:

An access modifier is a keyword of the language that is used to specify the access level of members of a class.
 Different Access Modifiers in C# are Public, Private, Protected, internal, protected internal.
 Default access modifier for members of class is private.
 Namespace will not have access modifier.
 Default access modifier for class ,struct, Interface, Enum, Delegate  is Internal.
 Default access modifier for class and struct members is private.
 No access modifier can be applied to interface members and always interface members are public.
 Enum members are always public and no access modifier can be applied.

There are  following access modifiers.
 Public: When Members of a class are declared as public, then they can be accessed
1.    Within the class in which they are declared.
2.    Within the derived classes of that class available within the same assembly.
3.    Outside the class within the same assembly.
4.    Within the derived classes of that class available outside the assembly.
5.    Outside the class outside the assembly.
Internal: When Members of a class are declared as internal, then they can be accessed
1.    Within the class in which they are declared.
2.    Within the derived classes of that class available within the same assembly.
3.    Outside the class within the same assembly.
Protected: When  Members  of  a  class  are  declared  as  protected,  then  they  can  be accessed
1.    Within the class in which they are declared.
2.    Within the derived classes of that class available within the same assembly.
3.    Within the derived classes of that class available outside the assembly.
Protected internal: When Members of a class are declared as protected internal, then they can be    accessed
1.    Within the class in which they are declared.
2.    Within the derived classes of that class available within the same assembly.
3.    Outside the class within the same assembly.
4.    Within the derived classes of that class available outside the assembly.
Private: Private members of a class are completely restricted and are accessible only within the class in which  they are declared.