1. What is a class?
A class is a template for a specific object or groups of objects that will always have the same features. It is a collection of objects.
Ex: 1.public class student { } 2.Paper pattern for a shirt
Here paper pattern is the class and shirt is the object.
2. What is an object?
It is a real time entity. Objects lets you declare variables and procedures once and then reuse them whenever needed.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior.
Ex: 1.student objstudent=new student ();
When you drag &drop a control from the toolbox onto a form, you are actually creating an object (an instance of a class)
3. What is a Method?
A method defines the behavior to be exhibited by instances of the associated class at program runtime.
4. What is abstract method?
It is one with only a signature and no implementation body. It is often used to specify that a sub class must provide an implementation of the method.
5. What are the different types of classes in c#?
There are Partial, abstract, static, sealed and instance classes in c#.
Partial Class: Partial class is useful when the class functionality is too big (i.e. when number of lines of code in the class is too big) and when a developer want to share some of the functionalities with other developers this is useful.
Sealed Class: when the class is functionality is complete and you don’t want to allow any other class to extend your class, then you need to declare your class as sealed. No other Class can extend or use your sealed class as base class.
Abstract Class: When the developer/programmer doesn’t know the functionality of the class fully and, you want to leave the implementation to the derived classes, and then use the Abstract class. In the abstract class you can have 0 or more abstract methods, properties and along with implemented methods. You cannot create an instance to the Abstract Class. And also if you have family of related classes and all those classes having some common functionality try pushing then into a common base class. This way you will get code re-usability and can get easy maintainability.
Static Class: when any class is most frequently used or if any class is qualified as helper class (helper class is one which will be repeatedly used by all other classes) then try using Static Class. Advantage with static class is “Object instantiation overhead is reduced”. And this class always has single memory location where in every other class will hit the same memory location. If class A changed some data in static class, Changed data is available to every other subsequent classes who access the static class.
6. OOPS concepts in c#
There are 4 concepts.
1. Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit.
Ex for encapsulation is class. A class can contain data structures and methods.
2. Abstraction:
Abstraction is a process of hiding the implementation details and displaying the essential features.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.
Example: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works. You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.
So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member
Functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
3. Inheritance:
Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity.
Example:
Public class A
{
Public void A_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Public class B: A
{
Public void B_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Note:
1. Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.
2. How can you implement multiple inheritance in C#?
Ans: Using Interfaces.
4. Polymorphism:
When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
Features:
Polymorphism is of two types:
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Example:
Public class Shape
{
Public void Area (float r)
{
float a = (float)3.14 * r;
// here we have used function overload with 1 parameter.
Console.WriteLine ("Area of a circle: {0}",a);
}
Public void Area(float l, float b)
{
float x = (float)l* b;
// here we have used function overload with 2 parameters.
Console.WriteLine ("Area of a rectangle: {0}",x);
}
public void Area(float a, float b, float c)
{
float s = (float)(a*b*c)/2;
// here we have used function overload with 3 parameters.
Console.WriteLine ("Area of a circle: {0}", s);
}
}
Runtime time polymorphism:
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
Example:
public class Print
{
public void display(string name)
{
Console.WriteLine ("Your name is : " + name);
}
public void display(int age, float marks)
{
Console.WriteLine ("Your age is : " + age);
Console.WriteLine ("Your marks are :" + marks);
}
}
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.
You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.
Things to keep in mind while method overloading
If you use overload for method, there are couple of restrictions that the compiler imposes.
The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.
There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.
Things to keep in mind while method overriding
Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class.This is done by using virtual/override keywords.
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
9. What is static & void?
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
Ex: UtilityClass.MethodA ();
When used as the return type for a method, void specifies that the method does not return a value.
Void is not allowed in a method's parameter list. A method that takes no parameters and returns no value is declared as follows:
Ex: void MyMethod ();
10. What is an assembly?
When we create a project in Visual Studio .Net and compile it, assemblies are created. These assemblies are the fundamental units of applications in the .NET Framework. An assembly can contain classes, structures, interfaces, and resources that an application requires.
When we compile a program, the compiler translates the source code into the Intermediate Language code (IL). In addition to translating the code into IL, the compiler also produces metadata about the program during the process of the compilation. Metadata contains the description of the program, such as the classes and interfaces, the dependencies, and the versions of the components used in the program.
The IL and the metadata are linked in an assembly.
An IL and metadata exist in portable executable file (EXE/DLL).
If we look at any project folder, we will find a bin folder that contains, say myproject.dll/ myproject.exe and myproject.pdb files. The myproject.dll/ myproject.exe is the assembly, and myproject.pdb (program database) file contains debugging information for the assembly. The .pdb file also contains information the linker can use when debugging the assembly.
So, when we create and compile the project in VS.Net, the assembly is automatically generated and copied into the application's bin directory. An assembly also contains an assembly manifest that contains the assembly metadata. This metadata contains information about the assembly version, its security identity, the resources required by the assembly and the scope of the assembly. This information is stored within the assembly file (DLL/EXE) itself. Note that the assembly contains two types of metadata. One, is the type metadata and the other is the assembly metadata.
Process assemblies (EXE) and library assemblies (DLL):
A process assembly represents a process which uses classes defined in library assemblies. The compiler will have a switch to determine if the assembly is a process or a library and will set a flag in the PE(portable executables)file.NET does not use the extension to determine if the file is a process or library. This means that a library may have either .dll or .exe as its extension.
The .Net CLR while executing looks for the metadata in order to locate and load classes, as well as generate native code and security.
Note that the assembly metadata is assembly manifest and it simplifies the deployment model. Because it contains so much information about the assembly, you can simply XCOPY the assembly onto another computer, along with its related manifest.
Why use Assemblies?
The goal of the assembly model is the elimination of DLL Hell. Under the current COM/COM+ model, a catalog of DLLs is centralized in the Windows Registry. When a new version of a DLL is published, the registry re-references the catalog to point to the new DLL. This centralized registration paradigm makes it challenging for multiple applications to depend on the same DLL. Most often, the application binds to a DLL in a centralized location, rather than run multiple versions of a component by using side-by-side execution.
The .NET Framework makes it easy to run multiple versions of a component because it stores assemblies in local application directories by default. This isolates the assembly from use by any other application and protects the assembly from system changes.
Types of Assemblies:
Assemblies can be private or shared. The assembly which is used by a single application is called as private assembly. Suppose we have created a DLL which encapsulates business logic. This DLL is used by the client application only and not by any other application. In order to run the application properly the DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to the application.
Suppose we are creating a general purpose DLL which provides functionality to be used by a variety of applications. Now, instead of each client application having its own copy of DLL we can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.
When we create an application in Visual Studio.Net that uses a component, which is not in the GAC, the assembly is automatically copied to the project´s bin folder. So, if we simply copy the project´s bin folder, the assembly for the component is copied as well. Since the files the application needs are in the same folder, the application can run without registration.
Global assembly cache is nothing but a special disk folder where all the shared assemblies are kept. It is located under <drive>:\Windows\Assembly folder on every machine running the .NET framework.
GAC acts as a central location for assemblies that is accessible by any application.
11. What is msi (Microsoft Installer API)?
The Windows Installer (MSI) (previously known as Microsoft Installer, codename Darwin) is an engine for the installation, maintenance, and removal of software on modern Microsoft Windows systems. The installation information, and often the files themselves, are packaged in installation packages, loosely relational databases structured as OLE Structured Storage Files and commonly known as "MSI files", from their default file extension (compare: .deb, RPM, .pbi). Windows Installer is a significant improvement over its predecessor, Setup API: several new features, such as a GUI framework, the automatic generation of the uninstallation sequence and the powerful deployment capabilities, made Windows Installer a viable alternative to stand-alone executable installer frameworks such as older versions of InstallShield and WISE (later versions are based on Windows Installer) and NSIS.
Microsoft encourages third parties to use Windows Installer as the basis for installation frameworks, so that they synchronize correctly with other installers and keep the internal database of installed products consistent. Important features such as rollback and versioning (see DLL hell) depend on a consistent internal database for reliable operation.
This collection of modules and scripts lets you create and manipulate MSI databases programmatically using Perl. The main API is provided by the MSI::Installer module; however the other modules provide useful APIs as well.
12. What is CAB?
Cab files are nothing but cabinet files which are developed by Microsoft in order to distribute their software in a compressed and secured format.
13. What are the differences between different versions of visual studio?
2003 and 2005:
In 2005 we have default web server for web application but in 2003 we have to configure iis
In 2005 we can directly create website (means web application) it will use classes that will help to create web application..By this deployment makes easier.
In 2005 we can select option to write inline coding.But in 2003 we don’t have this option
In 2005 we have login control, password recovery control, directly we can create user in asp.net database..This is very secure. In 2003 we don’t have this.
In 2005 we have master pages and themes instead of using css files we can use themes ...
In 2005 we does not require single line of code to do any operations with grid view.
In 2005 we have sitemap navigator, Xmldatasource.
New control is available like tree-view, menu-tree .Crystal-report’s new version is there. Sql-server will come inbuilt with vs2005 for the run a query and all things
2005 and 2008:
Visual Studio 2008 is having lot of advanced concepts like WPF, WCF, WWF, and Linq etc. Entity Framework also an advanced approach introduced in .Net 3.5 SP.
Visual Studio 2005 was upgraded to support all the new features introduced in .NET Framework 2.0, including generics and ASP.NET 2.0. The IntelliSense feature in Visual Studio was upgraded for generics and new project types were added to support ASP.NET web services. It also includes a local web server, separate from IIS that can host ASP.NET applications during development and testing. It also supports all SQL Server 2005 databases.
Visual Studio 2008 came that supports .net framework 3.0 and 3.5. Its features include an XAML-based designer workflow designer, LINQ to SQL designer, XSLT debugger, JavaScript Debugging support, JavaScript IntelliSense support, support for UAC manifests, a concurrent build system, among others.
Visual Studio 2010 IDE supports the upcoming .net framework 4.0. It has been redesigned which, according to Microsoft, clears the UI organization and "reduces clutter and complexity". It has integrated support for developing Microsoft Silver light applications, including an interactive designer.
INTERFACES:
what is an Interface?Explain with an example?
An Interface is created using the keyword interface.It provides a way to achieve run time polymorphism. An example is shown below.
using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Please enter Deposit Money");
}
public void WithdrawMoney()
{
Console.WriteLine("Please enter Withdraw Money");
}
public static void Main()
{
Bank objBank = new Bank();
objBank.DepositMoney();
objBank.WithdrawMoney();
}
}
}
In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();
Method declarations does not have access modifiers like public, private, etc
NOTE:
1. By default all interface members are public. It is a compile time error to use access modifiers on interface member declarations.
2. Interface methods have only declarations and not implementation. It is a compile time error to provide implementation for any interface member.
In our example as the Bank class is inherited from the IBankCustomer interface, the Bank class has to provide the implementation for both the methods (WithdrawMoney() and DepositMoney()) that is inherited from the interface. If the class fails to provide implementation for any of the inherited interface member, a compile time error will be generated.
Can an Interface contain fields?
No, an Interface cannot contain fields.
What is the difference between class inheritance and interface inheritance?
Classes and structs can inherit from interfaces just like how classes can inherit a base class or struct. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example depicting the same is shown below.
using System;
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}
//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}
//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}
2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.
Can an interface inherit from another interface?
Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.
Can you create an instance of an interface?
No, you cannot create an instance of an interface.
If a class inherits an interface, what are the 2 options available for that class?
Provide Implementation for all the members inherited from the interface.
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}
If the class does not wish to provide Implementation for all the members inherited from the interface, then the class has to be marked as abstract.
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}
A class inherits from 2 interfaces and both the interfaces have the same method name as shown below. How should the class implement the drive method for both Car and Bus interface?
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}
To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method type cast the demo object to the respective interface and then call the drive method.
using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}
static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}
What do you mean by "Explicitly Implemeting an Interface". Give an example?
If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An example is shown below.
using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
static void Main()
{
Demo DemoObject = new Demo();
//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type cast the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}
partial classes, structs and methods:
What is a partial class. Give an example?
A partial class is a class whose definition is present in 2 or more files. Each source file contains a section of the class, and all parts are combined when the application is compiled. To split a class definition, use the partial keyword as shown in the example below. Student class is split into 2 parts. The first part defines the study() method and the second part defines the Play() method. When we compile this program both the parts will be combined and compiled. Note that both the parts uses partial keyword and public access modifier.
using System;
namespace PartialClass
{
public partial class Employee
{
public void Work()
{
Console.WriteLine("I am working");
}
}
public partial class Employee
{
public void Learn()
{
Console.WriteLine("I am Learning New Technologies");
}
}
public class Demo
{
public static void Main()
{
Employee objEmp = new Employee();
objEmp.Study();
objEmp.Play();
}
}
}
It is very important to keep the following points in mind when creating partial classes.
1. All the parts must use the partial keyword.
2. All the parts must be available at compile time to form the final class.
3. All the parts must have the same access modifiers - public, private, protected etc.
4. Any class members declared in a partial definition are available to all the other parts.
5. The final class is the combination of all the parts at compile time.
What are the advantages of using partial classes?
1. When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
2. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
Is it possible to create partial structs, interfaces and methods?
Yes, it is possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial classes.
Will the following code compile?
using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public abstract partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
}
}
}
No, a compile time error will be generated stating "Cannot create an instance of the abstract class or interface "PartialClass.Student". This is because, if any part is declared abstract, then the whole class becomes abstract. Similarly if any part is declared sealed, then the whole class becomes sealed and if any part declares a base class, then the whole class inherits that base class.
Can you create partial delegates and enumerations?
No, you cannot create partial delegates and enumerations.
Can different parts of a partial class inherit from different interfaces?
Yes, different parts of a partial class can inherit from different interfaces.
Can you specify nested classes as partial classes?
Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.
class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}
How do you create partial methods?
To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are removed at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration consists of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
The following are the points to keep in mind when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
What is the use of partial methods?
Partial methods can be used to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
Nested Types:
What is a nested type. Give an example?
A type(class or a struct) defined inside another class or struct is called a nested type. An example is shown below. InnerClass is inside ContainerClass, Hence InnerClass is called as nested class.
using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
Will the following code compile?
using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
}
class Demo
{
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
No, the above code will generate a compile time error stating - The type or namespace name 'InnerClass' could not be found (are you missing a using directive or an assembly reference?). This is bcos InnerClass is inside ContainerClass and does not have any access modifier. Hence inner class is like a private member inside ContainerClass. For the above code to compile and run, we should make InnerClass public and use the fully qualified name when creating the instance of the nested class as shown below.
using System;
namespace Nested
{
class ContainerClass
{
public class InnerClass
{
public string str = "A string variable in nested class";
}
}
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
Can the nested class access, the Containing class. Give an example?
Yes, the nested class, or inner class can access the containing or outer class as shown in the example below. Nested types can access private and protected members of the containing type, including any inherited private or protected members.
using System;
namespace Nested
{
class ContainerClass
{
string OuterClassVariable = "I am an outer class variable";
public class InnerClass
{
ContainerClass ContainerClassObject = new ContainerClass();
string InnerClassVariable = "I am an Inner class variable";
public InnerClass()
{
Console.WriteLine(ContainerClassObject.OuterClassVariable);
Console.WriteLine(this.InnerClassVariable);
}
}
}
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
}
}
}
What is the output of the following program?
using System;
namespace Nested
{
class ContainerClass
{
public ContainerClass()
{
Console.WriteLine("I am a container class");
}
public class InnerClass : ContainerClass
{
public InnerClass()
{
Console.WriteLine("I am an inner class");
}
}
}
class DemoClass : ContainerClass.InnerClass
{
public DemoClass()
{
Console.WriteLine("I am a Demo class");
}
public static void Main()
{
DemoClass DC = new DemoClass();
}
}
}
Output:
I am a container class
I am an inner class
I am a Demo class
The above program has used the concepts of inheritance and nested classes. The ContainerClass is at the top in the inheritance chain. The nested InnerClass derives from outer ContainerClass. Finally the DemoClass derives from nested InnerClass. As all the 3 classes are related by inheritance we have the above output.
Destructors:
What is a Destructor?
A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.
Can a class have more than 1 destructor?
No, a class can have only 1 destructor.
Can structs in C# have destructors?
No, structs can have constructors but not destructors, only classes can have destructors.
Can you pass parameters to destructors?
No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.
Can you explicitly call a destructor?
No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.
Why is it not a good idea to use Empty destructors?
When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.
Is it possible to force garbage collector to run?
Yes, it possible to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance over head. Usually the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.
Usually in .NET, the CLR takes care of memory management. Is there any need for a programmer to explicitly release memory and resources? If yes, why and how?
If the application is using expensive external resource, it is recommend to explicitly release the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.
When do we generally use destructors to release resources?
If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.
constructors:
What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object.
In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.
Structs are not reference types. Can structs have constructors?
Yes, even though Structs are not reference types, structs can have constructors.
We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.
Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.
using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.
Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}
public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}
If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
Will the following code compile?
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
//Call the base class contructor from child class
public ChildClass() : base("A call to base class constructor")
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.
using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 150;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}
Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.
Can you have parameters for static constructors?
No, static constructors cannot have parameters.
What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Does C# provide copy constructor?
No, C# does not provide copy constructor.
Questions on Methods / Functions:
Is the following code legal?
using System;
namespace Demo
{
class Program
{
public static void Main()
{
}
public void Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
}
public int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
}
}
}
No, The above code does not compile. You cannot overload a method based on the return type. To overload a method in C# either the number or type of parameters should be different. In general the return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.
What is the difference between method parameters and method arguments. Give an example?
In the example below FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}
Explain the difference between passing parameters by value and passing parameters by reference with an example?
We can pass parameters to a method by value or by reference. By default all value types are passed by value where as all reference types are passed by reference. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method.An example is shown below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
int K = Function(I);
Console.WriteLine("I = " + I);
Console.WriteLine("K = " + K);
}
public static int Function(int Number)
{
int ChangedValue = Number + 1;
return ChangedValue;
}
}
}
By default, reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy of the object. Changes made through this reference will therefore be reflected in the calling method. Reference types are created by using the class keyword as shown in the example below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
ReferenceTypeExample Object = new ReferenceTypeExample();
Object.Number = 20;
Console.WriteLine("Original Object Value = " + Object.Number);
Function(Object);
Console.WriteLine("Object Value after passed to the method= " + Object.Number);
}
public static void Function(ReferenceTypeExample ReferenceTypeObject)
{
ReferenceTypeObject.Number = ReferenceTypeObject.Number + 5;
}
}
class ReferenceTypeExample
{
public int Number;
}
}
Can you pass value types by reference to a method?
Yes, we can pass value types by by reference to a method. An example is shown below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = " + I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by reference= " + I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}
If a method's return type is void, can you use a return keyword in the method?
Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}
}
}
Properties:
What are Properties in C#. Explain with an example?
Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.
The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.
using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;
// public FirstName property exposes _firstName variable
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}
}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}
Explain the 3 types of properties in C# with an example?
1. Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2. Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.
What are the advantages of properties in C#?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value of other fields.
What is a static property. Give an example?
A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.
using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}
What is a virtual property. Give an example?
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.
using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is virtual
public virtual string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
}
class BankCustomer : Customer
{
// Overiding the FullName virtual property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}
What is an abstract property. Give an example?
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.
using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}
Can you use virtual, override or abstract keywords on an accessor of a static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.
C# Interview Questions on Constants:
What are constants in C#?
Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.
using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}
Can you declare a class or a struct as constant?
No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.
Does C# support const methods, properties, or events?
No, C# does not support const methods, properties, or events.
Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the example below, the constant field PI is always 3.14, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, PI), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference.
using System;
class Circle
{
public const double PI = 3.14;
}
How do you access a constant field declared in a class?
Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. In the example below constant field PI can be accessed in the Main method using the class name and not the instance of the class. Trying to access a constant field using a class instance will generate a compile time error.
using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}
C# Interview Questions on Fields:
What are the 2 broad classifications of fields in C#?
1. Instance fields
2. Static fields
What are instance fields in C#?
Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object.
What is a static field?
A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.
Will the following code compile?
using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}
No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields can only be accessed using the name of the class and not the instance of the class. The above sample program is rewritten as shown below.
using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}
Can you declare a field readonly?
Yes, a field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. An example is shown below.
using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}
Will the following code compile?
using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
A.PI = 3.15;
Console.WriteLine(A.PI);
}
}
No, PI is readonly. You can only read the value of PI in the Main() method. You cannot assign any value to PI.
What is wrong with the sample program below?
using System;
class Area
{
public const double PI = 3.14;
static Area()
{
Area.PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}
You cannot assign a value to the constant PI field.
What is the difference between a constant and a static readonly field?
A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.
Access Modifiers:
What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.
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.
Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
What are Access Modifiers used for?
Access Modifiers are used to control the accessibilty of types and members with in the types.
Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.
Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}
When you compile the above code an error will be generated stating "Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass".To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
Is the following code legal?
using System;
private class Test
{
public static void Main()
{
}
}
No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support inheritance.
Can the accessibility of a type member be greater than the accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.
Can destructors have access modifiers?
No, destructors cannot have access modifiers.
What does protected internal access modifier mean?
The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.
What is the default access modifier for a class,struct and an interface declared directly with a namespace?
internal
Will the following code compile?
using System;
interface IExampleInterface
{
public void Save();
}
No, you cannot specify access modifer for an interface member. Interface members are always public.
Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.
Why should you override the ToString() method
Why should you override the ToString() method?
All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below.
using System;
public class MainClass
{
public static void Main()
{
int Number = 10;
Console.WriteLine(Number.ToString());
}
}
In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method.
If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class.
using System;
public class Customer
{
public string FirstName;
public string LastName;
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}
The code sample below shows how to override the ToString() method in a class, that would give the output you want.
using System;
public class Customer
{
public string FirstName;
public string LastName;
public override string ToString()
{
return LastName + ", " + FirstName;
}
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}
Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method.
polymorphism:
Explain polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];
DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}
When can a derived class override a base class member?
A derived class can override a base class member only if the base class member is declared as virtual or abstract.
What is the difference between a virtual method and an abstract method?
A virtual method must have a body where as an abstract method should not have a body.
Can fields inside a class be virtual?
No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.
Give an example to show for hiding base class methods?
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}
public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}
Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}
public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}
C# Interview Questions on Abstract and Sealed Class Members:
What is an abstract class?
An abstract class is an incomplete class and must be implemented in a derived class.
Can you create an instance of an abstract class?
No, abstract classes are incomplete and you cannot create an instance of an abstract class.
What is a sealed class?
A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}
What are abstract methods?
Abstract methods are methods that only the declaration of the method and no implementation.
Will the following code compile?
using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a compile time error stating "Customer.Test() cannot declare a body because it is marked abstract"
Is the following code legal?
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}
No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"
How can you force derived classes to provide new method implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}
public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}
public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation.
}
}
When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.
Can a sealed class be used as a base class?
No, sealed class cannot be used as a base class. A compile time error will be generated.
Will the following code compile?
public abstract sealed class Test
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.
C# Interview Questions on Inheritance:
What are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Do structs support inheritance?
No, structs do not support inheritance, but they can implement interfaces.
What is the main advantage of using inheritance?
Code reuse
Is the following code legal?
class ChildClass : ParentClassA, ParentClassB
{
}
No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.
What will be the output of the following code?
using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.
Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.
C# Interview Questions on structs :
Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"
Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No
Can you instantiate a struct without using a new operator in C#?
Yes, you can instantiate a struct without using a new operator
Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.
Can a struct inherit from an interface in C#?
Yes
Are structs value types or reference types?
Structs are value types.
What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.
Basic C# Interview Questions on classes and structs
What do you mean by saying a "class is a reference type"?
A class is a reference type means when an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
What do you mean by saying a "struct is a value type"?
A struct is a value type mean when a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
When do you generally use a class over a struct?
A class is used to model more complex behavior, or data that is intended to be modified after a class object is created. A struct is best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
List the 5 different access modifiers in C#?
1. public
2. protected
3. internal
4. protected internal
5. private
If you donot specify an access modifier for a method, what is the default access modifier?
private
Classes and structs support inheritance. Is this statement true or false?
False, Only classes support inheritance. structs donot support inheritance.
If a class derives from another class, will the derived class automatically contain all the public, protected, and internal members of the base class?
Yes, the derived class will automatically contain all the public, protected, and internal members of the base class except its constructors and destructors.
Can you create an instance for an abstract class?
No, you cannot create an instance for an abstract class.
How do you prevent a class from being inherited by another class?
Use the sealed keyword to prevent a class from being inherited by another class.
Classes and structs can be declared as static, Is this statement true or false?
False, only classes can be declared as static and not structs.
Can you create an instance of a static class?
No, you cannot create an instance of a static class.
Can a static class contain non static members?
No, a static class can contain only static members.
C# Interview Questions on Data Types
What are the 3 types of comments in C#?
1. Single Line Comments. You define single line comments with // as shown below.
//This is an example for single line comment
2. Multi line comments. You define multi line comments with /* */ as shown below.
/*This is an example for
Multi Line comments*/
3. XML Comments. You define XML comments with /// as shown below.
///This is an example for defining XML comments.
Is C# a strongly-typed language?
Yes
What are the 2 broad classifications of data types available in C#?
1. Built in data types.
2. User defined data types.
Give some examples for built in datatypes in C#?
1. int
2. float
3. bool
How do you create user defined data types in C#?
You use the struct, class, interface, and enum constructs to create your own custom types. The .NET Framework class library itself is a collection of custom types provided by Microsoft that you can use in your own applications.
C# Interview Questions on value types and reference types:
What are the 2 types of data types available in C#?
1. Value Types
2. Reference Types
If you define a user defined data type by using the struct keyword, Is it a a value type or reference type?
Value Type
If you define a user defined data type by using the class keyword, Is it a a value type or reference type?
Reference type
Are Value types sealed?
Yes, Value types are sealed.
What is the base class from which all value types are derived?
System.ValueType
Give examples for value types?
Enum
Struct
Give examples for reference types?
Class
Delegate
Array
Interface
What are the differences between value types and reference types?
1. Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.
C# Interview Questions on data type casting
What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.
What are the 2 kinds of data type conversions in C#?
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.
What is the difference between an implicit conversion and an explicit conversion?
1. Explicit conversions require a cast operator where as an implicit converstion is done automatically.
2. Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.
What type of data type conversion happens when the compiler encounters the following code?
ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();
Implicit Conversion. For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.
Will the following code compile?
double d = 9999.11;
int i = d;
No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.
double d = 9999.11;
int i = (int)d; //Cast double to int.
If you want to convert a base type to a derived type, what type of conversion do you use?
Explicit conversion as shown below.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;
// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.
If casting fails what type of exception is thrown?
InvalidCastException
C# Interview questions on Boxing and Unboxing
What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing
Unboxing - Converting a reference type to a value typpe is called unboxing. An example is shown below.
obj = 101;
i = (int)obj; // Unboxing
Is boxing an implicit conversion?
Yes, boxing happens implicitly.
Is unboxing an implicit conversion?
No, unboxing is an explicit conversion.
What happens during the process of boxing?
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.
Basic C# Interview Questions on arrays:
What is an array?
An array is a data structure that contains several variables of the same type.
What are the 3 different types of arrays?
1. Single-Dimensional
2. Multidimensional
3. Jagged
What is Jagged Array?
A jagged array is an array of arrays.
Are arrays value types or reference types?
Arrays are reference types.
What is the base class for Array types?
System.Array
Can you use foreach iteration on arrays in C#?
Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#.
Basic C# Interview Questions on strings
What is the difference between string keyword and System.String class?
string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.
Are string objects mutable or immutable?
String objects are immutable.
What do you mean by String objects are immutable?
String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.
string s1 = "First String ";
string s2 = "Second String";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: First String Second String
What will be the output of the following code?
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);
The output of the above code is "Hello" and not "Hello C#". This is bcos, if you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.
What is a verbatim string literal and why do we use it?
The "@" symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:
string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg
string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/
string DoubleQuotesString = @"My Name is ""Vankat.""";
//Output: My Name is "Vankat."
More C# interview questions on strings
Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);
The above code will compile, but at runtime System.NullReferenceException will be thrown.
How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;
What is the difference between System.Text.StringBuilder and System.String?
1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.
How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.
string str = "One";
int i = 0;
if(int.TryParse(str,out i))
{
Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
Console.WriteLine("string does not contain Integer");
}
What is the difference between int.Parse and int.TryParse methods?
Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.
ASP.NET Interview Questions:
What is the difference between const and static read-only member?
A const field must be initialized at the place where it is declared as shown in the example below.
class Program
{
public const int Number = 100;
}
It is a compile time error to declare a const without a value. The code below will generate a compiler error stating "A const field requires a value to be provided"
class Program
{
public const int Number;
}
It is a compile time error to change the value of a constant. The following code will generate a compiler error stating "The left-hand side of an assignment must be a variable, property or indexer"
class Program
{
public const int Number = 100;
static void Main()
{
Number = 200;
}
}
It is not mandatory to initialize a static readonly field where it is declared. You can declare a static readonly field without an initial value and can later initialize the static field in a static constructor as shown below.
class Program
{
public static readonly int Number;
static Program()
{
Number = 100;
}
}
Once a static readonly field is initialized, the value cannot be changed. The code below will generate a compiler error stating "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)"
class Program
{
public static readonly int Number;
static Program()
{
Number = 100;
}
static void Main()
{
Number = 200;
}
}
In short, the difference is that static readonly field can be modified by the containing class, but const field can never be modified and must be initialized where it is declared. A static readonly field can be changed by the containing class using static constructor as shown below.
class Program
{
// Initialize the static readonly field
// to an initial value of 100
public static readonly int Number=100;
static Program()
{
//Value changed to 200 in the static constructor
Number = 200;
}
}
Linq Interview Questions Part 1:
What is LINQ?
LINQ, or Language INtegrated Query, is a set of classes added to the .NET Framework 3.5. LINQ adds a rich, standardized query syntax to .NET programming languages that allows developers to interact with any type of data.
What are the advantages of using LINQ or Language INtegrated Query?
In any data driven application, you get data either from a Database, or an XML file or from collection classes. Prior to LINQ, working with each data source requires writing a different style of code. Moreover, working with external resources like data bases, XML files involves communicating with that external resource in some syntax specific to that resource. To retrieve data from a database you need to send it a string that contains the SQL query to execute, similarly, to work with an XML document involves specifying an XPath expression in the form of a string. The idea is that using LINQ you can work with disparate data sources using a similar style without having to know a separate syntax for communicating with the data source (e.g., SQL or XPath) and without having to resort to passing opaque strings to external resources.
In any data driven web application or windows application, we use database as a datasource for the application. In order to get data from the database and display it in a web or windows application, we typically do the following.
1. Prepare your SQL Statements.
2. Execute SQL Statements against the database.
3. Retrieve the results.
4. Populate the Business Objects.
5. Display the Data in the Web Form or Windows From.
In order to send a query to the database we must first establish a connection to the database. We then must encode the logic - the SQL query, its parameters, and the parameters' values - into strings that are supplied to the SqlCommand object. And because these inputs are encoded into opaque strings, there is no compile-time error checking and very limited debugging support. For example, if there is a spelling mistake in the SELECT query causing the Customets table name to be misspelled, this typographical error won't show up until runtime when this page is viewed in a web browser. These typographical errors are easy to make as there is no IntelliSense support. When we use LINQ, Visual Studio would display an error message alerting us about the incorrect table name.
Another mismatch between the programming language and the database is that the data returned by the database is transformed for us into objects accessible through the SqlDataReader, but these objects are not strongly-typed objects like we'd like. To get this data into strongly-typed objects we must write code ourselves that enumerates the database results and populates each record into a corresponding object.
LINQ was designed to address all these issues. LINQ also offers a unified syntax for working with data, be it data from a database, an XML file, or a collection of objects. With LINQ you don't need to know the intricacies of SQL, the ins and outs of XPath, or various ways to work with a collection of objects. All you need be familiar with is LINQ's classes and the associated language enhancements centered around LINQ.
In other words, LINQ provides type safety, IntelliSense support, compile-time error checking, and enhanced debugging scenarios when working with different datasources.
LINQ Interview Questions Part 2:
What are the three main components of LINQ or Language INtegrated Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Providers
How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface.
How are Standard Query Operators useful in LINQ?
Standard Query Operators in LINQ can be used for working with collections for any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.
6. Filter the results
List the important language extensions made in C# to make LINQ a reality?
1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions
What is the purpose of LINQ Providers in LINQ?
LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source.
What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.
Write a program using LINQ to find the sum of first 5 prime numbers?
Best pactices in developing asp.net applications - Part 1:
1.Remove unused private fields and functions.
2. Do not cast unnecessarily. Avoid duplicate casts where possible, since there is a cost associated with them.
3. Properties that return arrays are prone to code inefficiencies. Consider using a collection or making this a method.
4. To test for empty strings, check if String.Length is equal to zero. Constructs such as "".Equals(someString) and String.Empty.Equals(someString) are less efficient than testing the string length. Replace these with checks for someString.Length == 0.
5. Methods in the same type that differ only by return type can be difficult for developers and tools to properly recognize. When extending a type, be sure not to define new methods that differ from base type methods only by type.
6. Use stringbuilder instead of string types for string manipulation.
7. Use String.Format instead of concatenating and appending strings.
8. Use Type.TryParse rather than Convert.ToDestinationType(). For example use int.TryParse() rather than Convert.ToInt32() which might throw an exception.
9. Override Equals() method wherever applicable in your classes.
10. Consider passing base types as parameters - Using base types as parameters to methods improves re-use of these methods if you only use methods & properties from the parameter's base class. E.g. use Stream instead of FileStream as a parameter when only calling Stream.Read(), this makes the method work on all kind of streams instead of just File streams.
Best pactices in developing asp.net applications - Part 2:
Do not catch general exception types - You should not catch Exception or SystemException. Catching generic exception types can hide run-time problems from the library user, and can complicate debugging. You should catch only those exceptions that you can handle gracefully.
2. Use properties instead of visible instance fields.
3. Follow the same naming conventions accross the solution.
4. Remove unwanted commented code, Indent code properly.
5. Use curly braces with in an if statement, even if there is a single statement in the if block. This will provide better readability.
6. Make sure to refactor your code to move the duplicated code to common reusable functions.
7. Move one time control settings into the .aspx page rather than having them in the code behind in if(!IsPostback) block.
8. Use inheritance whereever possible, which enables code reuse and also reduces the amount of code we have to write and test.
9. Move the reusable javascript functions to an external .js file instead of having them on the page.
10. For controls that are declarativley specified on the page, tie the event handlers to the controls events on the aspx page rather than initializing them in the codebehind. If the controls are built dynamically then we donot have a choice.
11. Make sure to check for nulls when using any type retrieved from a session, querystring or a database to avoid NullReferenceExceptions.
12. Use foreach loop instead of using for loop which may lead to out of boundary run time exceptions.
ASP.NET Interview Questions on Data Access Security
What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.
Why is "Connecting to SQL Server using Integrated Security" considered a best practice?
Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.
What is the advantage of storing an XML file in the applications?
App_Data folder? The contents of the App_Data folder will not be returned in response to direct HTTP requests.
What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.
What is SQL injection?
A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application.
What are the best practices to keep in mind when accepting user input on a web application?
1. Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.
What are the steps to follow to avoid Script Injection attacks?
1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode.
What are the steps to follow to avoid SQL Injection attacks?
Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together.
Can you encrypt view state data of an aspx page?
Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.
ASP.NET Interview Questions on HTTP modules and HTTP Handlers:
What is an HTTP Handler?
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
What is HTTP module?
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
What is the interface that you have to implement if you have to create a Custom HTTP Handler?
Implement IHttpHandler interface to create a synchronous handler.
Implement IHttpAsyncHandler to create an asynchronous handler.
What is the difference between asynchronous and synchronous HTTP Handlers?
A synchronous handler does not return until it finishes processing the HTTP request for which it is called.
An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.
Which class is responsible for receiving and forwarding a request to the appropriate HTTP handler?
IHttpHandlerFactory Class
Can you create your own custom HTTP handler factory class?
Yes, we can create a custom HTTP handler factory class by creating a class that implements the IHttpHandlerFactory interface.
What is the use of HTTP modules?
HTTP modules are used to implement various application features, such as forms authentication, caching, session state, and client script services.
What is the difference between HTTP modules and HTTP handlers?
An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.
What is the common way to register an HTTP module?
The common way to register an HTTP module is to have an entry in the application's Web.config file.
Much of the functionality of a module can be implemented in a global.asax file. When do you create an HTTP module over using Global.asax File?
You create an HTTP module over using Global.asax file if the following conditions are true
1. You want to re-use the module in other applications.
2. You want to avoid putting complex code in the Global.asax file.
3. The module applies to all requests in the pipeline.
ASP.NET Interview Questions on Themes and Skins:
What is a "theme" in ASP.NET?
A "theme" is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.
What is the extension for a skin file?
.skin
What are the 2 types of control skins in ASP.NET?
1. Default skins
2. Named skins
What is the difference between Named skins and Default skins?
A default skin automatically applies to all controls of the same type when a theme is applied to a page. A control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)
A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application.
What are the 3 levels at which a theme can be applied for a web application?
1. At the page level - Use the Theme or StyleSheetTheme attribute of the @ Page directive.
2. At the application level - Can be applied to all pages in an application by setting the <pages> element in the application configuration file.
3. At the web server level - Define the <pages> element in machine.config file. This will apply the theme to all the web applications on that web server.
What is the name of the folder that contains the application themes?
App_Themes
What is a global theme?
A global theme is a theme that you can apply to all the Web sites on a server. Global themes allow you to define an overall look for your domain when you maintain multiple Web sites on the same server.
What is the difference between themes and CSS?
1. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.
2. Themes can include graphics.
3. Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property.
4. Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.
What are the security concerns to keep in mind when using themes?
Themes can cause security issues when they are used on your Web site. Malicious themes can be used to:
1. Alter a control's behavior so that it does not behave as expected.
2. Inject client-side script, therefore posing a cross-site scripting risk.
3. Expose sensitive information.
4. The mitigations for these common threats are:
5. Protect the global and application theme directories with proper access control settings. Only trusted users should be allowed to write files to the theme directories.
6. Do not use themes from an untrusted source. Always examine any themes from outside your organization for malicious code before using them on you Web site.
7. Do not expose the theme name in query data. Malicious users could use this information to use themes that are unknown to the developer and thereby expose sensitive information.
ASP.NET Interview Questions on DataSet:
What is a DataSet?
DataSet is an in-memory cache of data.
In which namespace is the DataSet class present?
System.Data
Can you add more than one table to a dataset?
Yes
Can you enforce constarints and relations on tables inside a DataSet?
Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.
What happens when you invoke AcceptChanges() method on a DataSet?
Invoking AcceptChanges() method on the DataSet causes AcceptChanges() method to be called on each table within the DataSet.
Both the DataRow and DataTable classes also have AcceptChanges() methods. Calling AcceptChanges() at the DataTable level causes the AcceptChanges method for each DataRow to be called.
When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes. Added and Modified rows become Unchanged, and Deleted rows are removed.
If the DataSet contains ForeignKeyConstraint objects, invoking the AcceptChanges method also causes the AcceptRejectRule to be enforced.
Is there a way to clear all the rows from all the tables in a DataSet at once?
Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.
What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
DataSet.Copy() copies both the structure and data.
How do you get a copy of the DataSet containing all changes made to it since it was last loaded?
Use DataSet.GetChanges() method
What is the use of DataSet.HasChanges() Method?
DataSet.HasChanges method returns a boolean true if there are any changes made to the DataSet, including new, deleted, or modified rows. This method can be used to update a DataSource only if there are any changes.
How do you roll back all the changes made to a DataSet since it was created?
Invoke the DataSet.RejectChanges() method to undo or roll back all the changes made to a DataSet since it was created.
What happnes when you invoke RejectChanges method, on a DataSet that contains 3 tables in it?
RejectChanges() method will be automatically invoked on all the 3 tables in the dataset and any changes that were done will be rolled back for all the 3 tables.
When the DataTable.RejectChanges method is called, any rows that are still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state. The DataRowState for all the modified and deleted rows will be flipped back to unchanged.
What is the DataSet.CaseSensitive property used for?
When you set the CaseSensitive property of a DataSet to true, string comparisons for all the DataTables within dataset will be case sensitive. By default the CaseSensitive property is false.
ASP.NET Interview Questions on Globalization:
What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application into multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.
The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application’s current culture, and much of the work is done automatically!
What are the 3 different ways to globalize web applications?
Detect and redirect approach : In this approach we create a separate Web application for each supported culture, and then detect the user’s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.
Run-time adjustment approach : In this approach we create a single Web application that detects the user’s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.
Satellite
assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user’s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.
In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object’s UserLanguages property to return a list of the user’s language preferences. The first element of the array returned by UserLanguages is the user’s current language on his/her computer.
What are the steps to follow to get user's culture at run time?
To get the user’s culture at run time, follow these steps:
1. Get the Request object’s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user’s current culture.
For example, the following code gets the user’s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}
What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.
What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific Web site.
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.
What is the use of culture attribute of the globalization element in web.config?
The Web.config file’s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.
Web.config globalization settings in subordinate folders override the globalization settings in the application’s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user’s CurrentCulture.
The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.
<body dir="rtl">
You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.
What do you mean by neutral cultures?
Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.
What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn’t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don’t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.
For what type of web applications setting the culture dynamically is best suited?
Setting the culture dynamically is best suited for simple Web applications that don’t contain large amounts of text that must be translated into different languages.
C# Interview Questions - Arrays :
What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below
1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
int[] IntegerArray; // not int IntegerArray[];
2. Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.
int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array
What are the 3 different types of arrays that we have in C#?
1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays
Are arrays in C# value types or reference types?
Reference types.
What is the base class for all arrays in C#?
System.Array
How do you sort an array in C#?
The Sort static method of the Array class can be used to sort array items.
Give an example to print the numbers in the array in descending order?
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}
What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}
Give an example to show how to copy one array into another array?
We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}
XML Interview Questions - Validating XML documents:
What determines the validity of an XML document?
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.
What is a valid XML document?
XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.
What are the 2 types of XML parsers?
Nonvalidating Parsers - Parsers that don’t support validation
Validating Parsers - Parsers that support validation
Can you combine both Schema and DTD references in a single XML document?
Yes
Are DTD's well-formed XML documents?
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.
Are XML schema's well-formed XML documents?
Yes.
What is the difference between an XML schema and a DTD?
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.
How do you define references to schemas in an XML document?
References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.
<rootelement xmlns:xsi=”http://www.w3.org/2001/XMLSchemainstance” xsi:noNamespaceSchemaLocation=”schemafile.xsd”>
The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.
You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.
XML related Interview Questions:
What Is XML?
XML stands for Extensible Markup Language, and it is used to describe documents and data in a standardized, text-based format that can be easily transported via standard Internet protocols. XML, like HTML, is based on, Standard Generalized Markup Language (SGML).
What are Well-formed XML documents?
XML, is very strict about a small core of format requirements that make the difference between a text document containing a bunch of tags and an actual XML document. XML documents that meet W3C XML document formatting recommendations are described as being well-formed XML documents. Well-formed XML documents can contain elements, attributes, and text.
What is an empty XML element?
Elements with no attributes or text are called as empty XML element. Empty XML elements can be represented in an XML document as shown below:
<element/>
What is meant by XML document declaration?
Most XML documents start with an <?xml?> element at the top of the page. This is called an XML document declaration. An XML document declaration is an optional element that is useful to determine the version of XML and the encoding type of the source data. It is not a required element for an XML document to be well formed. Most common XML document declaration is shown below:
<?xml version=”1.0” encoding=”UTF-8”?>
What does UTF stands for?
UTF stands for Universal Character Set Transformation Format.
Should every XML document have a root element?
Yes.
Can an XML document contain multiple root level elements?
No, an XML document can contain only one root level element.
What is the use of XML attributes?
XML attributes are used for adding more information and descriptions to the values of elements,and the text associated with elements.
Is XML case sensitive?
Yes
How do you comment lines in XML?
You can comment lines in XML as shown below.
<! -- This is commented line in an XML document -->
What are XML namespaces?
Namespaces are a method for separating and identifying duplicate XML element names in an XML document. Namespaces can also be used as identifiers to describe data types and other information. Namespace declarations can be compared to defining a short variable name for a long variable (such as pi=3.14159....) in programming languages. In XML, the variable assignment is defined by an attribute declaration. The variable name is the attribute name, and the variable value is the attribute value. In order to identify namespace declarations versus other types of attribute declarations, a reserved xmlns: prefix is used when declaring a namespace name and value. The attribute name after the xmlns: prefix identifies the name for the defined namespace. The value of the attribute provides the unique identifier for the namespace. Once the namespace is declared, the namespace name can be used as a prefix in element names.
Why is it a good idea to use a URL as the XML namespace value?
Although the namespace declaration value does not need to be a URL or resolve to an actual URL destination, it is a good idea to use a URL anyway, and to choose a URL that could resolve to an actual destination, just in case developers want to add documentation for the namespace to the URL in the future.
When to use namespaces?
Namespaces are optional components of basic XML documents. However, namespace declarations are recommended if your XML documents have any current or future potential of being shared with other XML documents that may share the same element names. Also, newer XML-based technologies such as XML Schemas,SOAP, and WSDL make heavy use of XML namespaces to identify data encoding types and important elements of their structure.
ASP.NET Interview Questions on caching application data
Which object can used to store frequently used items in the server’s memory for quick retrieval?
Cache object can be used to store frequently used items in the server’s memory for quick retrieval.
Is the cache object available for all web forms with in a web application?
Yes, the Cache object is global, that is, data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.
What are the 3 different ways to store data in the Cache object?
Use assignment.
Assigning a value to an unused key in the Cache object automatically creates that key and assigns the value to that key. Assigning a value to a key that already exists replaces the cached value with the assigned value.
Use the Insert method.
The Insert method uses parameters rather than assignment to create or change cached data. Insert optionally accepts parameters to establish dependencies and set expiration policy.
Use the Add method.
The Add method is similar to Insert; however, it requires all parameters and returns an object reference to the cached data.
For example, the following Cache statements all add the same item to the cache:
using System.Web.Caching;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Cache["NewItem"] = "Some string data";
Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null);
Cache.Insert("NewItem", "Some string data");
}
}
What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?
absoluteExpiration
A DateTime object that identifies when the data should be removed from the cache. If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.
slidingExpiration
A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.
Which delegate can be used to notify the application when items are removed from the cache?
onRemoveCallback is used to notify the application when items are removed from the cache.
How do you retrieve the value of a cache item stored in the servers memory?
You can retrieve the value of a cache item stored in the servers memory through the item’s key, just as you do with the Application and Session objects. Because cached items might be removed from memory, you should always check for their existence before attempting to retrieve their value, as shown in the following code:
private void Button1_Click(object sender, EventArgs e)
{
if (Cache["ChachedItem"] == null)
{
Lable1.Text = "Cached Item not found.";
}
else
{
Lable1.Text = Cache["ChachedItem"].ToString();
}
}
Which method can be used to remove data from the cache?
Cache object’s Remove method can be used to remove data from the cache as shown in the following code example / sample.
private void RemoveButton_Click(object sender, System.EventArgs e)
{
Cache.Remove("CachedItem");
}
How do you control how long data is cached?
The Cache object’s Add and Insert method parameters allow you to control how long an item is stored in the server’s memory. In practice, these parameter settings provide only indirect control of how long data remains in memory. If your server runs low on available memory, ASP.NET recovers as much memory as possible from expired cache items. If that’s not enough, ASP.NET will unload unexpired items from the cache based on their priority and when they were last accessed.
What is CacheItemPriority enumeration used for?
CacheItemPriority enumeration is used to set the relative importance of cached items. CacheItemPriority.NotRemoveable has the highest priority and CacheItemPriority.Low has the lowest priority.
Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object.
How do you update the Cache object when data changes?
Items stored in the cache are often copies of data that is stored and maintained elsewhere, such as records in a database. Use the Add and Insert methods’ dependency parameter to establish a relationship between a cached data item and an external source, such as a file, a folder, or a group of files.
The dependency parameter accepts a CacheDependency object, which in turn identifies the file, folder, or set of files to watch for changes. ASP.NET checks the time stamp of the items in the CacheDependency object, if one of those time stamps is later than the DateTime entered for the cached item, ASP.NET unloads that item from the cache.
ASP.NET Interview Questions on fragment caching:
What is fragment caching?
Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.
What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.
What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control’s class declaration to enable fragment caching.
What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.
VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).
If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can’t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.
When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect.
If the Web form’s cache duration is longer than the user control’s, both the Web form response and the user control response will expire using the Web form setting.
ASP.NET Interview Questions on Caching:
What is caching?
High-performance Web applications
should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form’s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.
Caching an item incurs considerable overhead, so it’s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form’s server-side content so that changes to that content do not appear until the cache is refreshed.
What directive is used to cache a web form?
The @OutputCache page directive is used to cache a Web form in the server’s memory.
What is the use of duration attribute of @OutputCache page directive?
The @OutputCache directive’s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.
The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.
After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.
What are the 2 required attributes of the @OutputCache directive?
The @OutputCache directive has two required attributes:
1. Duration
2. VaryByParam.
How do you cache multiple responses from a single Web form?
The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.
You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.
The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application’s Global.asax file.
Is it possible to cache a web form without using @OutputCache directive?
Yes, you can cache a web form using the Response object’s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive’s attributes.
Give a simple example to show how to cache a web form without using @OutputCache directive?
For example, the following code caches the Web form’s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}
The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"
What is @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property used for?
The @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheability setting as more of a request than a command.
What is HttpCachePolicy object’s SetAllowResponseInBrowserHistory method used for?
You can override the cache location settings using the HttpCachePolicy object’s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client’s history folder even if the location setting is None or Server.
Application build related ASP.NET Interview Questions:
What are the 2 build options for an ASP.NET web application?
1. Debug
2. Release
What are the 3 levels at which we can have a configuration file for an ASP.NET web application?
1. At the web server level : The Machine.config file located in the Windows\Microsoft.NET\Framework\version\config directory. This sets the base configuration for all .NET assemblies running on the server.
2. At the application or web site level : The Web.config file located in the IIS root directory.This sets the base configuration for all Web applications and overrides settings in Machine.config.
3. In the sub directory of an application root folder : These settings override the settings in the root folder's web.config file.
What happens when you make changes to an application’s Web.config file?
When you make changes to an application’s Web.config file, IIS automatically restarts the application and applies the changes. This has the side effect of resetting current Application or Session state variables, which can adversely affect users.
What happens when you access the Web.config file from a browser?
For security reasons, you can’t access the Web.config file from a browser. If a user requests the Web.config file from your Web site, he or she will receive an "This type of page is not served" error message.
What happens when you access the Global.asax file from a browser?
For security reasons, you can’t access the Global.asax file from a browser. If a user requests the Global.asax file from your Web site, he or she will receive an "This type of page is not served" error message.
What are the steps to follow to host a web application on a web server?
1. Use IIS to set up a virtual folder for the application.
2. Copy the Web application to the virtual directory.
3. Add any shared .NET components to the server’s global assembly cache (GAC).
4. Set the security permissions on the server to allow the application to access required resources.
What are the 2 components that should be installed on a web server where, the ASP.NET web application runs?
ASP.NET Web applications run under IIS, so both IIS and the Microsoft .NET Framework must be installed on the server before that server can host Web applications.
What is the purpose of default start page in IIS?
A default page enables IIS to display a page if the user does not specify one in his or her request. For example, a user might make a request using only your domain name, such as http://www.venkataspinterview.blogspot.com/. If a default page is enabled, IIS will respond with http://www.venkataspinterview.blogspot.com/default.aspx.
Don’t confuse IIS default pages with the Web Forms application start page in Visual Studio .NET. Visual Studio .NET requires that you set a start page for each project so that the development environment knows which page to display first during debugging. This setting has no effect on the IIS default page settings.
How do you copy the COM component to the server and register?
COM components generally provide a setup program to install or remove them from the system. If the component doesn’t provide a setup program, you can copy it to the server and register it using the MFC RegSvr32.exe utility, as shown below:
RegSvr32 MyComname.dll
What is GAC?
GAC stands for Global Assembly Cache. The global assembly cache (GAC) is a special subfolder within the Windows folder that stores the shared .NET components.
What is the difference between weak-named .NET components and strong-named .NET components?
This difference is how the names are stored within the assembly. Weak names are not guaranteed to be unique and thus cannot be shared without potentially causing conflicts. Strong names are digitally signed and provide a public key that ensures there are no conflicts. Furthermore, .NET components with strong names can’t call unmanaged code (such as COM components) and thus avoid potential conflicts with dependencies.
Weak-named .NET components must be individually copied to the /bin directories of the Web applications where they are used. Strong-named .NET components can be copied into the server’s GAC
What is the account under which the ASP.NET worker process run?
By default, the ASP.NET worker process runs using the ASPNET account, which is created when you install the .NET Framework. This account has limited privileges, which can cause permission-denied errors if your application writes files or tries to read files outside the current Web application’s boundaries.
What are the 3 ways in which you can modify the additional permissions required by your application?
1. Grant the ASPNET user access to the required files. To use this option, the server must be using the Windows NT file system (NTFS).
2. Change the group the ASPNET user belongs to.
3. Use impersonation to run the process as another user.
Why is it not a good idea to add ASPNET user to the Administrators group?
Adding the ASPNET user to the Administrators group gives your Web application full privileges on the server; however, it also poses a potential security risk because outside users might be able to manipulate your application to hack your server.
How do you impersonate the ASP.NET worker process?
To use impersonation to run the ASP.NET worker process as a user other than ASPNET, set the identity element’s impersonation attribute in the application’s Web.config file.
ASP.NET Interview Questions on Master Pages:
What are Master Pages in ASP.NET? or What is a Master Page?
ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.
What are the 2 important parts of a master page?
The following are the 2 important parts of a master page
1. The Master Page itself
2. One or more Content Pages
Can Master Pages be nested?
Yes, Master Pages be nested.
What is the file extension for a Master Page?
.master
How do you identify a Master Page?
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages.
Can a Master Page have more than one ContentPlaceHolder?
Yes, a Master Page can have more than one ContentPlaceHolder
What is a ContentPlaceHolder?
ContentPlaceHolder is a region where replaceable content will appear.
How do you bind a Content Page to a Master Page?
MasterPageFile attribute of a content page's @ Page directive is used to bind a Content Page to a Master Page.
Can the content page contain any other markup outside of the Content control?
No.
What are the advantages of using Master Pages?
1. They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
2. They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master page to create a menu that applies to all pages.
3. They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
4. They provide an object model that allows you to customize the master page from individual content pages.
What are the 3 levels at which content pages can be attached to Master Page?
At the page level - You can use a page directive in each content page to bind it to a master page
At the application level - By making a setting in the pages element of the application's configuration file (Web.config), you can specify that all ASP.NET pages (.aspx files) in the application automatically bind to a master page.
At the folder level - This strategy is like binding at the application level, except that you make the setting in a Web.config file in one folder only. The master-page bindings then apply to the ASP.NET pages in that folder.
What is @MasterType directive used for?
@MasterType directive is used to create a strongly typed reference to the master page.
Are controls on the master page accessible to content page code?
Yes, controls on the master page are accessible to content page code.
At what stage of page processing master page and content page are merged?
During the initialization stage of page processing, master page and content page are merged.
Can you dynaimically assign a Master Page?
Yes, you can assign a master page dynamically during the PreInit stage using the Page class MasterPageFile property as shown in the code sample below.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MasterPage.master";
}
Can you access non public properties and non public methods of a master page inside a content page?
No, the properties and methods of a master page must be public in order to access them on the content page.
From the content page code how can you reference a control on the master page?
Use the FindControl() method as shown in the code sample below.
void Page_Load()
{
// Gets a reference to a TextBox control inside
// a ContentPlaceHolder
ContentPlaceHolder ContPlaceHldr = (ContentPlaceHolder)Master.FindControl ("ContentPlaceHolder1");
if(ContPlaceHldr != null)
{
TextBox TxtBox = (TextBox)ContPlaceHldr.FindControl("TextBox1");
if(TxtBox != null)
{
TxtBox.Text = "TextBox Present!";
}
}
// Gets a reference to a Label control that not in
// a ContentPlaceHolder
Label Lbl = (Label)Master.FindControl("Label1");
if(Lbl != null)
{
Lbl.Text = "Lable Present";
}
}
Can you access controls on the Master Page without using FindControl() method?
Yes, by casting the Master to your MasterPage as shown in the below code sample.
protected void Page_Load(object sender, EventArgs e)
{
MyMasterPage MMP = this.Master;
MMP.MyTextBox.Text = "Text Box Found";
}
ASP.NET Interview Questions on Passport Authentication:
What is Passport Authentication?
Passport authentication identifies users via Microsoft Passport’s single sign-on service. Microsoft Passport is meant to provide Internet users with a single identity that they can use to visit a wide variety of Web sites that require authentication. Information about the user is available to your application through a profile that is stored with Microsoft.
What are the advantages of Passport authentication?
The advantages of Passport authentication are that the user doesn’t have to remember separate user names and passwords for various Web sites and that the user can maintain his or her profile information in a single location. Passport authentication also provides access to other Microsoft services, such as Passport Express Purchase.
What is passport software development kit (passport SDK)?
To use Passport authentication in your Web application, you must install the Passport SDK. The Passport SDK is free for preproduction development and testing. To deploy a site for public use, you must obtain an annual license from Microsoft.
How does Passport authentication work?
When a user accesses an application that implements Passport authentication, ASP.NET checks the user’s machine for a current passport authentication cookie. If none is found, ASP.NET directs the user to a Passport sign-on page. Once the user signs in, the Passport service authenticates the user, stores an authentication cookie on the user’s computer, and directs the user back to the originally requested Web page.
What are the steps to follow to use Passport authentication?
1. Install the Passport SDK. Passport is not included with Visual Studio, although the .NET Framework does include classes for working with the Passport SDK once it is installed.
2. Set the application’s authentication mode to Passport in Web.config. Set authorization to deny unauthenticated users.
3. Use the PassportAuthentication_OnAuthenticate event to access the user’s Passport profile to identify and authorize the user.
4. Implement a sign-out procedure to remove Passport cookies from the user’s machine.
Where is PassportAuthentication_OnAuthenticate event present?
PassportAuthentication_OnAuthenticate event is present in Global.asax.
SSL and HTTPS related ASP.NET Interview Questions
How do you provide Secure Communication over the world wide web?
Security is not just a matter of identifying users and preventing unauthorized users from accessing your Web applications, but it’s just as important to ensure that sensitive data sent across the Internet can’t be read by others.
To provide secure communication across the Internet, IIS supports a standardized means of encrypting and decrypting Web requests and responses. This cryptography requires that you request an encryption key called a server certificate from an independent third party called a certificate authority.
What is Secure Sockets Layer (SSL)?
The Secure Sockets Layer (SSL) is the standard means of ensuring that data sent over the Internet can’t be read by others. When a user requests a secure Web page, the server generates an encryption key for the user’s session and then encrypts the page’s data before sending a response. On the client side, the browser uses that same encryption key to decrypt the requested Web page and to encrypt new requests sent from that page.
Explain the process of secure communication using SSL?
Using SSL in your application requires special authorization from a recognized certificate authority. This authorization comes in the form of a server certificate, which you install in IIS to identify your server. The certificate authority licenses server certificates (for a fee) and acts as a clearinghouse to verify your server’s identity over the Internet.
When a user’s browser begins secure communications, it requests the server certificate and checks it against a list of trusted sites provided by the certificate authority. If the server certificate does not match one of the sites already authorized by the user, or if the server certificate does not match the Web address for which it was registered, or if there are any other problems with the server certificate, the browser displays a warning.
In this way, the certificate authority not only provides encryption for secure data transmission, but it also provides assurance to users that your Web site is authentic.
What is the largest certificate authority?
The largest certificate authority is VeriSign.
What are the steps to follow to use SSL in your Web application?
1. Generate a certificate request from IIS.
2. Request a certificate from a certificate authority.
3. Install the certificate on the server using IIS.
4. Install the certificate on browsers if you are using a test certificate.
5. Use the Secure Hypertext Transfer Protocol (HTTPS) when accessing secure pages in your application.
What should you do before you can request a server certificate from a certificate authority?
Before you can request a server certificate from a certificate authority, you must generate a certificate request from IIS. The certificate request contains encrypted information about your server that the certificate authority uses to identify your server over the Internet.
What are the steps to follow to generate a certificate request from the IIS?
1. Select Default Web Site in the console tree of the IIS, and then choose Properties from the Action menu. IIS displays the Default Web Site Properties dialog box.
2. Click the Directory Security tab in the Properties dialog box, and then click Server Certificate. IIS starts the Web Server Certificate Wizard.
3. Step through the wizard by reading each screen and clicking Next. The wizard instructions are straightforward.
4. When you click Finish at the end, the wizard creates an encrypted text file with the .cer file extension. That file is the certificate request that you send to the certificate authority.
Why do you have to select Default Web Site when generating a Certificate Request from IIS?
IIS requires that a certificate be created at the server root before secure communications can be created or configured for subordinate sites on the server. That’s why you have to select Default Web Site (or the root Web site if you have renamed it). After you have installed a server certificate at the root, you can repeat the process for subordinate sites if you want separate certificates for those sites.
What is the file extension of a server certificate?
.cer
What are the steps to follow to install the Certificate to enable SSL for your Web applications?
To install a server certificate in IIS:
1. Select Default Web Site in the console tree of the IIS snap-in, and then choose Properties from the Action menu. IIS displays the Default Web Site Properties dialog box.
2. Click the Directory Security tab in the Properties dialog box, and then click Server Certificate. IIS starts the Web Server Certificate Wizard.
3. Click Next, and select Process The Pending Request And Install The Certificate.
4. Click Next, and enter the name of the certificate file.
5. Click Next, and then click Finish to complete the installation.
What is the protocol on which secure pages are generally requested?
HTTPS, the protocol HTTPS is what initializes the secure communication. When you’ve begun secure communication, it continues until you specify a nonsecure site.
What are the steps to follow to make a web page secure in a web application?
To require secure communication for a Web page using IIS, follow these steps
1. Select the folder or file that requires secure communication, and then choose Properties from the Action menu. IIS displays the Properties dialog box.
2. Click the Directory Security tab, and then click Edit in the Secure Communications group. IIS displays the Secure Communications dialog box.
3. Select the Require Secure Channel (SSL) check box, and click OK.
Can a user access secure web page over HTTP protocol instead of HTTPS?
No, When you require secure communication for a Web page, that page can’t be viewed using HTTP. The user must type in or click a link using HTTPS, otherwise, access will be denied.
ASP.NET Forms Authentication related interview questions:
What is the advantage of using Forms authentication?
The advantage of using Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications, particularly commercial sites where customers order products, want to have access to user information. Forms authentication makes these types of applications easier to create.
List the steps to use Forms authentication in a web application?
1.Set the authentication mode in Web.config to Forms.
2.Create a Web form to collect logon information.
3.Create a file or database to store user names and passwords.
4.Write code to add new users to the user file or database.
5.Write code to authenticate users against the user file or database.
What happens when someone accesses a Web application that uses Forms authentication?
When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config. Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by the authentication settings in Web.config.
What is the difference between Windows authentication and Forms authentication?
The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those items against a list of authorized users.
What is the use of mode attribute in authentication element in a web.config file?
You use the mode attribute to specify the type of authentication your web application is using. Set the mode attribute to forms to enable Forms authentication.
What is the use of name attribute and loginUrl attribute of a forms element in a web.config file?
Name attribute of forms element is used to set the name of the cookie in which to store the user’s credential. The default is .authaspx. If more than one application on the server is using Forms authentication, you need to specify a unique cookie name for each application.
loginUrl attribute of forms element is used to set the name of the Web form to display if the user has not already been authenticated. If omitted, the default is Default.aspx.
What is protection attribute in a forms element used for in web.config file?
The protection attribute of a forms element of web.config file is used for setting how ASP.NET protects the authentication cookie stored on the user’s machine. The default is All, which performs encryption and data validation. Other possible settings are Encryption, Validation, and None.
What is timeout attribute in a forms element used for in web.config file?
Timeout attribute is used to set the number of minutes the authentication cookie persists on the user’s machine. The default is 30, indicating 30 minutes. ASP.NET renews the cookie automatically if it receives a request from the user and more than half of the allotted time has expired.
In which namespace the FormsAuthentication class is present?
System.Web.Security namespace
Which method checks the user name and password against the user list found in the credentials element of Web.config?
The FormsAuthentication class’s Authenticate method checks the user name and password against the user list found in the credentials element of Web.config.
Which method can be used to remove forms authentication cookie?
Use the signout() method of FormsAuthentication class to sign out when the user has finished with the application or when you want to remove the authentication cookie from his or her machine. For example, the following code ends the user’s access to an application and requires him or her to sign back in to regain access
FormsAuthentication.SignOut();
What is the advantage of Authenticating Users with a Database?
You can authenticate users based on a list in Web.config. The FormsAuthentication class’s Authenticate method is set up to read from web.config file automatically. That’s fine if user names and passwords are created and maintained by a system administrator, but if you allow users to create their own user names or change their passwords, you’ll need to store that information outside the Web.config file. This is because changing Web.config at run time causes the Web application to restart, which resets any Application state and Session state variables used by the application.
What are the advantages of storing user names and passwords in a database rather than a file?
You can store user names and passwords in any type of file; however, using a database has the following significant advantages:
1. User names can be used as primary keys to store other information about the user.
2. Databases can provide high performance for accessing user names and passwords.
3. Adding, modifying, and accessing records are standardized through SQL.
Can you encrypt user names and passwords stored in a file or a database?
Yes, you encrypt user names and passwords stored in a file or a database. You can encrypt them using the FormsAuthentication class’s HashPasswordForStoringInConfigFile method. This method uses the SHA1 or MD5 algorithms to encrypt data, as shown below:
Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");
Can you change authentication type in a subfolder's web.config file?
Authentication type (Windows, Forms, or Passport) can be set only at the application’s root folder. To change authentication type in a subfolder's web.config file, you must create a new Web application project and application starting point for that subfolder.
How can you control access to subfolders in a web application?
The authorization settings in the Web.config file apply hierarchically within the folder structure of a Web application. For instance, you might want to allow all users access to the root folder of a Web application but restrict access to Web forms (and tasks) available from a subfolder. To do this, set the authentication type in the root folder’s Web.config file, and then use the authorization element in the subfolder’s Web.config file to restrict access.
ASP.NET Interview Questions on windows authentication:
What is the advantage of using Windows authentication in a Web application?
Windows authentication uses the security features integrated into the Windows NT and Windows XP operating systems to authenticate and authorize Web application users. The advantage of Windows authentication is that your Web application
can use the exact same security scheme that applies to your corporate network - user names, passwords, and permissions are the same for network resources and Web applications. One of the key advantages of Windows authentication is that users who are logged on to the network don’t have to log on again to access the Web application.
What is the default authentication method when you create a new Web application project?
Windows authentication is the default authentication method when you create a new Web application project.
How do you allow or deny access to specific users using an authorization list from Web.config file, when using windows authentication?
When the application uses Windows authentication, ASP.NET checks the project’s Web.config authorization list to see which network users are allowed to access the application. The asterisk (*) and question mark (?) characters have special meaning in the authorization list. The * character indicates all users. The ? character indicates unauthenticated users.
To restrict access to specific users, list their names separated by commas in an element. When ASP.NET checks the authorization list in Web.config, it accepts the first match that it finds. Be sure to end the authorization list with a element to deny access to any nonapproved users.
What is Role-Based authorization in windows authentication?
Role-based authorization lets you identify groups of users to allow or deny based on their role in your organization. In Windows NT and Windows XP, roles map to names used to identify user groups. Windows defines several built-in groups, including Administrators, Users, and Guests. You can view, modify, or add groups using the Computer Management console
To allow or deny access to certain groups of users, add the element to the authorization list in your Web application’s Web.config file.
How do you get a User Identity?
Once a user is authenticated and authorized, your application can get information about the user by using the User object’s Identity property. The Identity property returns an object that includes the user name and role information, as shown in the following code:
private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = User.Identity.IsAuthenticated.ToString();
Label2.Text = User.Identity.Name;
Label3.Text = User.Identity.AuthenticationType;
}
How do you determine, what is the role of the current user?
The User object provides an IsInRole method to determine the role of the current user, as shown in the following example:
if(User.IsInRole("Administrators"))
{
// Do something.
}
Can you specify authorization settings both in Web.config and in IIS?
Yes, you can specify authorization settings both in Web.config and in IIS. The IIS setting is evaluated first and then the setting in Web.config is evaluated. In general, this means that the most restrictive setting will be used.
What is the user account under which an ASP.NET web application runs by default?
Web application runs under the identity of the ASPNET user account by default.
How can you set the web application to run under a specific user’s account?
You can set the application to run under a specific user’s account by setting the application’s identity element to enable impersonation
How can you see the impersonated identity under which code is executing?
To see the impersonated identity under which code is executing, use the WindowsIdentity class’s GetCurrent method, as shown in the sample code below
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
The identity element can be used with any type of authentication; however, it is most useful with Windows authentication because Windows authentication users have accounts with specific permissions.
Frequently asked ADO.NET Interview Questions:
How do you create an instance of SqlDataReader class?
To create an instance of SqlDataReader class, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.
//Error! Cannot use SqlDataReader() constructor
//to create an instance of SqlDataReader class
SqlDataReader ReaderObject = new SqlDataReader();
//Call the ExecuteReader method of the SqlCommand object
SqlCommand CommandObject = new SqlCommand();
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
Creating an instance of SqlDataReader class using SqlDataReader() constructor generates a compile time error - The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined.
How do you programatically check if a specified SqlDataReader instance has been closed?
Use the IsClosed property of SqlDataReader to check if a specified SqlDataReader instance has been closed. If IsClosed property returns true, the SqlDataReader instance has been closed else not closed.
How do you get the total number of columns in the current row of a SqlDataReader instance?
FieldCount property can be used to get the total number of columns in the current row of a SqlDataReader instance.
Give an example for executing a stored procedure with parameters?
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify to CommandObject that you intend to execute a Stored Procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Create an SQL Parameter object
SqlParameter ParameterObject = new SqlParameter();
//Specify the name of the SQL Parameter
ParameterObject.ParameterName = "Parameter1";
//Assign the Parameter value
ParameterObject.Value = "Some Value";
//Specify the Database DataType of the Parameter
ParameterObject.DbType = DbType.String;
//Specify the type of parameter - input-only, output-only, bidirectional
ParameterObject.Direction = ParameterDirection.Input;
//Associate the Parameter to the Command Object
CommandObject.Parameters.Add(ParameterObject);
//Open the connection
ConnectionObject.Open();
//Execute the command
int Records_Affected = CommandObject.ExecuteNonQuery();
//Close the Connection
ConnectionObject.Close();
What is the use of SqlParameter.Direction Property?
SqlParameter.Direction Property is used to specify the Sql Parameter type - input-only, output-only, bidirectional, or a stored procedure return value parameter. The default is Input.
How do you retrieve two tables of data at the same time by using data reader?
Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.
The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.
//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
ConnectionObject.Open();
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
{
while (ReaderObject.Read())
{
//Do Something
}
}
//Close the Reader
ReaderObject.Close();
//Close the Connection
ConnectionObject.Close();
What are the advantages of using SQL stored procedures instead of adhoc SQL queries in an ASP.NET web application?
Better Performance : As stored procedures are precompiled objects they execute faster than SQL queries. Every time we run a SQL query, the query has to be first compiled and then executed where as a stored procedure is already compiled. Hence executing stored procedures is much faster than executing SQL queries.
Better Security : For a given stored procedure you can specify who has the rights to execute. You cannot do the same for an SQL query. Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements.
Reduced Network Traffic : Stored Procedures reside on the database server. If you have to execute a Stored Procedure from your ASP.NET web application, you just specify the name of the Stored Procedure. So over the network you just send the name of the Stored Procedure. With an SQL query you have to send all the SQL statements over the network to the database server which could lead to increased network traffic.
Can you update the database using DataReader object?
No, You cannot update the database using DataReader object. DataReader is read-only, foward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record.
What is the difference between a DataReader and a DataSet?
DataReader
1. DatReader works on a Connection oriented architecture.
2. DataReader is read only, forward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record. So using a DataReader you read in forward direction only.
3. Updations are not possible with DataReader.
4. As DataReader is read only, forward only it is much faster than a DataSet.
DataSet
1. DataSet works on disconnected architecture.
2. Using a DataSet you can move in both directions. DataSet is bi directional.
3. Database can be updated from a DataSet.
4. DataSet is slower than DataReader.
Give an example scenario of using a DataSet and a DataReader?
If you want to just read and display the data(No updates, deletes, or inserts) then use a DataReader.
If you want to do a batch inserts, updates and deletes then use a DataSet.
Basic ADO.NET Interview Questions
What is Microsoft ADO.NET?
Visual Studio
.NET provides access to databases through the set of tools and namespaces collectively referred to as Microsoft ADO.NET
What are the 3 major types of connection objects in ADO.NET?
OleDbConnection object : Use an OleDbConnection object to connect to a Microsoft Access or third-party database, such as MySQL. OLE database connections use the OleDbDataAdapter object to perform commands and return data.
SqlConnection object : Use a SqlConnection object to connect to a Microsoft SQL Server database. SQL database connections use the SqlDataAdapter object to perform commands and return data.
OracleConnection object : Use an OracleConnection object to connect to Oracle databases. Oracle database connections use the OracleDataAdapter object to perform commands and return data. This connection object was introduced in Microsoft .NET Framework version 1.1.
List the 4 common ADO.NET Namespaces?
System.Data : Contains Classes, types, and services for creating and accessing data sets and their subordinate objects
System.Data.SqlClient : Contains Classes and types for accessing Microsoft SQL Server databases
System.Data.OracleClient : Contains Classes and types for accessing Oracle databases (Microsoft .NET Framework version 1.1 and later)
System.Data.OleDb : Contains Classes and types for accessing other databases
List all the steps in order, to access a database through ADO.NET?
1. Create a connection to the database using a connection object.
2. Invoke a command to create a DataSet object using an adapter object.
3. Use the DataSet object in code to display data or to change items in the database.
4. Invoke a command to update the database from the DataSet object using an adapter object.
5. Close the database connection if you explicitly opened it in step 2 using the Open method. Invoking commands without first invoking the Open method implicitly opens and closes the connection with each request.
Why will you usually create an ASPNET user account in the Database for an ASP.NET web application?
Web applications run using the ASPNET user account. The SQL database administrator will have to set up this account and grant it permissions before your Web application will have access to a SQL database. For file-based databases, such as Microsoft Access, you must grant permissions on the database file to the ASPNET user account using Windows file security settings.
What is the difference between DataReader and DataAdapter?
1. Data Reader is read only forward only and much faster than DataAdapter.
2. If you use DataReader you have to open and close connection explicitly where as if you use DataAdapter the connection is automatically opened and closed.
3. DataReader is connection oriented where as Data Adapter is disconnected
Can you inherit from SqlConnection Class?
No, you cannot inheirt from SqlConnection Class. SqlConnection Class is a sealed class. It is a compile time error.
Will the connection be closed, if the SqlConnection object goes out of scope?
No, If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose.
What happens if connection pooling is enabled?
If connection pooling is enabled and when you call Close or Dispose methods, then the connection is returned to the connection pool. This connection can then be resused.If connection pooling is disabled and when you call Close or Dispose methods, the underlying connection to the server is actually closed.
How do you ensure that the database connections are always closed?
To ensure that the database connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (SqlConnection ConnectionObject = new SqlConnection())
{
ConnectionObject.Open();
//The database connection will be closed when the control exits the using code block
}
How do you read an XML file into a DataSet?
Using the DataSet object’s ReadXML method.
When do you use ExecuteReader, ExecuteNonQuery, ExecuteScalar methods?
If the command or stored procedure that is being executed returns a set of rows, then we use ExecuteReader method.
If the command or stored procedure that is being executed returns a single value then we use ExecuteScalar method.
If the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use ExecuteNonQuery method. ExecuteNonQuery method returns an integer specifying the number of rows inserted, deleted or updated.
Can your class inherit from SqlCommand Class?
No, you cannot inheirt from SqlCommand Class. SqlCommand Class is a sealed class. It is a compile time error.
Give an example that shows how to execute a stored procedure in ADO.NET?
using (SqlConnection ConnectionObject = new SqlConnection())
{
//Specify the name of the stored procedure to execute and the Connection Object to use
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify the SQL Command type is a stored procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Open the connection
ConnectionObject.Open();
//Execute the Stored Procedure
int RecordsAffected = CommandObject.ExecuteNonQuery();
}
Can you reuse a SqlCommand object?
Yes, you can reset the CommandText property and reuse the SqlCommand object.
What are the methods that can ensure asynchronous execution of the Transact-SQL statement or stored procedure?
BeginExecuteNonQuery
BeginExecuteReader
What is SqlCommand.CommandTimeout Property used for?
CommandTimeout Property is used to Get or set the wait time before terminating the attempt to execute a command and generating an error.
//Specify the CommandTimeout property value
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Wait for 10 seconds to execute the Stored procedure
CommandObject.CommandTimeout = 10;
The time is in seconds. The default is 30 seconds.
Interview Questions on ASP.NET controls
What are the 2 types of controls that you can use on a webform in ASP.NET?
Web Server Controls
HTML Controls
What’s the difference between Server controls and HTML controls?
1. Server controls can trigger control-specific events on the server.HTML controls can trigger only page- level events on server (postback).
2. Data entered in a server control is maintained across requests. Server controls retain state.Data is not maintained in an HTML control. Data must be saved and restored using page-level scripts.
3. The Microsoft .NET Framework provides a set of properties for each server control. Properties allow you to change the server control’s appearance and behavior within server-side code.HTML controls have HTML attributes only.
4. Server controls automatically detect browser and adapt display as appropriate.HTML controls do not adapt automatically. You must detect browser in code or write for least common denominator.
What are the 2 Layouts supported by a Web form in ASP.NET?
Grid layout - Controls are placed exactly where you draw them, and they have absolute positions on the page. Use grid layout for Microsoft Windows–style applications, in which controls are not mixed with large amounts of text. Pages using grid layout will not always display correctly in non-Microsoft browsers.
Flow layout - This layout positions controls relative to other elements on the page. If you add elements at run time, the controls that appear after the new element move down. Use flow layout for document-style applications, in which text and controls are intermingled.
When do you choose between GridLayout and Flow layout for Web forms?
You use GridLayout for Web forms that have a fixed appearance. You use FlowLayout for Web forms that incorporate text and controls.When you create controls with GridLayout, Visual Studio adds style attributes to each control that set the position of the control.When you create controls with FlowLayout, Visual Studio omits the style attribute.
Give 3 reasons why we use HTML controls over Server Controls?
Migration from earlier versions of Active Server Pages (ASP) : You can load an ASP application into Visual Studio and revise it gradually, rather than rewrite it completely. Earlier versions of ASP supported only HTML elements, and these elements become HTML controls when you load the project in Visual Studio .NET.
Not all controls require server-side events or state management : This is particularly true when you’re doing data binding. Bound items are usually refreshed from the data source with each request, so it’s more efficient not to maintain state information for bound controls. This means that you can use HTML controls or turn off state management for bound server controls.
You have complete control over what is rendered with HTML controls : ASP.NET adjusts the appearance of server controls based on the browser making the request. HTML controls are not adjusted, so you have direct control over their appearance.
How can you prevent users from editing Text in TextBox control on a web form?
By making the TextBox a readonly TextBox. To make a TextBox readonly set the ReadOnly property to True.
How do you convert an ASP.NET TextBox to accept passwords?
To convert and ASP.NET TextBox to accept passwords set the TextMode property to "Password"
What happens when you set the AutoPostBack property of a TextBox to true?
When AutoPostBack property is set to True, the TextBox control fires a TextChanged postback event when the user leaves the TextBox control after changing the contents. By default, this property is set to False and the TextChanged event is cached until some other postback event occurs.
What are the 3 values that a TextMode property of TextBox can have?
SingleLine : Single Line TextBox
MultiLine : Multi Line TextBox(scrollable)
Password : When set to Password, the text box displays dots in place of the characters typed.
How do you limit the number of characters entered by a user in the ASP.NET TextBox?
By setting the MaxLength property of the TextBox. If you set the MaxLength property to 10, a user can enter only 10 characters into the TextBox.
ASP.NET Interview Questions on Cookies:
What are Cookies in ASP.NET?
Cookies are small pieces of information stored on the client computer.Use cookies to store small amounts of information on the client’s machine. Web sites often use cookies to store user preferences or other information that is client-specific. Because cookies can be refused, it is important to check whether the browser allows them before you try to create them.They are limited to storing only character data and they are limited to 4K in size.
What are different types of Cookies?
Session Cookies
Persistent Cookies
What are Session Cookies?
Session cookies are stored in-memory during the client browser session. When the browser is closed the session cookies are lost.
How can you create Session Cookies?
You can create session cookies by calling the Add method of the Cookies collection on the Response object. The Cookies collection contains individual cookie objects of type HttpCookie.
//Code to create a UserName cookie containing the name David.
HttpCookie CookieObject = new HttpCookie("UserName", "David");
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
Request.Cookies["UserName"].Value;
What is the difference between Session Cookies and Persistent Cookies?
Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine that there is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site.
What are Persistent Cookies used for?
Persistent cookies are generally used to store information that identifies a returning user to a Web site. Typical information found in Persistent Cookies includes user names or user IDs.
How do you create a Persistent Cookie?
You create a persistent cookie the same way as session cookies except that you set the Expires property to a Date in the future which will store the Cookie to the client computer harddrive.
//Code to create a UserName Persistent Cookie that lives for 10 days
HttpCookie CookieObject = new HttpCookie("UserName", "David");
CookieObject.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
Request.Cookies["UserName"].Value;
What is Cookie Dictionary?
A cookie dictionary is a single cookie object that stores multiple pieces of information. You use the Values property to access and assign new values to the cookie dictionary.
Give an example using Cookie Dictionary?
//Code to create a Cookie Dictionary
HttpCookie CookieObject = new HttpCookie("UserPreference");
//Use the Values property to assign new values to the cookie dictionary
CookieObject.Values.Add("UserName", "David");
CookieObject.Values.Add("Country", "USA");
CookieObject.Values.Add("PreviousVisit", DateTime.Now.ToString());
CookieObject.Expires = DateTime.MaxValue;
//Add the Cookie to the client machine using the Response object
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
HttpCookie ObjectCookie = Request.Cookies["UserPreference"];
string UserName = ObjectCookie.Values["UserName"];
string Country = ObjectCookie.Values["Country"];
string PreviousVisit = ObjectCookie.Values["PreviousVisit"];
What are the advantages of Using Cookies?
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).
What are the disadvantages of Using Cookies?
1. Users can delete a cookies.
2. Users browser can refuse cookies,so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.
How do you create a Cookie that never expires?
To create a Cookie that never expires set the Expires property of the Cookie object to DateTime.MaxValue.
Are Cookies secure?
No, Cookies are not secure. You must pay attention to the type of data you store in cookies.
1. Cookies are not designed to store critical information so storing passwords in a cookie is a bad idea.
2. Keep the lifetime of a cookie as short as practically possible.
3. Encrypt cookie data to help protect the values stored in the cookie.
ASP.NET Events related Interview Questions
What are the different levels at which events can occur in an ASP.NET web application?
Web application events occur at the application, page, and server control levels
Give some examples for application level events?
1. Application_Start
Occurs when the first user visits a page within your Web application.
2. Application_End
Occurs when there are no more users of the application.
3. Application_BeginRequest
Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application.
4. Application_EndRequest
Occurs when at the end of each request to the server.
5. Session_Start
Occurs when a new user visits a page within your application.
6. Session_End
Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file.
7. Application_Error
Occurs when when there is an unhandled exception in an application.
Where are the application level event handlers present in an ASP.NET web application?
Application level event handlers are present in Global.asax of an ASP.NET web application
What is the difference between Application and Session Events?
At an application level we can have Application and Session events. Use Application events to initialize objects and data that you want to make available to all the current sessions of your Web application. Use Session events to initialize data that you want to keep throughout individual sessions, but that you don’t want to share between sessions.
Give an example of how to use Application and Session events?
To see how Application and Session events occur, add the following code to the Global.asax file in a Web forms project.
void Application_Start(object sender, EventArgs e)
{
// Create Application state variables.
Application["AppCount"] = 0;
Application["SessCount"] = 0;
// Record application start.
Application["AppCount"] = (int)Application["AppCount"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Count sessions.
Application["SessCount"] = (int)Application["SessCount"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement sessions.
Application["SessCount"] = (int)Application["SessCount"] - 1;
}
Add the following code to WebForm1.aspx file in a Web forms project and set WebForm1 as start up page.
protected void Page_Load(object sender, EventArgs e)
{
// Display Application count.
Response.Write("Number of applications: " +
Application["AppCount"] + "
");
// Display session count.
Response.Write("Number of sessions: " +
Application["SessCount"] + "
");
}
To demonstrate the events, run the preceding code, and then start a new instance of the browser and navigate to the address. Each new instance of the browser increments the session count, but the application count stays at 1.
How long a webform instance is available on the web server?
Web forms live for barely a moment. When we request a webform from the browser, the applications executable creates an instance of the requested Web form, generates the HTML to respond to the request, and posts that response to the browser. It then destroys the instance of the Web form.
When the client browser has the generated HTML, the user can type text in boxes, select options, and perform other tasks until triggering a postback event, such as a button click. Postback events cause the browser to send the page’s data (view state) back to the server for event processing. When the server receives the view state, it creates a new instance of the Web form, fills in the data from the view state, and processes any events that occurred. As soon as the server has finished, it posts the resulting HTML back to the browser and destroys the instance of the Web form.
Give some examples for page level events and when they occur?
1. Page_Init
During Page_Init the server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.
2. Page_Load
During Page_Load the server controls are loaded in the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.
3. Page_PreRender
During Page_PreRender the application is about to render the Page object.
4. Page_Unload
During Page_Unload the page is unloaded from memory.
5. Page_Disposed
During Page_Disposed the Page object is released from memory. This is the last event in the life of a Page object.
6. Page_Error
Page_Error event is raised when an unhandled exception occurs.
7. Page_AbortTransaction
Page_AbortTransaction is raised when a transaction is aborted.
8. Page_CommitTransaction
Page_CommitTransaction is raised when a transaction is commited.
9. Page_DataBinding
Page_DataBinding occurs when a server control on the page binds to a data source.
What is the order in which Page level events occur?
Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed
What page property is used to differentiate between a postback and initial get request of a page?
IsPostback property of the Page class.
What are the 3 types of Server Control Events?
Server controls, such as a Button, TextBox, and DropDownList, each have their own sets of events that occur in response to user actions. However, not all server control events are created equal. There are three types of server control events as listed below.
Postback events :
These events cause the Web page to be sent back to the server for immediate processing. Postback events affect perceived performance because they trigger a round-trip to the server. A Button control triggers a postback event. A dropdowinlist can also trigger a post back if the AutoPostBack property of the DropDownList is set to true, else a dropdownlist triggers a cached event. The same is the case with a TextBox.
Cached events :
These events are saved in the page’s view state to be processed when a postback event occurs. A DropDownList and a TextBox can trigger a cached event if the AutoPostBack property is set to false.
Validation events :
These events are handled on the page without posting back or caching. The validation server controls use these types of events.
How can you convert a Cached event of control to a post back event?
You can convert a Cached event of control to a post back event by setting the AutoPostBack property to true.
What is the order in which events are executed?
The validations controls are evaluated before the page is posted back to the server. When the page is posted back, the Page_Init and Page_Load events are handled, then cached events are handled, and finally the event that caused the postback is processed. Among cached events, the event order is determined by the order of the controls on the Web form.
Interview Questions on ASP.NET Exception Handling
What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.
What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation.
try
catch
finally
2. Use error events to deal with exceptions within the scope of an object.
Page_Error
Global_Error
Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.
Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.
Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.
What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.
How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the catch statement.
Will the following code block compile?
try
{
throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
}
No, a compile time error A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').
Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample, FileNotFoundException should be placed before the general Exception catch block.
What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception classes based on the ApplicationException class. For example, the following code defines a class for the UserLoggedOnException:
public class UserLoggedOnException : System.ApplicationException
{
// Exception constructor (overloaded).
public UserLoggedOnException()
: this("The user is already logged on to the server", null)
{
}
public UserLoggedOnException(string message)
: this(message, null)
{
}
public UserLoggedOnException(string message, Exception inner)
: base(message, inner)
{
}
}
The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception class provides only its own constructor to set the default message to display. This is a standard practice.
What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application, ASP.NET fires the error events shown below.
Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the following ways:
As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exception-handling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception in a log as part of an ongoing effort to improve your application.
Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the ClearError method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
// Get the error.
Exception ex = Server.GetLastError();
// Store the message in a session object.
Session["Error"] = ex.Message;
// Clear the error message.
Server.ClearError();
// Redisplay this page.
Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:
Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
// Display error. if any.
if (Session["Error"] != null)
{
litError.Text = "The following error occurred:
" +
Session["Error"].ToString();
// Clear the Session state variable.
Session["Error"] = null;
}
}
Can you have a try block without a catch or a finally block?
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either a catch block or a finally block or both.
Is the following code legal?
try
{
Response.Write("Try block executed");
}
finally
{
Response.Write("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.
What is wrong with using the following type of exception handler?
catch(Exception E)
{
//Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.
Will the second catch block handle the exception thrown by the first catch block?
try
{
throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
throw new Exception();
}
catch(Exception E)
{
Response.Write(E.Message);
}
No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.
What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
throw new Exception();
try
{
Response.Write("Hello");
}
catch (Exception E)
{
Response.Write(E.Message);
}
}
The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block.
Managed Code and Unmanaged Code related ASP.NET Interview Questions:
What is Managed Code and Unmanaged Code?
Microsoft ASP.NET Web applications run under the control of the common language runtime (CLR). The CLR controls how the application’s assembly executes, allocates, and recovers memory; therefore, ASP.NET applications are said to use managed code. In contrast, most other Windows executables use unmanaged code because the executable itself determines how memory is used.
Examples of unmanaged code include the Microsoft Win32 API, legacy DLLs and EXEs created for Windows applications prior to the Microsoft .NET Framework, and COM objects.
What is Platform Invoke or pinvoke?
The process of executing native code from within a .NET assembly is called platform invoke, or pinvoke for short. You use platform invoke to call the Win32 API directly, to access existing (legacy) DLLs your company uses, or to access procedures compiled to native code for performance reasons.
What are the steps to follow to use Platform Invoke?
To use platform invoke, follow the following steps:
1. Import the System.Runtime.InteropServices namespace.
2. Declare the unmanaged procedure using the DllImport attribute or the Declare statement.
3. Map the data types of the procedures parameters to the equivalent .NET types.
4. Call the unmanaged procedure and test its return value for success.
5. If the procedure did not succeed, retrieve and handle the exception code using the Marshal object’s GetLastWin32Error method.
What are the limitations of using Unmanaged Code from within a .NET assembly?
Performance : Although native-code DLLs can perform some operations more quickly than equivalent code managed by the CLR, these benefits might be offset by the time it takes to marshal the data to pass between the unmanaged procedure and the .NET assembly.
Type safety : Unlike .NET assemblies, unmanaged procedures might not be type-safe. This can affect the reliability of your .NET application. In general, reliability is a paramount concern with ASP.NET Web applications.
Code security : Unmanaged procedures do not use the .NET Framework’s model for code security.
Versioning:Unmanaged code does not support .NET versioning; therefore, assemblies that call unmanaged procedures might lose the benefit of being able to coexist with other versions of the same assembly.
What are COM objects?
COM objects are another type of unmanaged code that you can use from .NET assemblies. Because COM is widely used, Visual Studio includes built-in tools for importing and using COM objects within .NET assemblies. Visual Studio also includes the option of automatically registering .NET class library assemblies for use from COM.
List the steps in order, to use a COM object from a .NET assembly in Visual Studio?
1. Install and register the COM object on your system.
2. Open the .NET project in Visual Studio, and add a reference to the COM object, as shown in diagram below. If the COM object does not appear on the COM tab of the Add Reference dialog box, you can add a reference directly to the executable by clicking Browse.
3. Create an instance of the COM object in code, and use it as you would any other object.
What happens when you add a reference to a COM object from with in a dot net application?
When you add a reference to a COM object, Visual Studio automatically generates an interop assembly for the object and places it in the project’s /bin folder. The interop assembly is created from the COM object’s type information and contains the metadata that the CLR uses to call the unmanaged code in the COM object. You can then use COM objects from within .NET code the same way that you use .NET classes.
You can view this interop assembly using the Microsoft Intermediate Language Disassembler (Ildasm.exe) included in the .NET Framework.
Can we create a .NET object for use from COM?
Yes, Visual Studio can automatically generate type library information and register a .NET class library assembly for use from COM. These automatic tools do not work for ASP.NET Web applications, so you must isolate the code you want to use from COM in its own Class Library project.
How do you hide Public .NET Classes and other public members from COM?
In some cases, you might want to hide selected .NET classes from COM but keep them public for use from other .NET assemblies. The ComVisible attribute allows you to select which public .NET classes and members are included in the generated type library. This attribute applies hierarchically for the assembly, class, and member levels.
How do you handle exceptions between .NET and COM?
.NET handles errors through exception classes. COM handles errors through 32-bit data types called HRESULTs. All of the .NET exception classes include HResult properties that map to COM HRESULT codes.
If an exception occurs in a .NET object, the exception is automatically mapped to the appropriate HRESULT and returned to COM. Similarly, if an exception occurs in a COM object, the COM HRESULT is mapped to the appropriate exception class, which is returned to .NET, where it can be handled just like any other exception.
If you are creating your own .NET exception classes for use with COM, be sure to set the class’s HResult property so that the exception can be handled within COM.
What are the technical limitations of COM Interop?
The .NET Framework was developed to address the limitations of COM. Because of this evolution, there are limits to the .NET features that you can use from COM. The following list describes these limits:
Static members : COM requires objects to be created before use, so it does not support .NET Static members.
New members : COM flattens the inheritance tree of .NET objects, so members in a derived class that hides members inherited from a base class are not callable.
Constructors with parameters : COM can’t pass parameters to an object’s constructor.
What are the practical limitations of using COM objects?
The following are the practical limitations of using COM objects from .NET:
Shared solutions might not allow COM objects : ASP.NET host service providers that use nondedicated servers can limit or prohibit the installation of COM objects on their servers.
COM objects are prone to memory leaks : COM uses reference counting to determine when to destroy objects and free memory. It is possible for this reference count to become incorrect, leaving objects in memory indefinitely.
Type libraries might be inaccurate : Because COM separates the object’s description from its implementation, it’s possible for this description to not accurately reflect the object. In this case, the generated interop assembly will also include those inaccuracies.
COM is unmanaged code : All the limitations of unmanaged code apply to COM objects as well.
Interview Questions on ASP.NET Page navigation techniques :
What are different page navigation techniques in ASP.NET?
Hyperlink control : Navigate to another page.
Response.Redirect : Navigate to another page from code. This is equivalent to clicking a hyperlink.
Server.Transfer : End the current Web form and begin executing a new Web form. This method works only when navigating to a Web Forms page (.aspx).
Server.Execute : Begin executing a new Web form while still displaying the current Web form. The contents of both forms are combined. This method works only when navigating to a Web Forms page (.aspx).
Window.Open script method : Display a page in a new browser window on the client.
What is the difference between Response.Redirect and Server.Transfer?
1. When we use Server.Transfer the redirection happens on the server where as when we use Response.Redirect the redirection happens from the browser.
2. Server.Transfer is faster as there is no round trip involved while navigating from one webform to another webform. Response.Redirect is slower than Server.Transfer as there is round trip from the server to the client browser.
3. Server.Transfer works only with .aspx files where as Response.Redirect works with .aspx and .Htm pages.
4. Server.Transfer will work with files on the same web server. You can't use Server.Transfer to send the user to an external site where as Response.Redirect can do that.
5. Server.Transfer does not update the URL in the browser. For example when you navigate from WebForm1.aspx to WebForm2.aspx using Server.Transfer the URL in the browser still shows WebForm1.aspx while you are actually looking at WebForm2.aspx. Response.Redirect updates the URL in the browser.
What is the use of Server.Execute method?
Server.Execute method is used to process a second Web form without leaving the first Web form. This technique lets you direct the results from a Web form to a region on the current page.
Is it possible to send a webform's QueryString, ViewState, and event procedure information to another webform?
Yes, we can use Server.Transfer or Server.Execute to send a webform's QueryString, ViewState, and event procedure information to another webform.
For this to work you have to set the preserveForm argument to True.To be able to read one Web form’s ViewState from another, you must first set the EnableViewStateMac attribute in the Web form’s Page directive to False. By default, ASP.NET hashes ViewState information, and setting this attribute to False disables that hashing so that the information can be read on the subsequent Web form.
Interview Questions on Query Strings in ASP.NET
Give an example of using querystrings to send data from one page to another?
Query strings are a very simple and popular technique to pass data from one Web page to the next. You send data as part of the URL. In the below example FName and LName are sent as part of the URL. In the page load of QueryStrings2.aspx we use Request.QueryString to read the values. As we are sending more than one query string we use the & symbol to seperate query strings.
//Code to send query strings FName and LName as part of the URL
QueryStrings2.aspx?FName=David&LName=Boon
protected void Page_Load(object sender, EventArgs e)
{
//Code to read Query String values
string FirstName = Request.QueryString["FName"];
string LastName = Request.QueryString["LName"];
Response.Write("Data from QueryStrings1.aspx : " + FirstName + ", " + LastName);
}
Give an example to send Query Strings from code?
You can send query strings from server side code using the Response.Redirect() method as shown below.
Response.Redirect("QueryStrings2.aspx?FName=David&LName=Boon");
What are the advantages of using Query Strings?
1. Query strings are easy to implement.
2. Browser support for passing values in a query string is nearly universal.
3. Query strings are contained in the HTTP request for a specific URL and do not require server resources.
What are the disadvantages of using querystrings to send data from one page to another?
1. Query strings are insecure because the information in the query string is directly visible to the user on the address line in the browser.
2. Many browsers impose a 255 URL character limit which can limit their flexibility.
ASP.NET Interview Questions on web application Security :
What is the difference between Authentication and Authorization?
Authentication is the process of identifying users. Authorization is the process of granting access to those users based on identity. Together, authentication and authorization provide the means to keeping your Web application secure from intruders.
What is Anonymous access?
Anonymous access is the way most public Web sites work. Sites containing public information allow anyone to see that information, so they don’t authenticate users. ASP.NET Web applications provide anonymous access to resources on the server by impersonation. Impersonation is the process of assigning a user account to an unknown user.
What is the account that is associated with Anonymous access?
By default, the anonymous access account is named IUSER_machinename. You use that account to control anonymous users’ access to resources on the server.
What is the default user account under which an ASP.NET web application run on a web server?
Under the default settings, ASP.NET uses the ASPNET account to run the Web application. This means that if the application attempts to perform any tasks that are not included in the ASPNET account’s privileges, a security exception will occur and access will be denied.
How do you restrict the access of anonymous users?
You restrict the access of anonymous users by setting Windows file permissions. To be secure, your server must use the Microsoft Windows NT file system (NTFS). The earlier FAT or FAT32 file systems do not provide file-level security.
What are the 3 major ways to authenticate and authorize users within an ASP.NET Web application?
Windows authentication : Identifies and authorizes users based on the server’s user list. Access to resources on the server is then granted or denied based on the user account’s privileges. This works the same way as regular Windows network security.
Forms authentication : Directs users to a logon Web form that collects user name and password information, and then authenticates the user against a user list or database that the application maintains.
Passport authentication : Directs new users to a site hosted by Microsoft so that they can register a single user name and password that will authorize their access to multiple Web sites. Existing users are prompted for their Microsoft Passport user name and password, which the application then authenticates from the Passport user list.
What is the namespace where all security related classes are present?
System.Web.Security
What type of authentication can be used for Public Internet Web application?
Anonymous access. This is the common access method for most Web sites. No logon is required, and you secure restricted resources using NTFS file permissions.
What type of authentication can be used for Intranet Web application?
Windows authentication. Windows authentication authenticates network users through the domain controller. Network users have access to Web application resources as determined by their user privileges on the server.
What type of authentication can be used for Private corporate Web application?
Windows authentication. Corporate users can access the Web application using their corporate network user names and passwords. User accounts are administered using the Windows network security tools.
What type of authentication can be used for Commercial Web application?
Forms authentication. Applications that need to collect shipping and billing information should implement Forms authentication to gather and store customer information.
What type of authentication can be used for Multiple commercial Web applications?
Passport authentication. Passport authentication allows users to sign in once through a central authority. The user’s identity is then available to any application using the Passport SDK. Customer information is maintained in a Passport profile, rather than in a local database.
Can you use ASP.NET Authentication with HTM and HTML Files?
The three ASP.NET authentication modes apply to files that are part of the Web application. That includes Web forms (.aspx), modules (.asax), and other resources that are processed through the Web application’s executable. It does not automatically include HTML pages (.htm or .html). Those pages are handled by Internet Information Services (IIS), rather than ASP.NET. If you want to authenticate users who access HTML pages from within your Web application using Windows, Forms, or Passport authentication modes, you must map those files to the ASP.NET executable.
How do map .htm and .html files to the ASP.NET executable using the IIS snap-in?
To map .htm and .html files to the ASP.NET executable using the IIS snap-in, follow these steps:
1. In the IIS snap-in, select the folder containing your Web application, and then choose Properties from the Action menu. IIS displays the Properties dialog box.
2. Click the Home Directory or Virtual Directory tab, and then click Configuration. IIS displays the Application Configuration dialog box, as shown in the diagram below.
3. Click Add. IIS displays the Add/Edit Application Extension Mapping dialog box, as shown in the diagram below.
4. Click Browse, and select the aspnet_isapi.dll file. That file is stored in the Windows Microsoft .NET Framework directory; the path will be something like C:\Windows\Microsoft.NET\Framework\versionnumber\aspnet_isapi.dll.
5. Type .htm in the File Extension box, and click OK.
6. Repeat steps 3 through 5 for the .html file extension. Click OK to close the IIS dialog boxes when you’ve finished.
ASP.NET Session State and Application State Interview Questions:
What is a Session?
A Session is a unique instance of the browser. A single user can have multiple instances of the browser running on his or her machine. If each instance visits your Web application, each instance has a unique session.A session starts when a user accesses a page on a Web site for the first time, at which time they are assigned a unique session ID. The server stores the user's session ID in the Session.SessionID property.
What is the default session timeout period?
20 minutes.
Where do you generally specify the Session Timeout?
You specify the Session Timeout setting in the web.config file.
Can you specify Session Timeout in a code behind file?
Yes, can specify the Session.Timeout property as shown below in a code behind file.
Session.Timeout = 10;
How do you end a user session?
You can call the Session.Abandon() method to end a user session. If a user then tries to access a page the server will assign them a new session ID and it will clear all the previous session variables. You'll typically use Session.Abandon() on log-out pages.
What type of data can you store in Application State and Session State variables?
Application State and Session State variables are used to store data that you want to keep for the lifetime of an application or for the lifetime of a session. You can store any type of data in the Application or Session state, including objects.
Are Application State or Session State variables type safe?
No, Application and Session state variables are created on the fly, without variable name or type checking.
Do maintaining Session state affects performance?
Yes
Can you turn of Session state?
Yes, Session state can be turned off at the application and page levels.
Are Application state variables available throughout the current process?
Yes, Application state variables are available throughout the current process, but not across processes. If an application is scaled to run on multiple servers or on multiple processors within a server, each process has its own Application state.
How do you disable Session state for a Web form?
To turn Session state off for a Web form set EnableSessionState property of the Page to False.
How do you turn Session state off for an entire web application?
In the Web.config file, set the sessionstate tag to False.
What are Application State variables?
Application State variables are global variables that are available from anywhere in the application. All Sessions can access Application State variables.
How to add and remove data to Application State Variables?
//Code to add data to Application State
Application.Add("AppName", "Sample");
//Code to remove data from Application State
Application.Remove("AppName");
How do you remove all Application State Variables data?
//Code to remove all Application State Variables data
Application.RemoveAll();
Techniques to send data from one web form to another web form
What are the different techniques to send data from one web form to another web form?
1. Query strings :
Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so they should not contain secure information such as passwords.
2. Cookies :
Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility.
3. Session state :
Use Session state variables to store items that you want keep local to the current session (single user).
4. Application state :
Use Application state variables to store items that you want be available to all users of the application.
ASP.NET Interview Questions on Tracing
What is an exception log?
An exception log is a list of handled exceptions that occur while your application is running. Reviewing the exception log periodically helps you verify that exceptions are being handled correctly, are not occurring too frequently, and are not preventing users from accomplishing tasks with your application.
What is Tracing and what are the adavantages of using tracing to log exceptions?
Tracing is a technique for recording events, such as exceptions, in an application. There have always been ways to record errors in an application - usually by opening a file and writing error messages to it. But tracing offers the following significant advantages:
Standardization:Building tracing into the .NET Framework ensures that programming techniques are the same across all the applications you develop with the .NET Framework.
Built-in Web support:ASP.NET extends the .NET Framework tools by including information related to the performance and behavior of Web requests.
Configuration:You can turn tracing on and off using settings in your application’s configuration file. You don’t have to recompile your application to enable or disable tracing.
Performance:While disabled, tracing statements do not affect application performance.
How do you turn tracing on and off for an ASP.NET web application?
Tracing can be turned on or off for an entire Web application or for an individual page in the application:
1. To turn tracing on for an entire application, in the application’s Web.config file, set the trace element’s Enabled attribute to True.
Or
2. To turn tracing on for a single page, set the DOCUMENT object’s Trace property to True in the Visual Studio
.NET Properties window. This sets the @ Page directive’s Trace attribute to True in the Web form’s HTML.
Where is the trace output displayed by default?
By default, trace output is displayed at the end of each Web page.
While this is fine for debugging purposes, you’ll generally want to write trace output to a log file when you start testing your completed application. To write trace messages to a log file for an entire application, in the application’s Web.config file, set the trace element’s PageOutput attribute to False. ASP.NET then writes trace output to the Trace.axd file in your application’s root folder.
How do you specify, how many page requets should be written to the trace log?
The element's RequestLimit attribute can be used to specify how many page requests to write to the trace log. For example, the following line from a Web.config file turns on tracing for the application and writes the first 10 requests to the Trace.axd file:
How do you write trace messages to a log file for only selected pages in an application?
To write trace messages to a log file for only selected pages in an application, follow these steps:
In the application’s Web.config file, set the trace element’s Enabled attribute to True and PageOutput attribute to False.
For each Web page you want to exclude from tracing, set the @ Page directive’s Trace attribute to False.
What is the difference between Trace.Write() and Trace.Warn() methods of a trace object?
The Trace object provides the Write and Warn methods to allow you to write messages to a request’s trace information. The two methods are identical with one difference: messages written with Trace.Write are displayed in black, whereas messages written with Trace.Warn are displayed in red.
How do you programatically check if tracing is enabled?
The Trace object’s IsEnabled property can be used to programatically check if tracing is enabled.
How do you prevent from trace output being written at the bottom of the web page?
You can prevent from trace output being written at the bottom of the web page by setting the trace element’s PageOutput attribute to False in the Web.config file.
What is the name of the file to which trace log is written?
Trace.axd
Can you view Trace.axd from a remote machine?
No, by default, you can view Trace.axd only from the local server running the application. If you want to view the trace log from a remote machine, set the trace element’s LocalOnly attribute to False in the Web.config file
Transactions related ASP.NET Interview Questions
What is a transaction?
A transaction is a group of commands that change the data stored in a database. The transaction, which is treated as a single unit, assures that the commands are handled in an all-or-nothing fashion. if one of the commands fails, all of the commands fail, and any data that was written to the database by the commands is backed out. In this way, transactions maintain the integrity of data in a database. ADO.NET lets you group database operations into transactions.
What is the main purpose of database transactions?
The main purpose of database transactions is to maintain the integrity of data in a database.
How do you determine which SQL commands are part of a transaction?
You can determine what database commands belong in a transaction by using the ACID test. Commands must be atomic, consistent, isolated, and durable.
Commands belong in a transaction if they are:
Atomic:In other words, they make up a single unit of work. For example, if a customer moves, you want your data entry operator to change all of the customer’s address fields as a single unit, rather than changing street, then city, then state, and so on.
Consistent:All the relationships between data in a database are maintained correctly. For example, if customer information uses a tax rate from a state tax table, the state entered for the customer must exist in the state tax table. Isolated:Changes made by other clients can’t affect the current changes. For example, if two data entry operators try to make a change to the same customer at the same time, one of two things occurs: either one operator’s changes are accepted and the other is notified that the changes weren’t made, or both operators are notified that their changes were not made. In either case, the customer data is not left in an indeterminate state.
Durable:Once a change is made, it is permanent. If a system error or power failure occurs before a set of commands is complete, those commands are undone and the data is restored to its original state once the system begins running again.
Why is transaction processing very important for web applications?
Transaction processing is very important for Web applications that use data access, because Web applications are distributed among many different clients. In a Web application, databases are a shared resource, and having many different clients distributed over a wide area can present the below key problems.
Contention for resources:Several clients might try to change the same record at the same time. This problem gets worse the more clients you have.
Unexpected failures:The Internet is not the most reliable network around, even if your Web application and Web server are 100 percent reliable. Clients can be unexpectedly disconnected by their service providers, by their modems, or by power failures.
Web application life cycle:Web applications don’t follow the same life cycle as Windows applications—Web forms live for only an instant, and a client can leave your application at any point by simply typing a new address in his or her browser.
List the steps in order to process a transaction?
1.Begin a transaction.
2.Process database commands.
3.Check for errors.
4.If errors occurred, restore the database to its state at the beginning of the transaction. If no errors occurred, commit the transaction to the database.
Explain how a DataSet provides transaction processing?
DataSet provide transaction processing through the RejectChanges and Update methods. DataSet also provide an AcceptChanges method that resets the state of records in a data set to Unchanged. Data sets provide implicit transaction processing, because changes to a data set are not made in the database until you invoke the Update method on the data adapter object. This lets you perform a set of commands on the data and then choose a point at which to make the changes permanent in the database.
If an error occurs during the Update method, none of the changes from the data set is made in the database. At that point, you can either attempt to correct the error and try the Update method again or undo the changes pending in the data set using the data set’s RejectChanges method.
Give an example to show how DataSets provide transaction processing?
Let us assume we have a DataGrid that displays employee information. Every row also has a delete button, which when you click will delete that row. On this page we also have a Restore and Commit buttons. When you click the Restore button you should be able to restore the data to its previous state. When you click the Commit button you should be able to update the database with the deletions made in the DataSet.
The code for Commit and Restore buttons is shown below.
private void butRestore_Click(object sender, System.EventArgs e)
{
// Restore the data set to its original state.
dsContacts.RejectChanges();
// Refresh the data grid.
grdContacts.DataBind();
}
private void butCommit_Click(object sender, System.EventArgs e)
{
int intRows;
// Update the database from the data set.
intRows = adptContacts.Update(dsContacts);
// Save changes to state variable.
Session["dsContacts"] = dsContacts;
// Refresh the data grid.
grdContacts.DataBind();
}
The RejectChanges method in the preceding butRestore_Click event procedure returns the data set to its state before the row was deleted. The data set’s AcceptChanges method is the inverse of RejectChanges—it resets the DataRowState property for all the changed rows in a data set to Unchanged and removes any deleted rows.
The AcceptChanges method prevents the Update method from making those changes in the database, however, because Update uses the rows’ DataRowState property to determine which rows to modify in the database. For this reason, the AcceptChanges method is useful only when you do not intend to update a database from the data set.
What are the 3 types of transaction objects available in ADO.NET?
As we have 3 types of database connections in ADO.NET, there are also 3 types of transaction objects:
SqlTransaction
OracleTransaction
OleDbTransaction
What are the steps involved in using a transaction object in ADO.NET?
1.Open a database connection.
2.Create the transaction object using the database connection object’s BeginTransaction method.
3.Create command objects to track with this transaction, assigning the Transaction property of each command object to the name of the transaction object created in step 2.
4.Execute the commands. Because the purpose of transaction processing is to detect and correct errors before data is written to the database, this is usually done as part of an error-handling structure.
5.Commit the changes to the database or restore the database state, depending on the success of the commands.
Close the database connection.
What property of a transaction object determines how concurrent changes to a database are handled?
IsolationLevel property of the transaction object is used to determine how concurrent changes to a database are handled.
What are different isolation levels of a transaction object in ADO.NET?
ReadUncommitted:Does not lock the records being read. This means that an uncommitted change can be read and then rolled back by another client, resulting in a local copy of a record that is not consistent with what is stored in the database. This is called a dirty read because the data is inconsistent.
Chaos:Behaves the same way as ReadUncommitted, but checks the isolation level of other pending transactions during a write operation so that transactions with more restrictive isolation levels are not overwritten.
ReadCommitted:Locks the records being read and immediately frees the lock as soon as the records have been read. This prevents any changes from being read before they are committed, but it does not prevent records from being added, deleted, or changed by other clients during the transaction. This is the default isolation level.
RepeatableRead:Locks the records being read and keeps the lock until the transaction completes. This ensures that the data being read does not change during the transaction.
Serializable:Locks the entire data set being read and keeps the lock until the transaction completes. This ensures that the data and its order within the database do not change during the transaction.
What is the default isolation level in a transaction?
ReadCommitted
What is a Save Point in a transaction in ADO.NET?
SqlConnection object provide one transaction capability that is unavailable for OLE database connections: the ability to create save points within a transaction. Save points let you restore the database state to a specific position within the current transaction. To set a save point within a SQL transaction, use the Save method as shown below.
TransactionObject.Save("FirstStep");
How do you restore a SQL transaction to a specific save point?
To restore a SQL transaction to a save point, specify the name of the save point in the Rollback method as shown below.
TransactionObject.Rollback("FirstStep");
Interview Questions on ASP.NET Validation controls :
What are ASP.NET Validation controls?
ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database. Validation controls can be used to address the following questions.
1. Did the user enter anything?
2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)?
3. Is the data within a required range?(For example age cannot be greater than 100 years)
The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server.Most validity problems can be caught and corrected by the user without a round-trip to the server.
Where do the ASP.NET validation controls validate data, on the Client or on the Web Server?
ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then, client side validations are bypassed and validations are performed on the web server.
Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented.
What are the 6 different validation controls provided by ASP.NET?
RequiredFieldValidator:Checks whether a control contains data
CompareValidator:Checks whether an entered item matches an entry in another control
RangeValidator:Checks whether an entered item is between two values
RegularExpressionValidator:Checks whether an entered item matches a specified format
CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both
ValidationSummary:Displays validation errors in a central location or display a general validation error description
What property of the validation control is used to specify which control to validate?
ControlToValidate property.
Explain in simple steps how to use validation controls?
1.Draw a validation control on a Web form and set its ControlToValidate property to the control you want to validate.
2.If you’re using the CompareValidator control, you also need to specify the ControlToCompare property.
3.Set the validation control’s ErrorMessage property to the error message you want displayed if the control’s data is not valid.
4.Set the validation control’s Text property if you want the validation control to display a message other than the message in the ErrorMessage property when an error occurs. Setting the Text property lets you briefly indicate where the error occurred on the form and display the longer ErrorMessage property in a ValidationSummary control.
5.Draw a ValidationSummary control on the Web form to display the error messages from the validation controls in one place.
6.Provide a control that triggers a postback event. Although validation occurs on the client side, validation doesn’t start until a postback is requested.
Are the validation controls fired on the client side if javascript is disabled on the client browser?
No, validation controls are not fired on the client side if javascript is disabled on the client browser.
What is the use of CausesValidation property of an ASP.NET button control?
CausesValidation property of an ASP.NET button control is used to determine if the validation controls should be fired when the button is clicked. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done.
Give an example of real time scenario where you might use CausesValidation property of an ASP.NET button control?
Let us assume we have a Page that collects user information like name, age, date of birth, gender with a submit and reset buttons. When I click the submit button the information filled on the form should be validated and saved to the database. If I click the reset button then all the controls on the webform should default to their initial values without validation happening.So you have to set the CausesValidation property of the reset button to false for the validation to be bypassed. Other wise you will not be able to post back the page to the server.
What is ASP.NET Custom Validator used for?
ASP.NET Custom Validator is used to perform complex types of validation not provided by the standard validation control, use a CustomValidator control and write code to perform the validation on the server side and optionally on the client side.
How do you programatically check, if the client side validation is not bypassed by disabling the javascript on the client browser?
We use Page.IsValid property to determine if all the validations have succeeded. For this property to return true, all validation server controls in the current validation group must validate successfully.
How do you programatically invoke all validation controls on a page?
Call Page.Validate() method. When this method is invoked, it iterates through the validation controls contained in the ValidatorCollection object associated with the Page.Validators property and invokes the validation logic for each validation control in the current validation group.
What is a validation group?
Validation groups allow you to group validation controls on a page as a set. Each validation group can perform validation independently from other validation groups on the page.
How do you create a validation group?
You create a validation group by setting the ValidationGroup property to the same name for all the controls you want to group. You can assign any name to a validation group, but you must use the same name for all members of the group.
Explain how a validation group works when the Page is posted by clicking a button?
During postback, the Page class's IsValid property is set based only on the validation controls in the current validation group. The current validation group is determined by the control that caused validation to occur. For example, if a button control with a validation group of LoginGroup is clicked, then the IsValid property will return true if all validation controls whose ValidationGroup property is set to LoginGroup are valid.
Can a DropDownList fire validation controls?
Yes, DropDownList control can also fire validation if the control's CausesValidation property is set to true and the AutoPostBack property is set to true.
How do you programatically force all validation controls in a particular validation group to be fired?
Call the Page.Validate(string GroupName) method and pass the name of the validation group. This will fire only the validation controls in that validation group.
What is SetFocusOnError property of a validation control used for?
Use the SetFocusOnError property to specify whether focus is automatically set to the control specified by the ControlToValidate property when this validation control fails. This allows the user to quickly update the appropriate control.
If multiple validation controls fail and this property is set to true, the control specified in the ControlToValidate property for the first validation control receives focus.
What is InitialValue property of a RequiredFieldValidator?
Use this property to specify the initial value of the input control.Validation fails only if the value of the associated input control matches this InitialValue upon losing focus.
ViewState :
What is ViewState?
Web forms have very short lifetime.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.The data that ASP.NET preserves between requests is called the Web form’s view state.
How do you enable or disable a ViewState for a control on the page?
Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If EnableViewState is set to false ViewState is disabled for the control.
How do you enable or disable a ViewState at the page level?
At the page level you can enable or disable ViewState using EnableViewState property of the page.
What is the name of the hidden form field in which ViewState of the page is saved?
__ViewState
What are the performance implications of ViewState?
ViewState is usually good to retain the state of the controls on the webform across postbacks. If you have a huge DataGrid with tons of data being loaded on every page load. It is a good idea to disable the ViewState of the DataGrid for the page to load faster. If the ViewState of a large DataGrid is not disabled, ViewState can easily get very large, on the order of tens of kilobytes. Not only does the __ViewState form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.
When does ViewState restoration happens?
During the Page_Init event
What are the disadvantages of using ViewState?
1. On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __ViewState form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.
2. The __ViewState hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __ViewState form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.
Is ViewState encoded?
Yes, ViewState is base-64 encoded.
Can you encrypt ViewState of Page?
Yes, we can use the LosFormatter class to encrypt ViewState of Page
Can the HTML controls retian State accross postbacks?
No, by default HTML controls donot retain state accross postbacks.
Can you make HTML controls retain State accross postbacks?
Yes, HTML controls can retain State accross postbacks, if you convert HTML controls to Server Controls. There are 2 ways to convert HTML control to Server Controls.
1. Right click on the HTML Control and then click "Run As Server Control"
Or
2. Set runat="server" attribute for the Control.
Is ViewState supported in classic ASP?
No,ViewState is introduced in asp.net, it was not in classic asp.
When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server.
Is ViewState of one page available to another page?
No, ViewState of a Page is available only in that page. You cannot access ViewState of one page from another page.
Can you programatically store and retrieve data from ViewState?
Yes. In ASP.NET you can programatically store and retrieve data from ViewState.See the example below
//Save the value in ViewState object
ViewState("SomeVar") = txtFirstName.text;
//Retrieve the value from ViewState object
String strFirstName = ViewState("SomeVar").ToString();
Can someone view the Page HTML source and read ViewState?
No. ViewState is base-64 encoded. Hence you cannot read ViewState. If you right click on the Page and View Source you will find __ViewState is base-64 encoded.
What happens during the Page_Init event?
The server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.
Web application maintainance :
Why is it important to monitor a deployed a Web application?
After you have deployed a Web application
, you need to monitor how it performs on the server. Many issues can crop up at this point because of
1. The number of users accessing the application.
2. The unpredictable nature of user interaction.
3. The possibility of malicious attack.
What are the 3 major steps invloved in maintaining a deployed web application?
Maintaining a deployed application is an ongoing task that involves three major steps:
1. Monitoring the application for error, performance, and security issues.
2. Repairing the application as issues are discovered.
3. Tuning the application to respond to user traffic.
What are the MMC snap-ins provided by windows for monitoring security, performance, and error events?
The Event Viewer snap-in : Lists application, system, and security events as they occur on the system. Use this tool to see what is currently happening on the server and to get specific information about a particular event.
The Performance snap-in : Lets you create new events to display in the Event Viewer and allows you to track event counters over time for display graphically or in report form.
How do run the Event Viewer to view application, system, and security events as they happen?
To run the Event Viewer, choose Event Viewer from the Administrative Tools submenu on the Windows Start menu. (You can show the Administrative Tools menu in Windows XP Professional by opening the Start button’s Properties dialog box and clicking the Customize button on the Start Menu tab. The Administrative Tools option is located on the Advanced tab of the Customize Start Menu dialog box.) After clicking the Event Viewer shortcut, Windows displays the Event Viewer snap-in in the MMC.
What are the 3 levels at which the Event Viewer snap-in displays general application, system, and security events?
1. Informational events.
2. Warning events.
3. Error events.
Can you repair a deployed web application in place without restarting the server or IIS?
Yes, to repair a deployed Web application, copy the new assembly (.dll) and/or content files (.aspx, .ascx, and so on) to the application folder on the server. ASP.NET automatically restarts the application when you replace the assembly. You do not need to install or register the assembly on the server.
What is ASP.NET Process recycling?
ASP.NET Web applications have a limited ability to repair themselves through process recycling. Process recycling is the technique of shutting down and restarting an ASP.NET worker process (aspnet_wp.exe) that has become inactive or is consuming excessive resources. You can control how ASP.NET processes are recycled through attributes in the processModel element in the Machine.config file.
Describes the processModel attributes found in machine.config that relate to process recycling?
1. timeout attribute :The amount of time (hh:mm:ss) before the process is shut down and restarted. Use this setting to automatically recycle a process after a certain number of requests as a preventive measure.
2. shutDownTimeOut attribute : How much time each process has to shut itself down. After this amount of time, the process is terminated by the system if it still running.
3. requestLimit attribute : The number of queued requests to serve before the process is shut down and restarted. Use this setting the same way you use the timeout attribute.
4. restartQueueLimit attribute : The number of queued requests to retain while the process is shut down and restarted.
5. memoryLimit attribute : The percentage of physical memory the ASP.NET process is allowed to consume before that process is shut down and a new process is started. This setting helps prevent memory leaks from degrading the server.
6. responseRestart - DeadlockInterval : The amount of time to wait before restarting a process that was shut down because it was deadlocked. This setting is usually several minutes to prevent applications with serious errors from degrading the server.
7. responseDeadlockInterval : The amount of time to wait before restarting a process that is deadlocked. The process is restarted if there are queued requests and the process has not responded within this time limit.
What is the use of processModel element apart from providing process recycling?
The processModel element in the server’s Machine.config file provides attributes that control certain performance aspects, such as
1. The maximum number of requests to be queued.
2. How long to wait before checking whether a client is connected.
3. How many threads to allow per processor.
Describe the processModel attributes that relate to performance tuning?
requestQueueLimit
The number of queued requests allowed before ASP.NET returns response code 503 (Server too busy) to new requests
clientConnectedCheck
The amount of time (hh:mm:ss) to wait before checking whether a client is still connected
maxWorkerThreads
The maximum number of threads per processor
maxIOThreads
The maximum number of I/O threads per processor
In general, lowering these settings allows your server to handle fewer clients more quickly. Increasing these settings permits more clients and more queued requests, but slows response times.
How do you turn off Session state?
To turn off Session state, in the application’s Web.config file, set the sessionState element’s mode attribute to Off.
If you turn of Session State, can you use Session state variables in code anywhere in the application?
No
What is Optimization?
Optimization usually refers to writing code in a way that executes more quickly or consumes fewer resources. In general, optimizations simply reflect the good programming practices.
List some of the common steps to follow to optimize a web application for performance?
Turn off debugging for deployed applications.
Code that has been compiled with release options runs faster than code compiled with debug options.
Avoid round-trips between the client and server.
ASP.NET uses postbacks to process server events on a page. Try to design Web forms so that the data on the Web form is complete before the user posts the data to the server. You can use the validation controls to ensure that data is complete on the client side before the page is submitted.
Turn off Session state if it isn’t needed.
In some cases, you can design your code to use other techniques, such as cookies, to store client data.
Turn off ViewState for server controls that do not need to retain their values.
Saving ViewState information adds to the amount of data that must be transmitted back to the server with each request.
Use stored procedures with databases.
Stored procedures execute more quickly than ad hoc queries.
Use SqlDataReader rather than data sets for read-forward data retrieval.
Using SqlDataReader is faster and consumes less memory than creating a data set.
ASP.NET Interview Questions on web farm and web garden
What does the term Scalability mean?
Web applications
that serve a large number of users or that present large amounts of data need to able to add capacity as users’ demands increase. The ability to add capacity to an application is called scalability. ASP.NET Web applications support this concept through their ability to run in multiple processes and to have those processes distributed across multiple CPUs and/or multiple servers.
What is the difference between a web farm and a web garden?
A Web application running on a single server that has multiple CPUs is called a Web garden in the ASP.NET documentation. A Web application running on multiple servers is called a Web farm.
If your web server has multiple processors, how can you specify that ASP.NET runs on all or some of the CPUs?
If your server has multiple processors, you can specify that ASP.NET runs on all or some of the CPUs by setting the webGarden attribute of the processModel element in the server’s Machine.config file
What are the implications on Application and Session state variables in a web farm or a web garden?
In both a Web garden and a Web farm, client requests are directed to the ASP.NET process that is currently least busy. That means that a single client can interact with different CPUs or servers over the course of his or her session. This has the following implications for Application and Session state variables:
Application state variables are unique to each separate instance of the Web application.
Clients can share information through Application state if the Web application is running on a Web garden or a Web farm.
Session state variables are stored in-process by default.
To enable Session state in a Web garden or Web farm, you need to specify a Session state provider.
How can you share Application State in a web farm or a web garden?
To share data across multiple sessions in a Web garden or Web farm, you must save and restore the information using a resource that is available to all the processes. This can be done through an XML file, a database, or some other resource using the standard file or database access methods.
What are the two built-in ways provided by ASP.NET to share Session state information across a Web garden or Web farm?
ASP.NET provides two built-in ways to share Session state information across a Web garden or Web farm. You can share Session state using:
A state server, as specified by a network location
This technique is simple to implement and doesn’t require you to install Microsoft SQL Server.
A SQL database, as specified by a SQL connection
This technique provides the best performance for storing and retrieving state information.
What are the steps to follow to share Session state information using a state server?
To share Session state information using a state server, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and stateConnectionString attributes.
2. Run the aspnet_state.exe utility on the Session state server. The aspnet_state.exe utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional or Visual Studio .NET Enterprise Architect editions.
What are the steps to follow to share Session state information using a SQL database?
To share Session state information using a SQL database, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and sqlConnectionString attributes.
2. Run the InstallSqlState.sql utility on the Session state server. This utility installs the SQL database that shares Session state information across processes. The InstallSqlState.sql utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional, Visual Studio .NET Enterprise Developer, or Visual Studio .NET Enterprise Architect editions.
ASP.NET Interview Questions on web user controls
What are ASP.NET Custom controls?
Custom controls extend the tools available to Web developers. Using custom controls, you can encapsulate key aspects of the visual interface and program logic that you want to reuse throughout your application, or throughout your organization.
What are the 3 types of custom controls in ASP.NET?
Microsoft Visual Studio .NET provides three types of custom control for use on Web forms.
1. Web user controls
These combine existing server and HTML controls by using the Visual Studio .NET Designer to create functional units that encapsulate some aspect of the user interface. User controls reside in content files, which must be included in the project in which the controls are used.
2. Composite custom controls
These create new controls from existing server and HTML controls. Although similar to user controls, composite controls are created in code rather than visually, and therefore they can be compiled into an assembly (.dll), which can be shared between multiple applications and used from the Toolbox in Visual Studio .NET.
3. Rendered custom controls
These create entirely new controls by rendering HTML directly rather than using composition. These controls are compiled and can be used from the Toolbox, just like composite controls, but you must write extra code to handle tasks that are performed automatically in composite controls.
What are the limitations of user controls in ASP.NET?
As the user controls are not compiled into assemblies, they have the following limitations:
1. A copy of the control must exist in each Web application project in which the control is used.
2. User controls can’t be loaded in the Visual Studio .NET Toolbox; instead, you must create them by dragging the control from Solution Explorer to the Web form.
3. User control code is initialized after the Web form loads, which means that user control property values are not updated until after the Web form’s Load event.
What are the steps to follow for creating and using a user control in a Web application?
1. Add a Web user control page (.ascx) to your project.
2. Draw the visual interface of the control in the designer.
3. Write code to create the control’s properties, methods, and events.
4. Use the control on a Web form by dragging it from Solution Explorer to the Web form on which you want to include it.
5. Use the control from a Web form’s code by declaring the control at the module level and then using the control’s methods, properties, and events as needed within the Web form.
How do you identify user controls?
User controls are identified by their .ascx file extensions.
What is the base class from which user controls derive?
User controls derive from System.Web.UI.UserControl base class. This base class provides the base set of properties and methods you use to create the control.
What are the steps to follow to create properties and methods for the user control that you can use from a Web form?
To create properties and methods for the user control that you can use from a Web form, follow these steps:
1. Create the public property or method that you want to make available on the containing Web form.
2. Write code to respond to events that occur for the controls contained within the user control. These event procedures do the bulk of the work for the user control.
3. If the property or method needs to retain a setting between page displays, write code to save and restore settings from the control’s ViewState.
What happens when you drag a user control from solution explorer and drop it on a web form?
When you drag a user control from solution explorer and drop it on a web form, Visual Studio .NET generates a @Register directive and HTML tags to create the control on the Web form.
ASP.NET Custom Controls :
What are composite custom controls?
Composite custom controls combine one or more server or HTML controls within a single control class, which can be compiled along with other control classes to create an assembly (.dll) that contains a custom control library. Once created, the custom control library can be loaded into Visual Studio .NET and used in the same way as the standard server and HTML controls.
Composite custom controls are functionally similar to user controls, but they reside in their own assemblies, so you can share the same control among multiple projects without having to copy the control to each project, as you must do with user controls. However, composite controls are somewhat more difficult to create because you can’t draw them visually using the Visual Studio .NET Designer.
What are the steps to follow create and use a custom control in a Web application?
1. Create a solution containing a custom control project.
2. Add a Web application project to the solution, and set it as the startup project. You will use the Web application project to test the custom control during development.
3. Add a project reference from the Web application to the custom control project, and add an HTML @Register directive and control element to use the custom control on a Web form.
4. Create the custom control’s visual interface by adding existing controls to it through the custom control’s CreateChildControls method.
5. Add the properties, methods, and events that the custom control provides.
6. Build and test the custom control.
In general what is the base class for every composite custom control?
System.Web.UI.WebControls.WebControl
Which directive is used to add a custom control to a Web form?
Register directive.
What are the 3 Register directive's attributes?
TagPrefix
This name identifies the group that the user control belongs to. For example, the tag prefix for ASP.NET server controls is “asp”. You use this prefix to create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that contains the controls to register. Microsoft Visual Basic .NET uses the project name as an implicit namespace, so for controls written in Visual Basic .NET, use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The control assembly must be referenced by the Web application. Referencing the assembly maintains a copy of it in the Web application’s /bin directory.
What are the differences between User Controls and Custom Controls?
1. User Controls are easy to create where as Custom Controls are difficult to create.
2. User Controls cannot be compiled into an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user control in every project where you want to use it, where as this is not the case with custom controls. You can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.
5. User controls are used for reusing existing user interface elements and code, but are not useful for developing reusable components for multiple web applications.
CASCADING STYLE SHEETS(CSS):
What are the 2 ways provided by ASP.NET to format output in a Web application?
1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and behavior of the HTML elements on a Web page.
2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those elements.
What are Cascading style sheets?
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.
What are the 3 levels at which formatting can be applied with in a web application?
1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet.
2. You can also define styles in the page’s head element. These styles can be applied to all elements on the current page.
3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are defined.
Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading.
What are the advantages of storing style definitions in a style sheet file (.css) rather than locally in each Web form or inline with each HTML element?
1. Formatting can be maintained in one location so that you make changes only once for an entire application.
2. Several sets of parallel formatting rules can be maintained in separate style sheets for formatting output on different devices or for different user needs. For example, an application might provide standard, enlarged-type, and printer-friendly style sheets that the user can select at run time.
3. In general, you should use page and inline styles only when you have a really good reason to override the global styles. Relying heavily on page and inline styles can make it difficult to maintain the formatting in a Web application.
What HTML element is used to reference a style sheet on webform?
To reference a style sheet on webform you must add a link element to the page’s head element, as shown below.
<link href="Styles.css" type="text/css" rel="stylesheet">
What is the use of Style Builder?
Style Builder is used to change the appearance of any of the styles in a style sheet. Changes to the style sheet change the appearance of all Web forms that reference that style sheet.
How do you modify a style sheet using style builder?
To modify a style sheet using style builder, follow these steps:
1. Open the style sheet in Visual Studio. Visual Studio .NET displays the style definitions in the Document window and an outline of the style sheet in the Tool window
2. Select the style to modify from the Tool window. Visual Studio .NET displays the definition for that style in the Document window.
3. Right-click in the style definition or right-click the style in the Tool window, and select Build Style from the shortcut menu. Visual Studio .NET displays the Style Builder Wizard.
4. Use the Style Builder to compose the formatting that you want to add or modify in the selected style, and then click OK.
5. When you have finished, you’ll see that the Style Builder adds the new or modified style attributes to the style definition.
Can you apply styles using class names or element IDs?
Yes, Using class names allows you to apply a single style to a number of different elements or to style the same element differently, depending on how the element is used. Using element IDs allows you to apply a style to a unique element on one or more Web forms.
When you create a style rule for a class, Visual Studio .NET adds a style definition to the style sheet using a .classname identifier.
You apply the style class to HTML elements by using the class attribute. You apply the style to server controls by using the CssClass attribute.
Can you change style sheets at run time?
Yes.
String manipulation - Practical real time asp.net interview question asked in an interview
Questions:
Please write a sample program that parses the string into a series of substrings where the delimiter between the substrings is "^*!%~" and then reassembles the strings and delimiters into a single new string where each of the substrings is in the reverse order from the original string. The method must return the final string.
Original String:
Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E
Output String:
Token E^*!%~Token D^*!%~Token C^*!%~Token B^*!%~Token A
The code sample below shows how to solve the above question:
using System;
using System.Text;
namespace GenericsSample
{
class Program
{
static void Main()
{
string strOriginalString = "Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E";
string[] strSeperator = new string[1];
strSeperator[0] = "^*!%~";
string[] strArrayIndividualStrings = strOriginalString.Split(strSeperator, StringSplitOptions.RemoveEmptyEntries);
int intLengthOfStringArray = strArrayIndividualStrings.Length;
StringBuilder sbOutputString = new StringBuilder();
for (int i = (intLengthOfStringArray - 1); i >= 0; i--)
{
sbOutputString.Append(strArrayIndividualStrings[i] + strSeperator[0]);
}
Console.WriteLine("Original String : " + strOriginalString);
Console.WriteLine("Output String : " + sbOutputString.ToString());
Console.ReadLine();
}
}
}
Explanation of the above sample program:
1. We take the original string into a string variable strOriginalString. I named this variable as strOriginalString. str indicates that the variable is of string datatype. This will give a good impression to the person who reviews your code bcos you are following the coding standards.
2. I then store the string delimiter "^*!%~" in strSeperator variable. strSeperator is of string array data type. This is bcos the split function expects string array or character array as seprator.
3. I then split the strOriginalString into a string array using the split function.
4. I created a variable sbOutputString to store the Output string. sbOutputString data type is StringBuilder.
5. I then loop thru the array from the highest index to 0 and retrieve the individual strings and append to the sbOutputString. As the output string is changing as we loop thru the array it is good to use StringBuilder rather than System.String. Strings of type System.Text.StringBuilder are mutable where as strings of type System.String are immutable. If a string is manipulated many times always use StringBuilder over System.String.
6. Two good things to remember from this example are, follow the coding standards in naming the variables and always use StringBuilder class over Strings where we manipulate a particular string many times.
Bind an XML file to a dropdownlist
Question 2:
The XML file below has a list of employees. Your job is to bind the employee IDs and Names to a dropdownlist. ID must be dropdownlist value field and name must be the dropdownlist Text field. Also, only the active employees must be binded to the dropdownlist and the names should be in the ascending order. When I select a name from the dropdownlist, the name and ID of the selected employee must be printed on the webform.
Employees.xml
<Employees>
<Employee>
<Name>David</Name>
<ID>101</ID>
<IsActive>true</IsActive>
</Employee>
<Employee>
<Name>Tom</Name>
<ID>102</ID>
<IsActive>true</IsActive>
</Employee>
<Employee>
<Name>Rick</Name>
<ID>103</ID>
<IsActive>false</IsActive>
</Employee>
<Employee>
<Name>Mark</Name>
<ID>104</ID>
<IsActive>true</IsActive>
</Employee>
</Employees>
Code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Employees.xml"));
DataView DV = DS.Tables["Employee"].DefaultView;
DV.RowFilter = "IsActive='true'";
DV.Sort = "Name asc";
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
Code Explanation:
1. Read the XML data from Employees.xml file into a DataSet. We make use of the ReadXml() method. ReadXml method loads the XML data into the dataset DS. DS.ReadXml(Server.MapPath("Employees.xml"));
2. Now you have the Data in a relational format in the dataset. Create a DataView on the employees table in the DataSet. The DefaultView property of DataTable returns the DataView.
DataView DV = DS.Tables["Employee"].DefaultView;
3. After you have created the DataView, apply the RowFilter, to select only the active employees. You apply the RowFilter as shown below.
DV.RowFilter = "IsActive='true'";
4. Now sort the data in the DataView in ascending order. We sort the data on the Name column. You can apply the sort expression on a dataview as shown below.
DV.Sort = "Name asc";
5. Finally set the DataSource, DataValueField and DataTextField properties of the dropdownlist and call the DataBind() method as shown in the below code.
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
Untill now we have seen how to bind an XML file to dropdownlist. We have also seen how to create a DataView on DataTable. DataView is used for sorting and filtering the data. Now we have to get the SelecteValue and SelectedItem Text of a dropdownlist. To achieve this, follow the below steps.
1. Set the autopostback property of the dropdownlist to true. So, when ever a selection in the dropdownlist changes, the webform is posted back to the server automatically.
2. In the DropDownList1_SelectedIndexChanged event handler we can capture the employee name and id using the DropDownList1.SelectedItem.Text and DropDownList1.SelectedItem.Value properties as shown below.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
Note: If you have noticed, we binded the XML file to the dropdownlist only during the initial page load and not during every post back. We do this check by using if(!IsPostBack) property of the page.
Reading and writing to an XML file.
Question:
Create a simple web page , that can read and write to an XML file. The XML file has a list of email ids. The sample web form should have the following functionality. You have 30 minutes to code and test.
1. A TextBox to accept a valid email id.
2. A submit button. When you click the submit button, the email id entered in the TextBox must be saved to the XML file.
3. If I donot enter anything in the TextBox and click the submit button, the application should show a validation message stating "Email is required".
4. If I enter an invalid email, the application should show a message "Invalid Email".
5. If javascript is enabled the validation should happen on the client browser without postback. If javascript is disabled the validation should happen on the web server.
6. Finally we should have a list box, which will show all the existing email ids in the XML file. When you submit a new email, the listbox should be reloaded showing the newly added email along with already existing email ids.
Answer:
1. Create a webform and add a TextBox, RequiredFieldValidator, RegularExpressionValidator, Button and a ListBox.
2. Set the RequiredFieldValidator "ErrorMessage" property to "Email Required" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
3. Set the RegularExpressionValidator "ErrorMessage" property to "Invalid Email" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
4. Set the ListBox, "DataTextField" property to "Email" and DataValueField property to "Email"
5. The complete HTML of the web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
<title>Email List</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
Please enter a valid email:
</td>
<td>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /></td>
</tr>
</table>
<br />
Existing Email Ids
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="292px" Width="192px" DataTextField="Email" DataValueField="Email"></asp:ListBox>
</form>
</body>
</html>
6. Place the XML file that contains the list of email ids in the root folder of the web application. The sample XML file is shown below.
<?xml version="1.0" standalone="yes"?>
<EmailsList>
<Emails>
<Email>dhex@yahoo.com</Email>
</Emails>
<Emails>
<Email>dmexy@aol.com</Email>
</Emails>
<Emails>
<Email>dpitt@gmail.com</Email>
</Emails>
<Emails>
<Email>mston@microsoft.com</Email>
</Emails>
</EmailsList>
7. In the code behind file, write a function the can read the email ids from the XML file into a DataSet. Set this DataSet as the DataSource for the ListBox and call the DataBind() method. The function should be as shown below.
private void LoadExistingEmails()
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
ListBox1.DataSource = DS;
ListBox1.DataBind();
}
8. Call the above LoadExistingEmails() function in the Page_Load event handler as shown in the sample code below.
protected void Page_Load(object sender, EventArgs e)
{
LoadExistingEmails();
}
9. Finally, when you click the submit button write to the XML file as shown below.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
DataRow DR = DS.Tables[0].NewRow();
DR["Email"] = EmailTextBox.Text;
DS.Tables[0].Rows.Add(DR);
DS.WriteXml(Server.MapPath("Emails.xml"));
LoadExistingEmails();
}
}
Points to remember:
1. Validation controls work both on the client and on the server.
2. If javascript is enabled validations happen on the client browser without posting the page back to the server.
3. If javascript is disabled, validations happen on the server. To check if all the validation controls haved passed validation, use Page.IsValid property.
4. Page.IsValid returns "true" if the page has succeeded validation and "false" even if a single validation control has filed validation.
5. In our example, we write to the XML file only if Page.IsValid property returns true.
Testing the sample application:
To test if the validation controls are working on the server, disable javascript on the client browser. To disable javascript on the client browser follow the below steps.
1. Open internet explorer.
2. Click on Tools.
3. Click on Internet Options. You will see Internet Options dialog page.
4. Click on the Security tab.
5. On the Security tab, select Local intranet under Select a zone to view or change security settings.
6. Click "Custom Level" button under "Security Level for this zone"
7. On the "Security Setting - Local Intranet Zone" dialog page, scroll down to "Scripting" section.
8. Select "Disable" radio button under "Active scription" and click "OK" button.
write a custom reusable function to populate a dropdownlist
Write a custom function in c-sharp. The custom function parameters should be an instance of a dropdownlist, an xml file and a string.
1. The function should be capabale of populating the passed in dropdownlist.
2. The first item in the dropdownlist should be the passed in string parameter.
3. The data for the dropdownlist comes from the passed in XML file.
The idea is to create a custom function which can be reused through out the project for populating any dropdownlist on any web page. You have 20 minutes to code, test and demonstrate.
The sample code for custom function is shown below. For this example to work drop the XML file in the root folder of the web application.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
public void PopulateDropdownlist(System.Web.UI.WebControls.DropDownList DropDownListObjectToBePopulated,string XMLFilePath, string InitialString)
{
try
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(XMLFilePath));
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
}
catch(Exception Ex)
{
}
}
The XML file that has the data for the dropdownlist is as shown below.
<?xml version="1.0" encoding="utf-8" ?>
<StatesList>
<State>
<StateName>Virginia</StateName>
<StateCode>VA</StateCode>
</State>
<State>
<StateName>Iowa</StateName>
<StateCode>IA</StateCode>
</State>
<State>
<StateName>North Carolina</StateName>
<StateCode>NC</StateCode>
</State>
<State>
<StateName>Pennsylvania</StateName>
<StateCode>PA</StateCode>
</State>
<State>
<StateName>Texas</StateName>
<StateCode>TX</StateCode>
</State>
</StatesList>
Explanation of the code:
1. PopulateDropdownlist function has 3 parameters. DropDownList to be populated, the path of the XML file which has the data for the dropdownlist and the initial string.
2. Create an instance of DataSet. In our example the instance is DS.
DataSet DS = new DataSet();
3. Read the XML data into the dataset instance using ReadXml() method. Pass the path of the XML file to ReadXml() method. We used Server.MapPath() method to return the physical file path that corresponds to the specified virtual path on the web server.
DS.ReadXml(Server.MapPath(XMLFilePath));
4. We now have the data from the XML file in the dataset as a DataTable.
5. Check if the InitialString is empty. If not empty create a new ListItem object and populate the Text and Value properties. Then add the listitem object to the dropdownlist.
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
6. Finally loop thru the rows in the DataTable and create an instance of ListItem class. Populate the Text and Value properties to StateName and StateCode respectively. Finally add the ListItem object to the dropdownlist.
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
7. Drag and drop the dropdownlist on a webform. Call the PopulateDropdownlist() custom function in the Page_Load event handler. When you call the custom function pass the dropdownlist to be populated, XML file path and the initial string.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
List all the files in a directory on a web form in asp.net
List all the files in a directory on a web form. The files must be displayed in a gridview control. The name of the file and create date must be displayed.
1. Create a new web form. Drag and drop a gridview control from the toolbox onto the webform.
2. Create 2 bound fields for the gridview. One bound field will display the file name and the other will display the create date.
3. The HTML for your web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListFiles.aspx.cs" Inherits="ListFiles" %>
<html>
<head runat="server">
<title>List all the files in a directory</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="File Name"></asp:BoundField>
<asp:BoundField DataField="DateCreated" HeaderText="Date" DataFormatString="{0:d}"></asp:BoundField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
4. In the code behind file write a function which can get the list of files from the directory and bind to the gridview. The function is as shown below.
private void LoadFiles()
{
/* Create an instance of DirectoryInfo class for enumarating through the directory. */
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Server.MapPath("FilesDirectory"));
/* Call the GetFiles() instance method of the DirectoryInfo class object, which will return a files list from the current directory */
System.IO.FileInfo[] fiFiles = dirInfo.GetFiles();
/* Create a DataTable which can be used as the datasource for the gridview */
DataTable dtFileList = new DataTable("Files");
/* Create a DataColumn for file name */
DataColumn dcFileName = new DataColumn("FileName");
/* Create a DataColumn for file create date */
DataColumn dcDateCreated = new DataColumn("DateCreated", typeof(DateTime));
/* Add the 2 data columns to the data table */
dtFileList.Columns.Add(dcFileName);
dtFileList.Columns.Add(dcDateCreated);
/* Now loop through each FileInfo object and get the file name and file create date */
foreach (System.IO.FileInfo f in fiFiles)
{
DataRow dtNewRow = dtFileList.NewRow();
/* Get the file name using FileInfo object "Name" property */
dtNewRow["FileName"] = f.Name.ToString();
/* Get the file create date and time using FileInfo object "CreationTime" property */
dtNewRow["DateCreated"] = f.CreationTime.ToShortDateString();
/* Add the row to the DataTable */
dtFileList.Rows.Add(dtNewRow);
}
/* Set the datatable as the DataSource for the gridview and call the DataBind() method */
GridView1.DataSource = dtFileList;
GridView1.DataBind();
}
5. Finally call the LoadFiles() method on the page load event handler as shown below.
protected void Page_Load(object sender, EventArgs e)
{
LoadFiles();
}
Testing the application:
1. Right click on the project name in solution explorer, and left click on "NewFolder"
2. Rename the "NewFolder" to "FilesDirectory"
3. Drag and Drop some files into the directoy.
4. Then run the application. All the files in the "FilesDirectory" folder will be shown in the gridview.
Write and Read a cookie:
Give an example to show how to write and read a cookie from a client's computer.
1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores
FirstName
LastName
LastVisit
2. Create the user interface to enter FirstName and LastName. The HTML for the webform is as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesExample.aspx.cs" Inherits="CookiesExample" %>
<html>
<head runat="server">
<title>Write a cookie to the client computer</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td style="width: 100px">
First Name</td>
<td style="width: 100px">
<asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
Last Name
</td>
<td style="width: 100px">
<asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="WriteCookieButton" runat="server" Text="Write Cookie" OnClick="WriteCookieButton_Click" />
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="ReadCookieButton" runat="server" Text="Read Cookie" OnClick="ReadCookieButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}
4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}
5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.
A class is a template for a specific object or groups of objects that will always have the same features. It is a collection of objects.
Ex: 1.public class student { } 2.Paper pattern for a shirt
Here paper pattern is the class and shirt is the object.
2. What is an object?
It is a real time entity. Objects lets you declare variables and procedures once and then reuse them whenever needed.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior.
Ex: 1.student objstudent=new student ();
When you drag &drop a control from the toolbox onto a form, you are actually creating an object (an instance of a class)
3. What is a Method?
A method defines the behavior to be exhibited by instances of the associated class at program runtime.
4. What is abstract method?
It is one with only a signature and no implementation body. It is often used to specify that a sub class must provide an implementation of the method.
5. What are the different types of classes in c#?
There are Partial, abstract, static, sealed and instance classes in c#.
Partial Class: Partial class is useful when the class functionality is too big (i.e. when number of lines of code in the class is too big) and when a developer want to share some of the functionalities with other developers this is useful.
Sealed Class: when the class is functionality is complete and you don’t want to allow any other class to extend your class, then you need to declare your class as sealed. No other Class can extend or use your sealed class as base class.
Abstract Class: When the developer/programmer doesn’t know the functionality of the class fully and, you want to leave the implementation to the derived classes, and then use the Abstract class. In the abstract class you can have 0 or more abstract methods, properties and along with implemented methods. You cannot create an instance to the Abstract Class. And also if you have family of related classes and all those classes having some common functionality try pushing then into a common base class. This way you will get code re-usability and can get easy maintainability.
Static Class: when any class is most frequently used or if any class is qualified as helper class (helper class is one which will be repeatedly used by all other classes) then try using Static Class. Advantage with static class is “Object instantiation overhead is reduced”. And this class always has single memory location where in every other class will hit the same memory location. If class A changed some data in static class, Changed data is available to every other subsequent classes who access the static class.
6. OOPS concepts in c#
There are 4 concepts.
1. Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit.
Ex for encapsulation is class. A class can contain data structures and methods.
2. Abstraction:
Abstraction is a process of hiding the implementation details and displaying the essential features.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.
Example: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works. You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.
So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member
Functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
3. Inheritance:
Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity.
Example:
Public class A
{
Public void A_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Public class B: A
{
Public void B_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Note:
1. Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.
2. How can you implement multiple inheritance in C#?
Ans: Using Interfaces.
4. Polymorphism:
When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
Features:
- It allows you to invoke methods of derived class through base class reference during runtime.
- It has the ability for classes to provide different implementations of methods that are called through the same name.
Polymorphism is of two types:
- Compile time polymorphism/Overloading
- Runtime polymorphism/Overriding
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Example:
Public class Shape
{
Public void Area (float r)
{
float a = (float)3.14 * r;
// here we have used function overload with 1 parameter.
Console.WriteLine ("Area of a circle: {0}",a);
}
Public void Area(float l, float b)
{
float x = (float)l* b;
// here we have used function overload with 2 parameters.
Console.WriteLine ("Area of a rectangle: {0}",x);
}
public void Area(float a, float b, float c)
{
float s = (float)(a*b*c)/2;
// here we have used function overload with 3 parameters.
Console.WriteLine ("Area of a circle: {0}", s);
}
}
Runtime time polymorphism:
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
Example:
public class Print
{
public void display(string name)
{
Console.WriteLine ("Your name is : " + name);
}
public void display(int age, float marks)
{
Console.WriteLine ("Your age is : " + age);
Console.WriteLine ("Your marks are :" + marks);
}
}
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.
You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.
Things to keep in mind while method overloading
If you use overload for method, there are couple of restrictions that the compiler imposes.
The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.
There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.
Things to keep in mind while method overriding
Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class.This is done by using virtual/override keywords.
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
9. What is static & void?
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
Ex: UtilityClass.MethodA ();
When used as the return type for a method, void specifies that the method does not return a value.
Void is not allowed in a method's parameter list. A method that takes no parameters and returns no value is declared as follows:
Ex: void MyMethod ();
10. What is an assembly?
When we create a project in Visual Studio .Net and compile it, assemblies are created. These assemblies are the fundamental units of applications in the .NET Framework. An assembly can contain classes, structures, interfaces, and resources that an application requires.
When we compile a program, the compiler translates the source code into the Intermediate Language code (IL). In addition to translating the code into IL, the compiler also produces metadata about the program during the process of the compilation. Metadata contains the description of the program, such as the classes and interfaces, the dependencies, and the versions of the components used in the program.
The IL and the metadata are linked in an assembly.
An IL and metadata exist in portable executable file (EXE/DLL).
If we look at any project folder, we will find a bin folder that contains, say myproject.dll/ myproject.exe and myproject.pdb files. The myproject.dll/ myproject.exe is the assembly, and myproject.pdb (program database) file contains debugging information for the assembly. The .pdb file also contains information the linker can use when debugging the assembly.
So, when we create and compile the project in VS.Net, the assembly is automatically generated and copied into the application's bin directory. An assembly also contains an assembly manifest that contains the assembly metadata. This metadata contains information about the assembly version, its security identity, the resources required by the assembly and the scope of the assembly. This information is stored within the assembly file (DLL/EXE) itself. Note that the assembly contains two types of metadata. One, is the type metadata and the other is the assembly metadata.
Process assemblies (EXE) and library assemblies (DLL):
A process assembly represents a process which uses classes defined in library assemblies. The compiler will have a switch to determine if the assembly is a process or a library and will set a flag in the PE(portable executables)file.NET does not use the extension to determine if the file is a process or library. This means that a library may have either .dll or .exe as its extension.
The .Net CLR while executing looks for the metadata in order to locate and load classes, as well as generate native code and security.
Note that the assembly metadata is assembly manifest and it simplifies the deployment model. Because it contains so much information about the assembly, you can simply XCOPY the assembly onto another computer, along with its related manifest.
Why use Assemblies?
The goal of the assembly model is the elimination of DLL Hell. Under the current COM/COM+ model, a catalog of DLLs is centralized in the Windows Registry. When a new version of a DLL is published, the registry re-references the catalog to point to the new DLL. This centralized registration paradigm makes it challenging for multiple applications to depend on the same DLL. Most often, the application binds to a DLL in a centralized location, rather than run multiple versions of a component by using side-by-side execution.
The .NET Framework makes it easy to run multiple versions of a component because it stores assemblies in local application directories by default. This isolates the assembly from use by any other application and protects the assembly from system changes.
Types of Assemblies:
Assemblies can be private or shared. The assembly which is used by a single application is called as private assembly. Suppose we have created a DLL which encapsulates business logic. This DLL is used by the client application only and not by any other application. In order to run the application properly the DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to the application.
Suppose we are creating a general purpose DLL which provides functionality to be used by a variety of applications. Now, instead of each client application having its own copy of DLL we can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.
When we create an application in Visual Studio.Net that uses a component, which is not in the GAC, the assembly is automatically copied to the project´s bin folder. So, if we simply copy the project´s bin folder, the assembly for the component is copied as well. Since the files the application needs are in the same folder, the application can run without registration.
What is Global Assembly Cache?
An assembly that is shared by multiple applications is called a global assembly and is installed in the global assembly cache (GAC).Global assembly cache is nothing but a special disk folder where all the shared assemblies are kept. It is located under <drive>:\Windows\Assembly folder on every machine running the .NET framework.
GAC acts as a central location for assemblies that is accessible by any application.
11. What is msi (Microsoft Installer API)?
The Windows Installer (MSI) (previously known as Microsoft Installer, codename Darwin) is an engine for the installation, maintenance, and removal of software on modern Microsoft Windows systems. The installation information, and often the files themselves, are packaged in installation packages, loosely relational databases structured as OLE Structured Storage Files and commonly known as "MSI files", from their default file extension (compare: .deb, RPM, .pbi). Windows Installer is a significant improvement over its predecessor, Setup API: several new features, such as a GUI framework, the automatic generation of the uninstallation sequence and the powerful deployment capabilities, made Windows Installer a viable alternative to stand-alone executable installer frameworks such as older versions of InstallShield and WISE (later versions are based on Windows Installer) and NSIS.
Microsoft encourages third parties to use Windows Installer as the basis for installation frameworks, so that they synchronize correctly with other installers and keep the internal database of installed products consistent. Important features such as rollback and versioning (see DLL hell) depend on a consistent internal database for reliable operation.
This collection of modules and scripts lets you create and manipulate MSI databases programmatically using Perl. The main API is provided by the MSI::Installer module; however the other modules provide useful APIs as well.
12. What is CAB?
Cab files are nothing but cabinet files which are developed by Microsoft in order to distribute their software in a compressed and secured format.
13. What are the differences between different versions of visual studio?
2003 and 2005:
In 2005 we have default web server for web application but in 2003 we have to configure iis
In 2005 we can directly create website (means web application) it will use classes that will help to create web application..By this deployment makes easier.
In 2005 we can select option to write inline coding.But in 2003 we don’t have this option
In 2005 we have login control, password recovery control, directly we can create user in asp.net database..This is very secure. In 2003 we don’t have this.
In 2005 we have master pages and themes instead of using css files we can use themes ...
In 2005 we does not require single line of code to do any operations with grid view.
In 2005 we have sitemap navigator, Xmldatasource.
New control is available like tree-view, menu-tree .Crystal-report’s new version is there. Sql-server will come inbuilt with vs2005 for the run a query and all things
2005 and 2008:
Visual Studio 2008 is having lot of advanced concepts like WPF, WCF, WWF, and Linq etc. Entity Framework also an advanced approach introduced in .Net 3.5 SP.
Visual Studio 2005 was upgraded to support all the new features introduced in .NET Framework 2.0, including generics and ASP.NET 2.0. The IntelliSense feature in Visual Studio was upgraded for generics and new project types were added to support ASP.NET web services. It also includes a local web server, separate from IIS that can host ASP.NET applications during development and testing. It also supports all SQL Server 2005 databases.
Visual Studio 2008 came that supports .net framework 3.0 and 3.5. Its features include an XAML-based designer workflow designer, LINQ to SQL designer, XSLT debugger, JavaScript Debugging support, JavaScript IntelliSense support, support for UAC manifests, a concurrent build system, among others.
Visual Studio 2010 IDE supports the upcoming .net framework 4.0. It has been redesigned which, according to Microsoft, clears the UI organization and "reduces clutter and complexity". It has integrated support for developing Microsoft Silver light applications, including an interactive designer.
INTERFACES:
what is an Interface?Explain with an example?
An Interface is created using the keyword interface.It provides a way to achieve run time polymorphism. An example is shown below.
using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Please enter Deposit Money");
}
public void WithdrawMoney()
{
Console.WriteLine("Please enter Withdraw Money");
}
public static void Main()
{
Bank objBank = new Bank();
objBank.DepositMoney();
objBank.WithdrawMoney();
}
}
}
In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();
Method declarations does not have access modifiers like public, private, etc
NOTE:
1. By default all interface members are public. It is a compile time error to use access modifiers on interface member declarations.
2. Interface methods have only declarations and not implementation. It is a compile time error to provide implementation for any interface member.
In our example as the Bank class is inherited from the IBankCustomer interface, the Bank class has to provide the implementation for both the methods (WithdrawMoney() and DepositMoney()) that is inherited from the interface. If the class fails to provide implementation for any of the inherited interface member, a compile time error will be generated.
Can an Interface contain fields?
No, an Interface cannot contain fields.
What is the difference between class inheritance and interface inheritance?
Classes and structs can inherit from interfaces just like how classes can inherit a base class or struct. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example depicting the same is shown below.
using System;
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}
//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}
//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}
2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.
Can an interface inherit from another interface?
Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.
Can you create an instance of an interface?
No, you cannot create an instance of an interface.
If a class inherits an interface, what are the 2 options available for that class?
Provide Implementation for all the members inherited from the interface.
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}
If the class does not wish to provide Implementation for all the members inherited from the interface, then the class has to be marked as abstract.
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}
A class inherits from 2 interfaces and both the interfaces have the same method name as shown below. How should the class implement the drive method for both Car and Bus interface?
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}
To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method type cast the demo object to the respective interface and then call the drive method.
using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}
static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}
What do you mean by "Explicitly Implemeting an Interface". Give an example?
If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An example is shown below.
using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
static void Main()
{
Demo DemoObject = new Demo();
//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type cast the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}
partial classes, structs and methods:
What is a partial class. Give an example?
A partial class is a class whose definition is present in 2 or more files. Each source file contains a section of the class, and all parts are combined when the application is compiled. To split a class definition, use the partial keyword as shown in the example below. Student class is split into 2 parts. The first part defines the study() method and the second part defines the Play() method. When we compile this program both the parts will be combined and compiled. Note that both the parts uses partial keyword and public access modifier.
using System;
namespace PartialClass
{
public partial class Employee
{
public void Work()
{
Console.WriteLine("I am working");
}
}
public partial class Employee
{
public void Learn()
{
Console.WriteLine("I am Learning New Technologies");
}
}
public class Demo
{
public static void Main()
{
Employee objEmp = new Employee();
objEmp.Study();
objEmp.Play();
}
}
}
It is very important to keep the following points in mind when creating partial classes.
1. All the parts must use the partial keyword.
2. All the parts must be available at compile time to form the final class.
3. All the parts must have the same access modifiers - public, private, protected etc.
4. Any class members declared in a partial definition are available to all the other parts.
5. The final class is the combination of all the parts at compile time.
What are the advantages of using partial classes?
1. When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
2. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
Is it possible to create partial structs, interfaces and methods?
Yes, it is possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial classes.
Will the following code compile?
using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public abstract partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
}
}
}
No, a compile time error will be generated stating "Cannot create an instance of the abstract class or interface "PartialClass.Student". This is because, if any part is declared abstract, then the whole class becomes abstract. Similarly if any part is declared sealed, then the whole class becomes sealed and if any part declares a base class, then the whole class inherits that base class.
Can you create partial delegates and enumerations?
No, you cannot create partial delegates and enumerations.
Can different parts of a partial class inherit from different interfaces?
Yes, different parts of a partial class can inherit from different interfaces.
Can you specify nested classes as partial classes?
Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.
class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}
How do you create partial methods?
To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are removed at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration consists of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
The following are the points to keep in mind when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
What is the use of partial methods?
Partial methods can be used to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
Nested Types:
What is a nested type. Give an example?
A type(class or a struct) defined inside another class or struct is called a nested type. An example is shown below. InnerClass is inside ContainerClass, Hence InnerClass is called as nested class.
using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
Will the following code compile?
using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
}
class Demo
{
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
No, the above code will generate a compile time error stating - The type or namespace name 'InnerClass' could not be found (are you missing a using directive or an assembly reference?). This is bcos InnerClass is inside ContainerClass and does not have any access modifier. Hence inner class is like a private member inside ContainerClass. For the above code to compile and run, we should make InnerClass public and use the fully qualified name when creating the instance of the nested class as shown below.
using System;
namespace Nested
{
class ContainerClass
{
public class InnerClass
{
public string str = "A string variable in nested class";
}
}
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
Can the nested class access, the Containing class. Give an example?
Yes, the nested class, or inner class can access the containing or outer class as shown in the example below. Nested types can access private and protected members of the containing type, including any inherited private or protected members.
using System;
namespace Nested
{
class ContainerClass
{
string OuterClassVariable = "I am an outer class variable";
public class InnerClass
{
ContainerClass ContainerClassObject = new ContainerClass();
string InnerClassVariable = "I am an Inner class variable";
public InnerClass()
{
Console.WriteLine(ContainerClassObject.OuterClassVariable);
Console.WriteLine(this.InnerClassVariable);
}
}
}
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
}
}
}
What is the output of the following program?
using System;
namespace Nested
{
class ContainerClass
{
public ContainerClass()
{
Console.WriteLine("I am a container class");
}
public class InnerClass : ContainerClass
{
public InnerClass()
{
Console.WriteLine("I am an inner class");
}
}
}
class DemoClass : ContainerClass.InnerClass
{
public DemoClass()
{
Console.WriteLine("I am a Demo class");
}
public static void Main()
{
DemoClass DC = new DemoClass();
}
}
}
Output:
I am a container class
I am an inner class
I am a Demo class
The above program has used the concepts of inheritance and nested classes. The ContainerClass is at the top in the inheritance chain. The nested InnerClass derives from outer ContainerClass. Finally the DemoClass derives from nested InnerClass. As all the 3 classes are related by inheritance we have the above output.
Destructors:
What is a Destructor?
A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.
Can a class have more than 1 destructor?
No, a class can have only 1 destructor.
Can structs in C# have destructors?
No, structs can have constructors but not destructors, only classes can have destructors.
Can you pass parameters to destructors?
No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.
Can you explicitly call a destructor?
No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.
Why is it not a good idea to use Empty destructors?
When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.
Is it possible to force garbage collector to run?
Yes, it possible to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance over head. Usually the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.
Usually in .NET, the CLR takes care of memory management. Is there any need for a programmer to explicitly release memory and resources? If yes, why and how?
If the application is using expensive external resource, it is recommend to explicitly release the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.
When do we generally use destructors to release resources?
If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.
constructors:
What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object.
In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.
Structs are not reference types. Can structs have constructors?
Yes, even though Structs are not reference types, structs can have constructors.
We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.
Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.
using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.
Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}
public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}
If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
Will the following code compile?
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
//Call the base class contructor from child class
public ChildClass() : base("A call to base class constructor")
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.
using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 150;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}
Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.
Can you have parameters for static constructors?
No, static constructors cannot have parameters.
What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Does C# provide copy constructor?
No, C# does not provide copy constructor.
Questions on Methods / Functions:
Is the following code legal?
using System;
namespace Demo
{
class Program
{
public static void Main()
{
}
public void Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
}
public int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
}
}
}
No, The above code does not compile. You cannot overload a method based on the return type. To overload a method in C# either the number or type of parameters should be different. In general the return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.
What is the difference between method parameters and method arguments. Give an example?
In the example below FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}
Explain the difference between passing parameters by value and passing parameters by reference with an example?
We can pass parameters to a method by value or by reference. By default all value types are passed by value where as all reference types are passed by reference. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method.An example is shown below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
int K = Function(I);
Console.WriteLine("I = " + I);
Console.WriteLine("K = " + K);
}
public static int Function(int Number)
{
int ChangedValue = Number + 1;
return ChangedValue;
}
}
}
By default, reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy of the object. Changes made through this reference will therefore be reflected in the calling method. Reference types are created by using the class keyword as shown in the example below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
ReferenceTypeExample Object = new ReferenceTypeExample();
Object.Number = 20;
Console.WriteLine("Original Object Value = " + Object.Number);
Function(Object);
Console.WriteLine("Object Value after passed to the method= " + Object.Number);
}
public static void Function(ReferenceTypeExample ReferenceTypeObject)
{
ReferenceTypeObject.Number = ReferenceTypeObject.Number + 5;
}
}
class ReferenceTypeExample
{
public int Number;
}
}
Can you pass value types by reference to a method?
Yes, we can pass value types by by reference to a method. An example is shown below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = " + I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by reference= " + I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}
If a method's return type is void, can you use a return keyword in the method?
Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}
}
}
Properties:
What are Properties in C#. Explain with an example?
Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.
The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.
using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;
// public FirstName property exposes _firstName variable
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}
}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}
Explain the 3 types of properties in C# with an example?
1. Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2. Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.
What are the advantages of properties in C#?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value of other fields.
What is a static property. Give an example?
A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.
using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}
What is a virtual property. Give an example?
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.
using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is virtual
public virtual string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
}
class BankCustomer : Customer
{
// Overiding the FullName virtual property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}
What is an abstract property. Give an example?
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.
using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}
Can you use virtual, override or abstract keywords on an accessor of a static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.
C# Interview Questions on Constants:
What are constants in C#?
Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.
using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}
Can you declare a class or a struct as constant?
No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.
Does C# support const methods, properties, or events?
No, C# does not support const methods, properties, or events.
Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the example below, the constant field PI is always 3.14, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, PI), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference.
using System;
class Circle
{
public const double PI = 3.14;
}
How do you access a constant field declared in a class?
Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. In the example below constant field PI can be accessed in the Main method using the class name and not the instance of the class. Trying to access a constant field using a class instance will generate a compile time error.
using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}
C# Interview Questions on Fields:
What are the 2 broad classifications of fields in C#?
1. Instance fields
2. Static fields
What are instance fields in C#?
Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object.
What is a static field?
A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.
Will the following code compile?
using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}
No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields can only be accessed using the name of the class and not the instance of the class. The above sample program is rewritten as shown below.
using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}
Can you declare a field readonly?
Yes, a field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. An example is shown below.
using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}
Will the following code compile?
using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
A.PI = 3.15;
Console.WriteLine(A.PI);
}
}
No, PI is readonly. You can only read the value of PI in the Main() method. You cannot assign any value to PI.
What is wrong with the sample program below?
using System;
class Area
{
public const double PI = 3.14;
static Area()
{
Area.PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}
You cannot assign a value to the constant PI field.
What is the difference between a constant and a static readonly field?
A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.
Access Modifiers:
What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.
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.
Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
What are Access Modifiers used for?
Access Modifiers are used to control the accessibilty of types and members with in the types.
Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.
Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}
When you compile the above code an error will be generated stating "Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass".To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
Is the following code legal?
using System;
private class Test
{
public static void Main()
{
}
}
No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support inheritance.
Can the accessibility of a type member be greater than the accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.
Can destructors have access modifiers?
No, destructors cannot have access modifiers.
What does protected internal access modifier mean?
The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.
What is the default access modifier for a class,struct and an interface declared directly with a namespace?
internal
Will the following code compile?
using System;
interface IExampleInterface
{
public void Save();
}
No, you cannot specify access modifer for an interface member. Interface members are always public.
Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.
Why should you override the ToString() method
Why should you override the ToString() method?
All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below.
using System;
public class MainClass
{
public static void Main()
{
int Number = 10;
Console.WriteLine(Number.ToString());
}
}
In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method.
If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class.
using System;
public class Customer
{
public string FirstName;
public string LastName;
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}
The code sample below shows how to override the ToString() method in a class, that would give the output you want.
using System;
public class Customer
{
public string FirstName;
public string LastName;
public override string ToString()
{
return LastName + ", " + FirstName;
}
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}
Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method.
polymorphism:
Explain polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];
DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}
When can a derived class override a base class member?
A derived class can override a base class member only if the base class member is declared as virtual or abstract.
What is the difference between a virtual method and an abstract method?
A virtual method must have a body where as an abstract method should not have a body.
Can fields inside a class be virtual?
No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.
Give an example to show for hiding base class methods?
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}
public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}
Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}
public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}
C# Interview Questions on Abstract and Sealed Class Members:
What is an abstract class?
An abstract class is an incomplete class and must be implemented in a derived class.
Can you create an instance of an abstract class?
No, abstract classes are incomplete and you cannot create an instance of an abstract class.
What is a sealed class?
A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}
What are abstract methods?
Abstract methods are methods that only the declaration of the method and no implementation.
Will the following code compile?
using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a compile time error stating "Customer.Test() cannot declare a body because it is marked abstract"
Is the following code legal?
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}
No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"
How can you force derived classes to provide new method implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}
public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}
public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation.
}
}
When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.
Can a sealed class be used as a base class?
No, sealed class cannot be used as a base class. A compile time error will be generated.
Will the following code compile?
public abstract sealed class Test
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.
C# Interview Questions on Inheritance:
What are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Do structs support inheritance?
No, structs do not support inheritance, but they can implement interfaces.
What is the main advantage of using inheritance?
Code reuse
Is the following code legal?
class ChildClass : ParentClassA, ParentClassB
{
}
No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.
What will be the output of the following code?
using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.
Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.
C# Interview Questions on structs :
Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"
Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No
Can you instantiate a struct without using a new operator in C#?
Yes, you can instantiate a struct without using a new operator
Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.
Can a struct inherit from an interface in C#?
Yes
Are structs value types or reference types?
Structs are value types.
What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.
Basic C# Interview Questions on classes and structs
What do you mean by saying a "class is a reference type"?
A class is a reference type means when an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
What do you mean by saying a "struct is a value type"?
A struct is a value type mean when a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
When do you generally use a class over a struct?
A class is used to model more complex behavior, or data that is intended to be modified after a class object is created. A struct is best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
List the 5 different access modifiers in C#?
1. public
2. protected
3. internal
4. protected internal
5. private
If you donot specify an access modifier for a method, what is the default access modifier?
private
Classes and structs support inheritance. Is this statement true or false?
False, Only classes support inheritance. structs donot support inheritance.
If a class derives from another class, will the derived class automatically contain all the public, protected, and internal members of the base class?
Yes, the derived class will automatically contain all the public, protected, and internal members of the base class except its constructors and destructors.
Can you create an instance for an abstract class?
No, you cannot create an instance for an abstract class.
How do you prevent a class from being inherited by another class?
Use the sealed keyword to prevent a class from being inherited by another class.
Classes and structs can be declared as static, Is this statement true or false?
False, only classes can be declared as static and not structs.
Can you create an instance of a static class?
No, you cannot create an instance of a static class.
Can a static class contain non static members?
No, a static class can contain only static members.
C# Interview Questions on Data Types
What are the 3 types of comments in C#?
1. Single Line Comments. You define single line comments with // as shown below.
//This is an example for single line comment
2. Multi line comments. You define multi line comments with /* */ as shown below.
/*This is an example for
Multi Line comments*/
3. XML Comments. You define XML comments with /// as shown below.
///This is an example for defining XML comments.
Is C# a strongly-typed language?
Yes
What are the 2 broad classifications of data types available in C#?
1. Built in data types.
2. User defined data types.
Give some examples for built in datatypes in C#?
1. int
2. float
3. bool
How do you create user defined data types in C#?
You use the struct, class, interface, and enum constructs to create your own custom types. The .NET Framework class library itself is a collection of custom types provided by Microsoft that you can use in your own applications.
C# Interview Questions on value types and reference types:
What are the 2 types of data types available in C#?
1. Value Types
2. Reference Types
If you define a user defined data type by using the struct keyword, Is it a a value type or reference type?
Value Type
If you define a user defined data type by using the class keyword, Is it a a value type or reference type?
Reference type
Are Value types sealed?
Yes, Value types are sealed.
What is the base class from which all value types are derived?
System.ValueType
Give examples for value types?
Enum
Struct
Give examples for reference types?
Class
Delegate
Array
Interface
What are the differences between value types and reference types?
1. Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.
C# Interview Questions on data type casting
What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.
What are the 2 kinds of data type conversions in C#?
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.
What is the difference between an implicit conversion and an explicit conversion?
1. Explicit conversions require a cast operator where as an implicit converstion is done automatically.
2. Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.
What type of data type conversion happens when the compiler encounters the following code?
ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();
Implicit Conversion. For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.
Will the following code compile?
double d = 9999.11;
int i = d;
No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.
double d = 9999.11;
int i = (int)d; //Cast double to int.
If you want to convert a base type to a derived type, what type of conversion do you use?
Explicit conversion as shown below.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;
// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.
If casting fails what type of exception is thrown?
InvalidCastException
C# Interview questions on Boxing and Unboxing
What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing
Unboxing - Converting a reference type to a value typpe is called unboxing. An example is shown below.
obj = 101;
i = (int)obj; // Unboxing
Is boxing an implicit conversion?
Yes, boxing happens implicitly.
Is unboxing an implicit conversion?
No, unboxing is an explicit conversion.
What happens during the process of boxing?
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.
Basic C# Interview Questions on arrays:
What is an array?
An array is a data structure that contains several variables of the same type.
What are the 3 different types of arrays?
1. Single-Dimensional
2. Multidimensional
3. Jagged
What is Jagged Array?
A jagged array is an array of arrays.
Are arrays value types or reference types?
Arrays are reference types.
What is the base class for Array types?
System.Array
Can you use foreach iteration on arrays in C#?
Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#.
Basic C# Interview Questions on strings
What is the difference between string keyword and System.String class?
string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.
Are string objects mutable or immutable?
String objects are immutable.
What do you mean by String objects are immutable?
String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.
string s1 = "First String ";
string s2 = "Second String";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: First String Second String
What will be the output of the following code?
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);
The output of the above code is "Hello" and not "Hello C#". This is bcos, if you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.
What is a verbatim string literal and why do we use it?
The "@" symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:
string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg
string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/
string DoubleQuotesString = @"My Name is ""Vankat.""";
//Output: My Name is "Vankat."
More C# interview questions on strings
Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);
The above code will compile, but at runtime System.NullReferenceException will be thrown.
How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;
What is the difference between System.Text.StringBuilder and System.String?
1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.
How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.
string str = "One";
int i = 0;
if(int.TryParse(str,out i))
{
Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
Console.WriteLine("string does not contain Integer");
}
What is the difference between int.Parse and int.TryParse methods?
Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.
ASP.NET Interview Questions:
What is the difference between const and static read-only member?
A const field must be initialized at the place where it is declared as shown in the example below.
class Program
{
public const int Number = 100;
}
It is a compile time error to declare a const without a value. The code below will generate a compiler error stating "A const field requires a value to be provided"
class Program
{
public const int Number;
}
It is a compile time error to change the value of a constant. The following code will generate a compiler error stating "The left-hand side of an assignment must be a variable, property or indexer"
class Program
{
public const int Number = 100;
static void Main()
{
Number = 200;
}
}
It is not mandatory to initialize a static readonly field where it is declared. You can declare a static readonly field without an initial value and can later initialize the static field in a static constructor as shown below.
class Program
{
public static readonly int Number;
static Program()
{
Number = 100;
}
}
Once a static readonly field is initialized, the value cannot be changed. The code below will generate a compiler error stating "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)"
class Program
{
public static readonly int Number;
static Program()
{
Number = 100;
}
static void Main()
{
Number = 200;
}
}
In short, the difference is that static readonly field can be modified by the containing class, but const field can never be modified and must be initialized where it is declared. A static readonly field can be changed by the containing class using static constructor as shown below.
class Program
{
// Initialize the static readonly field
// to an initial value of 100
public static readonly int Number=100;
static Program()
{
//Value changed to 200 in the static constructor
Number = 200;
}
}
Linq Interview Questions Part 1:
What is LINQ?
LINQ, or Language INtegrated Query, is a set of classes added to the .NET Framework 3.5. LINQ adds a rich, standardized query syntax to .NET programming languages that allows developers to interact with any type of data.
What are the advantages of using LINQ or Language INtegrated Query?
In any data driven application, you get data either from a Database, or an XML file or from collection classes. Prior to LINQ, working with each data source requires writing a different style of code. Moreover, working with external resources like data bases, XML files involves communicating with that external resource in some syntax specific to that resource. To retrieve data from a database you need to send it a string that contains the SQL query to execute, similarly, to work with an XML document involves specifying an XPath expression in the form of a string. The idea is that using LINQ you can work with disparate data sources using a similar style without having to know a separate syntax for communicating with the data source (e.g., SQL or XPath) and without having to resort to passing opaque strings to external resources.
In any data driven web application or windows application, we use database as a datasource for the application. In order to get data from the database and display it in a web or windows application, we typically do the following.
1. Prepare your SQL Statements.
2. Execute SQL Statements against the database.
3. Retrieve the results.
4. Populate the Business Objects.
5. Display the Data in the Web Form or Windows From.
In order to send a query to the database we must first establish a connection to the database. We then must encode the logic - the SQL query, its parameters, and the parameters' values - into strings that are supplied to the SqlCommand object. And because these inputs are encoded into opaque strings, there is no compile-time error checking and very limited debugging support. For example, if there is a spelling mistake in the SELECT query causing the Customets table name to be misspelled, this typographical error won't show up until runtime when this page is viewed in a web browser. These typographical errors are easy to make as there is no IntelliSense support. When we use LINQ, Visual Studio would display an error message alerting us about the incorrect table name.
Another mismatch between the programming language and the database is that the data returned by the database is transformed for us into objects accessible through the SqlDataReader, but these objects are not strongly-typed objects like we'd like. To get this data into strongly-typed objects we must write code ourselves that enumerates the database results and populates each record into a corresponding object.
LINQ was designed to address all these issues. LINQ also offers a unified syntax for working with data, be it data from a database, an XML file, or a collection of objects. With LINQ you don't need to know the intricacies of SQL, the ins and outs of XPath, or various ways to work with a collection of objects. All you need be familiar with is LINQ's classes and the associated language enhancements centered around LINQ.
In other words, LINQ provides type safety, IntelliSense support, compile-time error checking, and enhanced debugging scenarios when working with different datasources.
LINQ Interview Questions Part 2:
What are the three main components of LINQ or Language INtegrated Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Providers
How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface.
How are Standard Query Operators useful in LINQ?
Standard Query Operators in LINQ can be used for working with collections for any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.
6. Filter the results
List the important language extensions made in C# to make LINQ a reality?
1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions
What is the purpose of LINQ Providers in LINQ?
LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source.
What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.
Write a program using LINQ to find the sum of first 5 prime numbers?
Best pactices in developing asp.net applications - Part 1:
1.Remove unused private fields and functions.
2. Do not cast unnecessarily. Avoid duplicate casts where possible, since there is a cost associated with them.
3. Properties that return arrays are prone to code inefficiencies. Consider using a collection or making this a method.
4. To test for empty strings, check if String.Length is equal to zero. Constructs such as "".Equals(someString) and String.Empty.Equals(someString) are less efficient than testing the string length. Replace these with checks for someString.Length == 0.
5. Methods in the same type that differ only by return type can be difficult for developers and tools to properly recognize. When extending a type, be sure not to define new methods that differ from base type methods only by type.
6. Use stringbuilder instead of string types for string manipulation.
7. Use String.Format instead of concatenating and appending strings.
8. Use Type.TryParse rather than Convert.ToDestinationType(). For example use int.TryParse() rather than Convert.ToInt32() which might throw an exception.
9. Override Equals() method wherever applicable in your classes.
10. Consider passing base types as parameters - Using base types as parameters to methods improves re-use of these methods if you only use methods & properties from the parameter's base class. E.g. use Stream instead of FileStream as a parameter when only calling Stream.Read(), this makes the method work on all kind of streams instead of just File streams.
Best pactices in developing asp.net applications - Part 2:
Do not catch general exception types - You should not catch Exception or SystemException. Catching generic exception types can hide run-time problems from the library user, and can complicate debugging. You should catch only those exceptions that you can handle gracefully.
2. Use properties instead of visible instance fields.
3. Follow the same naming conventions accross the solution.
4. Remove unwanted commented code, Indent code properly.
5. Use curly braces with in an if statement, even if there is a single statement in the if block. This will provide better readability.
6. Make sure to refactor your code to move the duplicated code to common reusable functions.
7. Move one time control settings into the .aspx page rather than having them in the code behind in if(!IsPostback) block.
8. Use inheritance whereever possible, which enables code reuse and also reduces the amount of code we have to write and test.
9. Move the reusable javascript functions to an external .js file instead of having them on the page.
10. For controls that are declarativley specified on the page, tie the event handlers to the controls events on the aspx page rather than initializing them in the codebehind. If the controls are built dynamically then we donot have a choice.
11. Make sure to check for nulls when using any type retrieved from a session, querystring or a database to avoid NullReferenceExceptions.
12. Use foreach loop instead of using for loop which may lead to out of boundary run time exceptions.
ASP.NET Interview Questions on Data Access Security
What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.
Why is "Connecting to SQL Server using Integrated Security" considered a best practice?
Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.
What is the advantage of storing an XML file in the applications?
App_Data folder? The contents of the App_Data folder will not be returned in response to direct HTTP requests.
What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.
What is SQL injection?
A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application.
What are the best practices to keep in mind when accepting user input on a web application?
1. Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.
What are the steps to follow to avoid Script Injection attacks?
1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode.
What are the steps to follow to avoid SQL Injection attacks?
Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together.
Can you encrypt view state data of an aspx page?
Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.
ASP.NET Interview Questions on HTTP modules and HTTP Handlers:
What is an HTTP Handler?
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
What is HTTP module?
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
What is the interface that you have to implement if you have to create a Custom HTTP Handler?
Implement IHttpHandler interface to create a synchronous handler.
Implement IHttpAsyncHandler to create an asynchronous handler.
What is the difference between asynchronous and synchronous HTTP Handlers?
A synchronous handler does not return until it finishes processing the HTTP request for which it is called.
An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.
Which class is responsible for receiving and forwarding a request to the appropriate HTTP handler?
IHttpHandlerFactory Class
Can you create your own custom HTTP handler factory class?
Yes, we can create a custom HTTP handler factory class by creating a class that implements the IHttpHandlerFactory interface.
What is the use of HTTP modules?
HTTP modules are used to implement various application features, such as forms authentication, caching, session state, and client script services.
What is the difference between HTTP modules and HTTP handlers?
An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.
What is the common way to register an HTTP module?
The common way to register an HTTP module is to have an entry in the application's Web.config file.
Much of the functionality of a module can be implemented in a global.asax file. When do you create an HTTP module over using Global.asax File?
You create an HTTP module over using Global.asax file if the following conditions are true
1. You want to re-use the module in other applications.
2. You want to avoid putting complex code in the Global.asax file.
3. The module applies to all requests in the pipeline.
ASP.NET Interview Questions on Themes and Skins:
What is a "theme" in ASP.NET?
A "theme" is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.
What is the extension for a skin file?
.skin
What are the 2 types of control skins in ASP.NET?
1. Default skins
2. Named skins
What is the difference between Named skins and Default skins?
A default skin automatically applies to all controls of the same type when a theme is applied to a page. A control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)
A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application.
What are the 3 levels at which a theme can be applied for a web application?
1. At the page level - Use the Theme or StyleSheetTheme attribute of the @ Page directive.
2. At the application level - Can be applied to all pages in an application by setting the <pages> element in the application configuration file.
3. At the web server level - Define the <pages> element in machine.config file. This will apply the theme to all the web applications on that web server.
What is the name of the folder that contains the application themes?
App_Themes
What is a global theme?
A global theme is a theme that you can apply to all the Web sites on a server. Global themes allow you to define an overall look for your domain when you maintain multiple Web sites on the same server.
What is the difference between themes and CSS?
1. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.
2. Themes can include graphics.
3. Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property.
4. Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.
What are the security concerns to keep in mind when using themes?
Themes can cause security issues when they are used on your Web site. Malicious themes can be used to:
1. Alter a control's behavior so that it does not behave as expected.
2. Inject client-side script, therefore posing a cross-site scripting risk.
3. Expose sensitive information.
4. The mitigations for these common threats are:
5. Protect the global and application theme directories with proper access control settings. Only trusted users should be allowed to write files to the theme directories.
6. Do not use themes from an untrusted source. Always examine any themes from outside your organization for malicious code before using them on you Web site.
7. Do not expose the theme name in query data. Malicious users could use this information to use themes that are unknown to the developer and thereby expose sensitive information.
ASP.NET Interview Questions on DataSet:
What is a DataSet?
DataSet is an in-memory cache of data.
In which namespace is the DataSet class present?
System.Data
Can you add more than one table to a dataset?
Yes
Can you enforce constarints and relations on tables inside a DataSet?
Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.
What happens when you invoke AcceptChanges() method on a DataSet?
Invoking AcceptChanges() method on the DataSet causes AcceptChanges() method to be called on each table within the DataSet.
Both the DataRow and DataTable classes also have AcceptChanges() methods. Calling AcceptChanges() at the DataTable level causes the AcceptChanges method for each DataRow to be called.
When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes. Added and Modified rows become Unchanged, and Deleted rows are removed.
If the DataSet contains ForeignKeyConstraint objects, invoking the AcceptChanges method also causes the AcceptRejectRule to be enforced.
Is there a way to clear all the rows from all the tables in a DataSet at once?
Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.
What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
DataSet.Copy() copies both the structure and data.
How do you get a copy of the DataSet containing all changes made to it since it was last loaded?
Use DataSet.GetChanges() method
What is the use of DataSet.HasChanges() Method?
DataSet.HasChanges method returns a boolean true if there are any changes made to the DataSet, including new, deleted, or modified rows. This method can be used to update a DataSource only if there are any changes.
How do you roll back all the changes made to a DataSet since it was created?
Invoke the DataSet.RejectChanges() method to undo or roll back all the changes made to a DataSet since it was created.
What happnes when you invoke RejectChanges method, on a DataSet that contains 3 tables in it?
RejectChanges() method will be automatically invoked on all the 3 tables in the dataset and any changes that were done will be rolled back for all the 3 tables.
When the DataTable.RejectChanges method is called, any rows that are still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state. The DataRowState for all the modified and deleted rows will be flipped back to unchanged.
What is the DataSet.CaseSensitive property used for?
When you set the CaseSensitive property of a DataSet to true, string comparisons for all the DataTables within dataset will be case sensitive. By default the CaseSensitive property is false.
ASP.NET Interview Questions on Globalization:
What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application into multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.
The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application’s current culture, and much of the work is done automatically!
What are the 3 different ways to globalize web applications?
Detect and redirect approach : In this approach we create a separate Web application for each supported culture, and then detect the user’s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.
Run-time adjustment approach : In this approach we create a single Web application that detects the user’s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.
Satellite
assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user’s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.
In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object’s UserLanguages property to return a list of the user’s language preferences. The first element of the array returned by UserLanguages is the user’s current language on his/her computer.
What are the steps to follow to get user's culture at run time?
To get the user’s culture at run time, follow these steps:
1. Get the Request object’s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user’s current culture.
For example, the following code gets the user’s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}
What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.
What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific Web site.
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.
What is the use of culture attribute of the globalization element in web.config?
The Web.config file’s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.
Web.config globalization settings in subordinate folders override the globalization settings in the application’s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user’s CurrentCulture.
The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.
<body dir="rtl">
You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.
What do you mean by neutral cultures?
Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.
What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn’t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don’t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.
For what type of web applications setting the culture dynamically is best suited?
Setting the culture dynamically is best suited for simple Web applications that don’t contain large amounts of text that must be translated into different languages.
C# Interview Questions - Arrays :
What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below
1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
int[] IntegerArray; // not int IntegerArray[];
2. Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.
int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array
What are the 3 different types of arrays that we have in C#?
1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays
Are arrays in C# value types or reference types?
Reference types.
What is the base class for all arrays in C#?
System.Array
How do you sort an array in C#?
The Sort static method of the Array class can be used to sort array items.
Give an example to print the numbers in the array in descending order?
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}
What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}
Give an example to show how to copy one array into another array?
We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}
XML Interview Questions - Validating XML documents:
What determines the validity of an XML document?
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.
What is a valid XML document?
XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.
What are the 2 types of XML parsers?
Nonvalidating Parsers - Parsers that don’t support validation
Validating Parsers - Parsers that support validation
Can you combine both Schema and DTD references in a single XML document?
Yes
Are DTD's well-formed XML documents?
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.
Are XML schema's well-formed XML documents?
Yes.
What is the difference between an XML schema and a DTD?
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.
How do you define references to schemas in an XML document?
References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.
<rootelement xmlns:xsi=”http://www.w3.org/2001/XMLSchemainstance” xsi:noNamespaceSchemaLocation=”schemafile.xsd”>
The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.
You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.
XML related Interview Questions:
What Is XML?
XML stands for Extensible Markup Language, and it is used to describe documents and data in a standardized, text-based format that can be easily transported via standard Internet protocols. XML, like HTML, is based on, Standard Generalized Markup Language (SGML).
What are Well-formed XML documents?
XML, is very strict about a small core of format requirements that make the difference between a text document containing a bunch of tags and an actual XML document. XML documents that meet W3C XML document formatting recommendations are described as being well-formed XML documents. Well-formed XML documents can contain elements, attributes, and text.
What is an empty XML element?
Elements with no attributes or text are called as empty XML element. Empty XML elements can be represented in an XML document as shown below:
<element/>
What is meant by XML document declaration?
Most XML documents start with an <?xml?> element at the top of the page. This is called an XML document declaration. An XML document declaration is an optional element that is useful to determine the version of XML and the encoding type of the source data. It is not a required element for an XML document to be well formed. Most common XML document declaration is shown below:
<?xml version=”1.0” encoding=”UTF-8”?>
What does UTF stands for?
UTF stands for Universal Character Set Transformation Format.
Should every XML document have a root element?
Yes.
Can an XML document contain multiple root level elements?
No, an XML document can contain only one root level element.
What is the use of XML attributes?
XML attributes are used for adding more information and descriptions to the values of elements,and the text associated with elements.
Is XML case sensitive?
Yes
How do you comment lines in XML?
You can comment lines in XML as shown below.
<! -- This is commented line in an XML document -->
What are XML namespaces?
Namespaces are a method for separating and identifying duplicate XML element names in an XML document. Namespaces can also be used as identifiers to describe data types and other information. Namespace declarations can be compared to defining a short variable name for a long variable (such as pi=3.14159....) in programming languages. In XML, the variable assignment is defined by an attribute declaration. The variable name is the attribute name, and the variable value is the attribute value. In order to identify namespace declarations versus other types of attribute declarations, a reserved xmlns: prefix is used when declaring a namespace name and value. The attribute name after the xmlns: prefix identifies the name for the defined namespace. The value of the attribute provides the unique identifier for the namespace. Once the namespace is declared, the namespace name can be used as a prefix in element names.
Why is it a good idea to use a URL as the XML namespace value?
Although the namespace declaration value does not need to be a URL or resolve to an actual URL destination, it is a good idea to use a URL anyway, and to choose a URL that could resolve to an actual destination, just in case developers want to add documentation for the namespace to the URL in the future.
When to use namespaces?
Namespaces are optional components of basic XML documents. However, namespace declarations are recommended if your XML documents have any current or future potential of being shared with other XML documents that may share the same element names. Also, newer XML-based technologies such as XML Schemas,SOAP, and WSDL make heavy use of XML namespaces to identify data encoding types and important elements of their structure.
ASP.NET Interview Questions on caching application data
Which object can used to store frequently used items in the server’s memory for quick retrieval?
Cache object can be used to store frequently used items in the server’s memory for quick retrieval.
Is the cache object available for all web forms with in a web application?
Yes, the Cache object is global, that is, data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.
What are the 3 different ways to store data in the Cache object?
Use assignment.
Assigning a value to an unused key in the Cache object automatically creates that key and assigns the value to that key. Assigning a value to a key that already exists replaces the cached value with the assigned value.
Use the Insert method.
The Insert method uses parameters rather than assignment to create or change cached data. Insert optionally accepts parameters to establish dependencies and set expiration policy.
Use the Add method.
The Add method is similar to Insert; however, it requires all parameters and returns an object reference to the cached data.
For example, the following Cache statements all add the same item to the cache:
using System.Web.Caching;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Cache["NewItem"] = "Some string data";
Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null);
Cache.Insert("NewItem", "Some string data");
}
}
What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?
absoluteExpiration
A DateTime object that identifies when the data should be removed from the cache. If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.
slidingExpiration
A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.
Which delegate can be used to notify the application when items are removed from the cache?
onRemoveCallback is used to notify the application when items are removed from the cache.
How do you retrieve the value of a cache item stored in the servers memory?
You can retrieve the value of a cache item stored in the servers memory through the item’s key, just as you do with the Application and Session objects. Because cached items might be removed from memory, you should always check for their existence before attempting to retrieve their value, as shown in the following code:
private void Button1_Click(object sender, EventArgs e)
{
if (Cache["ChachedItem"] == null)
{
Lable1.Text = "Cached Item not found.";
}
else
{
Lable1.Text = Cache["ChachedItem"].ToString();
}
}
Which method can be used to remove data from the cache?
Cache object’s Remove method can be used to remove data from the cache as shown in the following code example / sample.
private void RemoveButton_Click(object sender, System.EventArgs e)
{
Cache.Remove("CachedItem");
}
How do you control how long data is cached?
The Cache object’s Add and Insert method parameters allow you to control how long an item is stored in the server’s memory. In practice, these parameter settings provide only indirect control of how long data remains in memory. If your server runs low on available memory, ASP.NET recovers as much memory as possible from expired cache items. If that’s not enough, ASP.NET will unload unexpired items from the cache based on their priority and when they were last accessed.
What is CacheItemPriority enumeration used for?
CacheItemPriority enumeration is used to set the relative importance of cached items. CacheItemPriority.NotRemoveable has the highest priority and CacheItemPriority.Low has the lowest priority.
Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object.
How do you update the Cache object when data changes?
Items stored in the cache are often copies of data that is stored and maintained elsewhere, such as records in a database. Use the Add and Insert methods’ dependency parameter to establish a relationship between a cached data item and an external source, such as a file, a folder, or a group of files.
The dependency parameter accepts a CacheDependency object, which in turn identifies the file, folder, or set of files to watch for changes. ASP.NET checks the time stamp of the items in the CacheDependency object, if one of those time stamps is later than the DateTime entered for the cached item, ASP.NET unloads that item from the cache.
ASP.NET Interview Questions on fragment caching:
What is fragment caching?
Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.
What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.
What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control’s class declaration to enable fragment caching.
What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.
VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).
If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can’t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.
When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect.
If the Web form’s cache duration is longer than the user control’s, both the Web form response and the user control response will expire using the Web form setting.
ASP.NET Interview Questions on Caching:
What is caching?
High-performance Web applications
should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form’s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.
Caching an item incurs considerable overhead, so it’s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form’s server-side content so that changes to that content do not appear until the cache is refreshed.
What directive is used to cache a web form?
The @OutputCache page directive is used to cache a Web form in the server’s memory.
What is the use of duration attribute of @OutputCache page directive?
The @OutputCache directive’s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.
The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.
After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.
What are the 2 required attributes of the @OutputCache directive?
The @OutputCache directive has two required attributes:
1. Duration
2. VaryByParam.
How do you cache multiple responses from a single Web form?
The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.
You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.
The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application’s Global.asax file.
Is it possible to cache a web form without using @OutputCache directive?
Yes, you can cache a web form using the Response object’s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive’s attributes.
Give a simple example to show how to cache a web form without using @OutputCache directive?
For example, the following code caches the Web form’s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}
The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"
What is @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property used for?
The @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheability setting as more of a request than a command.
What is HttpCachePolicy object’s SetAllowResponseInBrowserHistory method used for?
You can override the cache location settings using the HttpCachePolicy object’s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client’s history folder even if the location setting is None or Server.
Application build related ASP.NET Interview Questions:
What are the 2 build options for an ASP.NET web application?
1. Debug
2. Release
What are the 3 levels at which we can have a configuration file for an ASP.NET web application?
1. At the web server level : The Machine.config file located in the Windows\Microsoft.NET\Framework\version\config directory. This sets the base configuration for all .NET assemblies running on the server.
2. At the application or web site level : The Web.config file located in the IIS root directory.This sets the base configuration for all Web applications and overrides settings in Machine.config.
3. In the sub directory of an application root folder : These settings override the settings in the root folder's web.config file.
What happens when you make changes to an application’s Web.config file?
When you make changes to an application’s Web.config file, IIS automatically restarts the application and applies the changes. This has the side effect of resetting current Application or Session state variables, which can adversely affect users.
What happens when you access the Web.config file from a browser?
For security reasons, you can’t access the Web.config file from a browser. If a user requests the Web.config file from your Web site, he or she will receive an "This type of page is not served" error message.
What happens when you access the Global.asax file from a browser?
For security reasons, you can’t access the Global.asax file from a browser. If a user requests the Global.asax file from your Web site, he or she will receive an "This type of page is not served" error message.
What are the steps to follow to host a web application on a web server?
1. Use IIS to set up a virtual folder for the application.
2. Copy the Web application to the virtual directory.
3. Add any shared .NET components to the server’s global assembly cache (GAC).
4. Set the security permissions on the server to allow the application to access required resources.
What are the 2 components that should be installed on a web server where, the ASP.NET web application runs?
ASP.NET Web applications run under IIS, so both IIS and the Microsoft .NET Framework must be installed on the server before that server can host Web applications.
What is the purpose of default start page in IIS?
A default page enables IIS to display a page if the user does not specify one in his or her request. For example, a user might make a request using only your domain name, such as http://www.venkataspinterview.blogspot.com/. If a default page is enabled, IIS will respond with http://www.venkataspinterview.blogspot.com/default.aspx.
Don’t confuse IIS default pages with the Web Forms application start page in Visual Studio .NET. Visual Studio .NET requires that you set a start page for each project so that the development environment knows which page to display first during debugging. This setting has no effect on the IIS default page settings.
How do you copy the COM component to the server and register?
COM components generally provide a setup program to install or remove them from the system. If the component doesn’t provide a setup program, you can copy it to the server and register it using the MFC RegSvr32.exe utility, as shown below:
RegSvr32 MyComname.dll
What is GAC?
GAC stands for Global Assembly Cache. The global assembly cache (GAC) is a special subfolder within the Windows folder that stores the shared .NET components.
What is the difference between weak-named .NET components and strong-named .NET components?
This difference is how the names are stored within the assembly. Weak names are not guaranteed to be unique and thus cannot be shared without potentially causing conflicts. Strong names are digitally signed and provide a public key that ensures there are no conflicts. Furthermore, .NET components with strong names can’t call unmanaged code (such as COM components) and thus avoid potential conflicts with dependencies.
Weak-named .NET components must be individually copied to the /bin directories of the Web applications where they are used. Strong-named .NET components can be copied into the server’s GAC
What is the account under which the ASP.NET worker process run?
By default, the ASP.NET worker process runs using the ASPNET account, which is created when you install the .NET Framework. This account has limited privileges, which can cause permission-denied errors if your application writes files or tries to read files outside the current Web application’s boundaries.
What are the 3 ways in which you can modify the additional permissions required by your application?
1. Grant the ASPNET user access to the required files. To use this option, the server must be using the Windows NT file system (NTFS).
2. Change the group the ASPNET user belongs to.
3. Use impersonation to run the process as another user.
Why is it not a good idea to add ASPNET user to the Administrators group?
Adding the ASPNET user to the Administrators group gives your Web application full privileges on the server; however, it also poses a potential security risk because outside users might be able to manipulate your application to hack your server.
How do you impersonate the ASP.NET worker process?
To use impersonation to run the ASP.NET worker process as a user other than ASPNET, set the identity element’s impersonation attribute in the application’s Web.config file.
ASP.NET Interview Questions on Master Pages:
What are Master Pages in ASP.NET? or What is a Master Page?
ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.
What are the 2 important parts of a master page?
The following are the 2 important parts of a master page
1. The Master Page itself
2. One or more Content Pages
Can Master Pages be nested?
Yes, Master Pages be nested.
What is the file extension for a Master Page?
.master
How do you identify a Master Page?
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages.
Can a Master Page have more than one ContentPlaceHolder?
Yes, a Master Page can have more than one ContentPlaceHolder
What is a ContentPlaceHolder?
ContentPlaceHolder is a region where replaceable content will appear.
How do you bind a Content Page to a Master Page?
MasterPageFile attribute of a content page's @ Page directive is used to bind a Content Page to a Master Page.
Can the content page contain any other markup outside of the Content control?
No.
What are the advantages of using Master Pages?
1. They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
2. They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master page to create a menu that applies to all pages.
3. They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
4. They provide an object model that allows you to customize the master page from individual content pages.
What are the 3 levels at which content pages can be attached to Master Page?
At the page level - You can use a page directive in each content page to bind it to a master page
At the application level - By making a setting in the pages element of the application's configuration file (Web.config), you can specify that all ASP.NET pages (.aspx files) in the application automatically bind to a master page.
At the folder level - This strategy is like binding at the application level, except that you make the setting in a Web.config file in one folder only. The master-page bindings then apply to the ASP.NET pages in that folder.
What is @MasterType directive used for?
@MasterType directive is used to create a strongly typed reference to the master page.
Are controls on the master page accessible to content page code?
Yes, controls on the master page are accessible to content page code.
At what stage of page processing master page and content page are merged?
During the initialization stage of page processing, master page and content page are merged.
Can you dynaimically assign a Master Page?
Yes, you can assign a master page dynamically during the PreInit stage using the Page class MasterPageFile property as shown in the code sample below.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MasterPage.master";
}
Can you access non public properties and non public methods of a master page inside a content page?
No, the properties and methods of a master page must be public in order to access them on the content page.
From the content page code how can you reference a control on the master page?
Use the FindControl() method as shown in the code sample below.
void Page_Load()
{
// Gets a reference to a TextBox control inside
// a ContentPlaceHolder
ContentPlaceHolder ContPlaceHldr = (ContentPlaceHolder)Master.FindControl ("ContentPlaceHolder1");
if(ContPlaceHldr != null)
{
TextBox TxtBox = (TextBox)ContPlaceHldr.FindControl("TextBox1");
if(TxtBox != null)
{
TxtBox.Text = "TextBox Present!";
}
}
// Gets a reference to a Label control that not in
// a ContentPlaceHolder
Label Lbl = (Label)Master.FindControl("Label1");
if(Lbl != null)
{
Lbl.Text = "Lable Present";
}
}
Can you access controls on the Master Page without using FindControl() method?
Yes, by casting the Master to your MasterPage as shown in the below code sample.
protected void Page_Load(object sender, EventArgs e)
{
MyMasterPage MMP = this.Master;
MMP.MyTextBox.Text = "Text Box Found";
}
ASP.NET Interview Questions on Passport Authentication:
What is Passport Authentication?
Passport authentication identifies users via Microsoft Passport’s single sign-on service. Microsoft Passport is meant to provide Internet users with a single identity that they can use to visit a wide variety of Web sites that require authentication. Information about the user is available to your application through a profile that is stored with Microsoft.
What are the advantages of Passport authentication?
The advantages of Passport authentication are that the user doesn’t have to remember separate user names and passwords for various Web sites and that the user can maintain his or her profile information in a single location. Passport authentication also provides access to other Microsoft services, such as Passport Express Purchase.
What is passport software development kit (passport SDK)?
To use Passport authentication in your Web application, you must install the Passport SDK. The Passport SDK is free for preproduction development and testing. To deploy a site for public use, you must obtain an annual license from Microsoft.
How does Passport authentication work?
When a user accesses an application that implements Passport authentication, ASP.NET checks the user’s machine for a current passport authentication cookie. If none is found, ASP.NET directs the user to a Passport sign-on page. Once the user signs in, the Passport service authenticates the user, stores an authentication cookie on the user’s computer, and directs the user back to the originally requested Web page.
What are the steps to follow to use Passport authentication?
1. Install the Passport SDK. Passport is not included with Visual Studio, although the .NET Framework does include classes for working with the Passport SDK once it is installed.
2. Set the application’s authentication mode to Passport in Web.config. Set authorization to deny unauthenticated users.
3. Use the PassportAuthentication_OnAuthenticate event to access the user’s Passport profile to identify and authorize the user.
4. Implement a sign-out procedure to remove Passport cookies from the user’s machine.
Where is PassportAuthentication_OnAuthenticate event present?
PassportAuthentication_OnAuthenticate event is present in Global.asax.
SSL and HTTPS related ASP.NET Interview Questions
How do you provide Secure Communication over the world wide web?
Security is not just a matter of identifying users and preventing unauthorized users from accessing your Web applications, but it’s just as important to ensure that sensitive data sent across the Internet can’t be read by others.
To provide secure communication across the Internet, IIS supports a standardized means of encrypting and decrypting Web requests and responses. This cryptography requires that you request an encryption key called a server certificate from an independent third party called a certificate authority.
What is Secure Sockets Layer (SSL)?
The Secure Sockets Layer (SSL) is the standard means of ensuring that data sent over the Internet can’t be read by others. When a user requests a secure Web page, the server generates an encryption key for the user’s session and then encrypts the page’s data before sending a response. On the client side, the browser uses that same encryption key to decrypt the requested Web page and to encrypt new requests sent from that page.
Explain the process of secure communication using SSL?
Using SSL in your application requires special authorization from a recognized certificate authority. This authorization comes in the form of a server certificate, which you install in IIS to identify your server. The certificate authority licenses server certificates (for a fee) and acts as a clearinghouse to verify your server’s identity over the Internet.
When a user’s browser begins secure communications, it requests the server certificate and checks it against a list of trusted sites provided by the certificate authority. If the server certificate does not match one of the sites already authorized by the user, or if the server certificate does not match the Web address for which it was registered, or if there are any other problems with the server certificate, the browser displays a warning.
In this way, the certificate authority not only provides encryption for secure data transmission, but it also provides assurance to users that your Web site is authentic.
What is the largest certificate authority?
The largest certificate authority is VeriSign.
What are the steps to follow to use SSL in your Web application?
1. Generate a certificate request from IIS.
2. Request a certificate from a certificate authority.
3. Install the certificate on the server using IIS.
4. Install the certificate on browsers if you are using a test certificate.
5. Use the Secure Hypertext Transfer Protocol (HTTPS) when accessing secure pages in your application.
What should you do before you can request a server certificate from a certificate authority?
Before you can request a server certificate from a certificate authority, you must generate a certificate request from IIS. The certificate request contains encrypted information about your server that the certificate authority uses to identify your server over the Internet.
What are the steps to follow to generate a certificate request from the IIS?
1. Select Default Web Site in the console tree of the IIS, and then choose Properties from the Action menu. IIS displays the Default Web Site Properties dialog box.
2. Click the Directory Security tab in the Properties dialog box, and then click Server Certificate. IIS starts the Web Server Certificate Wizard.
3. Step through the wizard by reading each screen and clicking Next. The wizard instructions are straightforward.
4. When you click Finish at the end, the wizard creates an encrypted text file with the .cer file extension. That file is the certificate request that you send to the certificate authority.
Why do you have to select Default Web Site when generating a Certificate Request from IIS?
IIS requires that a certificate be created at the server root before secure communications can be created or configured for subordinate sites on the server. That’s why you have to select Default Web Site (or the root Web site if you have renamed it). After you have installed a server certificate at the root, you can repeat the process for subordinate sites if you want separate certificates for those sites.
What is the file extension of a server certificate?
.cer
What are the steps to follow to install the Certificate to enable SSL for your Web applications?
To install a server certificate in IIS:
1. Select Default Web Site in the console tree of the IIS snap-in, and then choose Properties from the Action menu. IIS displays the Default Web Site Properties dialog box.
2. Click the Directory Security tab in the Properties dialog box, and then click Server Certificate. IIS starts the Web Server Certificate Wizard.
3. Click Next, and select Process The Pending Request And Install The Certificate.
4. Click Next, and enter the name of the certificate file.
5. Click Next, and then click Finish to complete the installation.
What is the protocol on which secure pages are generally requested?
HTTPS, the protocol HTTPS is what initializes the secure communication. When you’ve begun secure communication, it continues until you specify a nonsecure site.
What are the steps to follow to make a web page secure in a web application?
To require secure communication for a Web page using IIS, follow these steps
1. Select the folder or file that requires secure communication, and then choose Properties from the Action menu. IIS displays the Properties dialog box.
2. Click the Directory Security tab, and then click Edit in the Secure Communications group. IIS displays the Secure Communications dialog box.
3. Select the Require Secure Channel (SSL) check box, and click OK.
Can a user access secure web page over HTTP protocol instead of HTTPS?
No, When you require secure communication for a Web page, that page can’t be viewed using HTTP. The user must type in or click a link using HTTPS, otherwise, access will be denied.
ASP.NET Forms Authentication related interview questions:
What is the advantage of using Forms authentication?
The advantage of using Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications, particularly commercial sites where customers order products, want to have access to user information. Forms authentication makes these types of applications easier to create.
List the steps to use Forms authentication in a web application?
1.Set the authentication mode in Web.config to Forms.
2.Create a Web form to collect logon information.
3.Create a file or database to store user names and passwords.
4.Write code to add new users to the user file or database.
5.Write code to authenticate users against the user file or database.
What happens when someone accesses a Web application that uses Forms authentication?
When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config. Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by the authentication settings in Web.config.
What is the difference between Windows authentication and Forms authentication?
The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those items against a list of authorized users.
What is the use of mode attribute in authentication element in a web.config file?
You use the mode attribute to specify the type of authentication your web application is using. Set the mode attribute to forms to enable Forms authentication.
What is the use of name attribute and loginUrl attribute of a forms element in a web.config file?
Name attribute of forms element is used to set the name of the cookie in which to store the user’s credential. The default is .authaspx. If more than one application on the server is using Forms authentication, you need to specify a unique cookie name for each application.
loginUrl attribute of forms element is used to set the name of the Web form to display if the user has not already been authenticated. If omitted, the default is Default.aspx.
What is protection attribute in a forms element used for in web.config file?
The protection attribute of a forms element of web.config file is used for setting how ASP.NET protects the authentication cookie stored on the user’s machine. The default is All, which performs encryption and data validation. Other possible settings are Encryption, Validation, and None.
What is timeout attribute in a forms element used for in web.config file?
Timeout attribute is used to set the number of minutes the authentication cookie persists on the user’s machine. The default is 30, indicating 30 minutes. ASP.NET renews the cookie automatically if it receives a request from the user and more than half of the allotted time has expired.
In which namespace the FormsAuthentication class is present?
System.Web.Security namespace
Which method checks the user name and password against the user list found in the credentials element of Web.config?
The FormsAuthentication class’s Authenticate method checks the user name and password against the user list found in the credentials element of Web.config.
Which method can be used to remove forms authentication cookie?
Use the signout() method of FormsAuthentication class to sign out when the user has finished with the application or when you want to remove the authentication cookie from his or her machine. For example, the following code ends the user’s access to an application and requires him or her to sign back in to regain access
FormsAuthentication.SignOut();
What is the advantage of Authenticating Users with a Database?
You can authenticate users based on a list in Web.config. The FormsAuthentication class’s Authenticate method is set up to read from web.config file automatically. That’s fine if user names and passwords are created and maintained by a system administrator, but if you allow users to create their own user names or change their passwords, you’ll need to store that information outside the Web.config file. This is because changing Web.config at run time causes the Web application to restart, which resets any Application state and Session state variables used by the application.
What are the advantages of storing user names and passwords in a database rather than a file?
You can store user names and passwords in any type of file; however, using a database has the following significant advantages:
1. User names can be used as primary keys to store other information about the user.
2. Databases can provide high performance for accessing user names and passwords.
3. Adding, modifying, and accessing records are standardized through SQL.
Can you encrypt user names and passwords stored in a file or a database?
Yes, you encrypt user names and passwords stored in a file or a database. You can encrypt them using the FormsAuthentication class’s HashPasswordForStoringInConfigFile method. This method uses the SHA1 or MD5 algorithms to encrypt data, as shown below:
Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");
Can you change authentication type in a subfolder's web.config file?
Authentication type (Windows, Forms, or Passport) can be set only at the application’s root folder. To change authentication type in a subfolder's web.config file, you must create a new Web application project and application starting point for that subfolder.
How can you control access to subfolders in a web application?
The authorization settings in the Web.config file apply hierarchically within the folder structure of a Web application. For instance, you might want to allow all users access to the root folder of a Web application but restrict access to Web forms (and tasks) available from a subfolder. To do this, set the authentication type in the root folder’s Web.config file, and then use the authorization element in the subfolder’s Web.config file to restrict access.
ASP.NET Interview Questions on windows authentication:
What is the advantage of using Windows authentication in a Web application?
Windows authentication uses the security features integrated into the Windows NT and Windows XP operating systems to authenticate and authorize Web application users. The advantage of Windows authentication is that your Web application
can use the exact same security scheme that applies to your corporate network - user names, passwords, and permissions are the same for network resources and Web applications. One of the key advantages of Windows authentication is that users who are logged on to the network don’t have to log on again to access the Web application.
What is the default authentication method when you create a new Web application project?
Windows authentication is the default authentication method when you create a new Web application project.
How do you allow or deny access to specific users using an authorization list from Web.config file, when using windows authentication?
When the application uses Windows authentication, ASP.NET checks the project’s Web.config authorization list to see which network users are allowed to access the application. The asterisk (*) and question mark (?) characters have special meaning in the authorization list. The * character indicates all users. The ? character indicates unauthenticated users.
To restrict access to specific users, list their names separated by commas in an element. When ASP.NET checks the authorization list in Web.config, it accepts the first match that it finds. Be sure to end the authorization list with a element to deny access to any nonapproved users.
What is Role-Based authorization in windows authentication?
Role-based authorization lets you identify groups of users to allow or deny based on their role in your organization. In Windows NT and Windows XP, roles map to names used to identify user groups. Windows defines several built-in groups, including Administrators, Users, and Guests. You can view, modify, or add groups using the Computer Management console
To allow or deny access to certain groups of users, add the element to the authorization list in your Web application’s Web.config file.
How do you get a User Identity?
Once a user is authenticated and authorized, your application can get information about the user by using the User object’s Identity property. The Identity property returns an object that includes the user name and role information, as shown in the following code:
private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = User.Identity.IsAuthenticated.ToString();
Label2.Text = User.Identity.Name;
Label3.Text = User.Identity.AuthenticationType;
}
How do you determine, what is the role of the current user?
The User object provides an IsInRole method to determine the role of the current user, as shown in the following example:
if(User.IsInRole("Administrators"))
{
// Do something.
}
Can you specify authorization settings both in Web.config and in IIS?
Yes, you can specify authorization settings both in Web.config and in IIS. The IIS setting is evaluated first and then the setting in Web.config is evaluated. In general, this means that the most restrictive setting will be used.
What is the user account under which an ASP.NET web application runs by default?
Web application runs under the identity of the ASPNET user account by default.
How can you set the web application to run under a specific user’s account?
You can set the application to run under a specific user’s account by setting the application’s identity element to enable impersonation
How can you see the impersonated identity under which code is executing?
To see the impersonated identity under which code is executing, use the WindowsIdentity class’s GetCurrent method, as shown in the sample code below
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
The identity element can be used with any type of authentication; however, it is most useful with Windows authentication because Windows authentication users have accounts with specific permissions.
Frequently asked ADO.NET Interview Questions:
How do you create an instance of SqlDataReader class?
To create an instance of SqlDataReader class, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.
//Error! Cannot use SqlDataReader() constructor
//to create an instance of SqlDataReader class
SqlDataReader ReaderObject = new SqlDataReader();
//Call the ExecuteReader method of the SqlCommand object
SqlCommand CommandObject = new SqlCommand();
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
Creating an instance of SqlDataReader class using SqlDataReader() constructor generates a compile time error - The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined.
How do you programatically check if a specified SqlDataReader instance has been closed?
Use the IsClosed property of SqlDataReader to check if a specified SqlDataReader instance has been closed. If IsClosed property returns true, the SqlDataReader instance has been closed else not closed.
How do you get the total number of columns in the current row of a SqlDataReader instance?
FieldCount property can be used to get the total number of columns in the current row of a SqlDataReader instance.
Give an example for executing a stored procedure with parameters?
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify to CommandObject that you intend to execute a Stored Procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Create an SQL Parameter object
SqlParameter ParameterObject = new SqlParameter();
//Specify the name of the SQL Parameter
ParameterObject.ParameterName = "Parameter1";
//Assign the Parameter value
ParameterObject.Value = "Some Value";
//Specify the Database DataType of the Parameter
ParameterObject.DbType = DbType.String;
//Specify the type of parameter - input-only, output-only, bidirectional
ParameterObject.Direction = ParameterDirection.Input;
//Associate the Parameter to the Command Object
CommandObject.Parameters.Add(ParameterObject);
//Open the connection
ConnectionObject.Open();
//Execute the command
int Records_Affected = CommandObject.ExecuteNonQuery();
//Close the Connection
ConnectionObject.Close();
What is the use of SqlParameter.Direction Property?
SqlParameter.Direction Property is used to specify the Sql Parameter type - input-only, output-only, bidirectional, or a stored procedure return value parameter. The default is Input.
How do you retrieve two tables of data at the same time by using data reader?
Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.
The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.
//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
ConnectionObject.Open();
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
{
while (ReaderObject.Read())
{
//Do Something
}
}
//Close the Reader
ReaderObject.Close();
//Close the Connection
ConnectionObject.Close();
What are the advantages of using SQL stored procedures instead of adhoc SQL queries in an ASP.NET web application?
Better Performance : As stored procedures are precompiled objects they execute faster than SQL queries. Every time we run a SQL query, the query has to be first compiled and then executed where as a stored procedure is already compiled. Hence executing stored procedures is much faster than executing SQL queries.
Better Security : For a given stored procedure you can specify who has the rights to execute. You cannot do the same for an SQL query. Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements.
Reduced Network Traffic : Stored Procedures reside on the database server. If you have to execute a Stored Procedure from your ASP.NET web application, you just specify the name of the Stored Procedure. So over the network you just send the name of the Stored Procedure. With an SQL query you have to send all the SQL statements over the network to the database server which could lead to increased network traffic.
Can you update the database using DataReader object?
No, You cannot update the database using DataReader object. DataReader is read-only, foward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record.
What is the difference between a DataReader and a DataSet?
DataReader
1. DatReader works on a Connection oriented architecture.
2. DataReader is read only, forward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record. So using a DataReader you read in forward direction only.
3. Updations are not possible with DataReader.
4. As DataReader is read only, forward only it is much faster than a DataSet.
DataSet
1. DataSet works on disconnected architecture.
2. Using a DataSet you can move in both directions. DataSet is bi directional.
3. Database can be updated from a DataSet.
4. DataSet is slower than DataReader.
Give an example scenario of using a DataSet and a DataReader?
If you want to just read and display the data(No updates, deletes, or inserts) then use a DataReader.
If you want to do a batch inserts, updates and deletes then use a DataSet.
Basic ADO.NET Interview Questions
What is Microsoft ADO.NET?
Visual Studio
.NET provides access to databases through the set of tools and namespaces collectively referred to as Microsoft ADO.NET
What are the 3 major types of connection objects in ADO.NET?
OleDbConnection object : Use an OleDbConnection object to connect to a Microsoft Access or third-party database, such as MySQL. OLE database connections use the OleDbDataAdapter object to perform commands and return data.
SqlConnection object : Use a SqlConnection object to connect to a Microsoft SQL Server database. SQL database connections use the SqlDataAdapter object to perform commands and return data.
OracleConnection object : Use an OracleConnection object to connect to Oracle databases. Oracle database connections use the OracleDataAdapter object to perform commands and return data. This connection object was introduced in Microsoft .NET Framework version 1.1.
List the 4 common ADO.NET Namespaces?
System.Data : Contains Classes, types, and services for creating and accessing data sets and their subordinate objects
System.Data.SqlClient : Contains Classes and types for accessing Microsoft SQL Server databases
System.Data.OracleClient : Contains Classes and types for accessing Oracle databases (Microsoft .NET Framework version 1.1 and later)
System.Data.OleDb : Contains Classes and types for accessing other databases
List all the steps in order, to access a database through ADO.NET?
1. Create a connection to the database using a connection object.
2. Invoke a command to create a DataSet object using an adapter object.
3. Use the DataSet object in code to display data or to change items in the database.
4. Invoke a command to update the database from the DataSet object using an adapter object.
5. Close the database connection if you explicitly opened it in step 2 using the Open method. Invoking commands without first invoking the Open method implicitly opens and closes the connection with each request.
Why will you usually create an ASPNET user account in the Database for an ASP.NET web application?
Web applications run using the ASPNET user account. The SQL database administrator will have to set up this account and grant it permissions before your Web application will have access to a SQL database. For file-based databases, such as Microsoft Access, you must grant permissions on the database file to the ASPNET user account using Windows file security settings.
What is the difference between DataReader and DataAdapter?
1. Data Reader is read only forward only and much faster than DataAdapter.
2. If you use DataReader you have to open and close connection explicitly where as if you use DataAdapter the connection is automatically opened and closed.
3. DataReader is connection oriented where as Data Adapter is disconnected
Can you inherit from SqlConnection Class?
No, you cannot inheirt from SqlConnection Class. SqlConnection Class is a sealed class. It is a compile time error.
Will the connection be closed, if the SqlConnection object goes out of scope?
No, If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose.
What happens if connection pooling is enabled?
If connection pooling is enabled and when you call Close or Dispose methods, then the connection is returned to the connection pool. This connection can then be resused.If connection pooling is disabled and when you call Close or Dispose methods, the underlying connection to the server is actually closed.
How do you ensure that the database connections are always closed?
To ensure that the database connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (SqlConnection ConnectionObject = new SqlConnection())
{
ConnectionObject.Open();
//The database connection will be closed when the control exits the using code block
}
How do you read an XML file into a DataSet?
Using the DataSet object’s ReadXML method.
When do you use ExecuteReader, ExecuteNonQuery, ExecuteScalar methods?
If the command or stored procedure that is being executed returns a set of rows, then we use ExecuteReader method.
If the command or stored procedure that is being executed returns a single value then we use ExecuteScalar method.
If the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use ExecuteNonQuery method. ExecuteNonQuery method returns an integer specifying the number of rows inserted, deleted or updated.
Can your class inherit from SqlCommand Class?
No, you cannot inheirt from SqlCommand Class. SqlCommand Class is a sealed class. It is a compile time error.
Give an example that shows how to execute a stored procedure in ADO.NET?
using (SqlConnection ConnectionObject = new SqlConnection())
{
//Specify the name of the stored procedure to execute and the Connection Object to use
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify the SQL Command type is a stored procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Open the connection
ConnectionObject.Open();
//Execute the Stored Procedure
int RecordsAffected = CommandObject.ExecuteNonQuery();
}
Can you reuse a SqlCommand object?
Yes, you can reset the CommandText property and reuse the SqlCommand object.
What are the methods that can ensure asynchronous execution of the Transact-SQL statement or stored procedure?
BeginExecuteNonQuery
BeginExecuteReader
What is SqlCommand.CommandTimeout Property used for?
CommandTimeout Property is used to Get or set the wait time before terminating the attempt to execute a command and generating an error.
//Specify the CommandTimeout property value
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Wait for 10 seconds to execute the Stored procedure
CommandObject.CommandTimeout = 10;
The time is in seconds. The default is 30 seconds.
Interview Questions on ASP.NET controls
What are the 2 types of controls that you can use on a webform in ASP.NET?
Web Server Controls
HTML Controls
What’s the difference between Server controls and HTML controls?
1. Server controls can trigger control-specific events on the server.HTML controls can trigger only page- level events on server (postback).
2. Data entered in a server control is maintained across requests. Server controls retain state.Data is not maintained in an HTML control. Data must be saved and restored using page-level scripts.
3. The Microsoft .NET Framework provides a set of properties for each server control. Properties allow you to change the server control’s appearance and behavior within server-side code.HTML controls have HTML attributes only.
4. Server controls automatically detect browser and adapt display as appropriate.HTML controls do not adapt automatically. You must detect browser in code or write for least common denominator.
What are the 2 Layouts supported by a Web form in ASP.NET?
Grid layout - Controls are placed exactly where you draw them, and they have absolute positions on the page. Use grid layout for Microsoft Windows–style applications, in which controls are not mixed with large amounts of text. Pages using grid layout will not always display correctly in non-Microsoft browsers.
Flow layout - This layout positions controls relative to other elements on the page. If you add elements at run time, the controls that appear after the new element move down. Use flow layout for document-style applications, in which text and controls are intermingled.
When do you choose between GridLayout and Flow layout for Web forms?
You use GridLayout for Web forms that have a fixed appearance. You use FlowLayout for Web forms that incorporate text and controls.When you create controls with GridLayout, Visual Studio adds style attributes to each control that set the position of the control.When you create controls with FlowLayout, Visual Studio omits the style attribute.
Give 3 reasons why we use HTML controls over Server Controls?
Migration from earlier versions of Active Server Pages (ASP) : You can load an ASP application into Visual Studio and revise it gradually, rather than rewrite it completely. Earlier versions of ASP supported only HTML elements, and these elements become HTML controls when you load the project in Visual Studio .NET.
Not all controls require server-side events or state management : This is particularly true when you’re doing data binding. Bound items are usually refreshed from the data source with each request, so it’s more efficient not to maintain state information for bound controls. This means that you can use HTML controls or turn off state management for bound server controls.
You have complete control over what is rendered with HTML controls : ASP.NET adjusts the appearance of server controls based on the browser making the request. HTML controls are not adjusted, so you have direct control over their appearance.
How can you prevent users from editing Text in TextBox control on a web form?
By making the TextBox a readonly TextBox. To make a TextBox readonly set the ReadOnly property to True.
How do you convert an ASP.NET TextBox to accept passwords?
To convert and ASP.NET TextBox to accept passwords set the TextMode property to "Password"
What happens when you set the AutoPostBack property of a TextBox to true?
When AutoPostBack property is set to True, the TextBox control fires a TextChanged postback event when the user leaves the TextBox control after changing the contents. By default, this property is set to False and the TextChanged event is cached until some other postback event occurs.
What are the 3 values that a TextMode property of TextBox can have?
SingleLine : Single Line TextBox
MultiLine : Multi Line TextBox(scrollable)
Password : When set to Password, the text box displays dots in place of the characters typed.
How do you limit the number of characters entered by a user in the ASP.NET TextBox?
By setting the MaxLength property of the TextBox. If you set the MaxLength property to 10, a user can enter only 10 characters into the TextBox.
ASP.NET Interview Questions on Cookies:
What are Cookies in ASP.NET?
Cookies are small pieces of information stored on the client computer.Use cookies to store small amounts of information on the client’s machine. Web sites often use cookies to store user preferences or other information that is client-specific. Because cookies can be refused, it is important to check whether the browser allows them before you try to create them.They are limited to storing only character data and they are limited to 4K in size.
What are different types of Cookies?
Session Cookies
Persistent Cookies
What are Session Cookies?
Session cookies are stored in-memory during the client browser session. When the browser is closed the session cookies are lost.
How can you create Session Cookies?
You can create session cookies by calling the Add method of the Cookies collection on the Response object. The Cookies collection contains individual cookie objects of type HttpCookie.
//Code to create a UserName cookie containing the name David.
HttpCookie CookieObject = new HttpCookie("UserName", "David");
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
Request.Cookies["UserName"].Value;
What is the difference between Session Cookies and Persistent Cookies?
Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine that there is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site.
What are Persistent Cookies used for?
Persistent cookies are generally used to store information that identifies a returning user to a Web site. Typical information found in Persistent Cookies includes user names or user IDs.
How do you create a Persistent Cookie?
You create a persistent cookie the same way as session cookies except that you set the Expires property to a Date in the future which will store the Cookie to the client computer harddrive.
//Code to create a UserName Persistent Cookie that lives for 10 days
HttpCookie CookieObject = new HttpCookie("UserName", "David");
CookieObject.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
Request.Cookies["UserName"].Value;
What is Cookie Dictionary?
A cookie dictionary is a single cookie object that stores multiple pieces of information. You use the Values property to access and assign new values to the cookie dictionary.
Give an example using Cookie Dictionary?
//Code to create a Cookie Dictionary
HttpCookie CookieObject = new HttpCookie("UserPreference");
//Use the Values property to assign new values to the cookie dictionary
CookieObject.Values.Add("UserName", "David");
CookieObject.Values.Add("Country", "USA");
CookieObject.Values.Add("PreviousVisit", DateTime.Now.ToString());
CookieObject.Expires = DateTime.MaxValue;
//Add the Cookie to the client machine using the Response object
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
HttpCookie ObjectCookie = Request.Cookies["UserPreference"];
string UserName = ObjectCookie.Values["UserName"];
string Country = ObjectCookie.Values["Country"];
string PreviousVisit = ObjectCookie.Values["PreviousVisit"];
What are the advantages of Using Cookies?
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).
What are the disadvantages of Using Cookies?
1. Users can delete a cookies.
2. Users browser can refuse cookies,so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.
How do you create a Cookie that never expires?
To create a Cookie that never expires set the Expires property of the Cookie object to DateTime.MaxValue.
Are Cookies secure?
No, Cookies are not secure. You must pay attention to the type of data you store in cookies.
1. Cookies are not designed to store critical information so storing passwords in a cookie is a bad idea.
2. Keep the lifetime of a cookie as short as practically possible.
3. Encrypt cookie data to help protect the values stored in the cookie.
ASP.NET Events related Interview Questions
What are the different levels at which events can occur in an ASP.NET web application?
Web application events occur at the application, page, and server control levels
Give some examples for application level events?
1. Application_Start
Occurs when the first user visits a page within your Web application.
2. Application_End
Occurs when there are no more users of the application.
3. Application_BeginRequest
Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application.
4. Application_EndRequest
Occurs when at the end of each request to the server.
5. Session_Start
Occurs when a new user visits a page within your application.
6. Session_End
Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file.
7. Application_Error
Occurs when when there is an unhandled exception in an application.
Where are the application level event handlers present in an ASP.NET web application?
Application level event handlers are present in Global.asax of an ASP.NET web application
What is the difference between Application and Session Events?
At an application level we can have Application and Session events. Use Application events to initialize objects and data that you want to make available to all the current sessions of your Web application. Use Session events to initialize data that you want to keep throughout individual sessions, but that you don’t want to share between sessions.
Give an example of how to use Application and Session events?
To see how Application and Session events occur, add the following code to the Global.asax file in a Web forms project.
void Application_Start(object sender, EventArgs e)
{
// Create Application state variables.
Application["AppCount"] = 0;
Application["SessCount"] = 0;
// Record application start.
Application["AppCount"] = (int)Application["AppCount"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Count sessions.
Application["SessCount"] = (int)Application["SessCount"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement sessions.
Application["SessCount"] = (int)Application["SessCount"] - 1;
}
Add the following code to WebForm1.aspx file in a Web forms project and set WebForm1 as start up page.
protected void Page_Load(object sender, EventArgs e)
{
// Display Application count.
Response.Write("Number of applications: " +
Application["AppCount"] + "
");
// Display session count.
Response.Write("Number of sessions: " +
Application["SessCount"] + "
");
}
To demonstrate the events, run the preceding code, and then start a new instance of the browser and navigate to the address. Each new instance of the browser increments the session count, but the application count stays at 1.
How long a webform instance is available on the web server?
Web forms live for barely a moment. When we request a webform from the browser, the applications executable creates an instance of the requested Web form, generates the HTML to respond to the request, and posts that response to the browser. It then destroys the instance of the Web form.
When the client browser has the generated HTML, the user can type text in boxes, select options, and perform other tasks until triggering a postback event, such as a button click. Postback events cause the browser to send the page’s data (view state) back to the server for event processing. When the server receives the view state, it creates a new instance of the Web form, fills in the data from the view state, and processes any events that occurred. As soon as the server has finished, it posts the resulting HTML back to the browser and destroys the instance of the Web form.
Give some examples for page level events and when they occur?
1. Page_Init
During Page_Init the server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.
2. Page_Load
During Page_Load the server controls are loaded in the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.
3. Page_PreRender
During Page_PreRender the application is about to render the Page object.
4. Page_Unload
During Page_Unload the page is unloaded from memory.
5. Page_Disposed
During Page_Disposed the Page object is released from memory. This is the last event in the life of a Page object.
6. Page_Error
Page_Error event is raised when an unhandled exception occurs.
7. Page_AbortTransaction
Page_AbortTransaction is raised when a transaction is aborted.
8. Page_CommitTransaction
Page_CommitTransaction is raised when a transaction is commited.
9. Page_DataBinding
Page_DataBinding occurs when a server control on the page binds to a data source.
What is the order in which Page level events occur?
Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed
What page property is used to differentiate between a postback and initial get request of a page?
IsPostback property of the Page class.
What are the 3 types of Server Control Events?
Server controls, such as a Button, TextBox, and DropDownList, each have their own sets of events that occur in response to user actions. However, not all server control events are created equal. There are three types of server control events as listed below.
Postback events :
These events cause the Web page to be sent back to the server for immediate processing. Postback events affect perceived performance because they trigger a round-trip to the server. A Button control triggers a postback event. A dropdowinlist can also trigger a post back if the AutoPostBack property of the DropDownList is set to true, else a dropdownlist triggers a cached event. The same is the case with a TextBox.
Cached events :
These events are saved in the page’s view state to be processed when a postback event occurs. A DropDownList and a TextBox can trigger a cached event if the AutoPostBack property is set to false.
Validation events :
These events are handled on the page without posting back or caching. The validation server controls use these types of events.
How can you convert a Cached event of control to a post back event?
You can convert a Cached event of control to a post back event by setting the AutoPostBack property to true.
What is the order in which events are executed?
The validations controls are evaluated before the page is posted back to the server. When the page is posted back, the Page_Init and Page_Load events are handled, then cached events are handled, and finally the event that caused the postback is processed. Among cached events, the event order is determined by the order of the controls on the Web form.
Interview Questions on ASP.NET Exception Handling
What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.
What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation.
try
catch
finally
2. Use error events to deal with exceptions within the scope of an object.
Page_Error
Global_Error
Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.
Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.
Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.
What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.
How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the catch statement.
Will the following code block compile?
try
{
throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
}
No, a compile time error A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').
Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample, FileNotFoundException should be placed before the general Exception catch block.
What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception classes based on the ApplicationException class. For example, the following code defines a class for the UserLoggedOnException:
public class UserLoggedOnException : System.ApplicationException
{
// Exception constructor (overloaded).
public UserLoggedOnException()
: this("The user is already logged on to the server", null)
{
}
public UserLoggedOnException(string message)
: this(message, null)
{
}
public UserLoggedOnException(string message, Exception inner)
: base(message, inner)
{
}
}
The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception class provides only its own constructor to set the default message to display. This is a standard practice.
What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application, ASP.NET fires the error events shown below.
Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the following ways:
As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exception-handling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception in a log as part of an ongoing effort to improve your application.
Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the ClearError method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
// Get the error.
Exception ex = Server.GetLastError();
// Store the message in a session object.
Session["Error"] = ex.Message;
// Clear the error message.
Server.ClearError();
// Redisplay this page.
Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:
Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
// Display error. if any.
if (Session["Error"] != null)
{
litError.Text = "The following error occurred:
" +
Session["Error"].ToString();
// Clear the Session state variable.
Session["Error"] = null;
}
}
Can you have a try block without a catch or a finally block?
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either a catch block or a finally block or both.
Is the following code legal?
try
{
Response.Write("Try block executed");
}
finally
{
Response.Write("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.
What is wrong with using the following type of exception handler?
catch(Exception E)
{
//Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.
Will the second catch block handle the exception thrown by the first catch block?
try
{
throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
throw new Exception();
}
catch(Exception E)
{
Response.Write(E.Message);
}
No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.
What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
throw new Exception();
try
{
Response.Write("Hello");
}
catch (Exception E)
{
Response.Write(E.Message);
}
}
The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block.
Managed Code and Unmanaged Code related ASP.NET Interview Questions:
What is Managed Code and Unmanaged Code?
Microsoft ASP.NET Web applications run under the control of the common language runtime (CLR). The CLR controls how the application’s assembly executes, allocates, and recovers memory; therefore, ASP.NET applications are said to use managed code. In contrast, most other Windows executables use unmanaged code because the executable itself determines how memory is used.
Examples of unmanaged code include the Microsoft Win32 API, legacy DLLs and EXEs created for Windows applications prior to the Microsoft .NET Framework, and COM objects.
What is Platform Invoke or pinvoke?
The process of executing native code from within a .NET assembly is called platform invoke, or pinvoke for short. You use platform invoke to call the Win32 API directly, to access existing (legacy) DLLs your company uses, or to access procedures compiled to native code for performance reasons.
What are the steps to follow to use Platform Invoke?
To use platform invoke, follow the following steps:
1. Import the System.Runtime.InteropServices namespace.
2. Declare the unmanaged procedure using the DllImport attribute or the Declare statement.
3. Map the data types of the procedures parameters to the equivalent .NET types.
4. Call the unmanaged procedure and test its return value for success.
5. If the procedure did not succeed, retrieve and handle the exception code using the Marshal object’s GetLastWin32Error method.
What are the limitations of using Unmanaged Code from within a .NET assembly?
Performance : Although native-code DLLs can perform some operations more quickly than equivalent code managed by the CLR, these benefits might be offset by the time it takes to marshal the data to pass between the unmanaged procedure and the .NET assembly.
Type safety : Unlike .NET assemblies, unmanaged procedures might not be type-safe. This can affect the reliability of your .NET application. In general, reliability is a paramount concern with ASP.NET Web applications.
Code security : Unmanaged procedures do not use the .NET Framework’s model for code security.
Versioning:Unmanaged code does not support .NET versioning; therefore, assemblies that call unmanaged procedures might lose the benefit of being able to coexist with other versions of the same assembly.
What are COM objects?
COM objects are another type of unmanaged code that you can use from .NET assemblies. Because COM is widely used, Visual Studio includes built-in tools for importing and using COM objects within .NET assemblies. Visual Studio also includes the option of automatically registering .NET class library assemblies for use from COM.
List the steps in order, to use a COM object from a .NET assembly in Visual Studio?
1. Install and register the COM object on your system.
2. Open the .NET project in Visual Studio, and add a reference to the COM object, as shown in diagram below. If the COM object does not appear on the COM tab of the Add Reference dialog box, you can add a reference directly to the executable by clicking Browse.
3. Create an instance of the COM object in code, and use it as you would any other object.
What happens when you add a reference to a COM object from with in a dot net application?
When you add a reference to a COM object, Visual Studio automatically generates an interop assembly for the object and places it in the project’s /bin folder. The interop assembly is created from the COM object’s type information and contains the metadata that the CLR uses to call the unmanaged code in the COM object. You can then use COM objects from within .NET code the same way that you use .NET classes.
You can view this interop assembly using the Microsoft Intermediate Language Disassembler (Ildasm.exe) included in the .NET Framework.
Can we create a .NET object for use from COM?
Yes, Visual Studio can automatically generate type library information and register a .NET class library assembly for use from COM. These automatic tools do not work for ASP.NET Web applications, so you must isolate the code you want to use from COM in its own Class Library project.
How do you hide Public .NET Classes and other public members from COM?
In some cases, you might want to hide selected .NET classes from COM but keep them public for use from other .NET assemblies. The ComVisible attribute allows you to select which public .NET classes and members are included in the generated type library. This attribute applies hierarchically for the assembly, class, and member levels.
How do you handle exceptions between .NET and COM?
.NET handles errors through exception classes. COM handles errors through 32-bit data types called HRESULTs. All of the .NET exception classes include HResult properties that map to COM HRESULT codes.
If an exception occurs in a .NET object, the exception is automatically mapped to the appropriate HRESULT and returned to COM. Similarly, if an exception occurs in a COM object, the COM HRESULT is mapped to the appropriate exception class, which is returned to .NET, where it can be handled just like any other exception.
If you are creating your own .NET exception classes for use with COM, be sure to set the class’s HResult property so that the exception can be handled within COM.
What are the technical limitations of COM Interop?
The .NET Framework was developed to address the limitations of COM. Because of this evolution, there are limits to the .NET features that you can use from COM. The following list describes these limits:
Static members : COM requires objects to be created before use, so it does not support .NET Static members.
New members : COM flattens the inheritance tree of .NET objects, so members in a derived class that hides members inherited from a base class are not callable.
Constructors with parameters : COM can’t pass parameters to an object’s constructor.
What are the practical limitations of using COM objects?
The following are the practical limitations of using COM objects from .NET:
Shared solutions might not allow COM objects : ASP.NET host service providers that use nondedicated servers can limit or prohibit the installation of COM objects on their servers.
COM objects are prone to memory leaks : COM uses reference counting to determine when to destroy objects and free memory. It is possible for this reference count to become incorrect, leaving objects in memory indefinitely.
Type libraries might be inaccurate : Because COM separates the object’s description from its implementation, it’s possible for this description to not accurately reflect the object. In this case, the generated interop assembly will also include those inaccuracies.
COM is unmanaged code : All the limitations of unmanaged code apply to COM objects as well.
Interview Questions on ASP.NET Page navigation techniques :
What are different page navigation techniques in ASP.NET?
Hyperlink control : Navigate to another page.
Response.Redirect : Navigate to another page from code. This is equivalent to clicking a hyperlink.
Server.Transfer : End the current Web form and begin executing a new Web form. This method works only when navigating to a Web Forms page (.aspx).
Server.Execute : Begin executing a new Web form while still displaying the current Web form. The contents of both forms are combined. This method works only when navigating to a Web Forms page (.aspx).
Window.Open script method : Display a page in a new browser window on the client.
What is the difference between Response.Redirect and Server.Transfer?
1. When we use Server.Transfer the redirection happens on the server where as when we use Response.Redirect the redirection happens from the browser.
2. Server.Transfer is faster as there is no round trip involved while navigating from one webform to another webform. Response.Redirect is slower than Server.Transfer as there is round trip from the server to the client browser.
3. Server.Transfer works only with .aspx files where as Response.Redirect works with .aspx and .Htm pages.
4. Server.Transfer will work with files on the same web server. You can't use Server.Transfer to send the user to an external site where as Response.Redirect can do that.
5. Server.Transfer does not update the URL in the browser. For example when you navigate from WebForm1.aspx to WebForm2.aspx using Server.Transfer the URL in the browser still shows WebForm1.aspx while you are actually looking at WebForm2.aspx. Response.Redirect updates the URL in the browser.
What is the use of Server.Execute method?
Server.Execute method is used to process a second Web form without leaving the first Web form. This technique lets you direct the results from a Web form to a region on the current page.
Is it possible to send a webform's QueryString, ViewState, and event procedure information to another webform?
Yes, we can use Server.Transfer or Server.Execute to send a webform's QueryString, ViewState, and event procedure information to another webform.
For this to work you have to set the preserveForm argument to True.To be able to read one Web form’s ViewState from another, you must first set the EnableViewStateMac attribute in the Web form’s Page directive to False. By default, ASP.NET hashes ViewState information, and setting this attribute to False disables that hashing so that the information can be read on the subsequent Web form.
Interview Questions on Query Strings in ASP.NET
Give an example of using querystrings to send data from one page to another?
Query strings are a very simple and popular technique to pass data from one Web page to the next. You send data as part of the URL. In the below example FName and LName are sent as part of the URL. In the page load of QueryStrings2.aspx we use Request.QueryString to read the values. As we are sending more than one query string we use the & symbol to seperate query strings.
//Code to send query strings FName and LName as part of the URL
QueryStrings2.aspx?FName=David&LName=Boon
protected void Page_Load(object sender, EventArgs e)
{
//Code to read Query String values
string FirstName = Request.QueryString["FName"];
string LastName = Request.QueryString["LName"];
Response.Write("Data from QueryStrings1.aspx : " + FirstName + ", " + LastName);
}
Give an example to send Query Strings from code?
You can send query strings from server side code using the Response.Redirect() method as shown below.
Response.Redirect("QueryStrings2.aspx?FName=David&LName=Boon");
What are the advantages of using Query Strings?
1. Query strings are easy to implement.
2. Browser support for passing values in a query string is nearly universal.
3. Query strings are contained in the HTTP request for a specific URL and do not require server resources.
What are the disadvantages of using querystrings to send data from one page to another?
1. Query strings are insecure because the information in the query string is directly visible to the user on the address line in the browser.
2. Many browsers impose a 255 URL character limit which can limit their flexibility.
ASP.NET Interview Questions on web application Security :
What is the difference between Authentication and Authorization?
Authentication is the process of identifying users. Authorization is the process of granting access to those users based on identity. Together, authentication and authorization provide the means to keeping your Web application secure from intruders.
What is Anonymous access?
Anonymous access is the way most public Web sites work. Sites containing public information allow anyone to see that information, so they don’t authenticate users. ASP.NET Web applications provide anonymous access to resources on the server by impersonation. Impersonation is the process of assigning a user account to an unknown user.
What is the account that is associated with Anonymous access?
By default, the anonymous access account is named IUSER_machinename. You use that account to control anonymous users’ access to resources on the server.
What is the default user account under which an ASP.NET web application run on a web server?
Under the default settings, ASP.NET uses the ASPNET account to run the Web application. This means that if the application attempts to perform any tasks that are not included in the ASPNET account’s privileges, a security exception will occur and access will be denied.
How do you restrict the access of anonymous users?
You restrict the access of anonymous users by setting Windows file permissions. To be secure, your server must use the Microsoft Windows NT file system (NTFS). The earlier FAT or FAT32 file systems do not provide file-level security.
What are the 3 major ways to authenticate and authorize users within an ASP.NET Web application?
Windows authentication : Identifies and authorizes users based on the server’s user list. Access to resources on the server is then granted or denied based on the user account’s privileges. This works the same way as regular Windows network security.
Forms authentication : Directs users to a logon Web form that collects user name and password information, and then authenticates the user against a user list or database that the application maintains.
Passport authentication : Directs new users to a site hosted by Microsoft so that they can register a single user name and password that will authorize their access to multiple Web sites. Existing users are prompted for their Microsoft Passport user name and password, which the application then authenticates from the Passport user list.
What is the namespace where all security related classes are present?
System.Web.Security
What type of authentication can be used for Public Internet Web application?
Anonymous access. This is the common access method for most Web sites. No logon is required, and you secure restricted resources using NTFS file permissions.
What type of authentication can be used for Intranet Web application?
Windows authentication. Windows authentication authenticates network users through the domain controller. Network users have access to Web application resources as determined by their user privileges on the server.
What type of authentication can be used for Private corporate Web application?
Windows authentication. Corporate users can access the Web application using their corporate network user names and passwords. User accounts are administered using the Windows network security tools.
What type of authentication can be used for Commercial Web application?
Forms authentication. Applications that need to collect shipping and billing information should implement Forms authentication to gather and store customer information.
What type of authentication can be used for Multiple commercial Web applications?
Passport authentication. Passport authentication allows users to sign in once through a central authority. The user’s identity is then available to any application using the Passport SDK. Customer information is maintained in a Passport profile, rather than in a local database.
Can you use ASP.NET Authentication with HTM and HTML Files?
The three ASP.NET authentication modes apply to files that are part of the Web application. That includes Web forms (.aspx), modules (.asax), and other resources that are processed through the Web application’s executable. It does not automatically include HTML pages (.htm or .html). Those pages are handled by Internet Information Services (IIS), rather than ASP.NET. If you want to authenticate users who access HTML pages from within your Web application using Windows, Forms, or Passport authentication modes, you must map those files to the ASP.NET executable.
How do map .htm and .html files to the ASP.NET executable using the IIS snap-in?
To map .htm and .html files to the ASP.NET executable using the IIS snap-in, follow these steps:
1. In the IIS snap-in, select the folder containing your Web application, and then choose Properties from the Action menu. IIS displays the Properties dialog box.
2. Click the Home Directory or Virtual Directory tab, and then click Configuration. IIS displays the Application Configuration dialog box, as shown in the diagram below.
3. Click Add. IIS displays the Add/Edit Application Extension Mapping dialog box, as shown in the diagram below.
4. Click Browse, and select the aspnet_isapi.dll file. That file is stored in the Windows Microsoft .NET Framework directory; the path will be something like C:\Windows\Microsoft.NET\Framework\versionnumber\aspnet_isapi.dll.
5. Type .htm in the File Extension box, and click OK.
6. Repeat steps 3 through 5 for the .html file extension. Click OK to close the IIS dialog boxes when you’ve finished.
ASP.NET Session State and Application State Interview Questions:
What is a Session?
A Session is a unique instance of the browser. A single user can have multiple instances of the browser running on his or her machine. If each instance visits your Web application, each instance has a unique session.A session starts when a user accesses a page on a Web site for the first time, at which time they are assigned a unique session ID. The server stores the user's session ID in the Session.SessionID property.
What is the default session timeout period?
20 minutes.
Where do you generally specify the Session Timeout?
You specify the Session Timeout setting in the web.config file.
Can you specify Session Timeout in a code behind file?
Yes, can specify the Session.Timeout property as shown below in a code behind file.
Session.Timeout = 10;
How do you end a user session?
You can call the Session.Abandon() method to end a user session. If a user then tries to access a page the server will assign them a new session ID and it will clear all the previous session variables. You'll typically use Session.Abandon() on log-out pages.
What type of data can you store in Application State and Session State variables?
Application State and Session State variables are used to store data that you want to keep for the lifetime of an application or for the lifetime of a session. You can store any type of data in the Application or Session state, including objects.
Are Application State or Session State variables type safe?
No, Application and Session state variables are created on the fly, without variable name or type checking.
Do maintaining Session state affects performance?
Yes
Can you turn of Session state?
Yes, Session state can be turned off at the application and page levels.
Are Application state variables available throughout the current process?
Yes, Application state variables are available throughout the current process, but not across processes. If an application is scaled to run on multiple servers or on multiple processors within a server, each process has its own Application state.
How do you disable Session state for a Web form?
To turn Session state off for a Web form set EnableSessionState property of the Page to False.
How do you turn Session state off for an entire web application?
In the Web.config file, set the sessionstate tag to False.
What are Application State variables?
Application State variables are global variables that are available from anywhere in the application. All Sessions can access Application State variables.
How to add and remove data to Application State Variables?
//Code to add data to Application State
Application.Add("AppName", "Sample");
//Code to remove data from Application State
Application.Remove("AppName");
How do you remove all Application State Variables data?
//Code to remove all Application State Variables data
Application.RemoveAll();
Techniques to send data from one web form to another web form
What are the different techniques to send data from one web form to another web form?
1. Query strings :
Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so they should not contain secure information such as passwords.
2. Cookies :
Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility.
3. Session state :
Use Session state variables to store items that you want keep local to the current session (single user).
4. Application state :
Use Application state variables to store items that you want be available to all users of the application.
ASP.NET Interview Questions on Tracing
What is an exception log?
An exception log is a list of handled exceptions that occur while your application is running. Reviewing the exception log periodically helps you verify that exceptions are being handled correctly, are not occurring too frequently, and are not preventing users from accomplishing tasks with your application.
What is Tracing and what are the adavantages of using tracing to log exceptions?
Tracing is a technique for recording events, such as exceptions, in an application. There have always been ways to record errors in an application - usually by opening a file and writing error messages to it. But tracing offers the following significant advantages:
Standardization:Building tracing into the .NET Framework ensures that programming techniques are the same across all the applications you develop with the .NET Framework.
Built-in Web support:ASP.NET extends the .NET Framework tools by including information related to the performance and behavior of Web requests.
Configuration:You can turn tracing on and off using settings in your application’s configuration file. You don’t have to recompile your application to enable or disable tracing.
Performance:While disabled, tracing statements do not affect application performance.
How do you turn tracing on and off for an ASP.NET web application?
Tracing can be turned on or off for an entire Web application or for an individual page in the application:
1. To turn tracing on for an entire application, in the application’s Web.config file, set the trace element’s Enabled attribute to True.
Or
2. To turn tracing on for a single page, set the DOCUMENT object’s Trace property to True in the Visual Studio
.NET Properties window. This sets the @ Page directive’s Trace attribute to True in the Web form’s HTML.
Where is the trace output displayed by default?
By default, trace output is displayed at the end of each Web page.
While this is fine for debugging purposes, you’ll generally want to write trace output to a log file when you start testing your completed application. To write trace messages to a log file for an entire application, in the application’s Web.config file, set the trace element’s PageOutput attribute to False. ASP.NET then writes trace output to the Trace.axd file in your application’s root folder.
How do you specify, how many page requets should be written to the trace log?
The element's RequestLimit attribute can be used to specify how many page requests to write to the trace log. For example, the following line from a Web.config file turns on tracing for the application and writes the first 10 requests to the Trace.axd file:
How do you write trace messages to a log file for only selected pages in an application?
To write trace messages to a log file for only selected pages in an application, follow these steps:
In the application’s Web.config file, set the trace element’s Enabled attribute to True and PageOutput attribute to False.
For each Web page you want to exclude from tracing, set the @ Page directive’s Trace attribute to False.
What is the difference between Trace.Write() and Trace.Warn() methods of a trace object?
The Trace object provides the Write and Warn methods to allow you to write messages to a request’s trace information. The two methods are identical with one difference: messages written with Trace.Write are displayed in black, whereas messages written with Trace.Warn are displayed in red.
How do you programatically check if tracing is enabled?
The Trace object’s IsEnabled property can be used to programatically check if tracing is enabled.
How do you prevent from trace output being written at the bottom of the web page?
You can prevent from trace output being written at the bottom of the web page by setting the trace element’s PageOutput attribute to False in the Web.config file.
What is the name of the file to which trace log is written?
Trace.axd
Can you view Trace.axd from a remote machine?
No, by default, you can view Trace.axd only from the local server running the application. If you want to view the trace log from a remote machine, set the trace element’s LocalOnly attribute to False in the Web.config file
Transactions related ASP.NET Interview Questions
What is a transaction?
A transaction is a group of commands that change the data stored in a database. The transaction, which is treated as a single unit, assures that the commands are handled in an all-or-nothing fashion. if one of the commands fails, all of the commands fail, and any data that was written to the database by the commands is backed out. In this way, transactions maintain the integrity of data in a database. ADO.NET lets you group database operations into transactions.
What is the main purpose of database transactions?
The main purpose of database transactions is to maintain the integrity of data in a database.
How do you determine which SQL commands are part of a transaction?
You can determine what database commands belong in a transaction by using the ACID test. Commands must be atomic, consistent, isolated, and durable.
Commands belong in a transaction if they are:
Atomic:In other words, they make up a single unit of work. For example, if a customer moves, you want your data entry operator to change all of the customer’s address fields as a single unit, rather than changing street, then city, then state, and so on.
Consistent:All the relationships between data in a database are maintained correctly. For example, if customer information uses a tax rate from a state tax table, the state entered for the customer must exist in the state tax table. Isolated:Changes made by other clients can’t affect the current changes. For example, if two data entry operators try to make a change to the same customer at the same time, one of two things occurs: either one operator’s changes are accepted and the other is notified that the changes weren’t made, or both operators are notified that their changes were not made. In either case, the customer data is not left in an indeterminate state.
Durable:Once a change is made, it is permanent. If a system error or power failure occurs before a set of commands is complete, those commands are undone and the data is restored to its original state once the system begins running again.
Why is transaction processing very important for web applications?
Transaction processing is very important for Web applications that use data access, because Web applications are distributed among many different clients. In a Web application, databases are a shared resource, and having many different clients distributed over a wide area can present the below key problems.
Contention for resources:Several clients might try to change the same record at the same time. This problem gets worse the more clients you have.
Unexpected failures:The Internet is not the most reliable network around, even if your Web application and Web server are 100 percent reliable. Clients can be unexpectedly disconnected by their service providers, by their modems, or by power failures.
Web application life cycle:Web applications don’t follow the same life cycle as Windows applications—Web forms live for only an instant, and a client can leave your application at any point by simply typing a new address in his or her browser.
List the steps in order to process a transaction?
1.Begin a transaction.
2.Process database commands.
3.Check for errors.
4.If errors occurred, restore the database to its state at the beginning of the transaction. If no errors occurred, commit the transaction to the database.
Explain how a DataSet provides transaction processing?
DataSet provide transaction processing through the RejectChanges and Update methods. DataSet also provide an AcceptChanges method that resets the state of records in a data set to Unchanged. Data sets provide implicit transaction processing, because changes to a data set are not made in the database until you invoke the Update method on the data adapter object. This lets you perform a set of commands on the data and then choose a point at which to make the changes permanent in the database.
If an error occurs during the Update method, none of the changes from the data set is made in the database. At that point, you can either attempt to correct the error and try the Update method again or undo the changes pending in the data set using the data set’s RejectChanges method.
Give an example to show how DataSets provide transaction processing?
Let us assume we have a DataGrid that displays employee information. Every row also has a delete button, which when you click will delete that row. On this page we also have a Restore and Commit buttons. When you click the Restore button you should be able to restore the data to its previous state. When you click the Commit button you should be able to update the database with the deletions made in the DataSet.
The code for Commit and Restore buttons is shown below.
private void butRestore_Click(object sender, System.EventArgs e)
{
// Restore the data set to its original state.
dsContacts.RejectChanges();
// Refresh the data grid.
grdContacts.DataBind();
}
private void butCommit_Click(object sender, System.EventArgs e)
{
int intRows;
// Update the database from the data set.
intRows = adptContacts.Update(dsContacts);
// Save changes to state variable.
Session["dsContacts"] = dsContacts;
// Refresh the data grid.
grdContacts.DataBind();
}
The RejectChanges method in the preceding butRestore_Click event procedure returns the data set to its state before the row was deleted. The data set’s AcceptChanges method is the inverse of RejectChanges—it resets the DataRowState property for all the changed rows in a data set to Unchanged and removes any deleted rows.
The AcceptChanges method prevents the Update method from making those changes in the database, however, because Update uses the rows’ DataRowState property to determine which rows to modify in the database. For this reason, the AcceptChanges method is useful only when you do not intend to update a database from the data set.
What are the 3 types of transaction objects available in ADO.NET?
As we have 3 types of database connections in ADO.NET, there are also 3 types of transaction objects:
SqlTransaction
OracleTransaction
OleDbTransaction
What are the steps involved in using a transaction object in ADO.NET?
1.Open a database connection.
2.Create the transaction object using the database connection object’s BeginTransaction method.
3.Create command objects to track with this transaction, assigning the Transaction property of each command object to the name of the transaction object created in step 2.
4.Execute the commands. Because the purpose of transaction processing is to detect and correct errors before data is written to the database, this is usually done as part of an error-handling structure.
5.Commit the changes to the database or restore the database state, depending on the success of the commands.
Close the database connection.
What property of a transaction object determines how concurrent changes to a database are handled?
IsolationLevel property of the transaction object is used to determine how concurrent changes to a database are handled.
What are different isolation levels of a transaction object in ADO.NET?
ReadUncommitted:Does not lock the records being read. This means that an uncommitted change can be read and then rolled back by another client, resulting in a local copy of a record that is not consistent with what is stored in the database. This is called a dirty read because the data is inconsistent.
Chaos:Behaves the same way as ReadUncommitted, but checks the isolation level of other pending transactions during a write operation so that transactions with more restrictive isolation levels are not overwritten.
ReadCommitted:Locks the records being read and immediately frees the lock as soon as the records have been read. This prevents any changes from being read before they are committed, but it does not prevent records from being added, deleted, or changed by other clients during the transaction. This is the default isolation level.
RepeatableRead:Locks the records being read and keeps the lock until the transaction completes. This ensures that the data being read does not change during the transaction.
Serializable:Locks the entire data set being read and keeps the lock until the transaction completes. This ensures that the data and its order within the database do not change during the transaction.
What is the default isolation level in a transaction?
ReadCommitted
What is a Save Point in a transaction in ADO.NET?
SqlConnection object provide one transaction capability that is unavailable for OLE database connections: the ability to create save points within a transaction. Save points let you restore the database state to a specific position within the current transaction. To set a save point within a SQL transaction, use the Save method as shown below.
TransactionObject.Save("FirstStep");
How do you restore a SQL transaction to a specific save point?
To restore a SQL transaction to a save point, specify the name of the save point in the Rollback method as shown below.
TransactionObject.Rollback("FirstStep");
Interview Questions on ASP.NET Validation controls :
What are ASP.NET Validation controls?
ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database. Validation controls can be used to address the following questions.
1. Did the user enter anything?
2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)?
3. Is the data within a required range?(For example age cannot be greater than 100 years)
The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server.Most validity problems can be caught and corrected by the user without a round-trip to the server.
Where do the ASP.NET validation controls validate data, on the Client or on the Web Server?
ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then, client side validations are bypassed and validations are performed on the web server.
Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented.
What are the 6 different validation controls provided by ASP.NET?
RequiredFieldValidator:Checks whether a control contains data
CompareValidator:Checks whether an entered item matches an entry in another control
RangeValidator:Checks whether an entered item is between two values
RegularExpressionValidator:Checks whether an entered item matches a specified format
CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both
ValidationSummary:Displays validation errors in a central location or display a general validation error description
What property of the validation control is used to specify which control to validate?
ControlToValidate property.
Explain in simple steps how to use validation controls?
1.Draw a validation control on a Web form and set its ControlToValidate property to the control you want to validate.
2.If you’re using the CompareValidator control, you also need to specify the ControlToCompare property.
3.Set the validation control’s ErrorMessage property to the error message you want displayed if the control’s data is not valid.
4.Set the validation control’s Text property if you want the validation control to display a message other than the message in the ErrorMessage property when an error occurs. Setting the Text property lets you briefly indicate where the error occurred on the form and display the longer ErrorMessage property in a ValidationSummary control.
5.Draw a ValidationSummary control on the Web form to display the error messages from the validation controls in one place.
6.Provide a control that triggers a postback event. Although validation occurs on the client side, validation doesn’t start until a postback is requested.
Are the validation controls fired on the client side if javascript is disabled on the client browser?
No, validation controls are not fired on the client side if javascript is disabled on the client browser.
What is the use of CausesValidation property of an ASP.NET button control?
CausesValidation property of an ASP.NET button control is used to determine if the validation controls should be fired when the button is clicked. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done.
Give an example of real time scenario where you might use CausesValidation property of an ASP.NET button control?
Let us assume we have a Page that collects user information like name, age, date of birth, gender with a submit and reset buttons. When I click the submit button the information filled on the form should be validated and saved to the database. If I click the reset button then all the controls on the webform should default to their initial values without validation happening.So you have to set the CausesValidation property of the reset button to false for the validation to be bypassed. Other wise you will not be able to post back the page to the server.
What is ASP.NET Custom Validator used for?
ASP.NET Custom Validator is used to perform complex types of validation not provided by the standard validation control, use a CustomValidator control and write code to perform the validation on the server side and optionally on the client side.
How do you programatically check, if the client side validation is not bypassed by disabling the javascript on the client browser?
We use Page.IsValid property to determine if all the validations have succeeded. For this property to return true, all validation server controls in the current validation group must validate successfully.
How do you programatically invoke all validation controls on a page?
Call Page.Validate() method. When this method is invoked, it iterates through the validation controls contained in the ValidatorCollection object associated with the Page.Validators property and invokes the validation logic for each validation control in the current validation group.
What is a validation group?
Validation groups allow you to group validation controls on a page as a set. Each validation group can perform validation independently from other validation groups on the page.
How do you create a validation group?
You create a validation group by setting the ValidationGroup property to the same name for all the controls you want to group. You can assign any name to a validation group, but you must use the same name for all members of the group.
Explain how a validation group works when the Page is posted by clicking a button?
During postback, the Page class's IsValid property is set based only on the validation controls in the current validation group. The current validation group is determined by the control that caused validation to occur. For example, if a button control with a validation group of LoginGroup is clicked, then the IsValid property will return true if all validation controls whose ValidationGroup property is set to LoginGroup are valid.
Can a DropDownList fire validation controls?
Yes, DropDownList control can also fire validation if the control's CausesValidation property is set to true and the AutoPostBack property is set to true.
How do you programatically force all validation controls in a particular validation group to be fired?
Call the Page.Validate(string GroupName) method and pass the name of the validation group. This will fire only the validation controls in that validation group.
What is SetFocusOnError property of a validation control used for?
Use the SetFocusOnError property to specify whether focus is automatically set to the control specified by the ControlToValidate property when this validation control fails. This allows the user to quickly update the appropriate control.
If multiple validation controls fail and this property is set to true, the control specified in the ControlToValidate property for the first validation control receives focus.
What is InitialValue property of a RequiredFieldValidator?
Use this property to specify the initial value of the input control.Validation fails only if the value of the associated input control matches this InitialValue upon losing focus.
ViewState :
What is ViewState?
Web forms have very short lifetime.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.The data that ASP.NET preserves between requests is called the Web form’s view state.
How do you enable or disable a ViewState for a control on the page?
Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If EnableViewState is set to false ViewState is disabled for the control.
How do you enable or disable a ViewState at the page level?
At the page level you can enable or disable ViewState using EnableViewState property of the page.
What is the name of the hidden form field in which ViewState of the page is saved?
__ViewState
What are the performance implications of ViewState?
ViewState is usually good to retain the state of the controls on the webform across postbacks. If you have a huge DataGrid with tons of data being loaded on every page load. It is a good idea to disable the ViewState of the DataGrid for the page to load faster. If the ViewState of a large DataGrid is not disabled, ViewState can easily get very large, on the order of tens of kilobytes. Not only does the __ViewState form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.
When does ViewState restoration happens?
During the Page_Init event
What are the disadvantages of using ViewState?
1. On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __ViewState form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.
2. The __ViewState hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __ViewState form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.
Is ViewState encoded?
Yes, ViewState is base-64 encoded.
Can you encrypt ViewState of Page?
Yes, we can use the LosFormatter class to encrypt ViewState of Page
Can the HTML controls retian State accross postbacks?
No, by default HTML controls donot retain state accross postbacks.
Can you make HTML controls retain State accross postbacks?
Yes, HTML controls can retain State accross postbacks, if you convert HTML controls to Server Controls. There are 2 ways to convert HTML control to Server Controls.
1. Right click on the HTML Control and then click "Run As Server Control"
Or
2. Set runat="server" attribute for the Control.
Is ViewState supported in classic ASP?
No,ViewState is introduced in asp.net, it was not in classic asp.
When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server.
Is ViewState of one page available to another page?
No, ViewState of a Page is available only in that page. You cannot access ViewState of one page from another page.
Can you programatically store and retrieve data from ViewState?
Yes. In ASP.NET you can programatically store and retrieve data from ViewState.See the example below
//Save the value in ViewState object
ViewState("SomeVar") = txtFirstName.text;
//Retrieve the value from ViewState object
String strFirstName = ViewState("SomeVar").ToString();
Can someone view the Page HTML source and read ViewState?
No. ViewState is base-64 encoded. Hence you cannot read ViewState. If you right click on the Page and View Source you will find __ViewState is base-64 encoded.
What happens during the Page_Init event?
The server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.
Web application maintainance :
Why is it important to monitor a deployed a Web application?
After you have deployed a Web application
, you need to monitor how it performs on the server. Many issues can crop up at this point because of
1. The number of users accessing the application.
2. The unpredictable nature of user interaction.
3. The possibility of malicious attack.
What are the 3 major steps invloved in maintaining a deployed web application?
Maintaining a deployed application is an ongoing task that involves three major steps:
1. Monitoring the application for error, performance, and security issues.
2. Repairing the application as issues are discovered.
3. Tuning the application to respond to user traffic.
What are the MMC snap-ins provided by windows for monitoring security, performance, and error events?
The Event Viewer snap-in : Lists application, system, and security events as they occur on the system. Use this tool to see what is currently happening on the server and to get specific information about a particular event.
The Performance snap-in : Lets you create new events to display in the Event Viewer and allows you to track event counters over time for display graphically or in report form.
How do run the Event Viewer to view application, system, and security events as they happen?
To run the Event Viewer, choose Event Viewer from the Administrative Tools submenu on the Windows Start menu. (You can show the Administrative Tools menu in Windows XP Professional by opening the Start button’s Properties dialog box and clicking the Customize button on the Start Menu tab. The Administrative Tools option is located on the Advanced tab of the Customize Start Menu dialog box.) After clicking the Event Viewer shortcut, Windows displays the Event Viewer snap-in in the MMC.
What are the 3 levels at which the Event Viewer snap-in displays general application, system, and security events?
1. Informational events.
2. Warning events.
3. Error events.
Can you repair a deployed web application in place without restarting the server or IIS?
Yes, to repair a deployed Web application, copy the new assembly (.dll) and/or content files (.aspx, .ascx, and so on) to the application folder on the server. ASP.NET automatically restarts the application when you replace the assembly. You do not need to install or register the assembly on the server.
What is ASP.NET Process recycling?
ASP.NET Web applications have a limited ability to repair themselves through process recycling. Process recycling is the technique of shutting down and restarting an ASP.NET worker process (aspnet_wp.exe) that has become inactive or is consuming excessive resources. You can control how ASP.NET processes are recycled through attributes in the processModel element in the Machine.config file.
Describes the processModel attributes found in machine.config that relate to process recycling?
1. timeout attribute :The amount of time (hh:mm:ss) before the process is shut down and restarted. Use this setting to automatically recycle a process after a certain number of requests as a preventive measure.
2. shutDownTimeOut attribute : How much time each process has to shut itself down. After this amount of time, the process is terminated by the system if it still running.
3. requestLimit attribute : The number of queued requests to serve before the process is shut down and restarted. Use this setting the same way you use the timeout attribute.
4. restartQueueLimit attribute : The number of queued requests to retain while the process is shut down and restarted.
5. memoryLimit attribute : The percentage of physical memory the ASP.NET process is allowed to consume before that process is shut down and a new process is started. This setting helps prevent memory leaks from degrading the server.
6. responseRestart - DeadlockInterval : The amount of time to wait before restarting a process that was shut down because it was deadlocked. This setting is usually several minutes to prevent applications with serious errors from degrading the server.
7. responseDeadlockInterval : The amount of time to wait before restarting a process that is deadlocked. The process is restarted if there are queued requests and the process has not responded within this time limit.
What is the use of processModel element apart from providing process recycling?
The processModel element in the server’s Machine.config file provides attributes that control certain performance aspects, such as
1. The maximum number of requests to be queued.
2. How long to wait before checking whether a client is connected.
3. How many threads to allow per processor.
Describe the processModel attributes that relate to performance tuning?
requestQueueLimit
The number of queued requests allowed before ASP.NET returns response code 503 (Server too busy) to new requests
clientConnectedCheck
The amount of time (hh:mm:ss) to wait before checking whether a client is still connected
maxWorkerThreads
The maximum number of threads per processor
maxIOThreads
The maximum number of I/O threads per processor
In general, lowering these settings allows your server to handle fewer clients more quickly. Increasing these settings permits more clients and more queued requests, but slows response times.
How do you turn off Session state?
To turn off Session state, in the application’s Web.config file, set the sessionState element’s mode attribute to Off.
If you turn of Session State, can you use Session state variables in code anywhere in the application?
No
What is Optimization?
Optimization usually refers to writing code in a way that executes more quickly or consumes fewer resources. In general, optimizations simply reflect the good programming practices.
List some of the common steps to follow to optimize a web application for performance?
Turn off debugging for deployed applications.
Code that has been compiled with release options runs faster than code compiled with debug options.
Avoid round-trips between the client and server.
ASP.NET uses postbacks to process server events on a page. Try to design Web forms so that the data on the Web form is complete before the user posts the data to the server. You can use the validation controls to ensure that data is complete on the client side before the page is submitted.
Turn off Session state if it isn’t needed.
In some cases, you can design your code to use other techniques, such as cookies, to store client data.
Turn off ViewState for server controls that do not need to retain their values.
Saving ViewState information adds to the amount of data that must be transmitted back to the server with each request.
Use stored procedures with databases.
Stored procedures execute more quickly than ad hoc queries.
Use SqlDataReader rather than data sets for read-forward data retrieval.
Using SqlDataReader is faster and consumes less memory than creating a data set.
ASP.NET Interview Questions on web farm and web garden
What does the term Scalability mean?
Web applications
that serve a large number of users or that present large amounts of data need to able to add capacity as users’ demands increase. The ability to add capacity to an application is called scalability. ASP.NET Web applications support this concept through their ability to run in multiple processes and to have those processes distributed across multiple CPUs and/or multiple servers.
What is the difference between a web farm and a web garden?
A Web application running on a single server that has multiple CPUs is called a Web garden in the ASP.NET documentation. A Web application running on multiple servers is called a Web farm.
If your web server has multiple processors, how can you specify that ASP.NET runs on all or some of the CPUs?
If your server has multiple processors, you can specify that ASP.NET runs on all or some of the CPUs by setting the webGarden attribute of the processModel element in the server’s Machine.config file
What are the implications on Application and Session state variables in a web farm or a web garden?
In both a Web garden and a Web farm, client requests are directed to the ASP.NET process that is currently least busy. That means that a single client can interact with different CPUs or servers over the course of his or her session. This has the following implications for Application and Session state variables:
Application state variables are unique to each separate instance of the Web application.
Clients can share information through Application state if the Web application is running on a Web garden or a Web farm.
Session state variables are stored in-process by default.
To enable Session state in a Web garden or Web farm, you need to specify a Session state provider.
How can you share Application State in a web farm or a web garden?
To share data across multiple sessions in a Web garden or Web farm, you must save and restore the information using a resource that is available to all the processes. This can be done through an XML file, a database, or some other resource using the standard file or database access methods.
What are the two built-in ways provided by ASP.NET to share Session state information across a Web garden or Web farm?
ASP.NET provides two built-in ways to share Session state information across a Web garden or Web farm. You can share Session state using:
A state server, as specified by a network location
This technique is simple to implement and doesn’t require you to install Microsoft SQL Server.
A SQL database, as specified by a SQL connection
This technique provides the best performance for storing and retrieving state information.
What are the steps to follow to share Session state information using a state server?
To share Session state information using a state server, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and stateConnectionString attributes.
2. Run the aspnet_state.exe utility on the Session state server. The aspnet_state.exe utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional or Visual Studio .NET Enterprise Architect editions.
What are the steps to follow to share Session state information using a SQL database?
To share Session state information using a SQL database, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and sqlConnectionString attributes.
2. Run the InstallSqlState.sql utility on the Session state server. This utility installs the SQL database that shares Session state information across processes. The InstallSqlState.sql utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional, Visual Studio .NET Enterprise Developer, or Visual Studio .NET Enterprise Architect editions.
ASP.NET Interview Questions on web user controls
What are ASP.NET Custom controls?
Custom controls extend the tools available to Web developers. Using custom controls, you can encapsulate key aspects of the visual interface and program logic that you want to reuse throughout your application, or throughout your organization.
What are the 3 types of custom controls in ASP.NET?
Microsoft Visual Studio .NET provides three types of custom control for use on Web forms.
1. Web user controls
These combine existing server and HTML controls by using the Visual Studio .NET Designer to create functional units that encapsulate some aspect of the user interface. User controls reside in content files, which must be included in the project in which the controls are used.
2. Composite custom controls
These create new controls from existing server and HTML controls. Although similar to user controls, composite controls are created in code rather than visually, and therefore they can be compiled into an assembly (.dll), which can be shared between multiple applications and used from the Toolbox in Visual Studio .NET.
3. Rendered custom controls
These create entirely new controls by rendering HTML directly rather than using composition. These controls are compiled and can be used from the Toolbox, just like composite controls, but you must write extra code to handle tasks that are performed automatically in composite controls.
What are the limitations of user controls in ASP.NET?
As the user controls are not compiled into assemblies, they have the following limitations:
1. A copy of the control must exist in each Web application project in which the control is used.
2. User controls can’t be loaded in the Visual Studio .NET Toolbox; instead, you must create them by dragging the control from Solution Explorer to the Web form.
3. User control code is initialized after the Web form loads, which means that user control property values are not updated until after the Web form’s Load event.
What are the steps to follow for creating and using a user control in a Web application?
1. Add a Web user control page (.ascx) to your project.
2. Draw the visual interface of the control in the designer.
3. Write code to create the control’s properties, methods, and events.
4. Use the control on a Web form by dragging it from Solution Explorer to the Web form on which you want to include it.
5. Use the control from a Web form’s code by declaring the control at the module level and then using the control’s methods, properties, and events as needed within the Web form.
How do you identify user controls?
User controls are identified by their .ascx file extensions.
What is the base class from which user controls derive?
User controls derive from System.Web.UI.UserControl base class. This base class provides the base set of properties and methods you use to create the control.
What are the steps to follow to create properties and methods for the user control that you can use from a Web form?
To create properties and methods for the user control that you can use from a Web form, follow these steps:
1. Create the public property or method that you want to make available on the containing Web form.
2. Write code to respond to events that occur for the controls contained within the user control. These event procedures do the bulk of the work for the user control.
3. If the property or method needs to retain a setting between page displays, write code to save and restore settings from the control’s ViewState.
What happens when you drag a user control from solution explorer and drop it on a web form?
When you drag a user control from solution explorer and drop it on a web form, Visual Studio .NET generates a @Register directive and HTML tags to create the control on the Web form.
ASP.NET Custom Controls :
What are composite custom controls?
Composite custom controls combine one or more server or HTML controls within a single control class, which can be compiled along with other control classes to create an assembly (.dll) that contains a custom control library. Once created, the custom control library can be loaded into Visual Studio .NET and used in the same way as the standard server and HTML controls.
Composite custom controls are functionally similar to user controls, but they reside in their own assemblies, so you can share the same control among multiple projects without having to copy the control to each project, as you must do with user controls. However, composite controls are somewhat more difficult to create because you can’t draw them visually using the Visual Studio .NET Designer.
What are the steps to follow create and use a custom control in a Web application?
1. Create a solution containing a custom control project.
2. Add a Web application project to the solution, and set it as the startup project. You will use the Web application project to test the custom control during development.
3. Add a project reference from the Web application to the custom control project, and add an HTML @Register directive and control element to use the custom control on a Web form.
4. Create the custom control’s visual interface by adding existing controls to it through the custom control’s CreateChildControls method.
5. Add the properties, methods, and events that the custom control provides.
6. Build and test the custom control.
In general what is the base class for every composite custom control?
System.Web.UI.WebControls.WebControl
Which directive is used to add a custom control to a Web form?
Register directive.
What are the 3 Register directive's attributes?
TagPrefix
This name identifies the group that the user control belongs to. For example, the tag prefix for ASP.NET server controls is “asp”. You use this prefix to create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that contains the controls to register. Microsoft Visual Basic .NET uses the project name as an implicit namespace, so for controls written in Visual Basic .NET, use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The control assembly must be referenced by the Web application. Referencing the assembly maintains a copy of it in the Web application’s /bin directory.
What are the differences between User Controls and Custom Controls?
1. User Controls are easy to create where as Custom Controls are difficult to create.
2. User Controls cannot be compiled into an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user control in every project where you want to use it, where as this is not the case with custom controls. You can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.
5. User controls are used for reusing existing user interface elements and code, but are not useful for developing reusable components for multiple web applications.
CASCADING STYLE SHEETS(CSS):
What are the 2 ways provided by ASP.NET to format output in a Web application?
1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and behavior of the HTML elements on a Web page.
2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those elements.
What are Cascading style sheets?
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.
What are the 3 levels at which formatting can be applied with in a web application?
1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet.
2. You can also define styles in the page’s head element. These styles can be applied to all elements on the current page.
3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are defined.
Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading.
What are the advantages of storing style definitions in a style sheet file (.css) rather than locally in each Web form or inline with each HTML element?
1. Formatting can be maintained in one location so that you make changes only once for an entire application.
2. Several sets of parallel formatting rules can be maintained in separate style sheets for formatting output on different devices or for different user needs. For example, an application might provide standard, enlarged-type, and printer-friendly style sheets that the user can select at run time.
3. In general, you should use page and inline styles only when you have a really good reason to override the global styles. Relying heavily on page and inline styles can make it difficult to maintain the formatting in a Web application.
What HTML element is used to reference a style sheet on webform?
To reference a style sheet on webform you must add a link element to the page’s head element, as shown below.
<link href="Styles.css" type="text/css" rel="stylesheet">
What is the use of Style Builder?
Style Builder is used to change the appearance of any of the styles in a style sheet. Changes to the style sheet change the appearance of all Web forms that reference that style sheet.
How do you modify a style sheet using style builder?
To modify a style sheet using style builder, follow these steps:
1. Open the style sheet in Visual Studio. Visual Studio .NET displays the style definitions in the Document window and an outline of the style sheet in the Tool window
2. Select the style to modify from the Tool window. Visual Studio .NET displays the definition for that style in the Document window.
3. Right-click in the style definition or right-click the style in the Tool window, and select Build Style from the shortcut menu. Visual Studio .NET displays the Style Builder Wizard.
4. Use the Style Builder to compose the formatting that you want to add or modify in the selected style, and then click OK.
5. When you have finished, you’ll see that the Style Builder adds the new or modified style attributes to the style definition.
Can you apply styles using class names or element IDs?
Yes, Using class names allows you to apply a single style to a number of different elements or to style the same element differently, depending on how the element is used. Using element IDs allows you to apply a style to a unique element on one or more Web forms.
When you create a style rule for a class, Visual Studio .NET adds a style definition to the style sheet using a .classname identifier.
You apply the style class to HTML elements by using the class attribute. You apply the style to server controls by using the CssClass attribute.
Can you change style sheets at run time?
Yes.
String manipulation - Practical real time asp.net interview question asked in an interview
Questions:
Please write a sample program that parses the string into a series of substrings where the delimiter between the substrings is "^*!%~" and then reassembles the strings and delimiters into a single new string where each of the substrings is in the reverse order from the original string. The method must return the final string.
Original String:
Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E
Output String:
Token E^*!%~Token D^*!%~Token C^*!%~Token B^*!%~Token A
The code sample below shows how to solve the above question:
using System;
using System.Text;
namespace GenericsSample
{
class Program
{
static void Main()
{
string strOriginalString = "Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E";
string[] strSeperator = new string[1];
strSeperator[0] = "^*!%~";
string[] strArrayIndividualStrings = strOriginalString.Split(strSeperator, StringSplitOptions.RemoveEmptyEntries);
int intLengthOfStringArray = strArrayIndividualStrings.Length;
StringBuilder sbOutputString = new StringBuilder();
for (int i = (intLengthOfStringArray - 1); i >= 0; i--)
{
sbOutputString.Append(strArrayIndividualStrings[i] + strSeperator[0]);
}
Console.WriteLine("Original String : " + strOriginalString);
Console.WriteLine("Output String : " + sbOutputString.ToString());
Console.ReadLine();
}
}
}
Explanation of the above sample program:
1. We take the original string into a string variable strOriginalString. I named this variable as strOriginalString. str indicates that the variable is of string datatype. This will give a good impression to the person who reviews your code bcos you are following the coding standards.
2. I then store the string delimiter "^*!%~" in strSeperator variable. strSeperator is of string array data type. This is bcos the split function expects string array or character array as seprator.
3. I then split the strOriginalString into a string array using the split function.
4. I created a variable sbOutputString to store the Output string. sbOutputString data type is StringBuilder.
5. I then loop thru the array from the highest index to 0 and retrieve the individual strings and append to the sbOutputString. As the output string is changing as we loop thru the array it is good to use StringBuilder rather than System.String. Strings of type System.Text.StringBuilder are mutable where as strings of type System.String are immutable. If a string is manipulated many times always use StringBuilder over System.String.
6. Two good things to remember from this example are, follow the coding standards in naming the variables and always use StringBuilder class over Strings where we manipulate a particular string many times.
Bind an XML file to a dropdownlist
Question 2:
The XML file below has a list of employees. Your job is to bind the employee IDs and Names to a dropdownlist. ID must be dropdownlist value field and name must be the dropdownlist Text field. Also, only the active employees must be binded to the dropdownlist and the names should be in the ascending order. When I select a name from the dropdownlist, the name and ID of the selected employee must be printed on the webform.
Employees.xml
<Employees>
<Employee>
<Name>David</Name>
<ID>101</ID>
<IsActive>true</IsActive>
</Employee>
<Employee>
<Name>Tom</Name>
<ID>102</ID>
<IsActive>true</IsActive>
</Employee>
<Employee>
<Name>Rick</Name>
<ID>103</ID>
<IsActive>false</IsActive>
</Employee>
<Employee>
<Name>Mark</Name>
<ID>104</ID>
<IsActive>true</IsActive>
</Employee>
</Employees>
Code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Employees.xml"));
DataView DV = DS.Tables["Employee"].DefaultView;
DV.RowFilter = "IsActive='true'";
DV.Sort = "Name asc";
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
Code Explanation:
1. Read the XML data from Employees.xml file into a DataSet. We make use of the ReadXml() method. ReadXml method loads the XML data into the dataset DS. DS.ReadXml(Server.MapPath("Employees.xml"));
2. Now you have the Data in a relational format in the dataset. Create a DataView on the employees table in the DataSet. The DefaultView property of DataTable returns the DataView.
DataView DV = DS.Tables["Employee"].DefaultView;
3. After you have created the DataView, apply the RowFilter, to select only the active employees. You apply the RowFilter as shown below.
DV.RowFilter = "IsActive='true'";
4. Now sort the data in the DataView in ascending order. We sort the data on the Name column. You can apply the sort expression on a dataview as shown below.
DV.Sort = "Name asc";
5. Finally set the DataSource, DataValueField and DataTextField properties of the dropdownlist and call the DataBind() method as shown in the below code.
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
Untill now we have seen how to bind an XML file to dropdownlist. We have also seen how to create a DataView on DataTable. DataView is used for sorting and filtering the data. Now we have to get the SelecteValue and SelectedItem Text of a dropdownlist. To achieve this, follow the below steps.
1. Set the autopostback property of the dropdownlist to true. So, when ever a selection in the dropdownlist changes, the webform is posted back to the server automatically.
2. In the DropDownList1_SelectedIndexChanged event handler we can capture the employee name and id using the DropDownList1.SelectedItem.Text and DropDownList1.SelectedItem.Value properties as shown below.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
Note: If you have noticed, we binded the XML file to the dropdownlist only during the initial page load and not during every post back. We do this check by using if(!IsPostBack) property of the page.
Reading and writing to an XML file.
Question:
Create a simple web page , that can read and write to an XML file. The XML file has a list of email ids. The sample web form should have the following functionality. You have 30 minutes to code and test.
1. A TextBox to accept a valid email id.
2. A submit button. When you click the submit button, the email id entered in the TextBox must be saved to the XML file.
3. If I donot enter anything in the TextBox and click the submit button, the application should show a validation message stating "Email is required".
4. If I enter an invalid email, the application should show a message "Invalid Email".
5. If javascript is enabled the validation should happen on the client browser without postback. If javascript is disabled the validation should happen on the web server.
6. Finally we should have a list box, which will show all the existing email ids in the XML file. When you submit a new email, the listbox should be reloaded showing the newly added email along with already existing email ids.
Answer:
1. Create a webform and add a TextBox, RequiredFieldValidator, RegularExpressionValidator, Button and a ListBox.
2. Set the RequiredFieldValidator "ErrorMessage" property to "Email Required" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
3. Set the RegularExpressionValidator "ErrorMessage" property to "Invalid Email" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
4. Set the ListBox, "DataTextField" property to "Email" and DataValueField property to "Email"
5. The complete HTML of the web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
<title>Email List</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
Please enter a valid email:
</td>
<td>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /></td>
</tr>
</table>
<br />
Existing Email Ids
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="292px" Width="192px" DataTextField="Email" DataValueField="Email"></asp:ListBox>
</form>
</body>
</html>
6. Place the XML file that contains the list of email ids in the root folder of the web application. The sample XML file is shown below.
<?xml version="1.0" standalone="yes"?>
<EmailsList>
<Emails>
<Email>dhex@yahoo.com</Email>
</Emails>
<Emails>
<Email>dmexy@aol.com</Email>
</Emails>
<Emails>
<Email>dpitt@gmail.com</Email>
</Emails>
<Emails>
<Email>mston@microsoft.com</Email>
</Emails>
</EmailsList>
7. In the code behind file, write a function the can read the email ids from the XML file into a DataSet. Set this DataSet as the DataSource for the ListBox and call the DataBind() method. The function should be as shown below.
private void LoadExistingEmails()
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
ListBox1.DataSource = DS;
ListBox1.DataBind();
}
8. Call the above LoadExistingEmails() function in the Page_Load event handler as shown in the sample code below.
protected void Page_Load(object sender, EventArgs e)
{
LoadExistingEmails();
}
9. Finally, when you click the submit button write to the XML file as shown below.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
DataRow DR = DS.Tables[0].NewRow();
DR["Email"] = EmailTextBox.Text;
DS.Tables[0].Rows.Add(DR);
DS.WriteXml(Server.MapPath("Emails.xml"));
LoadExistingEmails();
}
}
Points to remember:
1. Validation controls work both on the client and on the server.
2. If javascript is enabled validations happen on the client browser without posting the page back to the server.
3. If javascript is disabled, validations happen on the server. To check if all the validation controls haved passed validation, use Page.IsValid property.
4. Page.IsValid returns "true" if the page has succeeded validation and "false" even if a single validation control has filed validation.
5. In our example, we write to the XML file only if Page.IsValid property returns true.
Testing the sample application:
To test if the validation controls are working on the server, disable javascript on the client browser. To disable javascript on the client browser follow the below steps.
1. Open internet explorer.
2. Click on Tools.
3. Click on Internet Options. You will see Internet Options dialog page.
4. Click on the Security tab.
5. On the Security tab, select Local intranet under Select a zone to view or change security settings.
6. Click "Custom Level" button under "Security Level for this zone"
7. On the "Security Setting - Local Intranet Zone" dialog page, scroll down to "Scripting" section.
8. Select "Disable" radio button under "Active scription" and click "OK" button.
write a custom reusable function to populate a dropdownlist
Write a custom function in c-sharp. The custom function parameters should be an instance of a dropdownlist, an xml file and a string.
1. The function should be capabale of populating the passed in dropdownlist.
2. The first item in the dropdownlist should be the passed in string parameter.
3. The data for the dropdownlist comes from the passed in XML file.
The idea is to create a custom function which can be reused through out the project for populating any dropdownlist on any web page. You have 20 minutes to code, test and demonstrate.
The sample code for custom function is shown below. For this example to work drop the XML file in the root folder of the web application.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
public void PopulateDropdownlist(System.Web.UI.WebControls.DropDownList DropDownListObjectToBePopulated,string XMLFilePath, string InitialString)
{
try
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(XMLFilePath));
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
}
catch(Exception Ex)
{
}
}
The XML file that has the data for the dropdownlist is as shown below.
<?xml version="1.0" encoding="utf-8" ?>
<StatesList>
<State>
<StateName>Virginia</StateName>
<StateCode>VA</StateCode>
</State>
<State>
<StateName>Iowa</StateName>
<StateCode>IA</StateCode>
</State>
<State>
<StateName>North Carolina</StateName>
<StateCode>NC</StateCode>
</State>
<State>
<StateName>Pennsylvania</StateName>
<StateCode>PA</StateCode>
</State>
<State>
<StateName>Texas</StateName>
<StateCode>TX</StateCode>
</State>
</StatesList>
Explanation of the code:
1. PopulateDropdownlist function has 3 parameters. DropDownList to be populated, the path of the XML file which has the data for the dropdownlist and the initial string.
2. Create an instance of DataSet. In our example the instance is DS.
DataSet DS = new DataSet();
3. Read the XML data into the dataset instance using ReadXml() method. Pass the path of the XML file to ReadXml() method. We used Server.MapPath() method to return the physical file path that corresponds to the specified virtual path on the web server.
DS.ReadXml(Server.MapPath(XMLFilePath));
4. We now have the data from the XML file in the dataset as a DataTable.
5. Check if the InitialString is empty. If not empty create a new ListItem object and populate the Text and Value properties. Then add the listitem object to the dropdownlist.
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
6. Finally loop thru the rows in the DataTable and create an instance of ListItem class. Populate the Text and Value properties to StateName and StateCode respectively. Finally add the ListItem object to the dropdownlist.
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
7. Drag and drop the dropdownlist on a webform. Call the PopulateDropdownlist() custom function in the Page_Load event handler. When you call the custom function pass the dropdownlist to be populated, XML file path and the initial string.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
List all the files in a directory on a web form in asp.net
List all the files in a directory on a web form. The files must be displayed in a gridview control. The name of the file and create date must be displayed.
1. Create a new web form. Drag and drop a gridview control from the toolbox onto the webform.
2. Create 2 bound fields for the gridview. One bound field will display the file name and the other will display the create date.
3. The HTML for your web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListFiles.aspx.cs" Inherits="ListFiles" %>
<html>
<head runat="server">
<title>List all the files in a directory</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="File Name"></asp:BoundField>
<asp:BoundField DataField="DateCreated" HeaderText="Date" DataFormatString="{0:d}"></asp:BoundField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
4. In the code behind file write a function which can get the list of files from the directory and bind to the gridview. The function is as shown below.
private void LoadFiles()
{
/* Create an instance of DirectoryInfo class for enumarating through the directory. */
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Server.MapPath("FilesDirectory"));
/* Call the GetFiles() instance method of the DirectoryInfo class object, which will return a files list from the current directory */
System.IO.FileInfo[] fiFiles = dirInfo.GetFiles();
/* Create a DataTable which can be used as the datasource for the gridview */
DataTable dtFileList = new DataTable("Files");
/* Create a DataColumn for file name */
DataColumn dcFileName = new DataColumn("FileName");
/* Create a DataColumn for file create date */
DataColumn dcDateCreated = new DataColumn("DateCreated", typeof(DateTime));
/* Add the 2 data columns to the data table */
dtFileList.Columns.Add(dcFileName);
dtFileList.Columns.Add(dcDateCreated);
/* Now loop through each FileInfo object and get the file name and file create date */
foreach (System.IO.FileInfo f in fiFiles)
{
DataRow dtNewRow = dtFileList.NewRow();
/* Get the file name using FileInfo object "Name" property */
dtNewRow["FileName"] = f.Name.ToString();
/* Get the file create date and time using FileInfo object "CreationTime" property */
dtNewRow["DateCreated"] = f.CreationTime.ToShortDateString();
/* Add the row to the DataTable */
dtFileList.Rows.Add(dtNewRow);
}
/* Set the datatable as the DataSource for the gridview and call the DataBind() method */
GridView1.DataSource = dtFileList;
GridView1.DataBind();
}
5. Finally call the LoadFiles() method on the page load event handler as shown below.
protected void Page_Load(object sender, EventArgs e)
{
LoadFiles();
}
Testing the application:
1. Right click on the project name in solution explorer, and left click on "NewFolder"
2. Rename the "NewFolder" to "FilesDirectory"
3. Drag and Drop some files into the directoy.
4. Then run the application. All the files in the "FilesDirectory" folder will be shown in the gridview.
Write and Read a cookie:
Give an example to show how to write and read a cookie from a client's computer.
1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores
FirstName
LastName
LastVisit
2. Create the user interface to enter FirstName and LastName. The HTML for the webform is as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesExample.aspx.cs" Inherits="CookiesExample" %>
<html>
<head runat="server">
<title>Write a cookie to the client computer</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td style="width: 100px">
First Name</td>
<td style="width: 100px">
<asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
Last Name
</td>
<td style="width: 100px">
<asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="WriteCookieButton" runat="server" Text="Write Cookie" OnClick="WriteCookieButton_Click" />
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="ReadCookieButton" runat="server" Text="Read Cookie" OnClick="ReadCookieButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}
4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}
5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.
Thank you for posting lots of "C interview Questions". This is indeed great help for me. you did great job. Kudos to you!
ReplyDeleteelectronic signature for sharepoint
you did a great help to me . you posted all important topics and questions in one place.moreover answers are simple and easy to learn . i am preparing for interview .
ReplyDeletethanks a lot . i did like to give a party after my selection in interview.
i will be thankful i you post latest interview questions and trends in latest interviews.
thanks