Menus

Showing posts with label Interview Questions. Show all posts
Showing posts with label Interview Questions. Show all posts

Saturday, December 22, 2012

Object Oriented Programming Interview Questions

1. What is mean by Class?

Class is a structure that describes the state (property) and behavior (methods) of the object. It is a template or blueprint to create objects of the class. Class represents the noun and it can be used as type in programming language. E.g Car, Person etc

2. What is mean by Objects?

Object is an executable copy of a class. State and behavior of the objects are defined by class definition. We can create multiple objects for single class. It is also called as instance of the class. When an object is created from the class, memory will be allocated in RAM. e.g Car- Maruthi, Alto, Zen etc. Person- Ram, Sam, John etc

3. What is mean by Struture?

Structure is a light-weight class used to create user-defined types containing only public fields. Structure can't have implementation inheritance, but it can have interface inheritance. We cannot modify the default constructors as like a class. Structure is a value type holds their value in memory when they are declared.

4. What is difference between Class and Object?

Classes are the template or blueprint its state of how objects should be and behave, where as Object is an actual real term object. E.g CAR define state like it should have four wheel and body structure with moving, accelerating and break functionality. Maruthi, Alto or Zen is the real object which has different kind of state from one another.

5. What is difference between Class and Structure?

  • Class is Reference type(Reference types hold a reference to an object in memory) - Structure is a Value type(Value types hold their value in memory when they are declared)
  • User can modify default constructor and destructor of class- structure can't modify default constructor
  • Class supports inheritance - Structure will not support inheritance
  • Classes must be instantiated using the new operator - Structure can be instantiated without using the new operator

6. Which case we have to use Class and Structure?

Structure can be used for things that we no need for identity. Class can be used when we need the identity for an object.

7. What is the advantage of Structure over Class?

Since Stucture is a value type and if we use at the proper location, it will improve the performance.

9. What are advantages of using private constructor, method, property?

Due to security reason, methods and properties are not exposed outside the class using Private access modifier. For implementing Singleton pattern we go for Private Constructor, so we will not able to create instance. Separate method is used to create and return the instance.

10. What is mean by Partial class?

It is new features in .Net 2.0; partial classes mean that class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. The compiler intelligently combines the definitions together into a single class at compile-time.
Example for Partial Class
partial class Employee
    {
       string m_Name;
       public String Name
       {
           get { return m_Name; }
           set { m_Name = value; }
       }
    }

    partial class Employee
    {
        int m_Age;
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }
    }

    public class ExampleofPartical
    {
        public void Method1()
        {
            Employee objClass1 = new Employee();
            objClass1.Name="Name";
            objClass1.Age = 12;
        }
    } 

8. What are different access modifiers in .Net?

  • Private - The type or member can only be accessed by code in the same class or struct.
  • Protected - The type or member can only be accessed by code in the same class or struct, or in a derived class.
  • Internal - The type or member can be accessed by any code in the same assembly, but not from another assembly.
  • Procted Internal - The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
  • Public -The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Note: In VB.Net 'Internal' is called as 'Friend'

11. What is mean by Partial method?

Partial methods are methods defined in a partial class that are (optionally) divided across two files. With partial methods one file contains the method signature - the method name, its return type, and its input parameters - while the body is (optionally) defined in a separate file. If the partial method's body is not defined then the compiler automatically removes the partial method signature and all calls to the method at compile-time.
Example for Partial method
   {
       string m_Name;
       public String Name
       {
           get { return m_Name; }
           set { m_Name = value; }
       }
      public  partial  string GetEmpDetails(string ID);
      
    }

    partial class Employee
    {
        int m_Age;
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }
       public  partial string GetEmpDetails(string ID)
        {
            return "Employee1";
        }
    }

12. Why do we go for Partial method?

Partial methods are mainly useful in auto-generated code situations. A code generating tool might know that there are certain extension points that some users are going to be interested in customizing. For example, the objects created in LINQ to SQL have partial methods like OnLoaded, OnCreated, OnPropertyNameChanging, and OnPropertyNameChanged. The auto-generated code calls the OnCreated partial method from its constructor. If you want to run custom code when one of these objects is created you can create a partial class and define the body for the OnCreated partial method.

13. Why do we go for Partial class?

  1. Improve the readability of extremely large classes by partitioning related methods into separate files.
  2. Partial classes enable the code generator to generate code in one file while the developer who may need to extend the auto-generated logic can do so in a separate file, which eliminates the worry that the code generator might overwrite a developer's customizations.

14. Where we use Partial method and class?

Partial classes and partial methods are most commonly used in auto-generated code. It provides a simple and safe way to add new functionality or extend existing functionality of auto-generated code.

15. What are restrictions for Partial method?

  1. Partial definitions must preceded with the key word "Partial"
  2. Method signature should be same in both partial class file
  3. We cannot have partial implementation in one file and another implementation in other file. We can have declaration in one file and implementation in another file.

16. What is mean by Static class?

Static class is used to create attributes and methods that can be accessed without creating the instance of the class. Static classes are loaded automatically by the .NET Framework when application or assembly is loaded. 'Static' key word is used to mention the static class. e.g MyStaticClass.PI
Example for Static Class
public static class MyStaticClass
    {
        public static decimal PI = 3.14M;
        public  static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
        public static  string Append(string str1, string str2)
        {
            return str1 + str2;
        }
    }
  MyStaticClass.PI

17. What is mean by Static method?

Static method can be accessed without creating the instance of the class. 'Static' key word is used to mention the static method. Static methods can be created inside the normal class or static class. If we create the static method inside the normal class, static method will not be able to access by creating instance of the class. e.g Math.Add()

18. Can we override static method?

No, compiler will not allow overriding the static method.

19. What are uses of static class and method?

  1. Compiler will not allow creating the instance of the class
  2. Static class also makes the implementation simpler and faster
  3. Cannot inherit a static class since it is sealed

20. What is static constructor?

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Example:
public class MyStaticClass
        {
            static int count;

            static MyStaticClass()
            {
                count = 0;
                Console.WriteLine("Static class is initialized");
            }

            public static void MyMethod(string name)
            {
                Console.WriteLine("Static class is initialized " + name);
            }
        }

MyStaticClass.MyMethod("John");
Output:
Static class is initialized
Hello John 
 

21. What are shared (VB.NET)/Static(C#) variables?

Static members are not associated with a particular instance of any class, which can be invoked directly from the class level, rather than from its instance
Example
public static double  PI = 3.1457;

22. What is Nested Classes?

Classes with in classes are called as Nested class.
Example
public class MyClassLevel_1
    {
        public void Display()
        {
            Console.WriteLine("Level_1");
        }
      public  class MyClassLevel_2
        {
          public void Display()
          {
              Console.WriteLine("Level_2");
          }

          public class MyClassLevel_3
          {
              public void Display()
              {
                  Console.WriteLine("Level_3");
              }
          }
        }
    }
Creating instance of the nested class
MyClassLevel_1 L1 = new MyClassLevel_1();
            MyClassLevel_1.MyClassLevel_2 L2 = new MyClassLevel_1.MyClassLevel_2();
            MyClassLevel_1.MyClassLevel_2.MyClassLevel_3 L3 = new 
                MyClassLevel_1.MyClassLevel_2.MyClassLevel_3();
            L1.Display();
            L2.Display();
            L3.Display();

            Output
            Level_1
            Level_2
            Level_3

23. What are difference between Singleton and Static class?

  1. Singleton can extend classes and implement interfaces, while a static class cannot implement the interface.
  2. Singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded.
  3. Singleton class can be extended and it's methods can be overridden.

24. Why Main () method is static?

To ensure there is only one entry point to the application.

25. What is mean by inheritance?

Inheritance is one of the concepts of object-oriented programming, where a new class is created from an existing class. Inheritance class is often referred to as subclasses, comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. This can be used to create a highly specialized hierarchical class structure.
Example of Inheritance
class Circle
    {
        private double m_radius;

        public double Radius
        {
            get { return m_radius; }
            set { m_radius = value; }
        }
        public double Diameter
        {
            get { return Radius * 2; }
        }
        public double Circumference
        {
            get { return Diameter * 3.14; }
        }
        public double Area
        {
            get { return Radius * Radius * 3.14; }
        }
    }

    class Sphere : Circle
    {
        new public double Area
        {
            get { return 4 * Radius * Radius * 3.14; }
        }

        public double Volume
        {
            get { return 4 * 3.14 * Radius * Radius * Radius / 3; }
        }
    }

26. Can we inherit multiple classes?

No, multiple inheritances are not supported in .Net. Because consider the provided example. Here there are two Parent class Paretn1 and Parent2. This is inherited by Child class, In GetData method, child call the parent class method PrintData(). In this case which method will be executed? It is very difficult for CLR to identify which method to call. It shows that we multiple inheritance create ambiguity to oops concept. In order to avoid this ambiguity we are going for multiple interface implementations.
public class Parent1
    {
        public string PrintData()
        {
            return "This is parent1";
        }
    }
    public class Parent2
    {
        public string PrintData()
        {
            return "This is parent2";
        }
    }

    public class Child1 : Parent1, Parent2
    {
        public string GetData()
        {
            return this.PrintData();
        }
    }

27. What is mean by Shadowing?

When the method is defined in base class are not override able and we need to provide different implementation for the same in derived class. In this kind of scenario we can use hide the base class implementation and provide new implementation using Shadows (VB.Net)/new(C#) keyword.
Example:
Public Class ParentClass
    Public Sub Display()
        Console.WriteLine("Parent class")
    End Sub

End Class

Public Class ChildClass
    Inherits ParentClass

    Public Shadows Sub Display()
        Console.WriteLine("Child class")
    End Sub
End Class

  
 Dim p As New ParentClass
        Dim c As New ChildClass
        Dim pc As ParentClass = New ChildClass
        p.Display()
        c.Display()
        pc.Display()

Output:
Parent class
Child class
Parent class

28. How a base class method is hidden?

Using new keyword in the derived class, base class method can be hidden or suppressed. New implementation can be added to the derived class.

29. What does the keyword virtual mean in the method definition?

The method can be over-ridden.

30. How method overriding different from overloading?

If we are overriding the method, derived class method behavior is changed from the base class. In Overloading, method with same name by different signature is used.
Example:
{
            public virtual void Display()
            {
                Console.WriteLine("ParentClass");
            }
        }

        public class ChildClass : ParentClass
        {
            //Example for method override
            public override void Display()
            {
                Console.WriteLine("ChildClass");
            }

            //Example for method overload
            public void Display(string name)
            {
                Console.WriteLine(name);
            }
            //Example for method overload
            public void Display(string name, string country)
            { 
            Console.WriteLine("Name:"+name +"Country: "+ country );
            }
        }


  ParentClass p = new ParentClass();
            ChildClass c = new ChildClass();
            ParentClass pc = new ChildClass();
            p.Display();
            c.Display();
            pc.Display();

OutPut:
ParentClass
ChildClass
ChildClass 

31. Can you declare the override method static while the original method is non-static?

No

32. What is mean by Sealed Class?

Class which cannot be inherited is called as sealed class. If we need to prevent a class from being inherited, use Sealed keyword. But sealed class can inherited from other classes.
Example:
public class MyBaseClass
        {
            public void Display()
            {
                Console.WriteLine("Base class");
            }
        }

        //Compile Success: This class cannot be inherited
        public sealed class MySealedClass:MyBaseClass 
        {
            public void Display()
            {
                base.Display();
                Console.WriteLine("Sealed class");
            }
        }

        //Compilation Error: cannot derive from sealed type MySealedClass
        public class MyChildClass : MySealedClass
        { 
        
        }

33. Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

34. Will sealed class allows inheritance, if not why?

Sealed means it is not inheritable

35. What are the advantages of Private constructor?

  1. Private constructor will prevent the user from creating the instance of the class which contains only static members.
  2. Private constructor are used for implementing the singleton pattern

36. While using inheritance, derived class construct will call base class constructor?

Yes, base class constructor will be called before child class constructor

37. Overloaded constructor will call default constructor internally?

No, overload constructor will not call default constructor

38. What is difference between Overrides and Overridable?

Overridable (VB.Net)/ virtual (C#) is used in parent class to indicate that a method can be overridden. Overrides(VB.Net)/ override(C#) is used in the child class to indicate that you are overriding a method.

39. What is Method overloading?

Method overloading occurs when a class contains two methods with the same name, but different signatures.

40. What is operator overloading?

Operator overloading is used to provide a custom functionality to existing operators. For Example +,-,* and / operators are used for mathematical functionality. But we can overload these operators to perform custom operation on classes or structure.
Example:
To concatenate the two strings we have to use Concat method
Dim str1, str2, str3 As String
        str1 = "Hello"
        str2 = "world"
        str3 = String.Concat(str1, str2)
But .Net provides in build operator overloading for string we can use "˜+" operator for concatenating the string value
str3=str1+str2
Similarly we can also implement operator overloading for classes or structure
Employee3= Employee1 + Employee2

41. What is mean by abstraction?

Abstraction is the process of showing necessary information and hiding unwanted information. Let us consider the "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member

42. What is mean by abstraction class?

Abstract classes contain one or more abstract methods that do not have implementation. An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes allow specialization of inherited classes.

43. What id mean by Interface?

Interface defines the set of properties, signature of the methods and events. It does not include any implementation. Class which implements the interface can provide the behavior to the implemented method. For example two class MyEnglishClass and MyFreanchClass implementing same interface and provide two different set of behavior in their implementation.
public interface IMyInterface
    {
        string Hello(string name);
    }

    public class MyEnglishClass:IMyInterface 
    {
        public string Hello(string name)
        {
            return "Hello " + name;
        }
    }

    public class MyFrenchClass : IMyInterface
    {
        public String Hello(string name)
        {
            return "allo " + name; 
        }
    }

44. What is difference between Abstract class and Interface?

  • In Interface all the method must be abstract; in abstract class we can have both abstract and concrete methods.
  • Access modifiers cannot be specified in interface because it should always be public; in Abstract class, we can specify the access modifier.

45. In which Scenario you will go for Abstract or Interface Class?

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

46. What is mean by polymorphism?

Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

47. What are different types of polymorphism?

There are two types of polymorphism
Static polymorphism - defining the method with same name and different signature is called as static polymorphism. In the below example there are three different Add() functionality this Add() will be executed based on the parameter passed.
Example :
public int Add(int a, int b)
        { 
            return a + b; 
        }

        public double Add(double a, double b)
        {
            return a + b;
        }

        public long Add(long a, long b)
        {
            return a + b;
        }

Dynamic polymorphism: Dynamic polymorphism can be implemented using Virtual and Override keyword. By using polymorphism, each derived class can have its own behavior, Even though classes are derived or inherited from the same parent class
Example:
In the below example ClassB is inherited from ClassA. ClassB can have its own behavior by overriding the parent class method. Parent class method should be represented with virtual keyword to override the same method in derived class.
public class ClassA
    {
        public virtual void Display()
        {
            Console.WriteLine ( "ClassA");
        }
    }

    public class ClassB:ClassA 
    {
        public override  void Display()
        {
            Console.WriteLine ( "ClassB");
        }
    }

static void Main(string[] args)
        {
            ClassA a = new ClassA();
            ClassB b = new ClassB();
            ClassA c = new ClassB();
            a.Display();
            b.Display();
            c.Display();
            Console.ReadLine();

        }

OutPut:
ClassA
ClassB
ClassB


48. What you mean by Encapsulation?

Encapsulation is the procedure of covering up of data and functions into a single unit and protects the data from the outside world. Example "Class" only public functions and properties are exposed; functions implementation and private variables are hidden from outside world.

49. What is difference between data encapsulation and abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations. Storing data and functions in a single unit is called as encapsulation.

50. What is mean by Delegate?

Delegate is a type that holds a reference to a method or a function. . Once a delegate is assigned a method, it behaves exactly like that method. We can call the method using delegate instead of directly calling the method. Using delegate, we can also pass the parameter and get return value. Any method with matched the signature of the delegate can be assigned. Simply we can say .NET implements the concept of function pointers using delegate.
Example:
There are three step to following for using Delegate
  • Declaration
  • Instantiation
  • Invocation
In the below example we have declared the new delegate "MyDelegate", which accept string as parameter and return value as string. Two methods SayHello and SayBye function will be called using delegate.
//Declaring the delegate
        delegate string MyDelegate(string name);

        //function called by delegate dynamically
        private static  string SayHello(string name)
        {
            return "Hello " + name;
        }

        private static  string SayBye(string name)
        {
            return "Bye " + name;
        }

After declaration of delegate, we have initialized with SayHello function. Now this delegate will hold reference to specified function. Function will be called using Invoke () method of delegate. In this example we have called two methods (SayHello and SayBye) with same signature(parameter type and return type).
static void Main(string[] args)
        {
         
  //Initialllizing delegate with function name
            MyDelegate delg = new MyDelegate(SayHello);
            //Invoking function using delegate
            Console.WriteLine(delg.Invoke("Sam"));
            
            delg = new MyDelegate(SayBye);
            //Invoking diffent function using same delegate
            Console.WriteLine(delg.Invoke("Sam"));

            Console.ReadLine();
        }

OutPut:
Hello Sam
Bye Sam

51. What is a multicast delegate?

It is a delegate that stores the address of multiple methods and eventually fires off several methods. Multicast delegate must have a return type of void.

52. What is an Asynchronous delegate?

When you invoke a delegate asynchronously, no new thread is created. Instead, the CLR automatically assigns a free thread from a small thread pool that it maintains. Typically, this thread pool starts with one thread and increases to a maximum of about 25 free threads on a single-CPU computer. As a result, if you start 50 asynchronous operations, one after the other, the first 25 will complete first. As soon as one ends, the freed thread is used to execute the next asynchronous operation.

53. What is mean by Events?

Events are nothing but a publisher and subscriber model. Any subscriber who is interested in receiving notification from the publisher can subscribe the events. If source event is fired or publisher raises the event, a notification will be send to all subscribers. One publisher can have multiple subscribers. Internally events will try to make use of delegate for this publisher, subscription model.
Example:
In the below example, we have created new event called "SampleEvent" and this event will be fired once MyMethod() is called. Anyone who wants to subscribe to this event can create a instance of the MyClassWithEvent and add handler to the event. So when ever event is raised, add handler method will be called.
Public Class MyClassWithEvent

    'Created New Event, which will return a message to all subscriber
    Event SampleEvent(ByVal message As String)

    'Event will be fired once this method is called
    Public Sub MyMethod()
        Console.WriteLine("MyMethod is called")
        'Raising the event with message
        RaiseEvent SampleEvent("Event is Raised from MyClassWithEvent")
    End Sub
End Class

Module Module1

    Sub Main()
        
        Dim c As New MyClassWithEvent
        'First subscriber of the event
        AddHandler c.SampleEvent, AddressOf EventSubscriber1
        'Second subscriber of the event
        AddHandler c.SampleEvent, AddressOf EventSubscriber2
        c.MyMethod()
        Console.ReadLine()
    End Sub

    Private Sub EventSubscriber1(ByVal message As String)
        Console.WriteLine("Subscriber 1")
        Console.WriteLine("Message: " + message)
    End Sub

    Private Sub EventSubscriber2(ByVal message As String)
        Console.WriteLine("Subscriber 2")
        Console.WriteLine("Message: " + message)
    End Sub
End Module

OutPut:
MyMethod is called
Subscriber 1
Message: Event is Raised from MyClassWithEvent
Subscriber 2
Message: Event is Raised from MyClassWithEvent

54. Can events have access modifiers?

Yes, Events can have access modifier, if we mention it as Protected events can be subscribed only within inherited class, If you mention it as Internal(C#)/Friends(VB.Net) it can be subscribed by all class inside the assembly. If you mention it as Private it can subscribed with in class where it is declared.

55. Can we have static/shared events?

Yes, we can have static(C#)/shared(VB.Net) event, but only shared method can raise shared events.

56. Can we have different access modifier for Get/Set of the properties?

Yes, in C# 3.0 and above, we can use different access modifier for Get/Set of the properties, but this is not possible in C#2.0 and lower

57. What is an indexer?

An indexer is an accessor that enables an object to be treated in the same way as an array. An indexer is considered when a class is better represented as a virtual container of data that can be retrieved or set using indices. Since an indexer is nameless, its signature is specified by the keyword "this" followed by its indexing parameters within square brackets.
Example:
In the below example we have created new index for class of type string. During get and set operation string manipulations are done.
public class MyClassForIndexer
    {
        private string m_Name = "This is example for indexer";
        public string this[int index]
        {
            get 
            {
                return m_Name.Substring( index);
            }
            set
            {
                m_Name = m_Name.Insert(index, value);
            }
        }
}
 MyClassForIndexer ind = new MyClassForIndexer();
                            Console.WriteLine (ind[0]);
                            ind[7] = "Appended String";
                            Console.WriteLine(ind[0]);
Output:
This is example for indexer
This isAppended String example for indexer

58. What is ENUM?

ENUM means Enumeration; it is used to group related sets of constants. To create a enumeration you use the Enum statement
Example:
Enum Months
            January = 1
            Feburary = 2
            March = 3
            April = 4
            May = 5
            June = 6
            July = 7
            August = 8
            September = 9
            October = 10
            November = 11
            December = 12
        End Enum


 
 

Monday, December 3, 2012

What does Precompiled mean in Sql Server?

When you execute or Run a Stored Procedure for the first time,Sql Server would go through a Five Step Process, they are

1) Parse
2) Resolve
3) Optimize
4) Compile and
5) Execute

These prepares a query that is to be executed. This would create an execution plan that Sql Server will use to retrieve the data. The execution plan will be stored in the Buffer Cache, that is a reserved memory space for Sql Server to hold the execution plan information, With stored procedures, the subsequent execution of the same procedure will by-pass the Five steps process and go straight to the Execution plan. This is called as Pre-Compiled plan.

Sunday, November 25, 2012

ASP.net Interview Question (FAQ)



      1. Explain the differences between Server-side and Client-side code?
Ans. Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.

2. What type of code (server or client) is found in a Code-Behind class?
Ans. Server side code.

3. How to make sure that value is entered in an asp:Textbox control?
Ans. Use a RequiredFieldValidator control.

4. Which property of a validation control is used to associate it with a server control on that page?
Ans. ControlToValidate property.

5. How would you implement inheritance using VB.NET & C#?
Ans. C# Derived Class : Baseclass
VB.NEt : Derived Class Inherits Baseclass

6. Which method is invoked on the DataAdapter control to load the generated dataset with data?
Ans. Fill() method.

7. What method is used to explicitly kill a user's session?
Ans. Session.Abandon()

8. What property within the asp:gridview control is changed to bind columns manually?
Ans. Autogenerated columns is set to false

9. Which method is used to redirect the user to another page without performing a round trip to the client?
Ans. Server.Transfer method.

10. How do we use different versions of private assemblies in same application without re-build?
Ans.Inside the Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify assembly version.
assembly: AssemblyVersion

11. Is it possible to debug java-script in .NET IDE? If yes, how?
Ans. Yes, simply write "debugger" statement at the point where the breakpoint needs to be set within the javascript code and also enable javascript debugging in the browser property settings.

12. How many ways can we maintain the state of a page?
Ans. 1. Client Side - Query string, hidden variables, viewstate, cookies
2. Server side - application , cache, context, session, database

13. What is the use of a multicast delegate?
Ans. A multicast delegate may be used to call more than one method.

14. What is the use of a private constructor?
Ans. A private constructor may be used to prevent the creation of an instance for a class.

15. What is the use of Singleton pattern?
Ans. A Singleton pattern .is used to make sure that only one instance of a class exists.

16. When do we use a DOM parser and when do we use a SAX parser?
Ans. The DOM Approach is useful for small documents in which the program needs to process a large portion of the document whereas the SAX approach is useful for large documents in which the program only needs to process a small portion of the document.

17. Will the finally block be executed if an exception has not occurred?
Ans.Yes it will execute.

18. What is a Dataset?
Ans. A dataset is an in memory database kindof object that can hold database information in a disconnected environment.

19. Is XML a case-sensitive markup language?
Ans. Yes.

20. What is an .ashx file?
Ans. It is a web handler file that produces output to be consumed by an xml consumer client (rather than a browser).

21. What is encapsulation?
Ans. Encapsulation is the OOPs concept of binding the attributes and behaviors in a class, hiding the implementation of the class and exposing the functionality.

22. What is Overloading?
Ans. When we add a new method with the same name in a same/derived class but with different number/types of parameters, the concept is called overluoad and this ultimately implements Polymorphism.

23. What is Overriding?
Ans. When we need to provide different implementation in a child class than the one provided by base class, we define the same method with same signatures in the child class and this is called overriding.

24. What is a Delegate?
Ans. A delegate is a strongly typed function pointer object that encapsulates a reference to a method, and so the function that needs to be invoked may be called at runtime.

25. Is String a Reference Type or Value Type in .NET?
Ans. String is a Reference Type object.

26. What is a Satellite Assembly?
Ans. Satellite assemblies contain resource files corresponding to a locale (Culture + Language) and these assemblies are used in deploying an application globally for different languages.

27. What are the different types of assemblies and what is their use?
Ans. Private, Public(also called shared) and Satellite Assemblies.

28. Are MSIL and CIL the same thing?
Ans. Yes, CIL is the new name for MSIL.

29. What is the base class of all web forms?
Ans. System.Web.UI.Page

30. How to add a client side event to a server control?
Ans. Example... BtnSubmit.Attributes.Add("onclick","javascript:fnSomeFunctionInJavascript()");

31. How to register a client side script from code-behind?
Ans. Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder.

32. Can a single .NET DLL contain multiple classes?
Ans. Yes, a single .NET DLL may contain any number of classes within it.

33. What is DLL Hell?
Ans. DLL Hell is the name given to the problem of old unmanaged DLL's due to which there was a possibility of version conflict among the DLLs.

34. can we put a break statement in a finally block?
Ans. The finally block cannot have the break, continue, return and goto statements.

35. What is a CompositeControl in .NET?
Ans. CompositeControl is an abstract class in .NET that is inherited by those web controls that contain child controls within them.

36. Which control in asp.net is used to display data from an xml file and then displayed using XSLT?
Ans. Use the asp:Xml control and set its DocumentSource property for associating an xml file, and set its TransformSource property to set the xml control's xsl file for the XSLT transformation.

37. Can we run ASP.NET 1.1 application and ASP.NET 2.0 application on the same computer?
Ans. Yes, though changes in the IIS in the properties for the site have to be made during deployment of each.

38. What are the new features in .NET 2.0?
Ans. Plenty of new controls, Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes.

39. Can we pop a MessageBox in a web application?
Ans. Yes, though this is done clientside using an alert, prompt or confirm or by opening a new web page that looks like a messagebox.

40. What is managed data?
Ans. The data for which the memory management is taken care by .Net runtime’s garbage collector, and this includes tasks for allocation de-allocation.

41. How to instruct the garbage collector to collect unreferenced data?
Ans. We may call the garbage collector to collect unreferenced data by executing the System.GC.Collect() method.

42. How can we set the Focus on a control in ASP.NET?
Ans. txtBox123.Focus(); OR Page.SetFocus(NameOfControl);

43. What are Partial Classes in Asp.Net 2.0?
Ans. In .NET 2.0, a class definition may be split into multiple physical files but partial classes do not make any difference to the compiler as during compile time, the compiler groups all the partial classes and treats them as a single class.

44. How to set the default button on a Web Form?
Ans. <asp:form id="form1" runat="server" defaultbutton="btnGo"/>

45.Can we force the garbage collector to run?
Ans. Yes, using the System.GC.Collect(), the garbage collector is forced to run in case required to do so.

46. What is Boxing and Unboxing?
Ans. Boxing is the process where any value type can be implicitly converted to a reference type object while Unboxing is the opposite of boxing process where the reference type is converted to a value type.

47. What is Code Access security? What is CAS in .NET?
Ans. CAS is the feature of the .NET security model that determines whether an application or a piece of code is permitted to run and decide the resources it can use while running.

48. What is Multi-tasking?
Ans. It is a feature of operating systems through which multiple programs may run on the operating system at the same time, just like a scenario where a Notepad, a Calculator and the Control Panel are open at the same time.

49. What is Multi-threading?
Ans. When an application performs different tasks at the same time, the application is said to exhibit multithreading as several threads of a process are running.2

50. What is a Thread?
Ans. A thread is an activity started by a process and its the basic unit to which an operating system allocates processor resources.

51. What does AddressOf in VB.NET operator do?
Ans. The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.

52. How to refer to the current thread of a method in .NET?
Ans. In order to refer to the current thread in .NET, the Thread.CurrentThread method can be used. It is a public static property.

53. How to pause the execution of a thread in .NET?
Ans. The thread execution can be paused by invoking the Thread.Sleep(IntegerValue) method where IntegerValue is an integer that determines the milliseconds time frame for which the thread in context has to sleep.

54. How can we force a thread to sleep for an infinite period?
Ans. Call the Thread.Interupt() method.

55. What is Suspend and Resume in .NET Threading?
Ans. Just like a song may be paused and played using a music player, a thread may be paused using Thread.Suspend method and may be started again using the Thread.Resume method. Note that sleep method immediately forces the thread to sleep whereas the suspend method waits for the thread to be in a persistable position before pausing its activity.

56. How can we prevent a deadlock in .Net threading?
Ans. Using methods like Monitoring, Interlocked classes, Wait handles, Event raising from between threads, using the ThreadState property.

57. What is Ajax?
Ans. Asyncronous Javascript and XML - Ajax is a combination of client side technologies that sets up asynchronous communication between the user interface and the web server so that partial page rendering occur instead of complete page postbacks.

58. What is XmlHttpRequest in Ajax?
Ans. It is an object in Javascript that allows the browser to communicate to a web server asynchronously without making a postback.

59. What are the different modes of storing an ASP.NET session?
Ans. InProc (the session state is stored in the memory space of the Aspnet_wp.exe process but the session information is lost when IIS reboots), StateServer (the Session state is serialized and stored in a separate process call Viewstate is an object in .NET that automatically persists control setting values across the multiple requests for the same page and it is internally maintained as a hidden field on the web page though its hashed for security reasons.

60. What is a delegate in .NET?
Ans. A delegate in .NET is a class that can have a reference to a method, and this class has a signature that can refer only those methods that have a signature which complies with the class.

61. Is a delegate a type-safe functions pointer?
Ans. Yes

62. What is the return type of an event in .NET?
Ans. There is No return type of an event in .NET.

63. Is it possible to specify an access specifier to an event in .NET?
Ans. Yes, though they are public by default.

64. Is it possible to create a shared event in .NET?
Ans. Yes, but shared events may only be raised by shared methods.

65. How to prevent overriding of a class in .NET?
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.

66. How to prevent inheritance of a class in .NET?
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.

67. What is the purpose of the MustInherit keyword in VB.NET?
Ans. MustInherit keyword in VB.NET is used to create an abstract class.

68. What is the access modifier of a member function of in an Interface created in .NET?
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.

69. What does the virtual keyword in C# mean?
Ans. The virtual keyword signifies that the method and property may be overridden.

70. How to create a new unique ID for a control?
Ans. ControlName.ID = "ControlName" + Guid.NewGuid().ToString(); //Make use of the Guid class

71A. What is a HashTable in .NET?
Ans. A Hashtable is an object that implements the IDictionary interface, and can be used to store key value pairs. The key may be used as the index to access the values for that index.

71B. What is an ArrayList in .NET?
Ans. Arraylist object is used to store a list of values in the form of a list, such that the size of the arraylist can be increased and decreased dynamically, and moreover, it may hold items of different types. Items in an arraylist may be accessed using an index.

72. What is the value of the first item in an Enum? 0 or 1?
Ans. 0

73. Can we achieve operator overloading in VB.NET?
Ans. Yes, it is supported in the .NET 2.0 version, the "operator" keyword is used.

74. What is the use of Finalize method in .NET?
Ans. .NET Garbage collector performs all the clean up activity of the managed objects, and so the finalize method is usually used to free up the unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc.

75. How do you save all the data in a dataset in .NET?
Ans. Use the AcceptChanges method which commits all the changes made to the dataset since last time Acceptchanges was performed.

76. Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?
Ans. Use the GC.SuppressFinalize() method.

77. What is the use of the dispose() method in .NET?
Ans. The Dispose method in .NET belongs to IDisposable interface and it is best used to release unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc from the memory. Its performance is better than the finalize() method.

78. Is it possible to have have different access modifiers on the get and set methods of a property in .NET?
Ans. No we can not have different modifiers of a common property, which means that if the access modifier of a property's get method is protected, and it must be protected for the set method as well.

79. In .NET, is it possible for two catch blocks to be executed in one go?
Ans. This is NOT possible because once the correct catch block is executed then the code flow goes to the finally block.

80. Is there any difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable by nature whereas System.StringBuilder can have a mutable string in which plenty of processes may be performed.

81. What technique is used to figure out that the page request is a postback?
Ans. The IsPostBack property of the page object may be used to check whether the page request is a postback or not. IsPostBack property is of the type Boolean.

82. Which event of the ASP.NET page life cycle completely loads all the controls on the web page?
Ans. The Page_load event of the ASP.NET page life cycle assures that all controls are completely loaded. Even though the controls are also accessible in Page_Init event but here, the viewstate is incomplete.

83. How is ViewState information persisted across postbacks in an ASP.NET webpage?
Ans. Using HTML Hidden Fields, ASP.NET creates a hidden field with an ID="__VIEWSTATE" and the value of the page's viewstate is encoded (hashed) for security.

84. What is the ValidationSummary control in ASP.NET used for?
Ans. The ValidationSummary control in ASP.NET displays summary of all the current validation errors.

85. What is AutoPostBack feature in ASP.NET?
Ans. In case it is required for a server side control to postback when any of its event is triggered, then the AutoPostBack property of this control is set to true.

86. What is the difference between Web.config and Machine.Config in .NET?
Ans. Web.config file is used to make the settings to a web application, whereas Machine.config file is used to make settings to all ASP.NET applications on a server(the server machine).

87. What is the difference between a session object and an application object?
Ans. A session object can persist information between HTTP requests for a particular user, whereas an application object can be used globally for all the users.

88. Which control has a faster performance, Repeater or Datalist?
Ans. Repeater.

89. Which control has a faster performance, Datagrid or Datalist?
Ans. Datalist.

90. How to we add customized columns in a Gridview in ASP.NET?
Ans. Make use of the TemplateField column.

91. Is it possible to stop the clientside validation of an entire page?
Ans. Set Page.Validate = false;

92. Is it possible to disable client side script in validators?
Ans. Yes. simply EnableClientScript = false.

93. How do we enable tracing in .NET applications?
Ans. <%@ Page Trace="true" %>

94. How to kill a user session in ASP.NET?
Ans. Use the Session.abandon() method.

95. Is it possible to perform forms authentication with cookies disabled on a browser?
Ans. Yes, it is possible.

96. What are the steps to use a checkbox in a gridview?
Ans. <ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True"
OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>

97. What are design patterns in .NET?
Ans. A Design pattern is a repeatitive solution to a repeatitive problem in the design of a software architecture.

98. What is difference between dataset and datareader in ADO.NET?
Ans. A DataReader provides a forward-only and read-only access to data, while the DataSet object can carry more than one table and at the same time hold the relationships between the tables. Also note that a DataReader is used in a connected architecture whereas a Dataset is used in a disconnected architecture.

99. Can connection strings be stored in web.config?
Ans. Yes, in fact this is the best place to store the connection string information.

100. Whats the difference between web.config and app.config?
Ans. Web.config is used for web based asp.net applications whereas app.config is used for windows based applications.

ASP.Net interview Questions

How to redirect a page to another page?
A common question asked in interviews. The Response object has a famous Redirect method that is used most widely to transfer a web page visitor from one page to another page.
Syntax of Response.Redirect ...

Response.Redirect("DestinationPage.aspx")
There is another famous method called Transfer method of the Server object.
Syntax of Server.Transfer ...

Server.Transfer("DestinationPage.aspx") 

How to pass values between pages?
Every interviewer will expect this from you. There are several methods to pass values from one page to another page. Described below are few methods to pass values between pages:

QueryString - The QueryString method of passing values between web pages is one of the oldest methods of passing values between pages. A variable value is properly encoded before it is placed on a querystring. This is to make sure that characters that cause problems (like symbols and spaces) are encoded correctly. See the code below to see how QueryString functionality works.

//Code in InitialPage.aspx
String sString;
sString = Server.UrlEncode("string in InitialPage.aspx");
Response.Redirect("DestinationPage.aspx?Value=" & sString);

//Code in DestinationPage.aspx reads the QueryString
String sString;
sString = Request.QueryString("Value");
Response.Write("Your name is " & sString);

The data in the DestinationPage.aspx in the URL looks like this...

http://www.dotnetgig.com/DestinationPage.aspx?Value=dotnetUncle
Context - The context object is used to send values between pages. Its similar to the session object, the difference being that, the Context object goes out of scope when the page is sent to a browser. Example code below shows how to use Context object.
'InitialPage.aspx stores value in context before sending it
Context.Items("MyData") = "dotnetgig";
Server.Transfer("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's context
String sString;
sString = Context.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

Session - The session object is used to persist data across a user session during the user's visit to a website. It is almost same as the Context object. When we use Response.Redirect, it causes the Context object to go away, so rather the Session object is used in such a scenario. Session object uses more of server memory than a context object. Example code below shows how to use Session object.
'InitialPage.aspx stores value in session before sending it
Session.Items("MyData") = "dotnetgig";
Response.Redirect("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's session
String sString;
sString = Session.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

You may notice above, I have used Response.Redirect with session object, and server.transfer with a context object.

Application, Cache, Session - objects are used to store global variables.

What is the role of the ASP.NET worker process? What is aspnet_wp.exe?
This question is hot in every interview. For faster execution of ASP.NET applications, that are primarily based to be hosted on IIS servers, the aspnet_wp.exe comes into picture. This file (aspnet_wp.exe) is actually the ASP.NET worker process. The worker process is introduced to actually share the load on the IIS, so that application domains and other services may be maintained by a single worker process.

The aspnet_wp.exe worker process is a part of the Microsoft ASP.NET framework, and it is responsible for most of the technical processes in the ASP.NET framework. There may be multiple instances of ASP.NET worker process running on IIS 6 (a process running as inetinfo.exe), depending on multiple application pools. The worker process handles all the requests passed to the ASP.NET framework, so we may say that its actually the main engine that handles all requests pertaining to ASPNET. For example, when a request for an .aspx page is recieved by the IIS server, the dll called aspnet_isapi.dll passes this request to the aspnet_wp.exe worker process. 

How to store values between postbacks in ASP.NET? What is viewstate in ASP.NET?
The postback question is the heart of any interview on ASP NET. When a postback happens (i.e. when a form is submitted to a server), the variable values that are set in the code-behind page are erased from the memory of the client system. This concept would be different from what happens in Windows-based applications, where the variable variables persist in memory until they are freed from the memory either by the garbage collector, or by specific codes like dispose or finalize.

In web applications, variable values simply get erased. But it is very simple to persist these values. They may be persisted using the Viewstate object. Before the postback is invoked, the variable's value is saved in a viewstate object. In the recieving page, the viewstate's value may be retrieved back. See example code below...
//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();
Note that the viewstate value is saved and then passed to the next page by ASP.NET in the form of a hidden variable. Ideally, big values like datasets should not be saved in viewstate as they may tend to slow down the performance of the web page.

Apart from the viewstate object, values may also be sent across postbacks between pages using Application, Session and Cache objects.


How to store global variables?
Global variables should always be used with caution. They are the best means of storing data that has to be accessed anywhere. The most common ways of accessing global variables in ASP.NET are by using Application, Cache, and Session objects.

Application - Application objects are application level global variables, that need to be shared for all user sessions. Thus, data specific to a user should'nt be saved in application objects. While using application objects, the objects are locked so that multiple page requests cannot access a specific application object. Below is a code example for usage of application object...
Application.Lock();
Application("UserData") = "dotnetgig";
Application.UnLock();
Response.Redirect("DestinationPage.aspx");

//DestinationPage.aspx gets the value from the Application State
String sString = Application("UserData").ToString();
Cache - The cache object is similar to the application object in scope, however, it does not need any explicit locking and unlocking. Code below shows usage of Cache object...
Cache("Userdata") = "dotnetgig";
Response.Redirect("DestinationPage.aspx");

//Destination.aspx retrieves the value from Cache object
String sString = Cache("Userdate").ToString();
The cache object also shares data across all user sessions. The cache object has features like it can automatically expire cached content after specified time periods or once memory consumption has reached a maximum.

Session - The session object is used to store the data specific to a user for the entire length of a user's visit to a website. Below is a code that shows usage of the session object in ASP.NET ...
//InitialPage.aspx stores the user’s credentials in Session state
Session("UserName") = txtUserName.Text;
Server.Transfer("DestinationPage.aspx");

//DestinationPage.aspx gets the user’s name from Session state
String sString = Session("UserName").ToString();
ASP.NET stores session values in the server memory. If there are plenty of active user's of a website, then the memory consumption on the server increases by leaps. Because of this reason, large websites use very less Session Variables. Session state can be configured to be automatically stored in a SQL Server database, or it can be configured to be stored centrally in a state server within a server farm. By default, a user’s session ends 20 minutes after their last page request and their data goes out of scope, freeing it from memory. In case user information is to be tracked by a large website, then a oookie is preferred.

Cookie - A cookie is a piece of data that is stored on a user's browser. Thus, a cookie does not use any server memory.

What is a server control in ASP.NET?
This is very frequently asked in ASP NET Interviews. A server control in ASP.NET is a control that has the runat="server" attribute. The component is processed on the server, and its HTML equivalent stream is passed to the browser. Note that all server controls inherit from the System.Web.UI.Control class. The server side controls may be dragged to a web page from the standard toolbox. Note that HTML controls are not server side controls, but they may behave so if the runat="server" attribute is added to their source.

What is viewstate in ASP.NET?
The viewstate question should be well prepared before any ASP NET Interview.
Viewstate object is used to persist data of variables across postbacks. It even existed in classic ASP. In ASP.NET, a variable's value is assigned to a a viewstate object and then this is passed as a hidden variable and then may be retrieved by a page after a postback. See the example below...
//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();
Note that Viewstate object's value is accessible only at page level. This means that if a viewstate is created at page1.aspx, then it may be used only within page1.aspx after the postback, and cannot be used by any other page. To know how to pass values from one page to another.
How to send an email using ASP.NET? How to use System.Web.Mail?
ASP.NET 2.0 provides the System.Web.Mail class to send a mail. This class may be used to send a mail using ASP.NET. See code below, by Ryan Olshan that explains how to use System.Web.Mail to send a mail using ASP.NET.
'Code in VB.NET
Imports System.Net.Mail
Public Class MailHelper
''' <summary>
''' Sends a mail message
''' </summary>
''' <param name="from">Sender address</param>
''' <param name="recepient">Recepient address</param>
''' <param name="bcc">Bcc recepient</param>
''' <param name="cc">Cc recepient</param>
''' <param name="subject">Subject of mail message</param>
''' <param name="body">Body of mail message</param>

Public Shared Sub SendMailMessage(ByVal from As String, ByVal recepient As String, ByVal bcc As String, ByVal cc As String , ByVal subject As String, ByVal body As String)
' Instantiate a new instance of MailMessage
Dim mMailMessage As New MailMessage()
' Set the sender address of the mail message
mMailMessage.From = New MailAddress(from)
' Set the recepient address of the mail message
mMailMessage.To.Add(New MailAddress(recepient))

' Check if the bcc value is nothing or an empty string
If Not bcc Is Nothing And bcc <> String.Empty Then
   ' Set the Bcc address of the mail message
   mMailMessage.Bcc.Add(New MailAddress(bcc))
End If

' Check if the cc value is nothing or an empty value
If Not cc Is Nothing And cc <> String.Empty Then
  ' Set the CC address of the mail message
  mMailMessage.CC.Add(New MailAddress(cc))
End If

' Set the subject of the mail message
mMailMessage.Subject = subject
' Set the body of the mail message
mMailMessage.Body = body

' Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = True
' Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal

' Instantiate a new instance of SmtpClient
Dim mSmtpClient As New SmtpClient()
' Send the mail message
mSmtpClient.Send(mMailMessage)
End Sub
End Class

Add this in Web.config

<?xml version="1.0"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="defaultEmail@yourdomain.com">
<network host="smtp.yourdomain.com" port="25" userName="yourUserName" password="yourPassword"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
How to store information about a user's locale in ASP.NET? What is localization?
Localization is the feature of ASP.NET through which an application may be localized for a specific location. There are built-in mechanisms in .NET to allow localization process. The concept of localization is achieved in .NET as .NET is based on Unicode, thus it allows multiple characters of regions across the globe to be sent across in applications.

In .NET, the concept of localization is achieved using the System.Globalization namespace. A class named CultureInfo is used to localize .NET objects in the web applications. The functions provided in the globalization namespace work in tandem with the browswer's culture encoding properties. In order to set the culture encoding of a web application, changes may simply be done in the web.config file.
<configuration>
  <system.web>
   <globalization
   requestencoding="utf-8"
   responseencoding=" utf-8"
   fileencoding=" utf-8"
   culture="hi-IN"
   uiculture="en" />
 </system.web>
</configuration>
Here, the default culture is set to Hindi (hi-IN). However, the rest of the web application will use UTF8 character encoding. The default UI culture is "en" by default. Now in order to render different locality specific characters for different locations, different folders with their own Web.config files are created. Each of this folder will cater to a location. Note that in ASP.NET, a web.config file is allowed on any folder, this web.config file will override any settings provided in the web.config of any of its parent folder.

This is how locale specific directories are created for a site. Further note that culture settings may be set at page level as well. This is done using the @Page directive by setting its culture attribute to the desired culture.
<%@ Page Culture="hi-IN" UICulture="hi" ResponseEncoding="utf-8"%>
Instances of the CultureInfo class may also be created in code, to set the culture of a page through code.


How to add an event handler for a server control in ASP.NET?
In an interview, it might be expected of you to write some code snippet as well.
Say we create a server control named btnSubmit. In order to add an event handler to it, see the code below...
'Example in VB.NET Private Sub btnSubmit_Click() Handles btnSubmit.Click
btnSubmit.attribute.add("onclick","javascript:alert('You just added an attribute to the server button control btnSubmit by clicking on it');")
End Sub

What are validation controls in ASP.NET? How do validation controls work? What are validation groups in ASP.NET 2?
An interview in ASP NET can't be really complete without preparing this question.
Validation controls in ASP.NET are server side controls that validate input values client-side. Sounds strange? Well, the best approach to validate any input value is to validate it client-side to avoid any postback and load to the server. This approach is followed to reduce the load on the server.

ASP.NET validation controls greatly improve the perfomance of a web application and may be used by web developers to reduce plenty of code that they used to write previously to validate input values using javascript or vbscript.

Input validations improvise security of a web application, by preventing SQL Injection attacks.

There are 6 validations controls in both ASP.NET 1.1 and ASP.NET 2.0
1) RequiredFieldValidator - as the name suggests, this control makes sure that the input box is not left blank.
2) CompareValidator - This control validates values in two controls, and checks for equality
3) RangeValidator - This validation control makes sure that the value entered in the control falls within a range specified. This specification may be done using its properties.
4) RegularExpression - Based on a regular expression, values entered in an input box must match the ones specified by this control's RegulareExpression property
5) CustomValidator - This type of validator control may be customized & created by a developer as per need
6) ValidationSummary - This control may be used to show the summary of the information gathered using rest of the other validation controls

To use a validation control, set a validation control on a form. Associate it with a server control by using its ControlToValidate property. Note that the server control has a property called CausesValidation and this is set to true for the validation control to trigger. This property is true by default for every server control. The validation control also has an ErrorMessage property that is assigned some text to explain what the error is, in case the validation control is trigerred. The validation control actually calls a client-side script that comes with ASP.NET, and this script does the job of validation for us. All this validation is done client-side.

Suppose we want to use the RequiredFieldValidator control so that a textbox is'nt left blank, for this, see the inline code below...


Code used for RequiredFieldValidator used above
<asp:Button ID="btnGo" runat="server" Text="Go" />
<asp:TextBox ID="txtSomeText" runat="server" Text="" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvTextbox" runat="server" ControlToValidate="txtSomeText"
ErrorMessage="Please Enter Some Text" ></asp:RequiredFieldValidator>
The Page.IsValid property of the page is TRUE only if there are no validation errors returned.

Validation controls are supported by Internet Explorer, Firefox and Opera.

ASP.NET 2.0 provides a method to allow multiple sets of controls that may be grouped together into a validation group. The purpose of this approach makes it easy to invoke validation checks on specific server controls and not all ot them who have an associated validation control.

What is global.asax in ASP.NET? Application_start, Session_start?
The global.asax concept is the crux of any ASP NET interview. The global.asax file is used to add application level logic & processing. Note that the global.asax does not handle any UI related processing, nor does it process individual page level requests. It basically controls the following events...
Application_Start
Application_End
Session_Start
Session_End

Note that in Visual Studio 2003 automatically creates this file for every web application, but in Visual Studio 2005, this file has to be added to the web project specifically.

Code in the global.asax is compiled when the web appication is built for the first time. The application level code and variables may be declared in Application_Start. Similarly, session level code & variables may be declared in Session_Start event. Application level events are for the entire application, and may be used for any user, while Session level events are user specific for a length of a session.

What is an HTTP handler in ASP.NET? Can we use it to upload files? What is HttpModule?
An advanced programmer needs to be well prepared with this question in any interview.
The HttpHandler and HttpModule are used by ASP.NET to handle requests. Whenever the IIS Server recieves a request, it looks for an ISAPI filter that is capable of handling web requests. In ASP.NET, this is done by aspnet_isapi.dll. Same kind of process happens when an ASP.NET page is trigerred. It looks for HttpHandler in the web.config files for any request setting. As in machine.config default setting, the .aspx files are mapped to PageHandlerFactory, and the .asmx files are mapped to the WebServiceHandlerFactory. There are many requests processed by ASP.NET in this cycle, like BeginRequest, AuthenticateRequest, AuthorizeRequest, AcquireRequestState, ResolveRequestCache, Page Constructor, PreRequestHandlerExecute, Page.Init, Page.Load, PostRequestHandlerExecute, ReleaseRequestState, UpdateRequestCache, EndRequest, PreSendRequestHeaders, PreSendRequestContent.

Yes, the HttpHandler may be used to upload files.

HttpModules are components of .NET that implement the System.Web.IHttpModule interface. These components register for some events and are then invoked during the request processing. It implements the Init and the Dispose methods. HttpModules has events like AcquireRequestState, AuthenticateRequest, AuthorizeRequest, BeginRequest, Disposed , EndRequest, Error, PostRequestHandlerExecute, PreRequestHandlerExecute, PreSendRequestHeaders, ReleaseRequestState, ResolveRequestCache, UpdateRequestCache

What is a session in ASP.NET? Different ways to maintain session?
The most common used object, due to its usefulness is the Session object, and hence, it is a must-know in any interview related to ASP NET or web based programming.
Session - The session object is used to store the data specific to a user for the entire length of a user's visit to a website. Below is a code that shows usage of the session object in ASP.NET ...
//InitialPage.aspx stores the user’s credentials in Session state
Session("UserName") = txtUserName.Text;
Server.Transfer("DestinationPage.aspx");

//DestinationPage.aspx gets the user’s name from Session state
String sString = Session("UserName").ToString();
What is the @Register directive used for? What is the purpose of @Register directive in ASP.NET? How to create Web User Controls in ASP.NET?
Good developers must know the Register and User Control concept before any interview in ASP NET.
Directives in ASP.NET are used to set attributes for a page. The @Register directive is a directive used to register user defined controls on a web page. A user created server control has an ascx extenstion. These controls inherit from the namespace System.Web.UI.UserControl. This namespace inherits from the System.Web.UI.Control.

A user control may be embedded in an aspx web page using the @Register directive. A user control cannot be executed on its own independently, but may be registered on a web page and then used out there. Below is the syntax for registering an @register directive in an aspx page in ASP.NET
<%@ Register TagPrefix="UC1" TagName="UserControl1" Src="UserControl1.ascx" %>
The TagPrefix attributes is used to specify a unique namespace for the user control. The TagName is a name used to refer a user control uniquely by its name. Say we want to use this control in a webpage, we may use the code below...
<UC1:UserControl1 runat="server"/>

What is a cookie? Limitations of cookie? Permanent cookie?
The cookie object is the essence of any interview, be it ASP NET interview or Java interview or PHP interview.
Cookie - A cookie is a piece of data that is stored on a user's browser. Thus, a cookie does not use any server memory. It is actually a small text file which is created by the broswer on the hard disk of the user. It is actually a piece of information in the form of text strings. A web server sends a cookie to a user (client browser) and then the browser stores it.

A cookie is used to store information of a user & information about a user's preferences. How does the cookie works? - When a user visits a site, say www.amazon.com, and creates a profile out there, the server sends an ID (basically an ID to track this user) and saves the ID through the user's browser in the form of a cookie on the user's system. When the user revisits this site, the website tracks the user's system for the existence of any cookie, and in case it finds a cookie, it customizes the site based on the user's settings and preferences.

Now lets talk about how to create a cookie in ASP.NET. It is pretty simple. There is a class in the System.Web namespace by the name HttpCookie. This class may be used to easily create a cookie on the user's system. Below is a code sample on how to use a cookie in ASP.NET ...
//Creating a cookie HttpCookie sampleCookie = new HttpCookie("UserColorSetting");
sampleCookie.Values.Add("Background", txtBackgroundColor.Text);
sampleCookie.Expires = #12/31/2010#; Response.Cookies.Add(sampleCookie);

//Getting a cookie value from the user's computer
String sGetCookie;
sGetCookie = Request.Cookies("UserColorSetting")("Background").ToString();
Limitations of Cookies - Cookies are meant for infrequent storage of small pieces of information. They are not meant as a normal communication or mechanism. Note that web browsers are not required to save more than 300 cookies total, nor more than 20 cookies per web server (for the entire server, not just for the page or site on the server), nor to retain more than 4 kilobytes of data per cookie (both name and value count towards this 4 kilobyte limit). The biggest limitation of these is the 20 cookies per server limit, and so it is not a good idea to use a different cookie for each variable that has to be saved. Rather save a single cookie containing a lot of information.

How to implement a web farm and a web garden? Whats a web farm and a web garden in ASP.NET? What is the difference between a web farm and web garden in ASP.NET?
An ASP NET interview can't be really complete without the web farm question.
So what is a web farm. A Web Farm is a setup of a website across multiple servers.

A Web Garden is a setup of a website on a single server with multiple processors. To set a a multi-server web application in ASP.NET

Can dataset be stored in a viewstate?
This can be a tricky question in interviews.
Yes, a dataset may be stored in a viewstate. However, a viewstate is passed to the server as a hidden variable. Precaution should be taken that the dataset size is not too big, otherwise such an activity will take a toll on both the client and server system resources, and ultimately slow down rendering of the data on the client system. Also note that the viewstate data may not be sent to another aspx page, as thats a limitation of a viewstate object.

How to set view state for a server control? Enableviewstate property?
This is a popular interview question. The enableviewstate property of a server control indicates whether the server control persists its viewstate. It also controls the viewstate behavior of the child controls within it.

So what is Viewstate? - Viewstate is the property of a server control that groups all the other property values of the control, so that the entire set of property values is preserved across multiple HTTP requests. The enableviewstate property when set to true, makes the viewstate property persist all the other property values.

How does viewstate work? - The viewstate values are passed as an HTML hidden input element when HTTP requests are invoked. To see how a viewstate variable's value looks like, right click any aspx page and click view source, you will find something like this...
type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEw.. .. .. .. 2FzcF9hc3AubmV0LmFzcHgfB=="
An instance of the StateBag class is created to store the property values.

There are scenarios when a Viewstate is set to false. For example, say a database request is loaded to a server control, then the size of the database values may be humongous, for which the Viewstate is set to false.
Example of setting viewstate of a server control ...

<asp:TextBox id="txtName" runat="server" text="" enableviewstate="true" > 

What is smart navigation?
Before explaining what smart navigation is, let me point out that Smart Navigation is obsolete in .NET 2.0. It works with 1.1 & versions before it. The SetFocus and MaintainScrollPositionOnPostBack are used instead

Smart Navigation basically enhances a web pages' performance by doing the following:

* It eliminates the flash caused during navigation
* It persists element focus during postbacks
* It persists scroll position during postbacks between pages
* It retains the lasts page information in the history of the browser

I suggest not to use SmartNavigation because it does not work with many browsers.