Вы находитесь на странице: 1из 25

OOPS

1.What is class?
Class is a blue print, it contains data and behavior of a type. Let me take an example that,
consider a vehicle as a class, it can have type, color, price like data and calculate speed as
behavior of the class.

2.What is object?
Object is an instance of a class, and basically is a block of memory that has been allocated and
configured according to the blueprint(class).

3.What is Inheritance?
Inheritance is one of the main attribute in object-oriented language. It allows us to create a new
class which can reuse, extends or modifies behavior of parent class. The class whose behaviors
been inherited is called base class, and the class inherits the members of the base class is
derived class. For example: we have a vehicle class and a car class. Car class can be derived
from vehicle class to inherit all data and behaviors of base class.

4.Can you explain about polymorphism?


Basically, polymorphism means to be able to exists in multiple forms, in C# we have two
types of polymorphisms: Compile time polymorphism and runtime poly morphism.

Coming to compile time polymorphism, more than one method can have same name with
different parameters in terms of type of parameters and number of parameters, doesn’t make
any difference with return type. For example, in data access layer we can write several methods
with same name to get any table data.

But run time polymorphism, derived class can have a method implementation which have same
method name in its base class. So, we can add override the method in base class by adding
virtual key word to base class method, and override keyword to derived class method. So, we
will be able to customize our own functionality in derived class function.

5.What is abstraction and encapsulation?


Abstraction: It means hiding irrelevant data of an object and showing only the related
information to outside; Consider the example of console.writeline() method, here we abstracted
main functionality of the object and provide it to use only; usually achieve Abstraction at
design level trough interfaces and abstract classes.

Encapsulation: It is a strategy used as part of abstraction; and it refers to the state of the
objects- objects encapsulate their state and hide it from the outside; outside users of the class
interact with it through its methods. Here we provide getter and setter methods to access them.
we achieve encapsulation at implementation level though access specifiers like public, private
and protected.

6.Difference between abstract classes and interfaces?


Abstract classes contain abstract methods and normal methods, the abstract methods should be
implemented in its child classes and the normal methods can be over loaded in its child classes;
and abstract methods cannot be instantiated. Abstract classes avoid duplicate code.
Whereas interfaces contain only unimplemented methods, all methods must be implemented in
its child classes. All the methods implicitly abstract and public. Interfaces allow us to
implement multiple inheritance.
7.Can you explain about shadowing?
Shadowing is a concept of using polymorphism. It allows us to override a base class method
even though it doesn’t declare as virtual; and method in child class can have different
signature, with same name. In real time when you refer external libraries we may need to use
same method name as a method in library; where we use shadowing.

8.Different types of classes?


Abstract classes: Cannot be instantiated; should be inherited.
Static classes: Cannot be instantiated and cannot be inherited and should contain only
Static members
Sealed classes: Sealed class cannot be inherited and used to restrict the properties.
Partial classes: The source code of class divided into multiple files so at compile time all the
parts will be compiled. Partial classes cannot be inherited

9.What are access modifiers in C#?


public
The 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 be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class, or in a class that is
derived from that 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 assembly in
which it is declared, or from within a derived class in another assembly.
10. What do you know about constructors?
A special method that will be automatically invoked when an instance of the class is created
called constructor. There are five types of constructors:
Default Constructor: A constructor without any parameters; when the class is instantiated
the values for variables in constructor initialized.
Parameterized constructor: We can send parameters to the constructor to initialize certain
values to variables.
Copy constructor: Creates an object by copying variable values from another objects value
is called copy constructor
Static constructor: it will be invoked only once for all of instances of the class and it is
invoked during the creation of the first instance of the class or the first reference to a static
member in the class. A static constructor is used to initialize static fields of the class and to
write the code that needs to be executed only once
Private constructor: When a constructor is created with a private specifier, it is not possible
for other classes to derive from this class,
neither is it possible to create an instance of this class. They are usually used in classes that
contain static members
only.

11. Constructor Overloading?


Constructor over loading is possible in C#, as, we can create parameterized constructor over
default constructor. Whereas inheritance is not supported in C#.

12. Can you explain about cohesion and coupling?


Cohesion: A measure of how closely related the members of a module are to the other
members of the module. It is very desirable to increase the cohesion as that indicates that a
module has very specific task and does only that task.

Coupling: A measure of how much a module (package, class, method) relies on other
modules. It is desirable to reduce coupling, or reduce the amount that a given module relies
on the other modules of a system.

13. What are finalizers(Destructors)?


They are special methods that contains clean up code for the project. You cannot call them
explicitly in our code as they are implicitly called by GC.

14. Explain about solid principles?


Solid principles are basic principles to design good software architecture, As SOLID is
acronym for Single responsibility, open and closed principle, Liskov substitution principles,
Interface segregation and Dependency inversion.

Single responsibility: This principle states that every module/class should have single
responsibility.
Open Closed principle: The module code opens for extension and closed for modification.
Liskov Substitution Principle: LSP states that Parent object should be able to easily
replace Child Object without altering any of desirable properties of Parent class
Interface Segregation Principle: ISP states that no client should be forced to implement the
methods that are not used by it.
Dependency inversion principle: High level modules should not depend on low level
modules but should depend on abstraction.

C#

15. Can you discuss about C# language and its advantages?

16. Can you explain types of C#?


There are two kinds of types in the language that are value types and reference types.
Variables of value types directly contain data, whereas variables of reference types
contain references to the data.

C# value types further divides into simple types, enum types, struct types, and nullable
value types.
C# reference types further divides into class types, interface types, array types, delegate
types.

17. Can you explain difference between Boxing and Unboxing?


Boxing is a process of converting from value type to reference type; the conversion
process is implicit in default, when conversion takes place the new instance will be
created on managed heap and the value will be stored on it.
Unboxing is a process of converting from reference type to value type; process involves
two things that are, checking type of the unboxing variable and copy the variable to value
type variable. Unboxing is explicit.

18. Difference between ref and out?


Ref keyword causes an argument to be passed by reference, so that any changes to that
object in calling method will reflect in called method

Out keyword is also like ref keyword, but the variable should be initialized in calling
method. And useful for returning more than two values.

d/f
ref tells the compiler that the object is initialized before entering the function,
while out tells the compiler that the object will be initialized inside the function.
19. What are checked and unchecked keywords in C#?
In checked context arithmetic overflow rises an exception and in unchecked context
arithmetic overflow is ignored and the result is truncated.

20. Can you explain structures in C#?


Basically, structures are value types and class like software entity that can store bunch of
value types as a single value type. I have consider using structures over classes when the
design need to have semantic values and instances are small, short lived and not changing
the data frequently.

Structures instantiated with new operator supports constructors moreover doesn’t support
inheritance, and destructors.

21. Explain about Enumeration types?


Enums are value types and it is an efficient way to define set of named integral constants
that may be assigned to a variable. For example, we can define a enum ‘day’ which has
all days in it with underlaying data type as int. In default the constants start with
underlaying variable zero.

22. How do you explain Exception Handling?


Exception are run time errors and should handled properly to efficient execution of the
program. Either compilers can throw exceptions, or we can throw our own exceptions
using ‘throw’ keyword.
if a statement expects to throw exceptions that should be enclosed in try block. And the
exception will be handled in catch block.
The code in finally block will executes even though an exception handles in catch, so
we must write the code regarding closing files and leaving resources in finally block.

23. Explain about arrays?


Array is a data structure which can manage group of objects; which are strongly typed.
There are couple of different arrays in C#: single dimension, multi dimension, and Jagged
arrays.

Multi dimension arrays are used for matrix computations


And Jagged arrays are an array itself contains arrays which are different lengths unlike
multi-dimensional arrays.

24. Difference between Arrays and Collections?


Arrays are flexible way to work with group of strongly typed and fixed numbers of
objects, so that arrays cannot work with items that grows and shrinks dynamically.

Where as collections unlike arrays can manage group of objects that can grow and shrink
dynamically according to application needs. And for some collections we can insert key
value pairs.
There are two different types of collections: Generics and non-generics

25. Can you elaborate more about Collections?


Collections are two types generic and non-generic types.

Non-generic types can grow and shrink dynamically and accepts any types in the
collections. So, it actually accepts Object type to store. When we need to add any type,
that type will be boxed to Object type. We have collections like: ArrayList, SortedList,
HashTable, Stack and Queue.

Where as generic types are type safe and dynamically grows and shrinks. They are List,
SortedList, Dictionary, stack and queue.

26. Explain about Generics?


Generics introduced in C# 2.0. They can be defined using angle brackets with Generic
Type T in it. They provide type safety at complete time, avoids duplicated code, and
improves reusability.

For example, take method compare methods which takes two int arguments, later we
needed to compare strings. Generics helps here to not to write another method.

27. What are anonymous methods?


Anonyms methods are methods without name, and they must be declared with delegate
keyword and can be assigned to a variable of delegate.
They can access the variable outside of the function.
And can be passed to a function.

28. Difference between const and readonly keywords?


Though, const and readonly keywords used for same purpose as defining constant
variables. They have subtle difference that const variables should be initialized while
declaring it. Whereas readonly variables can be initialized at run time through declaring
them in constructors
AssemblyB references AssemblyA and uses these values in code. When this is compiled,
 in the case of the const value, it is like a find-replace, the value 2 is 'baked into'
the AssemblyB's IL. This means that if tomorrow I'll update I_CONST_VALUE to
20 in the future. AssemblyB would still have 2 till I recompile it.
 in the case of the readonly value, it is like a ref to a memory location. The value is not
baked into AssemblyB's IL. This means that if the memory location is
updated, AssemblyB gets the new value without recompilation. So,
if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do
not need to be recompiled
29. Difference between var and dynamic keyword?
Var declarations are resolved at compile time whereas dynamic declaration resolve at run
time. Basically, compiler knows about the type of var declaration, but for dynamic
declarations compiler doesn’t know, and knows at run time.

30. What are nullable types?


Nullable types are value types that can take null values. Usually value types don’t take
null values, nut nullable types can take null values. ‘int?’ is a null value. Nullble types
makes values types to behave like reference types.

31. Explain multithreading in C#?


Thread is a lightweight process and can run concurrently along with multiple threads in
an application to utilize resources effectively. Basically, our program itself is a thread and
called primary thread. We can create multiple auxiliary threads such that multiple
independent tasks like file writing, networking can be run concurrently.

By using threads, we can get several benefits like concurrency and effective CPU
utilization.

One of the major challenge in multithreading application is that to keeping threads in a


order; for example when more threads sharing a resource then, the result may be get
effected because of race condition or deadlocks. To avoid that all the threads need to be
synchronized by using lock, monitors or mutex.

Multithreading very useful for distributed and scalable server-side applications as each
thread can hold each user request so that no user waits until other users gets the response.
In C# we can achieve this using thread pools.

Thread pool is a pool of threads waits of the requests and handles the request and once
request has get done the same thread can be used by other requests.

32. What is difference between dispose and finalize methods in C#?


Finalize:
 Used to free unmanaged resources like files, database connections, COM etc. held
by an object before that object is destroyed.
 Internally, it is called by Garbage Collector and cannot be called by user code.
 It belongs to Object class.
 Implement it when you have unmanaged resources in your code and want to make
sure that these resources are freed when the Garbage collection happens.
 There are performance costs associated with Finalize method.
 Syntax for this method is protected virtual void Finalize ()
 By default, Object. Finalize method does nothing. If there is need then we must be
overridden by a derived class or provide destruction.
Dispose:
 It is used to free unmanaged resources like files, database connections, COM etc.
at any time.
 Explicitly, it is called by user code and the class implementing dispose method must
implement IDisposable interface.
 Implement this when you are writing a custom class that will be used by other
users.
 There is no performance costs associated with Dispose method.

.NET

33. What is .NET Framework?


The .NET Framework is set of technologies that form an integral part of the .NET Platform.
It is Microsoft's managed code programming model for building applications that have
visually stunning user experiences, seamless and secure communication, and the ability to
model a range of business processes.
The .NET Framework has two main components: the common language runtime (CLR)
and .NET Framework class library. The CLR is the foundation of the .NET framework and
provides a common set of services for projects that act as building blocks to build up
applications across all tiers. It simplifies development and provides a robust and simplified
environment which provides common services to build application. The .NET framework
class library is a collection of reusable types and exposes features of the runtime. It contains
of a set of classes that is used to access common functionality

34. What is CLR?


The .NET Framework provides a runtime environment called the Common Language
Runtime or CLR. The CLR can be compared to the Java Virtual Machine or JVM in Java.
CLR handles the execution of code and provides useful services for the implementation of
the program. In addition to executing code, CLR provides services such as memory
management, thread management, security management, code verification, compilation,
and other system services. It enforces rules that in turn provide a robust and secure
execution environment for .NET applications.

35. Explain about CTS?


Common Type System (CTS) describes the datatypes that can be used by managed code.
CTS defines how these types are declared, used and managed in the runtime. It facilitates
cross-language integration, type safety, and high-performance code execution. The rules
defined in CTS can be used to define your own classes and values.

36. What is CLS?


Common Language Specification (CLS) defines the rules and standards to which
languages must adhere to in order to be compatible with other .NET languages. This
enables C# developers to inherit from classes defined in VB.NET or other .NET
compatible languages.
37. What is managed code?
The .NET Framework provides a run-time environment called the Common Language
Runtime, which manages the execution of code and provides services that make the
development process easier. Compilers and tools expose the runtime's functionality and
enable you to write code that benefits from this managed execution environment. The
code that runs within the common language runtime is called managed code

The code, which is developed in .NET framework, is known as managed code. This code
is directly executed by CLR with help of managed code execution. Any language that is
written in .NET Framework is managed code.

Managed code uses CLR which in turns looks after your applications by managing
memory, handling security, allowing cross - language debugging, and so on.

38. What is unmanaged code?


The code, which is developed outside .NET, Framework is known as unmanaged code.

Applications that do not run under the control of the CLR are said to be unmanaged, and
certain languages such as C++ can be used to write such applications, which, for
example, access low - level functions of the operating system. Background compatibility
with code of VB, ASP and COM are examples of unmanaged code.

39. What do you know about MSIL?


When the code is compiled, the compiler translates your code into Microsoft intermediate
language (MSIL). The common language runtime includes a JIT compiler for converting
this MSIL then to native code.
MSIL contains metadata that is the key to cross language interoperability. Since this
metadata is standardized across all .NET languages, a program written in one language can
understand the metadata and execute code, written in a different language. MSIL includes
instructions for loading, storing, initializing, and calling methods on objects, as well as
instructions for arithmetic and logical operations, control flow, direct memory access,
exception handling, and other operations.

40. How JIT works?


JIT is a compiler that converts MSIL to native code. The native code consists of hardware
specific instructions that can be executed by the CPU.
Rather than converting the entire MSIL (in a portable executable[PE]file) to native code,
the JIT converts the MSIL as it is needed during execution. This converted native code is
stored so that it is accessible for subsequent calls.

41. What is an Assembly and contents of assembly?


An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental
unit for application development and deployment in the .NET Framework. An assembly
contains a collection of types and resources that are built to work together and form a
logical unit of functionality. An assembly provides the CLR with the information it needs
to be aware of type implementations.
A static assembly can consist of four elements:
· Assembly manifest - Contains the assembly metadata. An assembly manifest
contains the information about the identity and version of the assembly. It also
contains the information required to resolve references to types and resources.
· Type metadata - Binary information that describes a program.
· Microsoft intermediate language (MSIL) code.
· A set of resources.
42. What are different types of an assembly?
Assemblies can also be private or shared. A private assembly is installed in the installation
directory of an application and is accessible to that application only. On the other hand, a
shared assembly is shared by multiple applications. A shared assembly has a strong name
and is installed in the GAC.
We also have satellite assemblies that are often used to deploy language-specific resources
for an application.

43. What is strong name?


You need to assign a strong name to an assembly to place it in the GAC and make it globally
accessible. A strong name consists of a name that consists of an assembly's identity (text
name, version number, and culture information), a public key and a digital signature
generated over the assembly. The .NET Framework provides a tool called the Strong
Name Tool (Sn.exe), which allows verification and key pair and signature generation.

44. What is GAC?


The global assembly cache (GAC) is a machine-wide code cache that stores assemblies
specifically designated to be shared by several applications on the computer. You should
share assemblies by installing them into the global assembly cache only when you need to.

45. What is Garbage Collector and its generations?

In the common language runtime (CLR), the garbage collector serves as an automatic
memory manager. It provides the following benefits:

 Enables you to develop your application without having to free memory.


 Allocates objects on the managed heap efficiently.
 Reclaims objects that are no longer being used, clears their memory, and keeps the
memory available for future allocations. Managed objects automatically get clean
content to start with, so their constructors do not have to initialize every data field.
 Provides memory safety by making sure that an object cannot use the content of
another object.

The heap is organized into generations, so it can handle long-lived and short-lived
objects. Garbage collection primarily occurs with the reclamation of short-lived objects
that typically occupy only a small part of the heap. There are three generations of objects
on the heap:

 Generation 0. This is the youngest generation and contains short-lived objects. An


example of a short-lived object is a temporary variable. Garbage collection occurs
most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly
generation 0 collections, unless they are large objects, in which case they go on the
large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive
to the next generation.

 Generation 1. This generation contains short-lived objects and serves as a buffer


between short-lived objects and long-lived objects.
 Generation 2. This generation contains long-lived objects. An example of a long-
lived object is an object in a server application that contains static data that is live for
the duration of the process.

ADO .NET
46. What are main benefits of ADO.NET?
Following are the benefits of ADO.Net:

 Programmability
 Maintainability
 Interoperability
 Performance
 Scalability

47. What is difference between DataSet and DataReader?

Following are some major differences between DataSet and DataReader:

 DataReader provides forward-only and read-only access to data, while


the DataSet object can hold more than one table (in other words, more than one row
set) from the same data source as well as the relationships between them.
 DataSet is a disconnected architecture while DataReader is a connected architecture.
 DataSet can persist contents while DataReader cannot persist contents, they are
forward only.
48. What is the use of Command Objects?

They are used to connect a Connection object to a DataReader or DataSet. Following


are the methods provided by a Command object:

 ExecuteNonQuery
Executes the command defined in the CommandText property against the connection
defined in the Connection property for a query that does not return any row (an
UPDATE, DELETE, or INSERT). Returns an Integer indicating the number of rows
affected by the query.

 ExecuteReader
Executes the command defined in the CommandText property against the connection
defined in the Connection property. Returns a "reader" object that is connected to the
resulting row set within the database, allowing the rows to be retrieved.

 ExecuteScalar
Executes the command defined in the CommandText property against the connection
defined in the Connection property. Returns only a single value (effectively the first
column of the first row of the resulting row set, any other returned columns and rows
are discarded). It is fast and efficient when only a "singleton" value is required.

49. Explain about Data Adapter?


DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the
communication between the Dataset and the Datasource. We can use the DataAdapter in
combination with the DataSet Object. DataAdapter provides this combination by
mapping Fill method, which changes the data in the DataSet to match the data in the data
source, and Update, which changes the data in the data source to match the data in the
DataSet.
The DataAdapter can perform Select, Insert, Update and Delete SQL operations in the
Data Source

50. What is Connection Pooling?


Connection pooling consists of database connection so that the connection can be used or
reused whenever there is request to the database. This pooling technique enhances the
performance of executing the database commands. This pooling definitely reduces our
time and effort.

51. What are difference between OLEDB and SQLClient Providers?


OLEDB provider is used to access any database and provides flexibility of changing the
database at any time. SQLClient provider is used to access only SQL Server database but
it provides excellent performance than OLEDB provider while connecting with SQL
Server database.

SQL
52. Types of Indexing in SQL Server?
An index is an on-disk structure associated with a table or view that speeds retrieval of
rows from the table or view. An index contains keys built from one or more columns in
the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to
find the row or rows associated with the key values quickly and efficiently.

A table or view can contain the following types of indexes:

Clustered:

o Clustered indexes sort and store the data rows in the table or view based on their key
values. These are the columns included in the index definition. There can be only one
clustered index per table, because the data rows themselves can be sorted in only one
order.
o The only time the data rows in a table are stored in sorted order is when the table
contains a clustered index. When a table has a clustered index, the table is called a
clustered table. If a table has no clustered index, its data rows are stored in an
unordered structure called a heap.

Nonclustered:

o Nonclustered indexes have a structure separate from the data rows. A nonclustered
index contains the nonclustered index key values and each key value entry has a
pointer to the data row that contains the key value.
o The pointer from an index row in a nonclustered index to a data row is called a row
locator. The structure of the row locator depends on whether the data pages are stored
in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a
clustered table, the row locator is the clustered index key.

53. Difference between primary and foreign key?


Primary Key: A table typically has a column or combination of columns that contain
values that uniquely identify each row in the table. This column, or columns, is called the
primary key (PK) of the table and enforces the entity integrity of the table. Because
primary key constraints guarantee unique data, they are frequently defined on an identity
column.

When primary key is created for a table, data base engine automatically enforces data
uniqueness by creating unique index for the primary key columns. So that we cannot
have duplicated values for primary key column or columns. As well as we cannot have
null values in primary key values.

Foreign Key: A foreign key (FK) is a column or combination of columns that is used to
establish and enforce a link between the data in two tables to control the data that can be
stored in the foreign key table. In a foreign key reference, a link is created between two
tables when the column or columns that hold the primary key value for one table are
referenced by the column or columns in another table. This column becomes a foreign
key in the second table. Foreign key columns frequently used in join criteria of both
tables.

54. What is Database Normalization?


Database normalization is the process of organizing the fields and tables of a relational
database to minimize redundancy and dependency. Normalization usually involves
dividing large tables into smaller (and less redundant) tables and defining relationships
among them. Normalization is a bottom-up technique for database design.

55. Explain about stored procedures?


A Stored Procedure is a collection or a group of T-SQL statements. Stored Procedures are
a precompiled set of one or more statements that are stored together in the database. They
reduce the network load because of the pre-compilation. We can create a Stored
Procedure using the "Create proc" statement.
 They are a network load reducer and decrease execution time because they are
precompiled, and all the statements inside of it are executed as batch of code.
 Stored Procedures can be encrypted and that also prevents SQL Injection Attacks
 It is very easy to maintain a Stored Procedure and they are re-usable
 Improved performance.

56. Describe triggers?


A trigger is a special kind of stored procedure that automatically executes when an event
occurs in the database server. There are three types of triggers: DDL, DML, and LOGON
 DDL: DDL triggers execute in response to a variety of data definition language
(DDL) events. These events primarily correspond to Transact-SQL CREATE,
ALTER, and DROP statements, and certain system stored procedures that
perform DDL-like operations.
 DML: DML triggers execute when a user tries to modify data through a data
manipulation language (DML) event. DML events are INSERT, UPDATE, or
DELETE statements on a table or view. These triggers fire when any valid event
is fired, regardless of whether any table rows are affected
 LOGON: Logon triggers fire in response to the LOGON event that is raised when
a user session is being established

57. What are views?


A view is a virtual table whose contents are defined by a query. Like a table, a view
consists of a set of named columns and rows of data. Unless indexed, a view does not
exist as a stored set of data values in a database. The rows and columns of data come
from tables referenced in the query defining the view and are produced dynamically
when the view is referenced. There are three types of views:

 Indexed views
 Partitioned views
 System views
ASP.NET

58. Can you please explain application life cycle?


The application life cycle has the following stages:
 User makes a request for accessing application resource, a page. Browser sends this
request to the web server.
 A unified pipeline receives the first request and the following events take place:
o An object of the class ApplicationManager is created.
o An object of the class HostingEnvironment is created to provide information
regarding the resources.
o Top level items in the application are compiled.
 Response objects are created. The application objects such as HttpContext,
HttpRequest and HttpResponse are created and initialized.
 An instance of the HttpApplication object is created and assigned to the request.
 The request is processed by the HttpApplication class. Different events are raised by
this class for processing the request.

59. How do you explain ASP .NET page life cycle?


When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and
events are available, which could be overridden according to the need of the application.
Understanding the page cycle helps in writing codes for making some specific thing
happen at any stage of the page life cycle. It also helps in writing custom controls and
initializing them at right time, populate their properties with view-state data and run
control behavior code.
Following are the different stages of an ASP.NET page:
 Page request - When ASP.NET gets a page request, it decides whether to parse and
compile the page, or there would be a cached version of the page; accordingly, the
response is sent.
 Starting of page life cycle - At this stage, the Request and Response objects are set.
If the request is an old request or post back, the IsPostBack property of the page is set
to true. The UICulture property of the page is also set.
 Page initialization - At this stage, the controls on the page are assigned unique ID by
setting the UniqueID property and the themes are applied. For a new request, postback
data is loaded and the control properties are restored to the view-state values.
 Page load - At this stage, control properties are set using the view state and control
state values.
 Validation - Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.
 Postback event handling - If the request is a postback (old request), the related event
handler is invoked.
 Page rendering - At this stage, view state for the page and all controls are saved. The
page calls the Render method for each control and the output of rendering is written to
the OutputStream class of the Response property of page.
 Unload - The rendered page is sent to the client and page properties, such as Response
and Request, are unloaded and all cleanup done.

60. ASP.NET Page life cycle events?

At each stage of the page life cycle, the page raises some events, which could be coded.
An event handler is basically a function or subroutine, bound to the event, using declarative
attributes such as Onclick or handle.
Following are the page life cycle events:
 PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property
and determines whether the page is a postback. It sets the themes and master pages,
creates dynamic controls, and gets and sets profile property values. This event can be
handled by overloading the OnPreInit method or creating a Page_PreInit handler.
 Init - Init event initializes the control property and the control tree is built. This event
can be handled by overloading the OnInit method or creating a Page_Init handler.
 InitComplete - InitComplete event allows tracking of view state. All the controls turn
on view-state tracking.
 LoadViewState - LoadViewState event allows loading view state information into the
controls.
 LoadPostData - During this phase, the contents of all the input fields are defined with
the <form> tag are processed.
 PreLoad - PreLoad occurs before the post back data is loaded in the controls. This
event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.
 Load - The Load event is raised for the page first and then recursively for all child
controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.
 LoadComplete - The loading process is completed, control event handlers are run, and
page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler
 PreRender - The PreRender event occurs just before the output is rendered. By
handling this event, pages and controls can perform any updates before the output is
rendered.
 PreRenderComplete - As the PreRender event is recursively fired for all child
controls, this event ensures the completion of the pre-rendering phase.
 SaveStateComplete - State of control on the page is saved. Personalization, control
state and view state information is saved. The HTML markup is generated. This stage
can be handled by overriding the Render method or creating a Page_Render handler.
 UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the
UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is
done and all resources and references, such as database connections, are freed. This
event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad
handler.

61. What is the concept of Postback in ASP.NET?


A postback is a request sent from a client to server from the same page user is already
working with. ASP.NET was introduced with a mechanism to post an HTTP POST request
back to the same page. It’s basically posting a complete page back to server (i.e. sending
all of its data) on the same page. So, the whole page is refreshed.

In the below diagram, when first request is made from client to server for a web page (say
a simple registration form), IsPostback property value will be false. It will be
a GET request that may be initiated by:

 typing a web page URL in a browser window or


 using JavaScript window.open method
 or, clicking a hyperlink on a webpage page.

After user filled the returned form and presses a button (say submit button, or use
JavaScript to submit form), an HTTP Post request is made to server on same page with
data as shown in point 3. This time IsPostbackproperty value will be true. Server
processes the request and returns a response back to client.

Another concept related to this approach is "Callback" that is also asked sometimes
during a technical interview question. Click here to understand Postback Vs Callback in
ASP.NET.
62. Explain about ASP.NET MVC Page Life Cycle?

It is the sequence of events that happen every time an HTTP request is handled by our
application.
The entry point for every MVC application begins with routing. After the ASP.NET
platform has received a request, it figures out how it should be handled through the URL
Routing Module.
Modules are .NET components that can hook into the application life cycle and add
functionality. The routing module is responsible for matching the incoming URL to routes
that we define in our application.
All routes have an associated route handler with them and this is the entry point to the
MVC framework.
The MVC framework handles converting the route data into a concrete controller that can
handle requests. After the controller has been created, the next major step is Action
Execution. A component called the action invoker finds and selects an appropriate Action
method to invoke the controller.
After our action result has been prepared, the next stage triggers, which is Result
Execution. MVC separates declaring the result from executing the result. If the result is a
view type, the View Engine will be called and it's responsible for finding and rending our
view.
If the result is not a view, the action result will execute on its own. This Result Execution
is what generates an actual response to the original HTTP request.

63. What is difference between ASP.MVC and ASP.NET WebForms?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout,
whereas ASP.NET MVC uses Front controller approach. In case of Page controller
approach, every page has its own controller, i.e., code-behind file that processes the
request. On the other hand, in ASP.NET MVC, a common controller for all pages
processes the requests.

64. What are different types of validators in ASP.NET?

ASP.NET validation controls define an important role in validating the user input data.
Whenever the user gives the input, it must always be validated before sending it across to
various layers of an application. If we get the user input with validation, then chances are
that we are sending the wrong data. So, validation is a good idea to do whenever we are
taking input from the user.
There are the following two types of validation in ASP.NET:

 Client-Side Validation
 Server-Side Validation

Client-Side Validation:

When validation is done on the client browser, then it is known as Client-Side Validation.
We use JavaScript to do the Client-Side Validation.

Server-Side Validation:

When validation occurs on the server, then it is known as Server-Side Validation. Server-
Side Validation is a secure form of validation. The main advantage of Server-Side
Validation is if the user somehow bypasses the Client-Side Validation, we can still catch
the problem on server-side.

The following are the Validation Controls in ASP.NET:

 RequiredFieldValidator Control
 CompareValidator Control
 RangeValidator Control
 RegularExpressionValidator Control
 CustomFieldValidator Control
 ValidationSummary

65. State management in ASP.NET MVC?


As we all know, HTTP is a stateless protocol, i.e., each HTTP request does not know
about the previous request. If you are redirecting from one page to another page, then you
have to maintain or persist your data so that you can access it further. To do this, there
were many techniques available in ASP.NET like ViewState, SessionState,
ApplicationState etc.
ASP.NET MVC also provides state management techniques that can help us to maintain
the data when redirecting from one page to other page or in the same page after
reloading. There are several ways to do this in ASP.NET MVC -
1. Hidden Field
2. Cookies
3. Query String
4. ViewData
5. ViewBag
6. TempData
The above objects help us to persist our data on the same page or when moving from
“Controller” to “View” or “Controller” to Controller”. Let us start practical
implementation of these so that we can understand in a better way.
Hidden Field:
It is not new, we all know it from HTML programming. Hidden field is used to hide your
data on client side. It is not directly visible to the user on UI but we can see the value in
the page source. So, this is not recommended if you want to store a sensitive data. It’s
only used to store a small amount of data which is frequently changed.
Cookies:
Cookies are used for storing the data, but that data should be small. It is like a small text
file where we can store our data. The good thing is that a cookie is created on client-side
memory in the browser. Most of the times, we use a cookie for storing the user
information after login with some expiry time. Basically, a cookie is created by the server
and sent to the browser in response. The browser saves it in client-side memory.
Query String:
In ASP.NET, we generally use a query string to pass the value from one page to the next
page. Same we can do in ASP.NET MVC as well.
ViewData:
It helps us to maintain your data when sending the data from Controller to View. It is a
dictionary object and derived from ViewDataDictionary. As it is a dictionary object, it
takes the data in a key-value pair.
ViewBag:
The ViewBag’s task is same as that of ViewData. It is also used to transfer the data from
Controller to View. However, the only difference is that ViewBag is an object of
Dynamic property introduced in C# 4.a. It is a wrapper around ViewData. If you use
ViewBag rather than ViewData, you will not have to do typecasting with the complex
objects and do not need to check for null.
TempData:
TempData is also a dictionary object as ViewData and stores value in key/value pair. It is
derived from TempDataDictionary. It is mainly used to transfer the data from one request
to another request or we can say subsequent request. If the data for TempData has been
read, then it will get cleaned. To persist the data, there are different ways. It all depends
on how you read the data.
66. Difference between Tempdata and Session?
TempData is used to pass data from current request to subsequent request (means
redirecting from one page to another). It’s life is very short and lies only till the target view
is fully loaded.
Session is also used to pass data within the ASP.NET MVC application and Unlike
TempData, it persists for its expiration time (by default session expiration time is 20
minutes but it can be increased). Session is valid for all requests, not for a single redirect

67. Explain about caching in ASP.NET?


One of the most important factors in building high-performance, scalable Web
applications is the ability to store items, whether data objects, pages, or parts of a page, in
memory the initial time they are requested. You can cache, or store, these items on the
Web server or other software in the request stream, such as the proxy server or browser.
This allows you to avoid recreating information that satisfied a previous request,
particularly information that demands significant processor time or other resources.
ASP.NET provides two types of caching that you can use to create high-performance
Web applications. The first is output caching, which allows you to store dynamic page
and user control responses.
The second type of caching is application data caching, which you can use to
programmatically store arbitrary objects, such as application data, in server memory so
that your application can save the time and resources it takes to recreate them.

68. Caching in ASP.NET MVC?


In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is
the same concept as output caching in web forms. The output cache enables you to cache
the content returned by a controller action.
Output caching basically allows you to store the output of a particular controller in the
memory. Hence, any future request coming for the same action in that controller will be
returned from the cached result. That way, the same content does not need to be generated
each and every time the same controller action is invoked

69. What is MVC?


MVC stands for Model View Controller. It is an architectural pattern to develop
enterprise application. It is not a Microsoft technology, whether it is a common design
pattern that is used to create web application. It is used to create structure user-oriented
application.
The following is the detailed description:
Model
Model is entity class that encapsulates the properties and the behaviors of domain. It also
contains the business logic. MVC components use Model to perform logic. Model is
basically represented to data objects like it can be business logic, validation or data
access logic. The view and the controller both can access the Model.
View
It’s a GUI. View is nothing but a User Interface. Basically, user interacts with a View.
View is used to display data, add data or modify data. View is rendered on browser. It
renders the data in html form. So, we can say, a view is a result that a user can see while
interacting with web application.
Controller
It handles the request coming from the users and as per data it connects with Model and
perform some logic and display data on View. So, basically it validates the user request
and process data as per requirement.

70. What is ASP.NET MVC and Its advantages?


ASP.NET MVC is a framework that supports MVC Design Pattern to develop different
kinds of application. It is Microsoft Open Source Framework and also light weight to
other framework.It provides us numbers of benefits as compared to other programming
approach. The following are the features which force us to use ASP.NET MVC.
 Development
It supports Loose Coupling that means we can create a project with multiple
components; these components will not be dependent to each other. If there is some
complication in one component it will not be effect the development of other
component. So, this feature makes development very easy for developers
 Testability
It is a Test-Driven Development (TDD). As you know MVC is loosely coupled so we
can test a particular component without affecting other component. If one component
is going to be tested and it is dependent to other component then we can pass input as
mock component and test the particular component. So, Mocking makes testing very
easy.
 Performance
ASP.NET MVC does not support normal web form features like ViewState, Postback
etc. So, there is no need to maintain the state of control. It makes it faster in
performance.
 Full Html Control
It also does not support any server control and only supports pure html input control
that makes it faster to normal web form.
 Extensibility
It supports multiple view engines like aspx, razor. If you want to create your own
engine, you can create.

71. Different return types of a controller action method?


The base type of all these result types is ActionResult.
1. ViewResult (View): This return type is used to return a webpage from an action
method.
2. PartialviewResult (Partialview): This return type is used to send a part of a view
which will be rendered in another view.
3. RedirectResult (Redirect): This return type is used to redirect to any other controller
and action method depending on the URL.
4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is
used when we want to redirect to any other action method.
5. ContentResult (Content): This return type is used to return HTTP content type like
text/plain as the result of the action.
6. jsonResult (json): This return type is used when we want to return a JSON message.
7. javascriptResult (javascript): This return type is used to return JavaScript code that
will run in browser.
8. FileResult (File): This return type is used to send binary output in response.
9. EmptyResult: This return type is used to return nothing (void) in the result.

72. Explain Filters in ASP.NET MVC?


MVC, controllers define action methods and these action methods generally have a one-
to-one relationship with UI controls such as clicking a button or a link, etc. For example,
in one of our previous examples, the UserController class contained methods UserAdd,
UserDelete, etc. But many times, we would like to perform some action before or after a
particular operation. For achieving this functionality, ASP.NET MVC provides feature to
add pre and post action behaviors on controller's action methods.

Types of Filters:
 Action Filters: Action filters are used to implement logic that gets executed before
and after a controller action executes.
 Authorization Filters: Authorization filters are used to implement authentication and
authorization for controller actions.
 Result Filters: Result filters contain logic that is executed before and after a view
result is executed. For example, you might want to modify a view result right before
the view is rendered to the browser.
 Exception Filters: Exception filters are the last type of filter to run. You can use an
exception filter to handle errors raised by either your controller actions or controller
action results. You can also use exception filters to log errors.

Action filters are one of most commonly used filters to perform additional data
processing or manipulating the return values or cancelling the execution of action or
modifying the view structure at run time.

Action Filters are additional attributes that can be applied to either a controller section or
the entire controller to modify the way in which action is executed. These attributes are
special .NET classes derived from System.Attribute which can be attached to classes,
methods, properties and fields.

ASP.NET MVC provides the following action filters:

 Output Cache: This action filter caches the output of a controller action for a
specified amount of time.
 Handle Error: This action filter handles errors raised when a controller action
executes.
 Authorize: This action filter enables you to restrict access to a particular user or role.

73. Explain about MVC routing?

Routing is a mechanism to process the incoming url that is more descriptive and give
desired response. In this case, URL is not mapped to specific files or folder as was the
case of earlier days web sites.

There are two types of routing (after the introduction of ASP.NET MVC 5).
1. Convention based routing: to define this type of routing, we call MapRoute method
and set its unique name, URL pattern and specify some default values.
2. Attribute based routing: to define this type of routing, we specify the Route attribute
in the action method of the controller.

Routing is the URL pattern that is mapped together to a handler. Routing is responsible
for incoming browser request for particular MVC controller. In other ways let us say
routing help you to define a URL structure and map the URL with controller. There are
three segments for routing that are important,

1. Controller Name
2. ActionMethod Name
3. Parameter
74. Difference between view and Partial view?

View:
 It contains the layout page.
 Before any view is rendered, viewstart page is rendered.
 View might have markup tags like body, html, head, title, meta etc.
 View is not lightweight as compare to Partial View.
Partial View:
 It does not contain the layout page.
 Partial view does not verify for a viewstart.cshtml.We cannot put common code for a
partial view within the viewStart.cshtml.page.
 Partial view is designed specially to render within the view and just because of that it
does not consist any mark up.
 We can pass a regular view to the RenderPartial method.

75. What is view engine, razor views and explain advantages of Razor engine?

The view engine is responsible for creating HTML from your views. Views are usually
some kind of mix up of HTML and a programming language.
Razor is an ASP.NET programming syntax used to create dynamic web pages with
the C# or Visual Basic .NET programming languages. The Razor syntax is a template
markup syntax, based on the C# programming language, that enables the programmer to
use an HTML construction workflow.

For example, ASP.NET comes with its own view engine out of the box. That is the one
where views have lots of tags like <% %> and <%: %>. It uses the .aspx file extension.
With ASP.NET MVC3, another out-of-the-box view engine was added, Razor, which has
a more appealing syntax, e.g. <div>@Model.UserName</div>.

Instead of using the ASP.NET Web Forms (.aspx) markup syntax


with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with
an @ character and does not require explicit closing of the code-block.
Advantages:
 Compact & Expressive.
 Razor minimizes the number of characters and keystrokes required in a file and
enables a fast coding workflow.
 Easy to Learn.
 Works with any Text Editor
 Has great Intellisense
 Unit Testable

Вам также может понравиться