Monday, 21 April 2014

Asp.net Interview Question-Part 1

ASP.NET Interview Questions for Beginners and Professionals - Part 1

This ASP.NET Tutorial is an extension to my previous tutorial "Top 10 ASP.NET Interview Questions and Answers". In previous tutorial, focus was to present you with the most important and top ASP.NET Interview Questions that are normally asked during an ASP.NET developer Interview. Here in this article, I'll try to further extend those important questions as well as add more important questions.

Basically, this is how an interviewer normally does. Interviewer asked a question about a technical concept at high level. If he gets a right answer, he further goes into details related to that particular concept and its implementation details. For example, in previous article, we asked about the concept of View State in ASP.NET but in this tutorial, we will further explore the View State concept with more questions. But we will not repeat the questions already presented in previous post, so it's highly recommended to go through that ASP.NET Interview Questions tutorial first.

What are HttpHandlers and HttpModules in ASP.NET?

In order to fully comprehend the concept of HttpHandlers and HttpModules, I have written a detailed ASP.NET Tutorial. Here I am defining both the concepts as follows:

HttpHandler: ASP.NET Engine uses HttpHandlers to handle specific requests on the basis of it's extensions. ASP.NET Page Handler handles all requests coming for (.aspx) pages. We can define our own custom HttpHandler to handle a specific request with a specific extension, say .jpeg, .gif, or .ahmad. But there will always be only one handler for a specific request.

HttpModule: ASP.NET Engine uses HttpModules to inject some specific functionality along with ASP.NET default functionality for all incoming requests regardless of its extensions. There are a number of built-in modules already available in ASP.NET HTTP Pipeline. But we can write our own custom HTTP module to perform some additional functionality (for example, URL rewriting or implementing some security mechanism) for all incoming requests.

What is State Management?

HTTP is a stateless protocol by nature. So, we need some mechanism to preserve state (i.e. state of a webpage, a control or an object etc.) between subsequent requests to server from one or more clients. And this mechanism is referred as State Management.

What are the State Management Techniques used in ASP.NET?

State Management techniques used in ASP.NET can be categorized in two types:
  1. Client-Side State Management
    • View State
    • Control State
    • Hidden Fields
    • Cookies
    • Query String
  2. Server-Side State Management
    • Application State
    • Session State
    • Profile Properties

What is ViewState? or Explain ViewState as State Management Technique?

ViewState is one of the Client-Side State Management techniques that provides page-level state management, which means state is preserved between subsequent requests to same page. By using this technique, state of the page along with its controls is stored in a hidden form field  i.e. "__VIEWSTATE" and this field is again available on server when page is posted back with HTTP Request.
You can find this hidden field by looking into view source of an .ASPX page as:
<input type="hidden" name="__VIEWSTATE" value="wEPDwUKMTM4OTIxNTEzNA9kFgJmD2QWAgIBD2QWAgIDDxYCHgVzdHlsZQV" />
ViewState data is encoded in Base64 String encoded format.


Can we Enable/Disable ViewState?

Yes, ViewState can be enabled or disable at different levels:
  • Control Level
    ViewState for a specific control can be enabled or disabled by setting EnableViewState property as follows:
    aControl.EnableViewState = false;
  • Page Level
    We can enable/disable ViewState for a complete page as follows:
    <%@ Page Language="C#" EnableViewState="false" %>
  • Application Level
    For whole application, we can enable/disable views in configuration file as follows:
    <pages enableViewState="false">
        ....
    </pages>


What is the difference between Session.Clear() and Session.Abandon() in ASP.NET?

As we understand that Session is a Collection and it stores data as Key/Value pair. So,
 Session.Clear() clears all the session values but doesn't destroy the Session. however, 
 Session.Abandon() destroys the session object.
In other words, Session.Clear() is like deleting all files inside a folder (say "Root") but Session.Abandon() means deleting the "Root" folder.

What is the difference between Application and Session State?

Application state is basically a common data repository for an application's all users and their all sessions. On the other hand, Session state is specific to a single user session.
So, we can store data in application state object that is common for all users of a particular application as follows:
//Set Value
Application["UsersCounter"] = Convert.ToInt32(Application["UsersCounter"]) + 1;
//Retrieve Value
lblUsersCounter.Text = Application["UsersCounter"].ToString();
It's recommended to store smaller size values in application object.

Session object can store data for a specific session of user. Storage and retrieval is also simple just as for application object.
//Set Value
Session["ProductsCount"] = Convert.ToInt32(Session["ProductsCount"]) + 1;
//Retrieve Value
lblProductsCounter.Text = Session["ProductsCount"].ToString();

Interview Questions about Session State Modes and Session_Start/Session_End events in Global.asax are already explained here.


What is the difference between Label Control and Literal Control?

A Label control in ASP.NET renders text inside <span> tags while a Literal Control renders just the text without any tags.
With Label controls we can easily apply styles using it's CssClass property, however, if we don't want to apply style/formatting, it's better to go for a Literal control.

Hyperlink Vs LinkButton in ASP.NET?

A Hyperlink just redirects to a given URL identified by "NavigateURL" property. However a LinkButton which actually displays a Hyperlink style button causes a postback to the same page but it doesn't redirect to a given URL.

Validation Controls related Interview Questions are already given in previous post here.

Hopefully, this pool of ASP.NET Interview Questions and Answers along with previous list of Top 10 will be helpful for ASP.NET Developers.

dot net tips

Strong and Weak Typed Languages

C# is a strongly typed language. All variables in a program must be declared as being of a specific type. The variable's behaviour is defined by the chosen type. For example, an integer variable can only contain whole numbers. If a number in an integer variable needs a fractional part, it must first be converted to a different type, possibly being stored in a new variable as a part of the translation.
The alternative to a strongly typed language is a weakly typed language. An example would be VBScript used by many classic ASP developers. In VBScript, the type of the variable is not declared and the behaviour of the variable may appear to change from one line of code to the next.

Variable Declaration and Assignment

A variable can be declared with one line of code, specifying the variable type and its name. In the following code, an integer variable is declared using the data type int.
 int numberofArticles;
A variable can be given a value using the assignment operator, (=). The variable to the left of the operator is assigned the value to the right. The following code shows a variable being declared and assigned a value.
int numberofArticles;
numberofArticles=3;
You do not need to assign a value to a new variable immediately. There may be many lines of code between the declaring a variable and giving it a value. However, if you do wish to declare a variable and assign a value at the same time, this can be achieved in a single statement. For example:
int numberofArticles=3; 
It is possible to declare multiple variables of the same type in a single line of code. You can also assign the same value to multiple variables in one statement. To complicate things further (or to show the elegance of C#, depending on your viewpoint), these operations can be combined. The following code shows three examples.
NB: Multiple variables can be assigned the same value in this manner because the assignment operation returns the value that has been assigned.

Assignment Problems

Definite Assignment

The C# compiler enforces a rule known as definite assignment. This states that a variable may not be read until a value has been assigned. This prevents you from writing code that reads a variable with an undefined value, as this could give unpredictable results.
The following code fails to compile, displaying the error "Use of unassigned variable numberOfArticles".


  











 

 

 

 

  Numeric Data Type Reference

I will end this article with a quick reference to the numeric data types. For integer types, the declaration keyword, a description of the type, the range of possible values and the number of bits used to represent the value are given. For non-integers, the scale and the number of digits of accuracy are given, rather than minimum and maximum. This allows you to determine which data type should be used for any numeric variable.
The Boolean type is included, which although not technically numeric, fits well in this table. The Boolean type can hold either true or false. It is named after the mathematician, George Boole.

c# Components

 

Namespace and Assemblies


The first line of the “Hello, C# World!” program was this:

using System;

This line adds a reference to the System namespace to the program. After adding a reference to a namespace, you can access any member of the namespace. As mentioned, in .NET library references documentation, each class belongs to a namespace. But what exactly is a namespace?

To define .NET classes in a category so they’d be easy to recognize, Microsoft used the C++ class-packaging concept know as namespaces. A namespace is simply a grouping of related classes. The root of all namespaces is the System namespace. If you see namespaces in the .NET library, each class is defined in a group of similar category. For example, The System.Data namespace only possesses data-related classes, and System.Multithreading contains only multithreading classes.

When you create a new application using visual C#, you see that each application is defined as a namespace and that all classes belong to that namespace. You can access these classes from other application by referencing their namespaces.

 For example, you can create a new namespace MyOtherNamespace with a method Hello defined in it. The Hello method writes “Hello, C# World!” to the console. Listing2 shows the namespace.

Listing 2 Namespace wrapper for the hello class


// Called namespace
namespace MyOtherNamespace
{
class MyOtherClass
{
public void Hello()
{
Console.WriteLine ("Hello, C# World!");
}
}
}

In listing 3, you’ll see how to reference this namespace and call MyOtherClass’s Hello method from the main program.

In listing 2, the MyOtherClass and its members can be accessed from other namespaces by either placing the statement using MyOtherNamespace before the class declaration or by referring to the class my other namespace before the class declaration or by referring to the class as MyOtherNamespace.Hello, as shown in listing 3 and listing 4.

Listing 3. Calling my other Namespace Name space members

using System;
using MyOtherNamespace;

 // Caller namespace
namespace HelloWorldNamespace
{
      class Hello
      {
            static void Main()
            {
                  MyOtherClass cls = new MyOtherClass();

                  cls.Hello();
            }
      }
}

// Called namespace
namespace MyOtherNamespace
{
      class MyOtherClass
      {
            public void Hello()
            {
                  Console.WriteLine("Hello, C# World!");
            }
      }
}

As you have seen in listing 3, you include a namespace by adding the using directly. You can also reference a namespace direct without the using directive. Listing 4 shows you how to use MyOtherClass of MyOtherNamespace.

Listing 4. Calling the HelloWorld namespace member from the MyOtherNamespace

// Caller namespace
namespace HelloWorldNamespace
{
class Hello
{
static void Main()
{
   MyOtherNamespace.MyOtherClass cls =
       new MyOtherNamespace.MyOtherClass();
   cls.Hello();
}
}
}

Standard Input and Output Streams


The System.Console class provides the capability to read streams from and write streams to the System console. It also defines functionality for error streams. The Read operation reads data from the console to the standard input stream, and the Write operation writes data to the standard output stream. The standard error stream is responsible for storing error data. These streams are the automatically associated with the system console.

The error, in, and out properties of the Console class represents standard error output, standard input and standard output streams. In the standard output stream, the Read method reads the next character, and the ReadLine method reads the next line. The Write and WriteLine methods write the data to the standard output stream. Table 1 describes some of the console class methods.

Table 1. The System.Console Class methods

METHOD

DESCRIPTION

EXAMPLE

Read
Reads a single character
int i = Console.Read();
ReadLline
Reads a line
string str = Console.ReadLine();
Write
Writes a line
Console.Write ("Write: 1");
WriteLine
Writes a line followed by a line terminator
Console.WriteLine("Test Output Data with Line");




Listing 5 shows you how to use the Console class and its members

Listing 5. Console class example

using System;
namespace ConsoleSamp
{
class Classs1
{
static void Main(string[ ] args )
{
 Console.Write("Standard I/O Sample");
 Console.WriteLine("");
 Console.WriteLine ("= = = = = = = = ");
 Console.WriteLine ("Enter your name . . .");
 string name = Console.ReadLine();
 Console.WriteLine("Output: Your name is : "+ name);
}
}
}

Figure2 shows the output of listing 5.



Figure 2. The console class methods output


The Object Class


­­­­­­­­­­­­­­As described, in the .NET framework, all types are represented as objects and are derived from the Object class. The Object class defines five methods: Equals, ReferenceEquals GetHashCode, GetType and ToString. Table 2 describes these methods, which are available to all types in the .NET library.

Table 2. Object class methods

METHOD
DESCRIPTION
GetType
Return type of the object.
Equals
Compares two object instances. Returns true if they’re Equal; otherwise false.
ReferenceEquals
Compares two object instances. Returns true if both are Same instance; otherwise false.
ToString
Converts an instance to a string type.
GetHashCode
Return hash code for an object.



The following sections discuss the object class methods in more detail.

The GetType method


You can use the Type class to retrieve type information from the object. The GetType method of an object return a type object, which you can use to get information on an object such as its name, namespace, base type, and so on. Listing 6 retrieves the information of objects. In Listing 6, you get the type of the Object and System.String classes.

 

Listing 6 GetType example


using System;
class TypeClass
{
static void Main(string [] args)
{
//create object of type object and string
Object cls1 = new Object ();
System.String cls2 = "Test string";
// Call Get Type to return the type
Type type1 = cls1.GetType( );
Type type2 =cls2.GetType( );
// Object class output
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);

// String output
Console.WriteLine(type2.BaseType);
Console.WriteLine(type2.Name);
Console.WriteLine(type2.FullName);
Console.WriteLine(type2.Namespace);
}
}

Figure  shows the output of listing 6.



Figure 3. Output of listing

The Equals and ReferenceEqual Methods


The Equals method in the Object class can compare two objects. The ReferenceEqual method can compare the two objects’ instances. For example:

Console.WriteLine(Object.Equals(cls1, cls2));
Console.WriteLine(Object.Equals(str1, str2));

See listing 7 get type, equal, and reference Equals

Listing 7. Get Type, Equal, and ReferenceEquals

using System;
namespace TypesSamp
{
//define class 1
public class Class1: object
{
private void Method1()
{
 Console.WriteLine("1 method");
}
}

// Define class 2
public class Class2: Class1
{
private void Method2( )
{
 Console.WriteLine("2 method");
}
}

class TypeClass
{
static void Main(string [] args)
{
Class1 cls1 = new Class1();
Class2 cls2 = new Class2();
Console.WriteLine ("= = = = = = = = = = ");
Console.WriteLine ("Type Information");
Console.WriteLine ("= = = = = = = = = =");
// Getting type information
Type type1 =cls1.GetType( );
Type type2 = cls2.GetType( );
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);

// Comparing two objects
string str1 = "Test";
string str2 = "Test";
Console.WriteLine(" = = = = = = = = = = = ");
Console.WriteLine("comparison of two objects");
Console.WriteLine(object.Equals(cls1, cls2));
Console.WriteLine(object.Equals(str1, str2));
}
}
}

Figure 4 shows the output of listing 7.



Figure 4 get type and compare objects code output


The ToString Method and String Conversion


The ToString method of the Object class converts a type to a string type.


Listing 8 shows an example of the ToString method.

 

Listing 8. ToString method example


using System;
namespace ToStringSamp
{
class Test
{
static void Main(string [] args)
{
  int num1 =8;
  float num2 =162.034f;
  Console.WriteLine(num1.ToString( ));
  Console.WriteLine(num2.ToString( ));
}
 }
}

The GetHashCode method


A hashtable (also commonly known as a map or dictionary) is a data structure that stores one or more key- value pairs of data. Hashtables are useful when you want fast access to a list of data through a key (which can be a number, letter, string, or any object). In .NET the HashTable class represents a hashtable, which is implemented based on a hashing algorithm. This class also provides methods and constructors to define the size of the hash table. You can use the Add and Remove methods to add and remove items from a hashtable. The Count property of the HashTable class returns the number of items in a hashtable.

The GetHashCode method returns the hash code of an object. To return a hash code for a type, you must override the GetHashCode method. An integer value is returned, which represents whether an object is available in a hashtable.

Two other useful methods of the object class are MemberWiseClone and Finalize methods. The MemberWiseClone method creates a shallow copy of an object, which can be used as a clone of an object. The Finalize method acts as a destructor and can clean up the resources before the garbage collector calls the object. You need to override this method and write your own code to clean up the resources. The garbage collector automatically calls the Finalize method if an object is no longer in use.