Sunteți pe pagina 1din 187

Contents

OOP....................................................................................................................... 1
(B) What is Object Oriented Programming?........................................................1
(B) Whats a Class ?............................................................................................ 2
(B) Whats an Object ?........................................................................................ 2
(B) What are different properties provided by Object-oriented systems ?..........2
(B) What is a Interface ?..................................................................................... 3
(B)What is difference between abstract classes and interfaces?........................3
.NET ARCHITECTURE.............................................................................................. 7
FRAMEWORK.......................................................................................................... 9
ASP.NET................................................................................................................ 14
ADO.NET.............................................................................................................. 20
THREADING.......................................................................................................... 26
REMOTING AND WEB SERVICES...........................................................................27
CASHING.............................................................................................................. 29
SQL SERVER......................................................................................................... 34
XML...................................................................................................................... 36
SILVERLIGHT........................................................................................................ 39
WCF..................................................................................................................... 39
WWF.................................................................................................................... 39
DTSX.................................................................................................................... 39
MVC..................................................................................................................... 39
ENTITY FRAMEWORK............................................................................................ 39

GENERAL
What is an application server?
As defined in Wikipedia, an application server is a software engine that
delivers applications to client computers or devices. The application server runs your
server code. Some well known application servers are IIS (Microsoft), WebLogic Server
(BEA), JBoss (Red Hat), WebSphere (IBM).

What are design patterns?

Design patterns are common solutions to common design problems.

What is a connection pool?


A connection pool is a collection of connections which are shared between the clients
requesting one. Once the connection is closed, it returns back to the pool. This allows
the connections to be reused.

What is a flat file?


A flat file is the name given to text, which can be read or written only sequentially.

What are functional and non-functional requirements?


Functional requirements defines the behavior of a system whereas non-functional
requirements specify how the system should behave; in other words they specify the
quality requirements and judge the behavior of a system.
E.g.
Functional - Display a chart which shows the maximum number of products sold in a
region.
Non-functional The data presented in the chart must be updated every 5 minutes.

What is a stack? What is a heap? Give the differences between the two?
Stack is a place in the memory where value types are stored. Heap is a place in the
memory where the reference types are stored.

Stack vs. Heap: What's the difference?


The Stack is more or less responsible for keeping track of what's executing in our code
(or what's been "called"). The Heap is more or less responsible for keeping track of our
objects (our data, well... most of it; we'll get to that later).
Think of the Stack as a series of boxes stacked one on top of the next. We keep track of
what's going on in our application by stacking another box on top every time we call a
method (called a Frame). We can only use what's in the top box on the Stack. When
we're done with the top box (the method is done executing) we throw it away and
proceed to use the stuff in the previous box on the top of the Stack. The Heap is similar
except that its purpose is to hold information (not keep track of execution most of the
time) so anything in our Heap can be accessed at any time. With the Heap, there are
no constraints as to what can be accessed like in the Stack. The Heap is like the heap of
clean laundry on our bed that we have not taken the time to put away yet; we can grab
what we need quickly. The Stack is like the Stack of shoe boxes in the closet where we
have to take off the top one to get to the one underneath it.

The picture above, while not really a true representation of what's happening in memory,
helps us distinguish a Stack from a Heap.
The Stack is self-maintaining, meaning that it basically takes care of its own memory
management. When the top box is no longer used, it's thrown out. The Heap, on the
other hand, must worry about Garbage collection (GC), which deals with how to keep the
Heap clean (no one wants dirty laundry laying around, it stinks!).

What goes on the Stack and Heap?


We have four main types of things we'll be putting in the Stack and Heap as our code is
executing: Value Types, Reference Types, Pointers, and Instructions.
Value Types:
In C#, all the "things" declared with the following list of type declarations are Value
types (because they are from System.ValueType):

bool

byte

char

decimal

double

enum

float

int

long

sbyte

short

struct

uint

ulong

ushort

Reference Types:
All the "things" declared with the types in this list are Reference types (and inherit from
System.Object, except, of course, for object which is the System.Object object):

class

interface

delegate

object

string

Pointers:
The third type of "thing" to be put in our memory management scheme is a Reference to
a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers,
they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is
different than a Reference Type in that when we say something is a Reference Type, it
means we access it through a Pointer. A Pointer is a chunk of space in memory that
points to another space in memory. A Pointer takes up space just like any other thing
that we're putting in the Stack and Heap and its value is either a memory address or
null.

Instructions:
You'll see how the "Instructions" work later in this article...

How is it decided what goes where? (Huh?)


Ok, one last thing and we'll get to the fun stuff.
Here are our two golden rules:
1. A Reference Type always goes on the Heap; easy enough, right?

2. Value Types and Pointers always go where they were declared. This is a little
more complex and needs a bit more understanding of how the Stack works to
figure out where "things" are declared.
The Stack, as we mentioned earlier, is responsible for keeping track of where each
thread is during the execution of our code (or what's been called). You can think of it as
a thread "state" and each thread has its own Stack. When our code makes a call to
execute a method the thread starts executing the instructions that have been JIT
compiled and live on the method table, it also puts the method's parameters on the
thread Stack. Then, as we go through the code and run into variables within the method,
they are placed on top of the Stack. This will be easiest to understand with an example.
Take the following method:

public int AddFive(int pValue)


{
int result;
result = pValue + 5;
return result;
}
Here's what happens at the very top of the Stack. Keep in mind that what we are
looking at is placed on top of many other items already living in the Stack:
Once we start executing the method, the method's parameters are placed on the Stack
(we'll talk more about passing parameters later).

NOTE : the method does not live on the stack and is illustrated just
for reference.

Next, control (the thread executing the method) is passed to the instructions to the
AddFive() method which lives in our type's method table, a JIT compilation is performed
if this is the first time we are hitting the method.

As the method executes, we need some memory for the "result" variable and it is
allocated on the Stack.

The method finishes execution and our result is returned.

And all memory allocated on the Stack is cleaned up by moving a pointer to the available
memory address where AddFive() started and we go down to the previous method on
the stack (not seen here).

In this example, our "result" variable is placed on the stack. As a matter of fact, every
time a Value Type is declared within the body of a method, it will be placed on the stack.
Now, Value Types are also sometimes placed on the Heap. Remember the rule, Value
Types always go where they were declared? Well, if a Value Type is declared outside of a
method, but inside a Reference Type then it will be placed within the Reference Type on
the Heap.
Here's another example.
If we have the following MyInt class (which is a Reference Type because it is a class):
public class MyInt
{

public int MyValue;


}
and the following method is executing:
public MyInt AddFive(int pValue)
{
MyInt result = new MyInt();
result.MyValue = pValue + 5;
return result;
}
Then just as before, the thread starts executing the method and its parameters are
placed on sthe thread's stack.

Now is when it gets interesting.


Because MyInt is a Reference Type, it is placed on the Heap and referenced by a Pointer
on the Stack.

After AddFive() is finished executing (like in the first example), and we are cleaning up...

we're left with an orphaned MyInt in the Heap (there is no longer anyone in the Stack
standing around pointing to MyInt)!

This is where the Garbage Collection (GC) comes into play. Once our program reaches a
certain memory threshold and we need more Heap space, our GC will kick off. The GC
will stop all running threads (a FULL STOP), find all objects in the Heap that are not
being accessed by the main program and delete them. The GC will then reorganize all
the objects left in the Heap to make space and adjust all the Pointers to these objects in
both the Stack and the Heap. As you can imagine, this can be quite expensive in terms
of performance, so now you can see why it can be important to pay attention to what's
in the Stack and Heap when trying to write high-performance code.
Ok, that's great, but how does it really affect me?
Good question.
When we are using Reference Types, we're dealing with Pointers to the type, not the
thing itself. When we're using Value Types, we're using the thing itself. Clear as mud,
right?
Again, this is best described by example.
If we execute the following method:
public int ReturnValue()
{
int x = new int();
x = 3;
int y = new int();
y = x;
y = 4;
return x;
}
We'll get the value 3. Simple enough, right?
However, if we are using the MyInt class from before:

public class MyInt

public int MyValue;


}
and we are executing the following method:
public int ReturnValue2()
{
MyInt x = new MyInt();
x.MyValue = 3;
MyInt y = new MyInt();
y = x;
y.MyValue = 4;
return x.MyValue;
}
What do we get?

4!

Why?... How does x.MyValue get to be 4? Take a look at what we're doing and see if it
makes sense:
In the first example everything goes as planned:
public int ReturnValue()
{
int x = 3;
int y = x;
y = 4;
return x;
}

In the next example, we don't get "3" because both variables "x" and "y" point to the
same object in the Heap.

public int ReturnValue2()


{
MyInt x;
x.MyValue = 3;
MyInt y;
y = x;
y.MyValue = 4;
return x.MyValue;
}

Hopefully this gives you a better understanding of a basic difference between Value Type
and Reference Type variables in C# and a basic understanding of what a Pointer is and
when it is used. In the next part of this series, we'll get further into memory
management and specifically talk about method parameters.

What is code review?


The process of examining the source code generally through a peer, to verify it against
best practices.

What is logging?
Logging is the process of persisting information about the status of an application.

What are mock-ups?


Mock-ups are a set of designs in the form of screens, diagrams, snapshots etc., that
helps verify the design and acquire feedback about the applications requirements and
use cases, at an early stage of the design process.

What is a Form?
A form is a representation of any window displayed in your application. Form can be used
to create standard, borderless, floating, modal windows.

What is a multiple-document interface(MDI)?

A user interface container that enables a user to work with more than one document at a
time. E.g. Microsoft Excel.

What is a single-document interface (SDI) ?


A user interface that is created to manage graphical user interfaces and controls into
single windows. E.g. Microsoft Word

What is BLOB ?
A BLOB (binary large object) is a large item such as an image or an exe represented in
binary form.

What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish selfupdating applications that can be installed and run with minimal user interaction.

What is object role modeling (ORM) ?


An ORM (Object-Relational Mapping) is a tool that lets you query and manipulate data from a
database using an object paradigm.
It's a completely ordinary library written in your language that encapsulates the code needed to
manipulate the data, so you don't use SQL anymore, but directly an object of your language.
E.G., a completely imaginary case with a pseudo language :
You have a book class, you want to retrieve all the books of which the author is "Linus".
Manually, you would do something like that :
book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
book = new Book();
book.setAuthor(row.get('author');
book_list.add(book);
}
With an ORM, it would look like that :
book_list = BookTable.query(author="Linus");
The mechanical part is taken care automatically by the ORM.

What is a private assembly?


A private assembly is local to the installation directory of an application and is used only
by that application.

What is a shared assembly?

A shared assembly is kept in the global assembly cache (GAC) and can be used by one
or more applications on a machine.

What is the difference between user and custom controls?


User control: Any control inheriting from UserControl class; These types of controls
have a markup associated with them and can have code-behind based on the type of
project you have (whether your project is a website or a web application). These
controls are not good for re-usability across projects. They are very good candidates
to be used as Views in MVC (Model-View-Controller).
Custom control: Any control inheriting from Control,
or WebControl or CompositeControl or DataBoundControl or some other base classes
in .NET. These controls don't have associated markup with them. They are pretty
good for being encapsulated inside a DLL and being reused across multiple projects.
Custom controls usually need more understanding of how web works and you usually
overwrite CreateChildren or Render method to determine the output of the control.
A user control is a composition of existing controls while a custom control is a control
derived from one base control. This might be better in stackoverflow btw.

Where do custom controls reside?


In the global assembly cache (GAC).

What is a third-party control ?


A third-party control is one that is not created by the owners of a project. They are
usually used to save time and resources and reuse the functionality developed by others
(third-party).

What is a binary formatter?


Binary formatter is used to serialize and deserialize an object in binary format.

What is Boxing/Unboxing?
Boxing is used to convert value types to object.
E.g. int x = 1;
object obj = x ;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int)obj;
Boxing/unboxing is quiet an expensive operation.

What is a digital signature?

A digital signature is an electronic signature used to verify/gurantee the identity of the


individual who is sending the message.

What is garbage collection?


Garbage collection is the process of managing the allocation and release of memory in
your applications. Read this article for more information.

What is globalization?
Globalization is the process of customizing applications that support multiple cultures
and regions.

What is localization?
Localization is the process of customizing applications that support a given culture and
regions.

What is MIME?
Multipurpose Internet Mail.
MIME extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to
include multiple content, both textual and non-textual. Parts of the message may be
images, audio, or text in different character sets.

OOP
*(B) What is a Interface ?
Interface is a contract that defines the signature of the functionality. So if a
class is implementing a interface it says to the outer world, that it provides
specific behavior. Example if a class is implementing Idisposable interface
that means it has a functionality to release unmanaged resources. Now
external objects using this class know that it has contract by which it can
dispose unused unmanaged objects.
Single Class can implement multiple interfaces.
If a class implements a interface then it has to provide implementation to
all its methods.

*(B) What is difference between abstract classes and interfaces?

An interface is a contract: the guy writing the interface says, "hey, I accept things
looking that way", and the guy using the interface says "OK, the class I write looks
that way".
An interface is an empty shell, there are only the signatures (name / params /
return type) of the methods. The methods do not contain anything. The interface
can't do anything. It's just a pattern.

Implementing an interface consumes very little CPU, because it's not a class, just a
bunch of names, and therefore there is no expensive look-up to do. It's great when it
matters such as in embedded devices.

Abstract classes
Abstract classes, unlike interfaces, are classes. They are more expensive to use
because there is a look-up to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can
define a behavior for them. It's more about a guy saying, "these classes should look
like that, and they have that in common, so fill in the blanks!".

Implementation
While abstract classes and interfaces are supposed to be different concepts, the
implementations make that statement sometimes untrue. Sometimes, they are not
even what you think they are.
In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes
with no method declared.
In Python, abstract classes are more a programming trick you can get from the ABC
module and is actually using metaclasses, and therefore classes. And interfaces are
more related to duck typing in this language and it's a mix between conventions and
special methods that call descriptors (the __method__ methods).
As usual with programming, there is theory, practice, and practice in another
language :-)

*(B) What are different properties provided by Object-oriented


systems ?
Twist :- Can you explain different properties of Object Oriented Systems?
Note:- Difference between abstraction and encapsulation is one of the
favorite interview question and quiet confusing as both the terminology look
alike. Best is if you can brainstorm with your friends or do a little reading.
Following are characteristics of Object Oriented Systems
Abstraction It allows complex real world to be represented in simplified
manner. Example color is abstracted to RGB. By just making the combination

of these three colors we can achieve any color in world.Its a model of real
world or concept.
Encapsulation It is a process of hiding all the internal details of an object
from the outside world.
Communication using messages When application wants to achieve
certain task it can only be done using combination of objects. A single object
can not do all the task. Example if we want to make order processing form.We
will use Customer object, Order object, Product object and Payment object to
achieve this functionality. In short these objects should communicate with
each other. This is achieved when objects send messages to each other.
Object lifetime All objects have life time.Objects are created ,and initialized,
necessary functionalities are done and later the object is destroyed. Every
object have there own state and identity which differ from instance to
instance.
Class hierarchies (Inheritance and aggregation) Twist :- What is
difference between Association, Aggregation and Inheritance relationships? In
object oriented world objects have relation and hierarchies in between them.
There are basically three kind of relationship in Object Oriented world :
Association This is the simplest relationship between objects. Example
every customer has sales. So Customer object and sales object have an
association relation between them.
Aggregation This is also called as composition model. Example in order to
make a Accounts class it has use other objects example Voucher,
Journal and Cash objects. So accounts class is aggregation of these three
objects.202
Inheritance Hierarchy is used to define more specialized classes based on a
preexisting generalized class. Example we have VEHICLE class and we can
inherit this class make more specialized class like CAR, which will add new
attributes and use some existing qualities of the parent class. Its shows more
of a parent-child relationship. This kind of hierarchy is called inheritance.
Polymorphism When inheritance is used to extend a generalized class to a
more specialized class, it includes behavior of the top class(Generalized
class). The inheriting class often implement a behavior that can be somewhat
different than the generalized class, but the name of the behavior can be
same. It is important that a given instance of an object use the correct
behavior, and the property of polymorphism allows this to happen
automatically.

*(I) What are abstract classes ?

Following are features of a abstract class : You can not create a object of abstract class204
Abstract class is designed to act as a base class (to be inherited by other
classes). Abstract class is a design concept in program development and
provides a base upon which other classes are built.
Abstract classes are similar to interfaces. After declaring an abstract class,
it cannot be instantiated on its own, it must be inherited.
In VB.NET abstract classes are created using MustInherit keyword.In C#
we have Abstract keyword.
Abstract classes can have implementation or pure abstract methods which
should be implemented in the child class.

(B) What is Object Oriented Programming?


It is a problem solving technique to develop software systems. It is a
technique to think real world in terms of objects. Object maps the software
model to real world concept. These objects have responsibilities and provide
services to application or other objects.

(B) Whats a Class ?


A class describes all the attributes of objects, as well as the methods that
implement the behavior of member objects. Its a comprehensive data type
which represents a blue print of objects. Its a template of object.

(B) Whats an Object ?

It is a basic unit of a system. An object is an entity that has attributes,


behavior, and identity. Objects are members of a class. Attributes and
behavior of an object are defined by the class definition.
(B) What is a delegate ?

Delegate is a class that can hold a reference to a method or a function.


Delegate class has a signature and it can only reference those methods

whose signature is compliant with the class. Delegates are type-safe


functions pointers or callbacks.
(B) What are events ?

As compared to delegates events works with source and listener


methodology. So listeners who are interested in receiving some events they
subscribe to the source. Once this subscription is done the source raises
events to its entire listener when needed. One source can have multiple
listeners. In sample given below class ClsWithEvents is a event source
class, which has a event EventAddString(). Now the listeners who are
interested in receiving this events they can subscribe to this event. In class
FrmWithEvents you can see they handle clause which is associated with the
mobjClsWithEvents objects.
(B) If we inherit a class do the private variables also get inherited ?

Yes, the variables are inherited but can not be accessed directly by the class
interface.
(B) What are the different accessibility levels defined in .NET ?

Following are the five levels of access modifiers : Private : Only members of class have access.
Protected :-All members in current class and in derived classes can access
the variables. Friend (internal in C#) :- Only members in current project
have access to the elements. Protected friend (protected internal in C#) :All members in current project and all members in derived class can access
the variables.
Public :- All members have access in all classes and projects.
(B) What is the difference between 'protected' and 'protected internal'?
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 assembly in which it is declared, or
from within a derived class in another assembly.

(B) How do short-cuited operators work?

Do you know how to short-circuit operators? In C#, And (&) and Or (|) operators evaluate both
boolean expressions in the statement. However, the && operator only evaluates the first Boolean
if false and the || operator only evaluates the first Boolean if true. This technique prevents the
execution of the second expression if unnecessary therefore optimizing your logic.

(B) What does virtual keyword mean ?

They are that method and property can be overridden.


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

Static/Shared classes are used when a class provides functionality which is


not specific to any instance. In short if you want an object to be shared
between multiple instances you will use a static/Shared class.
Following are features of Static/Shared classes : They can not be instantiated. By default a object is created on the first
method call to that object.
Static/Shared classes can not be inherited.
Static/Shared classes can have only static members.
Static/Shared classes can have only static constructor.
(B) What is the difference between static methods in a Non static class and static
methods in a static class?
The only difference is that static methods in a nonstatic class cannot be extension methods.

In other words, this is invalid:


class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
whereas this is valid:
static class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
(B) What is the volatile keyword used for?
Consider this example:

int i = 5;
System.out.println(i);
The compiler may optimize this to just print 5, like this:
System.out.println(5);
However, if there is another thread which can change i, this is the wrong behaviour. If another
thread changes i to be 6, the optimized version will still print 5.
The volatile keyword prevents such optimization and caching, and thus is useful when a variable
can be changed by another thread.

(B) Difference between ref and out parameters in .NET


They're pretty much the same - the only difference is that a variable you pass as
an out parameter doesn't need to be initialised, and the method using the out parameter has to
set it to something.
int x;
Foo(out x); // OK
int y;
Foo(ref y); // Error
Ref parameters are for data that might be modified, out parameters are for data that's an
additional output for the function (eg int.TryParse) that are already using the return value for
something.

The caller of a method which takes an out parameter is not required to assign to the variable
passed as the out parameter prior to the call; however, the callee is required to assign to the out
parameter before returning.
In contrast ref parameters are considered initially assigned by the callee. As such, the callee is
not required to assign to the ref parameter before use. Ref parameters are passed both into and
out of a method.
So, out means out, while ref is for in and out.
These correspond closely to the [out] and [in,out] parameters of COM interfaces, the
advantages of out parameters being that callers need not pass a pre-allocated object in cases
where it is not needed by the method being called - this avoids both the cost of allocation, and
any cost that might be associated with marshaling (more likely with COM, but not uncommon
in .NET).

(B) What is Dispose method in .NET ?

.NET provides Finalize method in which we can clean up our resources. But
relying on this is not always good so the best is to implement Idisposable
interface and implement the Dispose method where you can put your clean
up routines.
(B) What is the difference between using IDisposable vs a destructor (Finalize) in
C#?

Finalizers are run by the Garbage Collection before an object that is eligible for collection is
reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections,
files, handles to OS stuff, &c. It works best in conjunction with the using block where the
compiler makes sure that Dispose() will be called immediately once you are done with an object
and also ensures that you cannot work with the object anymore once it's disposed.
Note that finalizers don't have to run, so relying on that can be dangerous:

What this means for you: Your programs cannot rely on finalizers keeping things tidy. Finalizers
are a safety net, not a primary means for resource reclamation. When you are finished with a
resource, you need to release it by calling Close or Disconnect or whatever cleanup method is
available on the object. (The IDisposable interface codifies this convention.)
Careful also with the precise time when an object becomes eligible for collection. Read the article
linked above it's neither scope (a weird word which has noting to do with the lifetime of an
object it's the region of program text in which it is legal to refer to [a named entity] by its
unqualified name.) nor is it strictly reference counting as an object can become eligible for
collection even before the last reference to it goes away.

(B) What is the significance of Finalize method in .NET?

.NET Garbage collector does almost all clean up activity for your objects. But
unmanaged resources (ex: - Windows API created objects, File, Database
connection objects, COM objects etc) is outside the scope of .NET framework
we have to explicitly clean our resources. For these types of objects .NET
framework provides Object. Finalize method 218 which can be overridden and
clean up code for unmanaged resources can be put in this section.
(B) What is the use of DISPOSE method?

Dispose method belongs to IDisposable interface. We had seen in the


previous section how bad it can be to override the finalize method for writing
the cleaning of unmanaged resources. So if any object wants to release its
unmanaged code best is to implement220 IDisposable and override the
Dispose method of IDisposable interface. Now once your class has exposed
the Dispose method its the responsibility of the client to call the Dispose
method to do the cleanup.
(B) What is the use of OverRides and Overridable keywords ?

Overridable is used in parent class to indicate that a method can be


overridden. Overrides is used in the child class to indicate that you are
overriding a method
(B) What is the difference between override and overload?
Polymorphism

Polymorphism means many forms (ability to take more than one form). In Polymorphism
poly means multiple and morph means forms so polymorphism means many forms.

In polymorphism we will declare methods with same name and different parameters in
same class or methods with same name and same parameters in different classes.
Polymorphism has ability to provide different implementation of methods that are
implemented with same name.

In Polymorphism we have 2 different types those are

- Overloading (Called as Early Binding or Compile Time Polymorphism or static


binding)

- Overriding (Called as Late Binding or Run Time Polymorphism or dynamic binding)

Overloading

Overloading means we will declare methods with same name but different signatures
because of this we will perform different tasks with same method name. This overloading
also called as compile time polymorphism or early binding.

Method Overloading or compile time polymorphism means same method names with
different signatures (different parameters)

For more details check this link polymorphism in c#

Overriding

Overriding also called as run time polymorphism or late binding or dynamic


polymorphism. Method overriding or run time polymorphism means same method
names with same signatures.

In this method overriding or run time polymorphism we can override a method in base
class by creating similar function in derived class this can be achieved by using
inheritance principle and using virtual &override keywords.

(B) What is the difference between System.String and System.StringBuilder


classes?

System.String is immutable; System.StringBuilder can have mutable string


where a variety of
operations can be performed.

Explain what the StringBuilder class is and why you'd want to use it?

string a,b,c,d;
a = b + c + d;

then it would be faster using strings and the plus operator. This is because (like Java, as Eric
points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that
StringBuilder also uses)
However, if what you are doing is closer to:
string a,b,c,d;
a = a + b;
a = a + c;
a = a + d;
Then you need to explicitly use a StringBuilder. .Net doesn't automatically create a StringBuilder
here, because it would be pointless. At the end of each line, "a" has to be an (immutable) string,
so it would have to create and dispose a StringBuilder on each line. For speed, you'd need to
use the same StringBuilder until you're done building:
string a,b,c,d;
StringBuilder e = new StringBuilder();
e.Append(b);
e.Append(c);
e.Append(d);
a = e.ToString();

(B) What does the keyword readonly means?

Generally, readonly means only that you can't re-assign a field outside the
constructor. The field itself can be modified as long as it stays the same instance.
So yes, you can add elements to the collection stored in readonly field.
Marking a field as read-only only means that you cannot change the value of that field. It has no
bearing on the internal state of the object there. In your examples, while you would not be able to
assign a new metadata object to the _metadata field, nor a new ICollection to the _items field
(outside of a constructor that is), you can change the internal values of the existing objects stored
in those fields.
There is nothing preventing you from mutating an object stored in a readonly field. So you CAN
call _items.Add() and metadata._Change() outside the constructor/initializer. readonly only
prevents you from assigning new values to those fields after construction.

(B) What is the difference between arrays and collection?


Array:
1.

You need to specify the size of an array at the time of its declaration. It cannot be resized
dynamically.

2.

The members of an array should be of the same data type.

Collection:
1.

The size of a collection can be adjusted dynamically, as per the user's requirement. It does
not have fixed size.

2.

Collection can have elements of different types.

(B) What are collections and generics?


A collection can be defined as a group of related items that can be referred to as a single unit.
TheSystem.Collections namespace provides you with many classes and interfaces. Some of
them are - ArrayList,List, Stack, ICollection, IEnumerable, and IDictionary.
Generics provide the type-safety to your class at the compile time. While creating a data structure,
you never need to specify the data type at the time of declaration.
The System.Collections.Generic namespace contains all the generic collections.

(I) Do events have return type ?

No, events do not have return type.


(I) What is shadowing ?

When two elements in a program have same name, one of them can hide and
shadow the other one. So in such cases the element which shadowed the
main element is referenced. Below is a sample code, there are two classes
ClsParent and ClsShadowedParent. In ClsParent there is a variable x
which is a integer. ClsShadowedParent overrides ClsParent and shadows
the x variable to a string.
(I) What is the difference between delegate and events?

Actually events use delegates in bottom. But they add an extra layer on the
delegates, thus forming the publisher and subscriber model.
As delegates are function to pointers they can move across any clients. So
any of the clients can add or remove events, which can be pretty confusing.
But events give the extra protection by adding the layer and making it a
publisher and subscriber model.

(I) Can you prevent a class from overriding ?

If you define a class as Sealed in C# and NotInheritable in VB.NET you


can not inherit the class any further.
(I) What is the use of MustInherit keyword in VB.NET ?

If you want to create a abstract class in VB.NET its done by using


MustInherit keyword.You can not create an object of a class which is
marked as MustInherit. When you define MustInherit keyword for class
you can only use the class by inheriting.
(I) Do interface have accessibility modifier?

All elements in Interface should be public. So by default all interface


elements are public by default.

(I) Whats a HashTable ?

Twist :- Whats difference between HashTable and ArrayList ? You can access
array using INDEX value of array, but how many times you know the real
value of index. Hashtable provides way of accessing the index using a user
identified KEY value, thus removing the INDEX problem.

(A) Different types of references in C#, weak references, soft references,


phantom references, strong references
Soft and phantom references come from Java, I believe. A long weak reference (pass true to
C#'s WeakReference constructor) might be considered similar to Java's PhantomReference. If
there is an analog to SoftReference in C#, I don't know what it is.
Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected
once all strong references have gone out of scope. They can be useful for holding on to large
objects that are expensive to initialize but should be avaialble for garabage collection if they are
not actively in use.
Whether or not this will be useful in reducing the memory consumption of your application will
depend completely on the specifics of the application. For example, if you have a moderate
number of cached objects hanging around which may or may not be reused in the future, weak
references could help improve the memory consumption of the caches. However, if the app is
working with a verly large number of small objects, weak references will make the problem worse
since the reference objects will take up as much or more memory.

(A) What is the relation between Classes and Objects ?

They look very much same but are not same. Class is a definition, while
object is a instance of the class created. Class is a blue print while objects are
actual objects existing in real world. Example we have class CAR which has
attributes and methods like Speed, Brakes, Type of Car etc. Class CAR is just
a prototype, now we can create real time objects which can be used to
provide functionality. Example we can create a Maruti car object with 100 km
speed and urgent brakes.
(A) Can events have access modifiers ?

Events are always public as they are meant to serve every one register ing
to it. But you can access modifiers in events.You can have events with
protected keyword which will be accessible only to inherited classes.You can
have private events only for object in that class.
(A) Can we have shared events ?

Yes, you can have shared events note only shared methods can raise shared
events.

(A) What is the difference between Shadowing and Overriding ?

Following are the differences between shadowing and overriding :-


Overriding redefines only the implementation while shadowing redefines the
whole element. In overriding derived classes can refer the parent class
element by using ME keyword, but in shadowing you can access it by
MYBASE.

(A) What is ArrayList ?

Array is whose size can increase and decrease dynamically. Array list can hold
item of different types. As Array list can increase and decrease size
dynamically you do not have to use the REDIM keyword. You can access any
item in array using the INDEX value of the array position.
(A) What is Indexer ?

An indexer is a member that enables an object to be indexed in the same way


as an array.

FRAMEWORK
*(B) What is a IL?

Twist :- What is MSIL or CIL , What is JIT? (IL)Intermediate Language is also


known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate
Language). All .NET source code is compiled to IL. This IL is then converted to
machine code at the point where the software is installed, or at run-time by a
Just-In- Time (JIT) compiler.
*(B) What is an Assembly?
Assembly is unit of deployment like EXE or a DLL. An assembly consists of
one or more files (dlls, exes, html files etc.), and represents a group of
resources, type definitions, and implementations of those types. An assembly
may also contain references to other assemblies. These resources, types and
references are described in a block of data called a manifest. The manifest is
part of the assembly, thus making the assembly self-describing.
An assembly is completely self-describing.An assembly contains metadata
information, which is used by the CLR for everything from type checking and
security to actually invoking the components methods. As all information is in
the assembly itself, it is independent of registry. This is the basic advantage as
compared to COM where the version was stored in registry.
Multiple versions can be deployed side by side in different folders. These
different versions can execute at the same time without interfering with each
other. Assemblies can be private or shared. For private assembly deployment,
the assembly is copied to the same directory as the client program that
references it. No registration is needed, and no fancy installation program is
required.100 When the component is removed, no registry cleanup is needed,
and no uninstall program is required. Just delete it from the hard drive.
In shared assembly deployment, an assembly is installed in the Global
Assembly Cache (or GAC). The GAC contains shared assemblies that are globally
accessible to all .NET applications on the machine.

*(B) What is NameSpace?


Namespace has two basic functionality :- NameSpace Logically group types,
example System.Web.UI logically groups our UI related features. In Object
Oriented world many times its possible that programmers will use the same class
name.By qualifying NameSpace with classname this collision is able to be
removed.
*(B) What is the difference between namespace and assembly?
NameSpace is a Collection of names while each name is Unique,They form
the logicalboundary for a Group of classes,Namespace must be specified in
Project-Properties.
While an assembly is physical grouping of logical units, Namespace, logically
groups classes.

a source code contains classes,interfaces and other type if we want to separate


different-2 type of functionality then we use namespace we make classes that
have different -2 type of functionality we placed it at different - 2 namespaces for
distinguishing the functionality separately, and when we built the application it
generate the physical unit called assembly having lot of logical namespaces and
classes
*(B) What is a Managed Code?
Managed code runs inside the environment of CLR i.e. .NET runtime. In short all
IL are managed code. But if you are using some third party software example
VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does
not have control over the source code execution of the language.
*(B) What is GAC ?

Twist :- What are situations when you register .NET assembly in GAC ? GAC
(Global Assembly Cache) is used where shared .NET assembly reside. GAC is
used in the following situations : If the application has to be shared among several application.
If the assembly has some special security requirements like only administrators
can remove the assembly. If the assembly is private then a simple delete of
assembly the assembly file will remove the assembly. Note :- Registering .NET
assembly in GAC can lead to the old problem of DLL hell, where COM version
was stored in central registry. So GAC should be used when absolutely
necessary.

*(B) How to add and remove an assembly from GAC?


There are two ways to install .NET assembly in GAC:-

Using Microsoft Installer Package. You can get download of installer from
http://www.microsoft.com.
Using Gacutil. Goto Visual Studio Command Prompt and type gacutil i
(assembly_name), where (assembly_name) is the DLL name of the project.

*(B) What is garbage collection?


Garbage collection is a CLR feature which automatically manages memory.
Programmers forget to release the objects while coding ..... Laziness (Remember
in VB6 where one of the good practices is to set object to nothing). CLR
automatically releases objects when they are no longer in use and refernced. CLR
runs on non-deterministic to see the unused objects and cleans them. One side
effect of this non-deterministic feature is that we cannot assume an object is
destroyed when it goes out of the scope of a function. Therefore, we should not
put code into a class destructor to release resources.
*(B) What is reflection?
All .NET assemblies have metadata information stored about the types defined in
modules. This metadata information can be accessed by mechanism called as
Reflection.System. Reflection can be used to browse through the metadata
information. Using reflection you can also dynamically invoke methods using
System.Type.Invokemember. Below is sample source code if needed you can also
get this code from CD provided, go to Source code folder in Reflection
Sample folder.

*(B) What are Value types and Reference types ?


Value types directly contain their data which are either allocated on the stack or
allocated in-line in a structure. Reference types store a reference to the value's
memory address, and are allocated on the heap. Reference types can be selfdescribing types, pointer types, or interface types. Variables that are value types
each have their own copy of the data, and therefore operations on one variable
do not affect other variables. Variables that are reference types can refer to the
same object; therefore, operations on one variable can affect the same object
referred to by another variable. All types derive from the System.Object base
type.
*(B) What is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET
framework. All Languages have runtime and its the responsibility of the runtime
to take care of the code execution of the program. For example VC++ has
MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc.
Similarly .NET has CLR. Following are the responsibilities of CLR Garbage
Collection :

- CLR automatically manages memory thus eliminating memory leaks. When


objects are not referred GC automatically releases those memories thus
providing efficient memory management. Code Access Security :
- CAS grants rights to program depending on the security configuration of the
machine. Example the program has rights to edit or create a new file but the
security configuration of machine does not allow the program to delete a file.
CAS will take care that the code runs under the environment of machines
security configuration. Code Verification :
- This ensures proper code execution and type safety while the code runs. It
prevents the source code to perform illegal operation such as accessing invalid
memory locations etc. IL( Intermediate language )-to-native translators and
optimizers :
- CLR uses JIT and compiles the IL code to machine code and then executes. CLR
also determines depending on platform what is optimized way of running the IL
code.

*(B) What is concept of Boxing and Unboxing ?


Boxing permits any value type to be implicitly converted to type object or to any
interface type implemented by value type. Boxing is a process in which object
instances are created and copy values in to that instance. Unboxing is vice versa
of boxing operation where the value is copied from the instance in to appropriate
storage location.
(B) What is a CTS?
In order that two language communicate smoothly CLR has CTS (Common Type
System).Example in VB you have Integer and in C++ you have long these
datatypes are not compatible so the interfacing between them is very
complicated. In order to able that two different languages can communicate
Microsoft introduced Common Type System. So Integer datatype in VB6 and
int datatype in C++ will convert it to System.int32 which is datatype of CTS.
CLS which is covered in the coming question is subset of CTS. Note: If you have
undergone COM programming period interfacing VB6 application with VC++
application was a real pain as the datatype of both languages did not have a
common ground where they can come and interface, by having CTS
interfacing is smooth.
(B) What is a CLS(Common Language Specification)?
This is a subset of the CTS which all .NET languages are expected to support. It
was always a dream of Microsoft to unite all different languages in to one
umbrella and CLS is one step towards that. Microsoft has defined CLS which are
nothing but guidelines that language to follow so that it can communicate with
other .NET languages in a seamless manner.

(B) Where is version information stored of an assembly ?


Version information is stored in assembly in manifest.
(B) What is the difference between VB.NET and C# ?
Well this is the most debatable issue in .NET community and people treat there
languages like religion. Its a subjective matter which language is best. Some like
VB.NETs natural style and some like professional and terse C# syntaxes. Both
use the same framework and speed is also very much equivalents. But still lets
list down some major differences between them :
- Advantages VB.NET : Has support for optional parameters which makes COM interoperability much
easy.
With Option Strict off late binding is supported.Legacy VB functionalities can be
used by using Microsoft.VisualBasic namespace.
Has the WITH construct which is not in C#.
The VB.NET part of Visual Studio .NET compiles your code in the background.
While this is considered an advantage for small projects, people creating very
large projects have found that the IDE slows down considerably as the project
gets larger.
Advantages of C#
XML documentation is generated from source code but this is now been
incorporated in Whidbey.
Operator overloading which is not in current VB.NET but is been introduced in
Whidbey.
Use of this statement makes unmanaged resource disposal simple.
Access to Unsafe code. This allows pointer arithmetic etc, and can improve
performance in some situations. However, it is not to be used lightly, as a lot of
the normal safety of C# is lost (as the name implies).This is the major difference
that you can access unmanaged code in C# and not in VB.NET.

(B) When we use windows API in .NET is it managed or unmanaged code ?


Windows API in .NET is unmanaged code. Note:- Even though VB6 and V C++
has gone off still many people do ask these old questions again and again.
Still there are decent old application which are working with COM very much
fine. So interviewer still asks you these questions so that those applications

can be ported to .NET. So lets play some old music... By the way my
favourite music is Kishore, whats yours???
(B) What are the main components of .NET Framework?
.NET Framework provides enormous advantages to software developers in comparison to the
advantages provided by other platforms. Microsoft has united various modern as well as existing
technologies of software development in .NET Framework. These technologies are used by
developers to develop highly efficient applications for modern as well as future business needs.
The following are the key components of .NET Framework:

.NET Framework Class Library

Common Language Runtime

Dynamic Language Runtimes (DLR)

Application Domains

Runtime Host

Common Type System

Metadata and Self-Describing Components

Cross-Language Interoperability

.NET Framework Security

Profiling

Side-by-Side Execution

(B) List the new features added in .NET Framework 4.0.


The following are the new features of .NET Framework 4.0:

Improved Application Compatibility and Deployment Support

Dynamic Language Runtime

Managed Extensibility Framework

Parallel Programming framework

Improved Security Model

Networking Improvements

Improved Core ASP.NET Services

Improvements in WPF 4

Improved Entity Framework (EF)

Integration between WCF and WF

(I) What are code contracts?


Code contracts help you to express the code assumptions and statements stating the behavior of
your code in a language-neutral way. The contracts are included in the form of pre-conditions,
post-conditions and object-invariants. The contracts help you to improve-testing by enabling runtime checking, static contract verification, and documentation generation.
The System.Diagnostics.Contracts namespace contains static classes that are used to
express contracts in your code.

(I) Is versioning applicable to private assemblies?


Versioning concept is only applicable to global assembly cache (GAC) as private
assembly lie in their individual folders.
(I) Give a brief introduction on side-by-side execution. Can two applications, one
using private assembly and the other using the shared assembly be stated as
side-by-side executables?
Side-by-side execution enables you to run multiple versions of an application or component and
CLR on the same computer at the same time. As versioning is applicable only to shared assemblies
and not to private assemblies, two applications, one using a private assembly and other using a
shared assembly, cannot be stated as side-by-side executables.

(I) What is the concept of strong names ?

Twist :- How do we generate strong names or what is the process of


generating strong names, What is use the of SN.EXE , How do we apply
strong names to assembly, How do you sign an assembly? Strong name is
similar to GUID(It is supposed to be unique in space and time) in COM
components.Strong Name is only needed when we need to deploy assembly in
GAC. Strong Names helps GAC to differentiate between two versions. Strong
names use public key cryptography (PKC) to ensure that no one can spoof it.PKC
use public key and private key concept. Following are the step to generate a
strong name and sign a assembly :
Go to Visual Studio Command Prompt. See below figure Visual studio
Command Prompt. Note the samples are compiled in 2005 but 2003
users do not have to worry about it. Same type of command prompt will
be seen in 2003 also.
After you are in command prompt type sn.exe -k c:\test.snk.

After generation of the file you can view the SNK file in a simple notepad.
After the SNK file is generated its time to sign the project with this SNK file.
Click on project -- properties and the browse the SNK file to the respective
folder and compile the project.
(I) Can we force garbage collector to run ?
System.GC.Collect() forces garbage collector to run. This is not recommended
but can be used if situations arises.
(I) What is the difference between System exceptions and Application
exceptions?
All exception derives from Exception Base class. Exceptions can be generated
programmatically or can be generated by system. Application Exception serves
as the base class for all application-specific exception classes. It derives from
Exception but does not provide any extended functionality. You should derive
your custom application exceptions from Application Exception. Application
exception is used when we want to define user defined exception, while system
exception is all which is defined by .NET.
(I) What is CODE Access security?
CAS is part of .NET security model that determines whether or not a piece of
code is allowed to run and what resources it can use while running. Example CAS
will allow an application to read but not to write and delete a file or a resource
from a folder..
(I) What is the difference between Convert.toString and .toString() method ?
Just to give an understanding of what the above question means seethe below
code. int i =0; MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i)); We can convert the integer i using
i.ToString() or Convert.ToString so whats the difference. The basic difference
between them is Convert function handles NULLS while i.ToString() does not
it will throw a NULL reference exception error. So as good coding practice using
convert is always safe.
(I) What is COM ?
Microsofts COM is a technology for component software development. It is a
binary standard which is language independent. DCOM is a distributed extension
of COM.

(A) What are the different types of Assembly?

There are two types of assembly Private and Public assembly. A private assembly
is normally used by a single application, and is stored in the application's
directory, or a sub-directory beneath. A shared assembly is normally stored in
the global assembly cache, which is a repository of assemblies maintained by the
.NET runtime. Shared assemblies are usually libraries of code which many
applications will find useful, e.g. Crystal report classes which will be used by all
application for Reports.
(A) What is Manifest?
Assembly metadata is stored in Manifest. Manifest contains all the metadata
needed to do the following things (See Figure Manifest View for more details):
Version of assembly
Security identity
Scope of the assembly Resolve references to resources and classes.
The assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a stand-alone PE file that
contains only assembly manifest information

ASP.NET
(B) Please briefly explain ASP.NET Page life Cycle?
ASP.NET page passes through a series of steps during its life cycle. Following is the
high-level explanation of life cycle stages/steps.
Initialization: Controls raise their Init event in this stage.Objects and variables are
initializes for complete lifecyle of request.
LoadViewState: is a post back stage and loads the view state for the controls that
enabled its view state property.
LoadPostBackData: is also a post back stage and loads the data posted for the
controls and update them.
Load: In this stage page as well as all the controls raise their Load event. Till this
stage all the controls are initialized and loaded. In most of the cases, we are coding
this event handler.
RaisePostBackEvent: is again a postback stage. For example, it's raise against a
button click event. We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering
HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.

(B) What is the sequence in which ASP.NET events are processed ?

Following is the sequence in which the events occur :

Page_Init.
Page_Load.
Control events
Page_Unload event.

Page_init event only occurs when first time the page is started, but
Page_Load occurs in subsequent request of the page.

(B) What is the difference between custom controls and user controls?
Custom controls are basically compiled code i.e. DLLs. These can be easily added to
toolbox, so it can be easily used across multiple projects using drag and drop
approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to
create but tightly couple with respect to User Interface and code. In order to use
across multiple projects, we need to copy and paste to the other project as well.

(B) In which event are the controls fully loaded ?

Page_load event guarantees that all controls are fully loaded. Controls are
also accessed in Page_Init events but you will see that viewstate is not fully
loaded during this event.
(B) 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 same page. So, the whole page is refreshed.
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.
(B) How can we identify that the Page is PostBack ?

Page object has a IsPostBack property which can be checked to know that
is the page posted back.
(B) How do we assign page specific attributes ?

Page attributes are specified using the @Page directive.


(B) What is the use of @ Register directives ?

@Register directive informs the compiler of any custom server control added
to the page.
(B) Whats the use of SmartNavigation property ?

Its a feature provided by ASP.NET to prevent flickering and redrawing when


the page is posted back. Note:- This is only supported for IE browser. Projects
who have browser compatibility as requirements have to think some other
ways of avoiding flickering.
(B) What is AppSetting Section in Web.Config file ?

Web.config file defines configuration for a webproject. Using AppSetting


section we can define user defined values. Example below defined is
ConnectionString section which will be used through out the project for
database connection. <configuration> <appSettings> <add
key="ConnectionString"
value="server=xyz;pwd=www;database=testing" /> </appSettings>
(B) Where is ViewState information stored ?

In HTML Hidden Fields.


(B) Can you explain what is AutoPostBack feature in ASP.NET ?

If we want the control to automatically postback in case of any event, we will


need to check this attribute as true. Example on a ComboBox change we
need to send the event immediately to the server side then set the
AutoPostBack attribute to true.
(B) How can you enable automatic paging in DataGrid ?

Following are the points to be done in order to enable paging in Datagrid : Set the AllowPaging to true.
In PageIndexChanged event set the current pageindex clicked.
(B) Whats the use of GLOBAL.ASAX file ?
Global.asax is basically ASP.NET Application file. Its a place to write code for
Application-level events such as Application start, Application end, Session start and
end, Application error etc. raised by ASP.NET or by HTTP Modules.
There is a good list of events that are fired but following are few of the important
events in Global.asax:

Application_Init occurs in case of application initialization for the very first

time.

Application_Start fires on application start.


Session_Start fires when a new user session starts
Application_Error occurs in case of an unhandled exception generated from

application.
Session_End fires when user session ends.
Application_End fires when application ends or time out.
(B) What is a SESSION and APPLICATION object ?

Session object store information between HTTP requests for a particular user,
while application object are global across users.

(B) Can you explain in brief how the ASP.NET authentication process works?

ASP.NET does not run by itself, it runs inside the process of IIS. So there are
two authentication layers which exist in ASP.NET system. First authentication
happens at the IIS level and then at the ASP.NET level depending on the
WEB.CONFIG file. Below is how the whole process works:- IIS first checks to
make sure the incoming request comes from an IP address that is allowed
access to the domain. If not it denies the request. Next IIS performs its own
user authentication if it is configured to do so. By default IIS allows
anonymous access, so requests are automatically authenticated, but you can
change this default on a per application basis with in IIS. If the request is
passed to ASP.net with an authenticated user, ASP.net checks to see whether
impersonation is enabled. If impersonation is enabled, ASP.net acts as though
it were the authenticated user. If not ASP.net acts with its own configured
account. Finally the identity from step 3 is used to request resources from
the operating system. If ASP.net authentication can obtain all the necessary
resources it grants the users request otherwise it is denied. Resources can
include much228 more than just the ASP.net page itself you can also use
.Nets code access security features to extend this authorization step to disk
files, Registry keys and other resources.
(B) Whats difference between Datagrid, Datalist and repeater ?

A Datagrid, Datalist and Repeater are all ASP.NET data Web controls. They
have many things in common like DataSource Property, DataBind Method
ItemDataBound and ItemCreated. When you assign the DataSource Property
of a Datagrid to a DataSet then each DataRow present in the DataRow
Collection of DataTable is assigned to a corresponding DataGridItem and this
is same for the rest of the two controls also. But The HTML code generated
for a Datagrid has an HTML TABLE <ROW> element created for the particular
DataRow and its a Table form representation with Columns and Rows. For a
Datalist its an Array of Rows and based on the Template Selected and the
RepeatColumn Property value We can specify how many DataSource records

should appear per HTML <table> row. In short in datagrid we have one record
per row, but in datalist we can have five or six rows per row. For a Repeater
Control, the Datarecords to be displayed depends upon the Templates
specified and the only HTML generated is the due to the Templates. In
addition to these, Datagrid has a in-built support for Sort, Filter and paging
the Data, which is not possible when using a DataList and for a Repeater
Control we would require to write an explicit code to do paging.
(B) How to disable client side script in validators?

Set EnableClientScript to false.


(B) What are the different types of Validation controls in ASP.NET?
In order to validate user input, ASP.NET provides validation server controls. All
validation controls inherits from BaseValidator class which contains the common
validation properties and methods
like ControlToValidate,Enabled, IsValid, EnableClientScript, ValidationGroup,Validat
e() etc.
ASP.NET provides a range of validation controls:

RequiredFieldValidator validates compulsory/required input.


RangeValidator validates the range. Validates that input falls between the
given range values.
CompareValidator validates or compares the input of a control with another
control value or with a fixed value.
RegularExpressionValidator validates input value against a defined regular
expression pattern.
CustomValidator allows to customize the validation logic with respect to our
application logic.
ValidationSummary displays all errors on page collectively.
(B) How can we kill a user session ?

Session.abandon
(B) What is the main difference between Gridlayout and FlowLayout ?

GridLayout provides absolute positioning for controls placed on the page.


Developers that have their roots in rich-client development environments like
Visual Basic will find it easier to develop their pages using absolute
positioning, because they can place items exactly where they want them. On
the other hand, FlowLayout positions items down the page like traditional
HTML. Experienced Web developers favor this approach because it results in
pages that are compatible with a wider range of browsers. If you look in to
the HTML code created by absolute positioning you can notice lot of DIV tags.
While in Flow layout you can see more of using HTML table to position
elements which is compatible with wide range of browsers

(B) What are resource files and how do we generate resource files?

Resource files are files which contain program resources. Many programmers
think resource files for only storing strings. But you can also store bitmaps,
icons, fonts, wav files in to resource files.
(B) Difference between .dll and .exe?
EXE:
1.
2.
3.
4.

It's a executable file


When loading an executable, no export is called, but only the module entry point.
When a system launches new executable, a new process is created
The entry thread is called in context of main thread of that process.

DLL:
1.
2.
3.

It's a Dynamic Link Library


There are multiple exported symbols.
The system loads a DLL into the context of an existing process.

(B) What is strong-typing versus weak-typing?


That'll be the theory answers taken care of, but the practice side seems to have been
neglected...
Strong-typing means that you can't use one type of variable where another is expected (or have
restrictions to doing so). Weak-typing means you can mix different types. In PHP for example,
you can mix numbers and strings and PHP won't complain because it is a weakly-typed
language.
$message = "You are visitor number ".$count;
If it was strongly typed, you'd have to convert $count from an integer to a string, usually with
either with casting:
$message = "you are visitor number ".(string)$count;
...or a function:
$message = "you are visitor number ".strval($count);
As for which is better, that's subjective. Advocates of strong-typing will tell you that it will help you
to avoid some bugs and/or errors and help communicate the purpose of a variable etc. They'll
also tell you that advocates of weak-typing will call strong-typing "unnecessary language fluff that
is rendered pointless by common sense", or something similar. As a card-carrying member of the
weak-typing group, I'd have to say that they've got my number... but I have theirs too, and I can
put it in a string :)

(B) Difference between == and .Equal(x)

n C#, there are two different kinds of equality: reference equality (also known as identity)

and value equality. Value equality is the generally understood meaning of equality: it
means that two objects contain the same values. For example, two integers with the
value of 2 have value equality. Reference equality means that there are not two objects
to compare. Instead, there are two object references and both of them refer to the same
object. This can occur through simple assignment, as shown in the following example:

C#
object a = new object();
object b = a;
bool areEqual = System.Object.ReferenceEquals(a, b); //returns true
System.Console.WriteLine("a and b {0} reference equality", areEqual ?
"have" : "do not have");
object c = b;
areEqual = System.Object.ReferenceEquals(a, c); //if a == b and b == c,
then a == c
System.Console.WriteLine("a and c {0} reference equality", areEqual ?
"have" : "do not have");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

In this code, only one object exists, but there are multiple references to that
object: a and b. Because they both refer to the same object, they have reference
equality. If two objects have reference equality, they also have value equality, but value
equality does not guarantee reference equality.
To check for reference equality, use ReferenceEquals. To check for value equality, you
should generally use Equals. However, Equals as it is implemented byObject just
performs a reference identity check. It is therefore important, when you call Equals, to
verify whether the type overrides it to provide value equality semantics. When you create
your own types, you should override Equals.
Because Equals is a virtual method, any class can override its implementation. Any class
that represents a value, essentially any value type, or a set of values as a group, such as
a complex number class, should override Equals. If the type implements IComparable, it
should override Equals.
The new implementation of Equals should follow all the guarantees of Equals:

x.Equals(x) returns true.

x. Equals (y) returns the same value as y. Equals (x).

if (x. Equals (y) && y. Equals (z)) returns true, then x. Equals (z) returns true.

Successive invocations of x. Equals (y) return the same value as long as the
objects referenced by x and y are not modified.

x. Equals (null) returns false (for non-nullable value types only. For more
information, see Nullable Types (C# Programming Guide).)

The new implementation of Equals should not throw exceptions. It is recommended that
any class that overrides Equals also override Object.GetHashCode. It is also
recommended that in addition to implementing Equals (object), any class also
implement Equals (type) for their own type, to enhance performance. For example:

class TwoDPoint : System.Object


{
public readonly int x, y;
public TwoDPoint(int x, int y)
{
this.x = x;
this.y = y;
}

//constructor

public override bool Equals(System.Object obj)


{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}

public override int GetHashCode()


{
return x ^ y;
}
}

Any derived class that can call Equals on the base class should do so before finishing its
comparison. In the following example, Equals calls the base class Equals, which checks
for a null parameter and compares the type of the parameter with the type of the derived
class. That leaves the implementation of Equals on the derived class the task of
checking the new data field declared on the derived class:
class ThreeDPoint : TwoDPoint
{
public readonly int z;
public ThreeDPoint(int x, int y, int z)
: base(x, y)
{
this.z = z;
}
public override bool Equals(System.Object obj)
{
// If parameter cannot be cast to ThreeDPoint return false:
ThreeDPoint p = obj as ThreeDPoint;
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return base.Equals(obj) && z == p.z;
}
public bool Equals(ThreeDPoint p)
{
// Return true if the fields match:
return base.Equals((TwoDPoint)p) && z == p.z;
}
public override int GetHashCode()
{
return base.GetHashCode() ^ z;
}
}
By default, the operator == tests for reference equality by determining whether two
references indicate the same object. Therefore, reference types do not have to
implement operator == in order to gain this functionality. When a type is immutable, that

is, the data that is contained in the instance cannot be changed, overloading
operator == to compare value equality instead of reference equality can be useful
because, as immutable objects, they can be considered the same as long as they have
the same value. It is not a good idea to override operator == in non-immutable types.
Overloaded operator == implementations should not throw exceptions. Any type that
overloads operator == should also overload operator !=. For example:
//add this code to class ThreeDPoint as defined previously
//
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
return !(a == b);
}
A common error in overloads of operator == is to use (a == b), (a == null), or (b ==
null) to check for reference equality. This instead creates a call to the overloaded
operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to
avoid the loop.

(B) What is an HttpHandler in ASP.NET


In the simplest terms, an ASP.NET HttpHandler is a class that implements
the System.Web.IHttpHandler interface.
ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web
application server. They run as processes in response to a request made to the ASP.NET Site.
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.
ASP.NET offers a few default HTTP handlers:

Page Handler (.aspx): handles Web pages

User Control Handler (.ascx): handles Web user control pages

Web Service Handler (.asmx): handles Web service pages

Trace Handler (trace.axd): handles trace functionality

You can create your own custom HTTP handlers that render custom output to the browser.
Typical scenarios for HTTP Handlers in ASP.NET are for example

delivery of dynamically created images (charts for example) or resized pictures.

RSS feeds which emit RSS-formated XML


You implement the IHttpHandler interface to create a synchronous handler and
the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you
to implement the ProcessRequest method and the IsReusable property.
The ProcessRequest method handles the actual processing for requests made, while the
Boolean IsReusable property specifies whether your handler can be pooled for reuse (to
increase performance) or whether a new handler is required for each request.

(B) What is an HttpModule in .NET?


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.
Typical uses for custom HTTP handlers include the following:

RSS feeds To create an RSS feed for a Web site, you can create a handler that
emits RSS-formatted XML. You can then bind a file name extension such as .rss to
the custom handler. When users send a request to your site that ends in .rss,
ASP.NET calls your handler to process the request.

Image server If you want a Web application to serve images in a variety of sizes,
you can write a custom handler to resize images and then send them to the user as
the handler's response.
Typical uses for HTTP modules include the following:

Security Because you can examine incoming requests, an HTTP module can
perform custom authentication or other security checks before the requested page,
XML Web service, or handler is called. In Internet Information Services (IIS) 7.0
running in Integrated mode, you can extend forms authentication to all content
types in an application.
Statistics and logging Because HTTP modules are called on every request, you
can gather request statistics and log information in a centralized module, instead of
in individual pages.
Custom headers or footers Because you can modify the outgoing response, you
can insert content such as custom header information into every page or XML Web
service response.

(B) What are tuples?


Tuple is a fixed-size collection that can have elements of either same or different data types.
Similar to arrays, a user must have to specify the size of a tuple at the time of declaration. Tuples
are allowed to hold up from 1 to 8 elements and if there are more than 8 elements, then the 8th
element can be defined as another tuple. Tuples can be specified as parameter or return type of a
method.
The following are two ways to instantiate a tuple:

Using the new operator. For example,

Tuple<String,int>t=newTuple<String,int>("Hellow",2);

Using the Create factory method available in the Tuple class. For example,

Tuple<int,int,int>t=Tuple.Create<int,int,int>(2,4,5);

(B) What is the difference between UserControl, Control and Component?


The main difference between User Control, Custom Control and Component is that they inherit
from different levels in the inheritance tree:
MyComponent
|-> Component
MyCustomControl
|-> Control
|-> Component
MyUserControl
|-> ContainerControl
|-> ScrollableControl
|-> Control
|-> Component
So, in short you get a different amount of pre-wired functionality with the different options.
When would you use the different options? (these are thoughts and opinions, not truths)

Create a component if you want to provide functionality without UI (such as Timer


components, data sources, ...)

Create a custom control if you want to make a component where you have full control
over its visual appearance, and you don't want any baggage of unnecessary functionality.
Typical cases would be simple controls with limited functionality (such as a button)

Create a user control if you are going to combine existing controls into reusable
building blocks (such as two lists with buttons where you can move items between the lists).
(B) Which is the root namespace for fundamental types in .NET Framework?
System.Object is the root namespace for fundamental types in .NET Framework.

(I) What is the difference between myCustomer.GetType() and typeof(Customer)


in C#?
The result of both are exactly the same in your case. It will be your custom type that derives
from System.Type. The only real difference here is that when you want to obtain the type from
an instance of your class, you use GetType. If you don't have an instance, but you know the type
name (and just need the actual System.Type to inspect or compare to), you would use typeof.

Important difference
Let me add that the call to GetType gets resolved at runtime, while typeof is resolved at
compile time.

(B) What is the difference between struct and class?


In .NET, there are two categories of types, reference types and value types.
Structs are value types and classes are reference types.
The general difference is that a reference type lives on the heap, and a value type lives inline,
that is, wherever it is your variable or field is defined.
A variable containing a value type contains the entire value type value. For a struct, that means
that the variable contains the entire struct, with all its fields.
A variable containing a reference type contains a pointer, or a reference to somewhere else in
memory where the actual value resides.
This has one benefit, to begin with:

value types always contains a value


reference types can contain a null-reference, meaning that they don't refer to anything at
all at the moment
Internally, reference types are implemented as pointers, and knowing that, and knowing how
variable assignment works, there are other behavioral patterns:

copying the contents of a value type variable into another variable, copies the entire
contents into the new variable, making the two distinct. In other words, after the copy,
changes to one won't affect the other

copying the contents of a reference type variable into another variable, copies the
reference, which means you now have two references to the same somewhere else storage
of the actual data. In other words, after the copy, changing the data in one reference will
appear to affect the other as well, but only because you're really just looking at the same
data both places
When you declare variables or fields, here's how the two types differ:

variable: value type lives on the stack, reference type lives on the stack as a pointer to
somewhere in heap memory where the actual memory lives
class/struct-field: value type lives inside the class, reference type lives inside the class as
a pointer to somewhere in heap memory where the actual memory lives.

(B) What do you mean by data encapsulation?


Data encapsulation is a concept of binding data and code in single unit called object and hiding all
the implementation details of a class from the user. It prevents unauthorized access of data and
restricts the user to use the necessary data only.

(I) Explain the concept of destructor?


A destructor is a special method for a class and is invoked automatically when an object is finally
destroyed. The name of the destructor is also same as that of the class but is followed by a prefix
tilde (~).

A destructor is used to free the dynamic allocated memory and release the resources. You can,
however, implement a custom method that allows you to control object destruction by calling the
destructor.
The main features of a destructor are as follows:

Destructors do not have any return type

Similar to constructors, destructors are also always public

Destructors cannot be overloaded.

(I) Is there a difference between just saying throw; and throw ex; assuming ex is
the exception you're catching?
throw ex; will erase your stacktrace. Don't do this unless you mean to clear the
stacktrace. Just use throw;

(I) What is impersonation in ASP.NET ?

By default, ASP.NET executes in the security context of a restricted user


account on the local machine. Sometimes you need to access network
resources such as a file on a shared drive, which requires additional
permissions. One way to overcome this restriction is to use impersonation.
With impersonation, ASP.NET can execute the request using the identity of
the client who is making the request, or ASP.NET can impersonate a specific
account you specify in web.config.
(I) How do I send email message from ASP.NET ?

ASP.NET provides two namespaces System.WEB.mailmessage classand


System.Web.Mail.Smtpmail class. Just a small homework create a Asp.NET
project and send a email at shiv_koirala@yahoo.com. Do not Spam.
(I) Can you explain Forms authentication in detail ?

In old ASP if you where said to create a login page and do authentication you
have to do hell lot of custom coding. But now in ASP.NET thats made easy by
introducing Forms authentication. So lets see in detail what form
authentication is. Forms authentication uses a ticket cookie to see that user is
authenticated or not. That means when user is authenticated first time a
cookie is set to tell that this user is authenticated. If the cookies expire then
Forms authentication mechanism sends the user to the login page.
(I) How do we get the current culture of the environment in windows and
ASP.NET?

CultureInfo.CurrentCulture displays the current culture of the environment.


For instance if you are running Hindi it will display hi-IN. Please note one

thing in mind CurrentCulture will only give you the culture on which your
application is running. So if its a windows application this will work fine. But
in ASP.NET 2.0 we need to know what culture the end user has.
(A) How can you turn-on and turn-off CAS?
YOU can use the Code Access Security Tool (Caspol.exe) to turn security on and off.
To turn off security, type the following command at the command prompt:

caspol -security off


To turn on security, type the following command at the command prompt:

caspol -security on
In the .NET Framework 4.0, for using Caspol.exe, you first need to set
the <LegacyCasPolicy> element to true.

(A) What is the difference between Server.Transfer and response.Redirect ?


Following are the major differences between them:-

Response.Redirect sends message to the browser saying it to move to some


different page, while server.transfer does not send any message to the
browser but rather redirects the user directly from the server itself. So in
server.transfer there is no round trip while response.redirect has a round trip
and hence puts a load on server.
Using Server.Transfer you can not redirect to a different from the server
itself. Example if your server is www.yahoo.com you can use server.transfer
to move to www.microsoft.com but yes you can move to
www.yahoo.com/travels, i.e. within websites. This cross server redirect is
possible only using Response.redirect.
With server.transfer you can preserve your information. It has a parameter
called as preserveForm. So the existing query string etc. will be able in the
calling page. In response.redirect you can maintain the state, but has lot of
drawbacks.

(A) What is the difference between Authentication and authorization?

This can be a tricky question. These two concepts seem altogether similar but
there is wide range of difference. Authentication is verifying the identity of a
user and authorization is process where we check does this identity have
access rights to the system. In short we227 can say the following
authentication is the process of obtaining some sort of credentials from the
users and using those credentials to verify the users identity. Authorization is
the process of allowing an authenticated user access to resources.
Authentication always proceed to Authorization; even if your application lets

anonymous users connect and use the application, it still authenticates them
as being anonymous.
(A) What are the various ways of authentication techniques in ASP.NET?

Selecting an authentication provider is as simple as making an entry in the


web.config file for the application. You can use one of these entries to select
the corresponding built in authentication provider:
<authentication mode=windows>
<authentication mode=passport>
<authentication mode=forms>
Custom authentication where you might install an ISAPI filter in IIS that
compares incoming requests to list of source IP addresses, and considers
requests to be authenticated if they come from an acceptable address. In
that case, you would set the authentication mode to none to prevent any of
the .net authentication providers from being triggered.

Windows authentication and IIS If you select windows


authentication for your ASP.NET application, you also have to configure
authentication within IIS. This is because IIS provides Windows
authentication. IIS gives you a choice for four different authentication
methods: Anonymous, basic digest and windows integrated If you select
anonymous authentication, IIS doesnt perform any authentication, Any one is
allowed to access the ASP.NET application. If you select basic authentication,
users must provide a windows username and password to connect. How ever
this information is sent over the network in clear text, which makes basic
authentication very much insecure over the internet. If you select digest
authentication, users must still provide a windows user name and password
to connect. However the password is hashed before it is sent across the
network.229 Digest authentication requires that all users be running Internet
Explorer 5 or later and that windows accounts to stored in active directory. If
you select windows integrated authentication, passwords never cross the
network. Users must still have a username and password, but the application
uses either the Kerberos or challenge/response protocols authenticate the
user. Windows-integrated authentication requires that all users be running
internet explorer 3.01 or later Kerberos is a network authentication protocol.
It is designed to provide strong authentication for client/server applications
by using secret-key cryptography. Kerberos is a solution to network security
problems. It provides the tools of authentication and strong cryptography
over the network to help to secure information in systems across entire
enterprise

Passport authentication Passport authentication lets you to use


Microsofts passport service to authenticate users of your application. If your
users have signed up with passport, and you configure the authentication
mode of the application to the passport authentication, all authentication
duties are off-loaded to the passport servers. Passport uses an encrypted
cookie mechanism to indicate authenticated users. If users have already
signed into passport when they visit your site, theyll be considered
authenticated by ASP.NET. Otherwise theyll be redirected to the passport
servers to log in. When they are successfully log in, theyll be redirected back
to your site To use passport authentication you have to download the
Passport Software Development Kit (SDK) and install it on your server. The
SDK can be found at http:// msdn.microsoft.com/library/default.asp?
url=/downloads/list/websrvpass.aps. It includes full details of implementing
passport authentication in your own applications.

Forms authentication Forms authentication provides you with a way


to handle authentication using your own custom logic with in an ASP.NET
application. The following applies if you choose forms authentication. When
a user requests a page for the application, ASP.NET checks for the presence
of a special session cookie. If the cookie is present, ASP.NET assumes the user
is authenticated and processes the request. 230 If the cookie isnt present,
ASP.NET redirects the user to a web form you provide You can carry out
whatever authentication, it checks you like it checks your form. When the
user is authenticated, you indicate this to ASP.NET by setting a property,
which creates the special cookie to handle subsequent requests.
(A) How does authorization work in ASP.NET?

ASP.NET impersonation is controlled by entries in the applications web.config


file. The default setting is no impersonation. You can explicitly specify that
ASP.NET shouldnt use impersonation by including the following code in the
file <identity impersonate=false/> It means that ASP.NET will not perform
any authentication and runs with its own privileges. By default ASP.NET runs
as an unprivileged account named ASPNET. You can change this by making a
setting in the processModel section of the machine.config file. When you
make this setting, it automatically applies to every site on the server. To user
a high-privileged system account instead of a low-privileged set the
userName attribute of the processModel element to SYSTEM. Using this
setting is a definite security risk, as it elevates the privileges of the ASP.NET
process to a point where it can do bad things to the operating system. When
you disable impersonation, all the request will run in the context of the
account running ASP.NET: either the ASPNET account or the system account.
This is true when you are using anonymous access or authenticating users in
some fashion. After the user has been authenticated, ASP.NET uses its own
identity to request access to resources. The second possible setting is to turn
on impersonation. <identity impersonate =true/> In this case, ASP.NET

takes on the identity IIS passes to it. If you are allowing anonymous access in
IIS, this means ASP.NET will impersonate the IUSR_ComputerName account
that IIS itself uses. If you arent allowing anonymous access,ASP.NET will take
on the credentials of the authenticated user and make requests for resources
as if it were that user. Thus by turning impersonation on and using a nonanonymous method of authentication in IIS, you can let users log on and use
their identities within your ASP.NET application. Finally, you can specify a
particular identity to use for all authenticated requests 231 <identity
impersonate=true username=DOMAIN\username password=password/
>With this setting, all the requests are made as the specified user (Assuming
the password it correct in the configuration file). So, for example you could
designate a user for a single application, and use that users identity every
time someone authenticates to the application. The drawback to this
technique is that you must embed the users password in the web.config file
in plain text. Although ASP.NET wont allow anyone to download this file, this
is still a security risk if anyone can get the file by other means.
(A) What is event bubbling ?

Server controls like Datagrid, DataList, Repeater can have other child controls
inside them. Example DataGrid can have combo box inside datagrid. These
child control do not raise there events by themselves, rather they pass the
event to the container parent (which can be a datagrid, datalist, repeater),
which passed to the page as ItemCommand event. As the child control
send there events to parent this is termed as event bubbling.
(A) Administrator wants to make a security check that no one has tampered with
ViewState, how can he ensure this ?

Using the @Page directive EnableViewStateMac to True.

(A) How do I sign out in forms authentication ?

FormsAuthentication.Signout()
(A) If cookies are not enabled at browser end does form Authentication work?

No, it does not work.

ADO.NET
*(B) What is the difference between DataSet and DataReader ?

Twist :- Why is DataSet slower than DataReader ? Fourth point is the answer
to the twist. Note:- This is my best question and I expect everyone to answer
it. It is asked almost 99% in all companies....Basic very Basic cram it.
Following are the major differences between DataSet and DataReader :-
DataSet is a disconnected architecture, while DataReader has live
connection while reading data. If we want to cache data and pass to a
different tier DataSet forms the best choice and it has decent XML support.
When application needs to access data from more than one table DataSet
forms the best choice. If we need to move back while reading records,
datareader does not support this functionality. But one of the biggest
drawbacks of DataSet is speed. As DataSet carry considerable overhead
because of relations, multiple tables etc speed is slower than DataReader.
Always try to use DataReader wherever possible, as its meant specially for
speed performance.
*(B) Whats difference between Optimistic and Pessimistic locking ?

In pessimistic locking when user wants to update data it locks the record and
till then no one can update data. Other users can only view the data when
there is pessimistic locking. In optimistic locking multiple users can open the
same record for updating, thus increase maximum concurrency. Record is
only locked when updating the record. This is the most 299 preferred way of
locking practically. Now a days browser based application is very common
and having pessimistic locking is not a practical solution.
*(I) What are major difference between classic ADO and ADO.NET ?

In ADO, we have a Recordset and in ADO.NET we have a DataSet.


In Recordset, we can only have one table. If we want to accommodate more
than one table, we need to do inner join and fill the Recordset. A DataSet can have
multiple tables.
All data is persisted in XML as compared to classic ADO where data is
persisted in binary format.
*(I)What is difference between Dataset. clone and Dataset. copy ?

Clone: - It only copies structure, does not copy data. Copy: - Copies both
structure and data.
*(A) How can we perform transactions in .NET?

The most common sequence of steps that would be performed while


developing a transactional application is as follows:
Open a database connection using the Open method of the connection
object.
Begin a transaction using the Begin Transaction method of the connection
object. This method provides us with a transaction object that we will use
later to commit or rollback the transaction. Note that changes caused by any

queries executed before calling the Begin Transaction method will be


committed to the database immediately after they execute. Set the
Transaction property of the command object to the above mentioned
transaction object.
Execute the SQL commands using the command object. We may use one or
more command objects for this purpose, as long as the Transaction property
of all the objects is set to a valid transaction object.
Commit or roll back the transaction using the Commit or Rollback method
of the transaction object.
Close the database connection.
(B) What is the namespace in which .NET has the data functionality classes ?

Following are the namespaces provided by .NET for data management :System.data This contains the basic objects used for accessing and storing
relational data, such as DataSet,DataTable, and DataRelation. Each of these is
independent of the type of data source and the way we connect to it.
System.Data.OleDB It contains the objects that we use to connect to a data
source via an OLE-DB provider, such as OleDbConnection, OleDbCommand,
etc. These objects inherit from the common base classes, and so have the
same properties, methods, and events as the SqlClient equivalents.
System.Data.SqlClient: This contains the objects that we use to connect to
a data source via the Tabular Data Stream (TDS) interface of Microsoft SQL
Server (only). This can generally provide better performance as it removes
some of the intermediate layers required by an OLE-DB connection.
System.XML This Contains the basic objects required to create, read, store,
write, and manipulate XML documents according to W3C recommendations.
(B) Can you give a overview of ADO.NET architecture ?

The most important section in ADO.NET architecture is Data Provider. Data


Provider provides access to datasource (SQL SERVER, ACCESS, ORACLE).In
short it provides object to achieve functionalities like opening and closing
connection, retrieve data and update data. In the below figure you can see
the four main sections of a data provider : Connection.
Command object (This is the responsible object to use stored
procedures)
Data Adapter (This object acts as a bridge between datastore and
dataset).
Datareader (This object reads data from data store in forward only
mode).

Dataset object represents disconnected and cached data. If you see the
diagram it is not in direct connection with the data store (SQL SERVER,
ORACLE etc) rather it talks with Data adapter, who is responsible for filling
the dataset. Dataset can have one or more Datatable and relations.

(B) What are the two fundamental objects in ADO.NET ?

Datareader and Dataset are the two fundamental objects in ADO.NET.


(B) 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
rowset) from the same data source as well as the relationships between
them.
Dataset is a disconnected architecture while datareader is connected
architecture. Dataset can persist contents while datareader can not persist
contents, they are forward only.
(B) What is the use of connection object ?

They are used to connect a data to a Command object.


An OleDbConnection object is used with an OLE-DB provider 284
A SqlConnection object uses Tabular Data Services (TDS) with MS SQL
Server
(B) What is the use of command objects and what are the methods provided by
the command object ?

They are used to connect connection object to Datareader or dataset.


Following are the methods provided by 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 rowset 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 single value (effectively the first column of the first row of the resulting
rowset) any other returned columns and rows are discarded. It is fast and
efficient when only a "singleton" value is required
(B) What is the use of dataadapter ?

These are objects that connect one or more Command objects to a Dataset
object. They provide logic that would get data from the data store and
populates the tables in the DataSet, or pushes the changes in the DataSet
back into the data store.
An OleDbDataAdapter object is used with an OLE-DB provider
A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.
(B) What are basic methods of Dataadapter ?

There are three most commonly used methods of Dataadapter :- Fill :Executes the SelectCommand to fill the DataSet object with data from the
data source. It an also be used to update (refresh) an existing table in a
DataSet with changes285 made to the data in the original datasource if there
is a primary key in the table in the DataSet. FillSchema :- Uses the
SelectCommand to extract just the schema for a table from the data source,
and creates an empty table in the DataSet object with all the corresponding
constraints. Update:- Calls the respective InsertCommand, UpdateCommand,
or DeleteCommand for each inserted, updated,or deleted row in the DataSet
so as to update the original data source with the changes made to the
content of the DataSet. This is a little like the UpdateBatch method provided
by the ADO Recordset object, but in the DataSet it can be used to update
more than one table.
(B) What is Dataset object?

The DataSet provides the basis for disconnected storage and manipulation of
relational data. We fill it from a data store,work with it while disconnected
from that data store, then reconnect and flush changes back to the data store
if required.
(B) What are the various objects in Dataset ?

Dataset has a collection of DataTable object within the Tables collection. Each
DataTable object contains a collection of DataRow objects and a collection of
DataColumn objects. There are also collections for the primary keys,
constraints, and default values used in this table which is called as constraint
collection, and the parent and child relationships between the tables. Finally,
there is a DefaultView object for each table. This is used to create a DataView
object based on the table, so that the data can be searched, filtered or
otherwise manipulated while displaying the data. Note :- Look back again to

the main diagram for ADO.NET architecture for visualizing this answer in
pictorial form.

(B) How can we connect to Microsoft Access , Foxpro , Oracle etc ?

Microsoft provides System.Data.OleDb namespace to communicate with


databases like scess , Oracle etc. In short any OLE DB-Compliant database
can be connected using System.Data.OldDb namespace.
(B) How can we force the connection object to close after my datareader is
closed ?

Command method Executereader takes a parameter called as


CommandBehavior where in we can specify saying close connection
automatically after the Datareader is close. pobjDataReader =
pobjCommand.ExecuteReader(CommandBehavior.CloseConnection)
(B) I want to force the datareader to return only schema of the datastore rather
than data ?

pobjDataReader =
pobjCommand.ExecuteReader(CommandBehavior.SchemaOnly)
(B) How can we fine tune the command object when we are expecting a single
row or a single value ?

Again CommandBehaviour enumeration provides two values SingleResult and


SingleRow. If you are expecting a single value then pass
CommandBehaviour.SingleResult and the query is optimized accordingly, if
you are expecting single row then pass CommandBehaviour.SingleRow and
query is optimized according to single row.
(B) Which is the best place to store connectionstring in .NET projects ?

Config files are the best places to store connectionstrings. If it is a web-based


application Web.config file will be used and if it is a windows application
App.config files will be used.
(B) How can we check that some changes have been made to dataset since it
was loaded ?

Twist :- How can we cancel all changes done in dataset ? How do we get
values which are changed in a dataset ? For tracking down changes Dataset
has two methods which comes as rescue GetChanges and HasChanges.
GetChanges Returns dataset which are changed since it was loaded or since
Acceptchanges was executed.

HasChanges This property indicates that has any changes been made since
the dataset was loaded or acceptchanges method was executed.

(B) What is basic use of DataView ?

DataView represents a complete table or can be small section of rows


depending on some criteria. It is best used for sorting and finding data with in
datatable. Dataview has the following methods :Find It takes a array of values and returns the index of the row.
FindRow This also takes array of values but returns a collection of
DataRow. If we want to manipulate data of DataTable object create
DataView (Using the DefaultView we can create DataView object)
of the DataTable object and use the following functionalities :AddNew Adds a new row to the DataView object.
Delete Deletes the specified row from DataView object.
(B) How can we load multiple tables in a DataSet ?

objCommand.CommandText = "Table1" objDataAdapter.Fill(objDataSet,


"Table1") objCommand.CommandText = "Table2"
objDataAdapter.Fill(objDataSet, "Table2") Above is a sample code which
shows how to load multiple DataTable objects in one DataSet object.
Sample code shows two tables Table1 and Table2 in object
ObjDataSet.298 lstdata.DataSource =
objDataSet.Tables("Table1").DefaultView In order to refer Table1 DataTable,
use Tables collection of DataSet and the Defaultview object will give you the
necessary output.
(B) Explain in detail the fundamental of connection pooling?

When a connection is opened first time a connection pool is created and is


based on the exact match of the connection string given to create the
connection object. Connection pooling only works if the connection string is
the same. If the connection string is different, then a new connection will be
opened, and connection pooling won't be used.

(A) Can you explain the difference between an ADO.NET Dataset and an ADO
Recordset?

There two main basic differences between recordset and dataset : With dataset you can retrieve data from two databases like oracle and sql
server and merge them in one dataset , with recordset this is not possible
All representation of Dataset is using XML while recordset uses COM.
Recordset can not be transmitted on HTTP while Dataset can be.

ENTITY FRAMEWORK

What is Entity Framework?


ADO.NET entity is an ORM (object relational mapping) which creates a higher
abstract object model over ADO.NET components. So rather than getting into
dataset, datatables, command, and connection objects as shown in the below code,
you work on higher level domain objects like customers, suppliers, etc.
Collapse | Copy Code

DataTable table = adoDs.Tables[0];


for (int j = 0; j < table.Rows.Count; j++)
{
DataRow row = table.Rows[j];
// Get the values of the fields
string CustomerName =
(string)row["Customername"];
string CustomerCode =
(string)row["CustomerCode"];
}

Below is the code for Entity Framework in which we are working on higher level
domain objects like customer rather than with base level ADO.NET components (like
dataset, datareader, command, connection objects, etc.).
Collapse | Copy Code

foreach (Customer objCust in obj.Customers)


{}

What are the benefits of using EF?


The main and the only benefit of EF is it auto-generates code for the Model (middle
layer), Data Access Layer, and mapping code, thus reducing a lot of development
time.

What are the different ways of creating


these domain / entity objects?
Entity objects can be created in two ways: from a database structure, or by starting
from scratch by creating a model.

What is pluralize and singularize in the


Entity Framework dialog box?
Pluralize and Singularize give meaningful naming conventions to objects. In
simple words it says do you want to represent your objects with the below naming
convention:

One Customer record means Customer (singular).


Lot of customer records means Customers (plural, watch the s)
If you select the below checkbox, Entity Framework generates a naming convention
which adheres to plural and singular coding conventions.

What is the importance of EDMX file in


Entity Framework?

EDMX (Entity Data Model XML) is an XML file which contains all the mapping details
of how your objects map with SQL tables. The EDMX file is further divided into three
sections: CSDL, SSDL, and MSL.

Can you explain CSDL, SSDL and MSL


sections in an EDMX file?

CSDL (Conceptual Schema definition language) is the conceptual abstraction


which is exposed to the application.
SSDL (Storage Schema Definition Language) defines the mapping with your
RDBMS data structure.
MSL (Mapping Schema Language) connects the CSDL and SSDL.
CSDL, SSDL and MSL are actually XML files.

Figure: CSDL, MSL, and SSDL

What are T4 templates?


T4 (Text Template Transformation Toolkit) is a template based code generation
engine. You can go and write C# code in T4 templates (.tt is the extension) files and
those C# codes execute to generate the file as per the written C# logic.
For instance, the below T4 C# code:
Collapse | Copy Code

<#@ template language="C#" #>


Hello <# Write(World!) #>

Will generate the following C# output:


Collapse | Copy Code

Hello
World !

What is the importance of T4 in Entity


Framework?
T4 files are the heart of EF code generation. The T4 code templates read the EDMX
XML file and generate C# behind code. This C# behind code is nothing but your
entity and context classes.

If you create a project using VS 2012, you will see the following hierarchy. At the top
we have the EDMX file, followed by the TT or T4 file, and then the .CS code file.

How can we read records using Entity


Framework classes?
In order to browse through records you can create the object of the context class and
inside the context class you will get the records.
For instance, in the below code snippet we are looping through a customer object
collection. This customer collection is the output given by the context
class CustomermytextEntities.
Collapse | Copy Code

CustomermytestEntities obj = new CustomermytestEntities();


foreach (Customer objCust in obj.Customers)
{}

How can we add, update, and delete


using EF?

Create the object of your entity class, add it to the data context
using AddObject method, and then call theSaveChanges method.
Collapse | Copy Code

CustomermytestEntities obj = new CustomermytestEntities();


Customer objCust = new Customer();
objCust.CustomerCode = "1001";
obj.Customers.AddObject(objCust);
obj.SaveChanges();

If you want to update, select the object, make changes to the object, and
call AcceptAllChanges.
Collapse | Copy Code

CustomermytestEntities objContext = new CustomermytestEntities();


Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objCustomer.CountryCode = "NEP";
objContext.AcceptAllChanges();

If you want to delete, call the DeleteObject method as shown in the below code
snippet:
Collapse | Copy Code

CustomermytestEntities objContext = new CustomermytestEntities();


Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objContext.DeleteObject(objCustomer);

You can see the following YouTube video which shows a simple insert, update, and
delete example using Entity Framework:

People say Entity Framework runs slow


By default EF has lazy loading behavior. Due to this default behavior if you are
loading a large number of records and especially if they have foreign key

relationships, you can have performance issues. So you need to be cautious if you
really need lazy loading behavior for all scenarios. For better performance, disable
lazy loading when you are loading a large number of records or use stored
procedures.

Can you explain lazy loading in a


detailed manner?
Lazy loading is a concept where we load objects on demand rather than loading
everything in one go. Consider a situation where you have 1 to many relationships
between the Customer and Address objects. Now lets say you are browsing the
customer data but you do not want address data to be loaded at that moment. But
the time you start accessing the address object you would like to load address data
from the database.
Entity Framework has lazy loading behavior by default enabled. For instance,
consider the below code. When we are doing a foreach on the Customer object, the
Address object is not loaded. But the time you start doing foreach on the address
collection, the Address object is loaded from SQL Server by firing SQL queries.
So in simple words, it will fire a separate query for each address record of the
customer, which is definitely not good for a large number of records.
Collapse | Copy Code

MyEntities context = new MyEntities();


var Customers = context.Customers.ToList();
foreach (Customercust in Customers) // In this line no address object loaded
{
foreach(Address add in cust.Addresses){}// Address object is loaded here
}

How can we turn off lazy loading?


The opposite of lazy loading is eager loading. In eager loading we load the objects
beforehand. So the first thing is we need to disable lazy loading by
setting LazyLoadingEnabled to false.
Collapse | Copy Code

context.ContextOptions.LazyLoadingEnabled = false;

Now we have to explicitly tell EF what objects we want to load by using


the include function. Below is a simple sample code where we tell EF to load
customer as well as address objects by using the include function.
Now the customer object and the related address objects will be loaded in one query
rather than multiple queries.

Collapse | Copy Code

var employees = context.Customers.Include("Addresses").Take(5);

How can we use stored procedures in


Entity Framework?
You can use stored procedure mapping details in EDMX as shown in the below figure.

Figure: Specify stored procedures

What are POCO classes in Entity


Framework?
POCO means Plain Old C# Object. When EDMX creates classes, they are cluttered
with a lot of entity tags. For instance, below is a simple customer class generated
using Entity Framework. Many times we would like to use simple .NET classes and
integrate them with Entity Framework.
Entity Framework allows this. In other words you can create a simple .NET class and
use the entity context object to load your simple .NET classes.
Below is a simple class generated by EF which is cluttered with a lot of EF attributes.
Collapse | Copy Code

[EdmEntityTypeAttribute(NamespaceName="CustomermytestModel", Name="Customer")]

[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Customer : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Customer object.
/// </summary>
/// <param name="id" />Initial value of the Id property.
/// <param name="customerCode" />Initial value of the CustomerCode property.
/// <param name="customername" />Initial value of the Customername property.
public static Customer CreateCustomer(global::System.Int32 id,
global::System.String customerCode, global::System.String customername)
{
Customer customer = new Customer();
customer.Id = id;
customer.CustomerCode = customerCode;
customer.Customername = customername;
return customer;
}
#endregion
#region Primitive Properties

How do we implement POCO in Entity


Framework?
To implement POCO is a three step process:

Go to the designer and set the code generation strategy to NONE. This step
means that you would be generating the classes on your own rather than relying on
EF auto code generation.
Now that we have stopped the auto generation of code, we need to create the
domain classes manually. Add a class file and create the domain classes like
the Customer class we created.
Collapse | Copy Code

public class Customer


{
private string _customerName;
public string CustomerName
{
get { return _customerName; }
set { _customerName = value; }
}
private int _Customerid;
public int Customerid
{
get { return _Customerid; }
set { _Customerid = value; }
}
}

Write your Context layer code inheriting from ObjectContext. This code you
can copy paste from the behind code of EF, also before disabling auto-generation.
Collapse | Copy Code

public partial class Test123Entities : ObjectContext


{
public Test123Entities()
: base("name=Test123Entities", "Test123Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
partial void OnContextCreated();
public ObjectSet<Customer> Customers
{
get
{
if ((_Customers == null))
{
_Customers = base.CreateObjectSet<Customer>("Customers");
}
return _Customers;
}
}
private ObjectSet<Customer> _Customers;
public void AddToCustomers(Customer customer)
{
base.AddObject("Customers", customer);
}
}

And finally you can use the above code in your client as if you where using EF
normally.
Collapse | Copy Code

Test123Entities oContext = new Test123Entities();


List<Customer> oCustomers = oContext.Customers.ToList<Customer>();

In POCO classes do we need EDMX


files?
Yes, you will still need EDMX files because the context object reads the EDMX files to
do the mapping.

What is Code First approach in Entity


Framework?
In Code First approach we avoid working with the Visual Designer of Entity
Framework. In other words the EDMX file is excluded from the solution. So you now
have complete control over the context class as well as the entity classes.

What is the difference between POCO,


Code First, and simple EF approach?
All these three approaches define how much control you want on your Entity
Framework code. Entity Framework is an OR mapper, it generates a lot of code, it
creates your middle tier (Entity), and Data Access layer (Context).
But a lot of times you want to enjoy the benefits of both worlds, you want the autogeneration part to minimize your development time and you want control on the
code so that you can maintain code quality.
Below is the difference table which defines each of the approaches. In simple Entity
Framework, everything is auto generated and so you need the EDMX XML file as well.
POCO is semi-automatic so you have full control on the entity classes but then the
context classes are still generated by the EDMX file.
In Code First, you have complete control on how you can create the entity and
context classes. Because you are going to manually create these classes, you do not
have dependency on the EDMX XML file. Below is a simple table which shows the
cross comparison.
EDMX

Entity

Context

Simple entity
framework

Needed

Auto

Auto

POCO approach

Needed

Manual

Auto

Code First

Not
Needed

Manual

Manual

How can we handle concurrency in


Entity Framework?
Note: Before this question, the interviewer can ask you about concurrency and what
is pessimistic and optimistic locking. Please do refer to the ADO.NET chapter for
those.
In EF, concurrency issue is resolved by using optimistic locking. Please refer to the
ADO.NET chapter for what is optimistic locking and pessimistic locking? To implement
optimistic locking, right click on the EDMX designer and set the concurrency mode
to Fixed, as shown in the below figure.

Now whenever we have concurrency issues you should get


an OptimisticConcurrencyException error as shown in the below figure. You can
then put a try / catch to handle this situation.

How can we do pessimistic locking in


Entity Framework?
We cannot do pessimistic locking using Entity Framework. You can invoke a stored
procedure from Entity Framework and do pessimistic locking by setting the isolation
level in the stored procedure. But directly, Entity Framework does not support
pessimistic locking.

What is client wins and store wins


mode in Entity Framework
concurrency?
Client wins and store wins are actions which you would like to take when concurrency
happens. In store wins / database wins, the data from the server is loaded into your
entity objects. Client wins is opposite to stored wins, data from the entity object is
saved to the database.

We need to use the Refresh method of the Entity Framework context and provide
the RefreshMode enum values. Below is a simple code snippet which
executes ClientWins.
Collapse | Copy Code

Context.Refresh(System.Data.Objects.RefreshMode.ClientWins,Obj);

What are scalar and navigation


properties in Entity Framework?

Scalar properties are those where actual values are contained in the entities. For
example, in the above customer entity, customername and customerid are scalar
properties. Normally a scalar property will map to a database field.
Navigation properties help to navigate from one entity to another entity. For
instance, consider the below example in which we have two entities: Customer and
Address, and a customer has multiple address objects.
Now we would like to have a facility where at any given moment we would like to
browse from a given customer object to the addresses collection and from the
address object to the customer.
If you open the Entity Designer, you would notice navigation properties as shown
below. The navigation properties are automatically created from the primary and
foreign key references.
So now because of those navigation properties, we can browse from the Customer to
the Addresses object, look at the below code:
Collapse | Copy Code

Customer Cust = oContext.Customers.ToList<Customer>()[0];

// From customer are browsing addresses


List<Address> Addresses = Cust.Addresses.ToList<Address>();

You can also do vice versa. In other words, from the Address object, you can
reference the Customer object, as shown in the below code.
Collapse | Copy Code

Address myAddress = Addresses[0];


// From address we can browse customer
Customer cus = myAddress.Customer;

What are complex types in Entity


Framework?
There can be situations where you have common properties across entities. For
example, consider the below figure where we have Customer and Supplier entities.
They have three fields in common: Address1,Address2, and PhoneNo. These fields
have been duplicated both in the Customer and Supplier entities.
So to remove these duplicate and redundant fields, we can move them to a common
complex type calledAddress. Complex types group common fields so that they can
be reused across entities.

To create a complex type, select the fields which you want to group in a complex
type, click on Refactor, and create the complex type. Below is a figure which shows
this. Once the complex type is created, you can then reuse the complex type with
other entities as well.

Whats the difference between LINQ to


SQL and Entity Framework?

LINQ to SQL is good for rapid development with SQL Server. EF is for
enterprise scenarios and works with SQL Server as well as other databases.
LINQ maps directly to tables. One LINQ entity class maps to one table. EF has
a conceptual model and that conceptual model maps to the storage model via
mappings. So one EF class can map to multiple tables, or one table can map to
multiple classes.
LINQ is more targeted towards rapid development while EF is for enterprise
level where the need is to develop a loosely coupled framework.

What is the difference between


DbContext and ObjectContext?
DbContext is a wrapper around ObjectContext, its a simplified version
of ObjectContext.

As a developer you can start with DbContext as its simple to use. When you feel
that some of the operations cannot be achieved by DbContext, you can then
access ObjectContext from DbContext, as shown in the below code:
Collapse | Copy Code

((IObjectContextAdapter)dbContext).ObjectContext

SQL SERVER
(B) What is normalization? What are different types of normalization?

Note :- A regular .NET programmer working on projects often stumbles in this


question, which is but obvious. Bad part is sometimes interviewer can take
this as a very basic question to be answered and it can be a turning point for
the interview. So let's cram it. It is set of rules that have been established to
aid in the design of tables that are meant to be connected through
relationships. This set of rules is known as Normalization. Benefits of

normalizing your database will include: Avoiding repetitive entries


Reducing required storage space Preventing the need to restructure
existing tables to accommodate new data. Increased speed and flexibility of
queries, sorts, and summaries.
(B) What is denormalization ?

Denormalization is the process of putting one fact in numerous places (its


vice-versa of normalization).Only one valid reason exists for denormalizing a
relational design - to enhance performance.The sacrifice to performance is
that you increase redundancy in database.
(B)What is a candidate key ?

A table may have more than one combination of columns that could uniquely
identify the rows in a table; each combination is a candidate key. During
database design you can pick up one of the candidate keys to be the primary
key. For example, in the supplier table supplierid and suppliername can be
candidate key but you will only pick up supplierid as the primary key.
(B) What are the different types of joins? What is the difference between them ?

INNER JOIN Inner join shows matches only when they exist in both
tables.Example, in the below SQL there are two tables Customers and Orders
and the inner join in made on Customers Customerid and Orders
Customerid.So this SQL will only give you result with customers who have
orders.If the customer does not have order it will not display that record.
SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON
Customers.CustomerID =Orders.CustomerID
LEFT OUTER JOIN Left join will display all records in left table of the SQL
statement.In SQL below customers with or without orders will be displayed.
Order data for customers without orders appears as NULL values. For
example, you want to determine the amount ordered by each customer and
you need to see who has not ordered anything as well. You can also see the
LEFT OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in
the next section) if you switch the side of each table. SELECT Customers.*,
Orders.* FROM Customers LEFT OUTER JOIN Orders ON
Customers.CustomerID =Orders.CustomerID307
RIGHT OUTER JOIN Right join will display all records in right table of the SQL
statement. In SQL below all orders with or without matching customer records
will be displayed. Customer data for orders without customers appears as
NULL values. For example, you want to determine if there are any orders in
the data with undefined CustomerID values (say, after a conversion or
something like it). You can also see the RIGHT OUTER JOIN as a mirror image
of the LEFT OUTER JOIN if you switch the side of each table. SELECT

Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON


Customers.CustomerID =Orders.CustomerID
(B) What is the difference between DELETE TABLE and TRUNCATE TABLE
commands?

Following are difference between them :- DELETE TABLE syntax logs the
deletes thus make the delete operation slow. TRUNCATE table does not log
any information but it logs information about deallocation of data page of the
table so TRUNCATE table is faster as compared to delete table. DELETE
table can have criteria while TRUNCATE can not. TRUNCATE table can not
trigger. Note :- Thanks to all the readers for pointing out my mistake for the
above question in my first edition. I had mentioned that TRUNCATE table can
not be rolled back while delete can be.
(B) What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

You can use Having Clause with the GROUP BY function in a query and
WHERE Clause is applied to each row before they are part of the GROUP BY
function in a query.
(B) What is the difference between UNION and UNION ALL SQL syntax ?

UNION SQL syntax is used to select information from two tables. But it selects
only distinct records from both the table, while UNION ALL selects all records
from both the tables. Note :- Selected records should have same datatype or
else the syntax will not work
(B) What is the difference between Stored Procedure (SP) and User Defined
Function (UDF)?

Following are some major differences between a stored procedure and user
defined functions:- UDF can be executed using the SELECT clause while
SPs can not be. UDF can not be used in XML FOR clause but SPs can be
used. UDF does not return output parameters while SPs return output
parameters. If there is an error in UDF its stops executing. But in SPs it just
ignores the error and moves to the next statement. UDF can not make
permanent changes to server environments while SPs can change some of
the server environment. Note :- SQL Server product is equivalently important
from interview point of view. Below are questions taken from my second book
SQL Server Interview questions. If you are interested in buying the book
mail bpb@bol.net.in / bpb@vsnl.com or call the nearest BPB book stall for my
book. For shop phone numbers you can either see the back or front page of
the book.

(A) What is SQl injection ?

It is a Form of attack on a database-driven Web site in which the attacker


executes unauthorized SQL commands by taking advantage of insecure code
on a system connected to the Internet, bypassing the firewall. SQL injection
attacks are used to steal information from a database from which the data
would normally not be available and/or to gain access to an organizations
host computers through the computer that is hosting the database. SQL
injection attacks typically are easy to avoid by ensuring that a system has
strong input validation. As name suggest we inject SQL which can be
relatively dangerous for the database. Example this is a simple SQL SELECT
email, passwd, login_id, full_name FROM members WHERE email = 'x' Now
somebody does not put x as the input but puts x ; DROP TABLE
members;. So the actual SQL which will execute is : SELECT email, passwd,
login_id, full_name FROM members WHERE email = 'x' ; DROP TABLE
members; Think what will happen to your database.
(A) How can you increase SQL performance ?

Following are tips which will increase your SQl performance :- Every index
increases the time takes to perform INSERTS, UPDATES and DELETES, so the
number of indexes should not be too much. Try to use maximum 4-5 indexes
on one table, not more. If you have read-only table, then the number of
indexes may be increased.308 Keep your indexes as narrow as possible.
This reduces the size of the index and reduces the number of reads required
to read the index. Try to create indexes on columns that have integer
values rather than character values. If you create a composite (multicolumn) index, the order of the columns in the key are very important. Try to
order the columns in the key as to enhance selectivity, with the most
selective columns to the leftmost of the key. If you want to join several
tables, try to create surrogate integer keys for this purpose and create
indexes on their columns. Create surrogate integer primary key (identity for
example) if your table will not have many insert operations. Clustered
indexes are more preferable than nonclustered, if you need to select by a
range of values or you need to sort results set with GROUP BY or ORDER BY.
If your application will be performing the same query over and over on the
same table, consider creating a covering index on the table. You can use
the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large
Tables" trace to determine which tables in your database may need indexes.
This trace will show which tables are being scanned by queries instead of
using an index.
(I) What are indexes? What is the difference between clustered and nonclustered
indexes?

Indexes in SQL Server are similar to the indexes in books. They help SQL
Server retrieve the data quickly. There are clustered and nonclustered
indexes. A clustered index is a special type of index that reorders the way in

which records in the table are physically stored. Therefore table can have
only one clustered index. The leaf nodes of a clustered index contain the data
pages. A nonclustered index is a special type of index in which the logical
order of the index does not match the physical stored order of the rows on
disk. The leaf node of a nonclustered index does not consist of the data
pages. Instead, the leaf nodes contain index rows.

MVC
Difference between ASP.NET WebForms and ASP.NET MVC?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In
this approach, every page has it's own controller i.e. code-behind file that processes
the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this
approach a common controller for all pages, processes the requests.

What is MVC (Model View Controller)?


MVC is an architectural pattern which separates the representation and user
interaction. Its divided into three broader sections, Model, View, and Controller.
Below is how each one of them handles the task.

The View is responsible for the look and feel.


Model represents the real world object and provides data to the View.
The Controller is responsible for taking the end user request and loading the
appropriate Model and View.

Figure: MVC (Model view controller)

Explain MVC application life cycle?

There are six broader events which occur in MVC application life cycle below
diagrams summarize it.

Image Courtesy: - http://www.dotnetinterviewquestions.in/article_explain-mvcapplication-life-cycle_210.html


Any web application has two main execution steps first understanding the request
and depending on the type of the request sending out appropriate response. MVC
application life cycle is not different it has two main phases first creating the request
object and second sending our response to the browser.
Creating the request object: -The request object creation has four major steps.
Below is the detail explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify
which controller and action to be invoked. So if the request is the first request the
first thing is to fill the route table with routes collection. This filling of route table
happens in the global.asax file.
Step 2 Fetch route: - Depending on the URL sent UrlRoutingModule searches the
route table to create RouteData object which has the details of which controller
and action to invoke.
Step 3 Request context created: - The RouteData object is used to create the
RequestContext object.
Step 4 Controller instance created: - This request object is sent to MvcHandler
instance to create the controller class instance. Once the controller class object is
created it calls the Execute method of the controller class.
Creating Response object: - This phase has two steps executing the action and
finally sending the response as a result to the view.

Is MVC suitable for both Windows and


Web applications?
The MVC architecture is suited for a web application than Windows. For Window
applications, MVP, i.e., Model View Presenter is more applicable. If you are using
WPF and Silverlight, MVVM is more suitable due to bindings.

What are the benefits of using MVC?


There are two big benefits of MVC:

Separation of concerns is achieved as we are moving the code-behind to a


separate class file. By moving the binding code to a separate class file we can reuse
the code to a great extent.
Automated UI testing is possible because now the behind code (UI interaction
code) has moved to a simple .NET class. This gives us opportunity to write unit tests
and automate manual testing.

Is MVC different from a three layered


architecture?
MVC is an evolution of a three layered traditional architecture. Many components of
the three layered architecture are part of MVC. So below is how the mapping goes:

Functionality

Three layered / tiered


architecture

Model view controller


architecture

Look and Feel

User interface

View

UI logic

User interface

Controller

Business logic
/validations

Middle layer

Model

Request is first sent to User interface

Controller

Accessing data

Data Access Layer

Data access layer

Figure: Three layered architecture

What is the latest version of MVC?


When this note was written, four versions were released of MVC: MVC 1 , MVC 2, MVC
3, and MVC 4. So the latest is MVC 4.

What is the difference between each


version of MVC?
Below is a detailed table of differences. But during an interview its difficult to talk
about all of them due to time limitation. So I have highlighted the important
differences that you can run through before the interviewer.
MVC 2
Client-side validation
Templated Helpers Areas
Asynchronous Controllers
Html.ValidationSummaryHelper Method
DefaultValueAttribute in Action-Method
Parameters binding
Binary data with Model Binders
DataAnnotations Attributes

MVC 3

MVC 4

Razor
Readymade project
templates
HTML 5 enabled
templates
Support for Multiple
View Engines, JavaScript,
and AJAX

A
R
modern
templa
templa
M
to sup
E

Model-Validator Providers
New RequireHttpsAttributeAction Filter
Templated Helpers
Display Model-Level Errors

Model Validation
Improvements

What are HTML helpers in MVC?


HTML helpers help you to render HTML controls in the view. For instance if you want
to display a HTML textbox on the view , below is the HTML helper code.
Collapse | Copy Code

<%= Html.TextBox("LastName") %>

For checkbox below is the HTML helper code. In this way we have HTML helper
methods for every HTML control that exists.
Collapse | Copy Code

<%= Html.CheckBox("Married") %>

What is the difference between


HTML.TextBox vs HTML.TextBoxFor?
Both of them provide the same HTML output, HTML.TextBoxFor is strongly typed
while HTML.TextBox isnt. Below is a simple HTML code which just creates a simple
textbox with CustomerCode as name.
Collapse | Copy Code

Html.TextBox("CustomerCode")

Below is Html.TextBoxFor code which creates HTML textbox using the property
name CustomerCode from object m.
Collapse | Copy Code

Html.TextBoxFor(m => m.CustomerCode)

In the same way we have for other HTML controls like for checkbox we have
Html.CheckBox and Html.CheckBoxFor.

What is routing in MVC?


Routing helps you to define a URL structure and map the URL with the controller.

asynch

For instance lets say we want that when a user types


http://localhost/View/ViewCustomer/, it goes to the Customer Controller and
invokes the DisplayCustomer action. This is defined by adding an entry in to
theroutes collection using the maproute function. Below is the underlined code
which shows how the URL structure and mapping with controller and action is
defined.
Collapse | Copy Code

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code


written?
The route mapping code is written in "RouteConfig.cs" file and registered using
"global.asax" application start event.

Can we map multiple URLs to the


same action?
Yes, you can, you just need to make two entries with different key names and specify
the same controller and action.

Explain attribute based routing in MVC?


This is a feature introduced in MVC 5. By using the "Route" attribute we can define
the URL structure. For example in the below code we have decorated the
"GotoAbout" action with the route attribute. The route attribute says that the
"GotoAbout" can be invoked using the URL structure "Users/about".
Collapse | Copy Code

public class HomeController : Controller


{
[Route("Users/about")]
public ActionResult GotoAbout()
{
return View();
}
}

What is the advantage of defining route


structures in the code?
Most of the time developers code in the action methods. Developers can see the URL
structure right upfront rather than going to the routeconfig.cs and see the lengthy
codes. For instance in the below code the developer can see right upfront that the
GotoAbout action can be invoked by four different URL structure.
This is much user friendly as compared to scrolling through the routeconfig.cs file
and going through the length line of code to figure out which URL structure is
mapped to which action.
Collapse | Copy Code

public class HomeController : Controller


{
[Route("Users/about")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout()
{
return View();
}
}

How can we navigate from one view to


another using a hyperlink?
By using the ActionLink method as shown in the below code. The below code will
create a simple URL which helps to navigate to the Home controller and invoke
the GotoHome action.
Collapse | Copy Code

<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be


invoked only by GET or POST?
We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict
the type of HTTP calls. For instance you can see in the below code snippet
the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP
POST on DisplayCustomer, it will throw an error.
Collapse | Copy Code

[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}

How can we maintain sessions in MVC?


Sessions can be maintained in MVC by three ways: tempdata, viewdata, and
viewbag.

What is the difference between


tempdata, viewdata, and viewbag?

Figure: Difference between tempdata, viewdata, and viewbag

Temp data - Helps to maintain data when you move from one controller to
another controller or from one action to another action. In other words when you
redirect, tempdata helps to maintain data between those redirects. It internally uses
session variables.
View data - Helps to maintain data when you move from controller to view.
View Bag - Its a dynamic wrapper around view data. When you
use Viewbag type, casting is not required. It uses the dynamic keyword internally.

Figure: dynamic keyword

Session variables - By using session variables we can maintain data from


any entity to any entity.
Hidden fields and HTML controls - Helps to maintain data from UI to
controller only. So you can send data from HTML controls or hidden fields to the
controller using POST or GET HTTP methods.
Below is a summary table which shows the different mechanisms for persistence.
Maintains data
between

ViewData/ViewB
ag

TempData

Hidden fields

Session

Controller to
Controller

No

Yes

No

Yes

Controller to View

Yes

No

No

Yes

View to Controller

No

No

Yes

Yes

What is difference between TempData


and ViewData ?
TempData maintains data for the complete request while ViewData maintains
data only from Controller to the view.

Does TempData preserve data in the


next request also?

TempData is available through out for the current request and in the subsequent
request its available depending on whether TempData is read or not.
So if TempData is once read it will not be available in the subsequent request.

What is the use of Keep and Peek in


TempData?
Once TempData is read in the current request its not available in the subsequent
request. If we want TempData to be read and also available in the subsequent
request then after reading we need to call Keep method as shown in the code
below.
Collapse | Copy Code

@TempData[&ldquo;MyData&rdquo;];
TempData.Keep(&ldquo;MyData&rdquo;);

The more shortcut way of achieving the same is by using Peek. This function helps
to read as well advices MVC to maintain TempData for the subsequent request.
Collapse | Copy Code

string str = TempData.Peek("Td").ToString();

If you want to read more in detail you can read from this detailed blog on MVC Peek
and Keep.

What are partial views in MVC?


Partial view is a reusable view (like a user control) which can be embedded inside
other view. For example lets say all your pages of your site have a standard
structure with left menu, header, and footer as shown in the image below.

Figure: Partial views in MVC

For every page you would like to reuse the left menu, header, and footer controls. So
you can go and create partial views for each of these items and then you call that
partial view in the main view.

How did you create a partial view and


consume it?
When you add a view to your project you need to check the Create partial view
check box.

Figure: Create partial view

Once the partial view is created you can then call the partial view in the main view
using theHtml.RenderPartial method as shown in the below code snippet:
Collapse | Copy Code

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

How can we do validations in MVC?

One of the easiest ways of doing validation in MVC is by using data annotations. Data
annotations are nothing but attributes which can be applied on model properties. For
example, in the below code snippet we have a simple Customer class with a
property customercode.
This CustomerCode property is tagged with a Required data annotation attribute. In
other words if this model is not provided customer code, it will not accept it.
Collapse | Copy Code

public class Customer


{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}

In order to display the validation error message we need to use


the ValidateMessageFor method which belongs to the Html helper class.
Collapse | Copy Code

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))


{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>

Later in the controller we can check if the model is proper or not by using
the ModelState.IsValid property and accordingly we can take actions.
Collapse | Copy Code

public ActionResult PostCustomer(Customer obj)


{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}

Below is a simple view of how the error message is displayed on the view.

Figure: Validations in MVC

Can we display all errors in one go?


Yes, we can; use the ValidationSummary method from the Html helper class.
Collapse | Copy Code

<%= Html.ValidationSummary() %>

What are the other data annotation attributes for validation in MVC?
If you want to check string length, you can use StringLength.
Collapse | Copy Code

[StringLength(160)]
public string FirstName { get; set; }

In case you want to use a regular expression, you can use


the RegularExpression attribute.
Collapse | Copy Code

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email {


get; set; }

If you want to check whether the numbers are in range, you can use
the Range attribute.
Collapse | Copy Code

[Range(10,25)]public int Age { get; set; }

Sometimes you would like to compare the value of one field with another field, we
can use the Compareattribute.
Collapse | Copy Code

public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use
the Errors collection.
Collapse | Copy Code

var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly
call TryUpdateModel in your controller to check if the object is valid or not.
Collapse | Copy Code

TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use
the AddModelError function.
Collapse | Copy Code

ModelState.AddModelError("FirstName", "This is my server-side error.");

How can we enable data annotation


validation on client side?
Its a two-step process: first reference the necessary jQuery files.
Collapse | Copy Code

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>


<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>"
type="text/javascript"></script>

The second step is to call the EnableClientValidation method.


Collapse | Copy Code

<% Html.EnableClientValidation(); %>

What is Razor in MVC?


Its a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor
was introduced in MVC 3.

Why Razor when we already have


ASPX?
Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For
example, in ASPX to display simple time, we need to write:
Collapse | Copy Code

<%=DateTime.Now%>

In Razor, its just one line of code:


Collapse | Copy Code

@DateTime.Now

So which is a better fit, Razor or ASPX?


As per Microsoft, Razor is more preferred because its light weight and has simple
syntaxes.

How can you do authentication and


authorization in MVC?
You can use Windows or Forms authentication for MVC.

How to implement Windows


authentication for MVC?
For Windows authentication you need to modify the web.config file and set the
authentication mode to Windows.
Collapse | Copy Code

<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>

Then in the controller or on the action, you can use the Authorize attribute which
specifies which users have access to these controllers and actions. Below is the code
snippet for that. Now only the users specified in the controller and action can access
it.
Collapse | Copy Code

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}

How do you implement Forms


authentication in MVC?
Forms authentication is implemented the same way as in ASP.NET. The first step is to
set the authentication mode equal to Forms. The loginUrl points to a controller here
rather than a page.
Collapse | Copy Code

<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>

We also need to create a controller where we will check if the user is proper or not. If
the user is proper we will set the cookie value.
Collapse | Copy Code

public ActionResult Login()


{
if ((Request.Form["txtUserName"] == "Shiv") &&
(Request.Form["txtPassword"] == "Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",true);
return View("About");
}
else
{
return View("Index");
}
}

All the other actions need to be attributed with the Authorize attribute so that any
unauthorized user making a call to these controllers will be redirected to the
controller (in this case the controller is Login) which will do the authentication.
Collapse | Copy Code

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}

How to implement AJAX in MVC?


You can implement AJAX in two ways in MVC:

AJAX libraries
jQuery
Below is a simple sample of how to implement AJAX by using the AJAX helper
library. In the below code you can see we have a simple form which is created by
using the Ajax.BeginForm syntax. This form calls a controller action
called getCustomer. So now the submit action click will be an asynchronous AJAX
call.
Collapse | Copy Code

<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>

<%
var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>

In case you want to make AJAX calls on hyperlink clicks, you can use
the Ajax.ActionLink function as shown in the below code.

Figure: Implement AJAX in MVC

So if you want to create an AJAX asynchronous hyperlink by name GetDate which


calls the GetDate function in the controller, below is the code for that. Once the
controller responds, this data is displayed in the HTML DIVtag named DateDiv.
Collapse | Copy Code

<span id="DateDiv" />


<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>

Below is the controller code. You can see how the GetDate function has a pause of
10 seconds.
Collapse | Copy Code

public class Default1Controller : Controller


{
public string GetDate()
{
Thread.Sleep(10000);
return DateTime.Now.ToString();
}
}

The second way of making an AJAX call in MVC is by using jQuery. In the below code
you can see we are making an AJAX POST call to a URL /MyAjax/getCustomer. This is
done by using $.post. All this logic is put into a function called GetData and you can
make a call to the GetData function on a button or a hyperlink click event as you
want.
Collapse | Copy Code

function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}

What kind of events can be tracked in


AJAX?

Figure: Tracked in AJAX

What is the difference between


ActionResult and ViewResult?

ActionResult is an abstract class while ViewResult derives from


the ActionResult class.ActionResult has several derived classes
like ViewResult, JsonResult, FileStreamResult, and so on.
ActionResult can be used to exploit polymorphism and dynamism. So if you
are returning different types of views dynamically, ActionResult is the best thing. For
example in the below code snippet, you can see we have a simple action
called DynamicView. Depending on the flag (IsHtmlView) it will either return
a ViewResult or JsonResult.
Collapse | Copy Code

public ActionResult DynamicView()


{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}

What are the different types of results


in MVC?
Note: Its difficult to remember all the 12 types. But some important ones you can
remember for the interview are ActionResult, ViewResult, and JsonResult. Below is a
detailed list for your interest:
There 12 kinds of results in MVC, at the top is the ActionResult class which is a base
class that can have 11 subtypes as listed below:
1.
ViewResult - Renders a specified view to the response stream
2.
PartialViewResult - Renders a specified partial view to the response stream
3.
EmptyResult - An empty response is returned
4.
RedirectResult - Performs an HTTP redirection to a specified URL
5.
RedirectToRouteResult - Performs an HTTP redirection to a URL that is
determined by the routing engine, based on given route data
6.
JsonResult - Serializes a given ViewData object to JSON format
7.
JavaScriptResult - Returns a piece of JavaScript code that can be executed on
the client
8.
ContentResult - Writes content to the response stream without requiring a
view
9.
FileContentResult - Returns a file to the client
10.
FileStreamResult - Returns a file to the client, which is provided by a Stream
11.
FilePathResult - Returns a file to the client

What are ActionFilters in MVC?


ActionFilters help you to perform logic while an MVC action is executing or after an
MVC action has executed.

Figure: ActionFilters in MVC

Action filters are useful in the following scenarios:


1.
2.

Implement post-processing logic before the action happens.


Cancel a current execution.

3.
4.

Inspect the returned value.


Provide extra data to the action.
You can create action filters by two ways:

Inline action filter.


Creating an ActionFilter attribute.
To create an inline action attribute we need to implement the IActionFilter interface.
The IActionFilterinterface has two
methods: OnActionExecuted and OnActionExecuting. We can implement preprocessing logic or cancellation logic in these methods.
Collapse | Copy Code

public class Default1Controller : Controller , IActionFilter


{
public ActionResult Index(Customer obj)
{
return View(obj);
}
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action is executing");
}
}

The problem with the inline action attribute is that it cannot be reused across
controllers. So we can convert the inline action filter to an action filter attribute. To
create an action filter attribute we need to inherit fromActionFilterAttribute and
implement the IActionFilter interface as shown in the below code.
Collapse | Copy Code

public class MyActionAttribute : ActionFilterAttribute , IActionFilter


{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action executing");
}
}

Later we can decorate the controllers on which we want the action attribute to
execute. You can see in the below code I have decorated the Default1Controller with
the MyActionAttribute class which was created in the previous code.
Collapse | Copy Code

[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}

Can we create our custom view engine


using MVC?
Yes, we can create our own custom view engine in MVC. To create our own custom
view engine we need to follow three steps:
Let say we want to create a custom view engine where in the user can type a
command like <DateTime> and it should display the current date and time.
Step 1: We need to create a class which implements the IView interface. In this
class we should write the logic of how the view will be rendered in
the render function. Below is a simple code snippet for that.
Collapse | Copy Code

public class MyCustomView : IView


{
private string _FolderPath; // Define where our views are stored
public string FolderPath
{
get { return _FolderPath; }
set { _FolderPath = value; }
}
public void Render(ViewContext viewContext, System.IO.TextWriter writer)
{
// Parsing logic <dateTime>
// read the view file
string strFileData = File.ReadAllText(_FolderPath);
// we need to and replace <datetime> datetime.now value
string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
// this replaced data has to sent for display
writer.Write(strFinal);
}
}

Step 2: We need to create a class which inherits


from VirtualPathProviderViewEngine and in this class we need to provide the folder
path and the extension of the view name. For instance, for Razor the extension is
cshtml; for aspx, the view extension is .aspx, so in the same way for our custom
view, we need to provide an extension. Below is how the code looks like. You can see
the ViewLocationFormats is set to the Views folder and the extension is .myview.
Collapse | Copy Code

public class MyViewEngineProvider : VirtualPathProviderViewEngine


{
// We will create the object of Mycustome view
public MyViewEngineProvider() // constructor
{
// Define the location of the View file
this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview",
"~/Views/Shared/{0}.myview" }; //location and extension of our views

}
protected override IView CreateView(
ControllerContext controllerContext, string viewPath, string masterPath)
{
var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj; // returned this view paresing
// logic so that it can be registered in the view engine collection
}
protected override IView CreatePartialView(ControllerContext controllerContext, string
partialPath)
{
var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj;
// returned this view paresing logic
// so that it can be registered in the view engine collection
}
}

Step 3: We need to register the view in the custom view collection. The best place to
register the custom view engine in the ViewEngines collection is the global.asax file.
Below is the code snippet for that.
Collapse | Copy Code

protected void Application_Start()


{
// Step3 :- register this object in the view engine collection
ViewEngines.Engines.Add(new MyViewEngineProvider());
&hellip;..
}

Below is a simple output of the custom view written using the commands defined at
the top.

Figure: Custom view engine using MVC

If you invoke this view, you should see the following output:

How to send result back in JSON format


in MVC

In MVC, we have the JsonResult class by which we can return back data in JSON
format. Below is a simple sample code which returns back a Customer object in JSON
format using JsonResult.
Collapse | Copy Code

public JsonResult getCustomer()


{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
return Json(obj,JsonRequestBehavior.AllowGet);
}

Below is the JSON output of the above code if you invoke the action via the browser.

What is WebAPI?
HTTP is the most used protocol. For the past many years, browser was the most
preferred client by which we consumed data exposed over HTTP. But as years passed
by, client variety started spreading out. We had demand to consume data on HTTP
from clients like mobile, JavaScript, Windows applications, etc.
For satisfying the broad range of clients REST was the proposed approach. You can
read more about REST from the WCF chapter.
WebAPI is the technology by which you can expose data over HTTP following REST
principles.

But WCF SOAP also does the same


thing, so how does WebAPI differ?
SOAP

WEB API

Size

Heavy weight
because of
complicated WSDL
structure.

Light weight, only the necessary information is


transferred.

Protocol

Independent of
protocols.

Only for HTTP protocol

SOAP

WEB API

Formats

To parse SOAP
message, the client
needs to
understand WSDL
format. Writing
custom code for
parsing WSDL is a
Output of WebAPI are simple string messages,
heavy duty task. If
JSON, simple XML format, etc. So writing parsing
your client is smart
logic for that is very easy.
enough to create
proxy objects like
how we have in
.NET (add
reference) then
SOAP is easier to
consume and call.

Principles

SOAP follows WS-*


specification.

WebAPI follows REST principles. (Please refer to


REST in WCF chapter.)

With WCF you can implement REST, so


why WebAPI?
WCF was brought into implement SOA, the intention was never to implement REST.
WebAPI is built from scratch and the only goal is to create HTTP services using REST.
Due to the one point focus for creating REST service, WebAPI is more preferred.

How to implement WebAPI in MVC


Below are the steps to implement WebAPI:
Step 1: Create the project using the WebAPI template.

Figure: Implement WebAPI in MVC

Step 2: Once you have created the project you will notice that the controller now
inherits from ApiControllerand you can now implement POST, GET, PUT, and DELETE
methods of the HTTP protocol.
Collapse | Copy Code

public class ValuesController : ApiController


{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}

Step 3: If you make an HTTP GET call you should get the below results:

Figure: HTTP

How can we detect that an MVC


controller is called by POST or GET?
To detect if the call on the controller is a POST action or a GET action we can use
the Request.HttpMethodproperty as shown in the below code snippet.

Collapse | Copy Code

public ActionResult SomeAction()


{
if (Request.HttpMethod == "POST")
{
return View("SomePage");
}
else
{
return View("SomeOtherPage");
}
}

What is bundling and minification in


MVC?
Bundling and minification helps us improve request load times of a page thus
increasing performance.

How does bundling increase


performance?
Web projects always need CSS and script files. Bundling helps us combine multiple
JavaScript and CSS files in to a single entity thus minimizing multiple requests in to a
single request.

For example consider the below web request to a page . This page consumes two
JavaScript files Javascript1.jsand Javascript2.js. So when this is page is requested it
makes three request calls:
One for the Index page.
Two requests for the other two JavaScript
files: Javascript1.js and Javascript2.js.
The below scenario can become worse if we have a lot of JavaScript files resulting in
multiple requests, thus decreasing performance. If we can somehow combine all the
JS files into a single bundle and request them as a single unit that would result in
increased performance (see the next figure which has a single request).

So how do we implement bundling in


MVC?
Open BundleConfig.cs from the App_Start folder.

In BundleConfig.cs, add the JS files you want bundle into a single entity in to the
bundles collection. In the below code we are combining all the javascript JS files
which exist in the Scripts folder as a single unit in to the bundle collection.
Collapse | Copy Code

bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));

Below is how your BundleConfig.cs file will look like:


Collapse | Copy Code

public class BundleConfig

{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
BundleTable.EnableOptimizations = true;
}
}

Once you have combined your scripts into one single unit we then to include all the
JS files into the view using the below code. The below code needs to be put in the
ASPX or Razor view.
Collapse | Copy Code

<%= Scripts.Render("~/Scripts/MyScripts") %>

If you now see your page requests you would see that script request is combined into
one request.

How can you test bundling in debug


mode?
If you are in a debug mode you need to set EnableOptimizations to true in
the bundleconfig.cs file or else you will not see the bundling effect in the page
requests.
Collapse | Copy Code

BundleTable.EnableOptimizations = true;

Explain minification and how to


implement it
Minification reduces the size of script and CSS files by removing blank spaces ,
comments etc. For example below is a simple javascript code with comments.
Collapse | Copy Code

// This is test
var x = 0;
x = x + 1;
x = x * 2;

After implementing minification the JavaScript code looks like below. You can see how
whitespaces and comments are removed to minimize file size, thus increasing
performance.
Collapse | Copy Code

var x=0;x=x+1;x=x*2;

How do we implement minification?


When you implement bundling, minification is implemented by itself. In other words
the steps to implement bundling and minification are the same.

Explain Areas in MVC?


Areas help you to group functionalities in to independent modules thus making your
project more organized. For example in the below MVC project we have four
controller classes and as time passes by if more controller classes are added it will
be difficult to manage. In bigger projects you will end up with 100s of controller
classes making life hell for maintenance.

If we can group controller classes in to logical section like Invoicing and


Accounting that would make life easier and thats what Area are meant to.

You can add an area by right clicking on the MVC solution and clicking on Area
menu as shown in the below figure.

In the below image we have two Areas created Account and Invoicing and in
that I have put the respective controllers. You can see how the project is looking
more organized as compared to the previous state.

Explain the concept of View Model in


MVC?
A view model is a simple class which represents data to be displayed on the view.
For example below is a simple customermodel object with CustomerName and
Amount property.
Collapse | Copy Code

CustomerViewModel obj = new CustomerViewModel();


obj.Customer.CustomerName = "Shiv";
obj.Customer.Amount = 1000;

But when this Customer model object is displayed on the MVC view it looks
something as shown in the below figure. It has CustomerName , Amount plus
Customer Buying Level fields on the view / screen. Customer buying Level is a
color indicationwhich indicates how aggressive the customer is buying.
Customer buying level color depends on the value of the Amount property. If the
amount is greater than 2000 then color is red , if amount is greater than 1500 then
color is orange or else the color is yellow.
In other words Customer buying level is an extra property which is calculated on
the basis of amount.

So the Customer viewmodel class has three properties

TxtCustomerName textbox takes data from CustomerName property as it


is.

TxtAmount textbox takes data from Amount property of model as it is.


CustomerBuyingLevelColor displays color value depending on the Amount
value.
Customer Model Customer ViewModel
CustomerName

TxtCustomerName

Amount

TxtAmount
CustomerBuyingLevelColor

What kind of logic view model class will


have?
As the name says view model this class has the gel code or connection code which
connects the view and the model.
So the view model class can have following kind of logics:

Color transformation logic: - For example you have a Grade property in


model and you would like your UI to display red color for high level grade, yellow
color for low level grade and green color of ok grade.
Data format transformation logic :-Your model has a property Status
with Married and Unmarried value. In the UI you would like to display it as a
checkbox which is checked if married and unchecked if unmarried.
Aggregation logic: -You have two differentCustomer and Address model
classes and you have view which displays both Customer and Address data on
one go.
Structure downsizing: - You have Customer model with customerCode
and CustomerName and you want to display just CustomerName. So you can
create a wrapper around model and expose the necessary properties.

How can we use two ( multiple) models


with a single view?

Let us first try to understand what the interviewer is asking. When we bind a model
with a view we use the model dropdown as shown in the below figure. In the below
figure we can only select one model.

But what if we want to bind Customer as well as Order class to the view.
For that we need to create a view model which aggregates both the classes as shown
in the below code. And then bind that view model with the view.
Collapse | Copy Code

public class CustOrderVM


{
public Customer cust = new Customer();
public Order Ord = new Order();
}

In the view we can refer both the model using the view model as shown in the below
code.
Collapse | Copy Code

<%= model.cust.Name %>


<%= model.Ord.Number %>

Explain the need of display mode in


MVC?
Display mode displays views depending on the device the user has logged in with. So
we can create different views for different devices anddisplay mode will handle the
rest.
For example we can create a view Home.aspx which will render for the desktop
computers andHome.Mobile.aspx for mobile devices. Now when an end user sends a
request to the MVC application, display mode checks the user agent headers and
renders the appropriate view to the device accordingly.

Explain MVC model binders?


Model binder maps HTML form elements to the model. It acts like a bridge between
HTML UI and MVC model. Many times HTML UI names are different than the model
property names. So in the binder we can write the mapping logic between the UI and
the model.

Explain the concept of MVC


Scaffolding?

Collapse | Copy Code

Note :- Do not get scared with the word. Its actually a very simple thing.

Scaffolding is a technique in which the MVC template helps to auto-generate CRUD


code. CRUD stands for create, read, update and delete.
So to generate code using scaffolding technique we need to select one of the types
of templates (leave the empty one).

For instance if you choose using Entity framework template the following code is
generated.

It creates controller code, view and also table structure as shown in the below figure.

What does scaffolding use internally to


connect to database?
It uses Entity framework internally.
Please do read this blog which has detailed steps of how model binders can be
created using IModelBinder interface: - Explain MVC model Binders?
Download an e-learning copy of MVC interview Q&A from the top of this article for
your preparation.
For technical training related to various topics including ASP.NET, Design Patterns,
WCF, MVC, BI, WPF contact SukeshMarla@gmail.com or visit www.sukesh-marla.com
Finally do not forget to visit my video site which covers lots of C# interview
questions and answers:www.questpond.com.

THREADING
*(B)What is Multi-tasking ?

Its a feature of modern operating systems with which we can run multiple
programs at same time example Word, Excel etc.
*(B)What is Multi-threading ?

Multi-threading forms subset of Multi-tasking. Instead of having to switch


between programs this feature switches between different parts of the same
program. Example you are writing in word and at the same time word is doing
a spell check in background.
*(B)What is a Thread ?

A thread is the basic unit to which the operating system allocates processor
time.
*(B) What is the difference between a process and a thread
Process
Each process provides the resources needed to execute a program. A process has a virtual
address space, executable code, open handles to system objects, a security context, a unique
process identifier, environment variables, a priority class, minimum and maximum working set
sizes, and at least one thread of execution. Each process is started with a single thread, often
called the primary thread, but can create additional threads from any of its threads.
Thread
A thread is the entity within a process that can be scheduled for execution. All threads of a
process share its virtual address space and system resources. In addition, each thread maintains
exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a
set of structures the system will use to save the thread context until it is scheduled. The thread
context includes the thread's set of machine registers, the kernel stack, a thread environment
block, and a user stack in the address space of the thread's process. Threads can also have
their own security context, which can be used for impersonating clients

(B) Can we have multiple threads in one App domain ?

One or more threads run in an AppDomain. An AppDomain is a runtime


representation of a logical process within a physical process. Each
AppDomain is started with a single thread, but can create additional threads
from any of its threads. Note :- All threading classes are defined in
System.Threading namespace.

(B) Which namespace has threading ?

Systems.Threading has all the classes related to implement threading. Any


.NET application who wants to implement threading has to import this
namespace. Note :- .NET program always has at least two threads running
one is the main program and second is the garbage collector.

(I) What's Thread.Sleep() in threading ?

Thread's execution can be paused by calling the Thread.Sleep method. This


method takes an integer value that determines how long the thread should
sleep. Example Thread.CurrentThread.Sleep(2000).
(A) What is Suspend and Resume in Threading

It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until
another thread calls Thread.Resume. The difference between Sleep and
Suspend is that the latter does not immediately place a thread in the wait
state. The thread does not suspend until the .NET runtime determines that it
is in a safe place to suspend it. Sleep will immediately place a thread in a
wait state

(A)How do I debug thread ?

This window is only seen when the program is running in debug mode. In
windows one of the window is Threads.
(I)Can we use events with threading ? Yes, you can use events with
thread; this is one of the techniques to synchronize one thread with other.
(B) What is the difference between thread and process? A thread is a
path of execution that run on CPU, a process is a collection of threads that
share the same virtual memory. A process has at least one thread of
execution, and a thread always run in a process context.

REMOTING AND WEB SERVICES


*(B) What is an application domain?

Previously PROCESS where used as security boundaries. One process has


its own virtual memory and does not over lap the other process virtual
memory; due to this one process can not crash the other process. So any
problem or error in one process does not affect the other process. In .NET
they went one step ahead introducing application domains. In application
domains multiple applications can run in same process with out influencing
each other. If one of the application domains throws error it does not affect
the other application domains. To invoke method in a object running in
different application domain .NET remoting is used.

*(B) What is .NET Remoting ?

.NET remoting is replacement of DCOM. Using .NET remoting you can make
remote object calls which lie in different Application Domains. As the remote
objects run in different process client calling the remote object can not call it
directly. So the client uses a proxy which looks like a real object. When client
wants to make method call on the remote object it uses proxy for it. These
method calls are called as Messages. Messages are serialized using
formatter class and sent to client channel. Client Channel communicates
with Server Channel. Server Channel uses as formatter to deserialize the
message and sends to the remote object.
*(B) What is a Web Service ?

Web Services are business logic components which provide functionality via
the Internet using standard protocols such as HTTP. Web Services uses Simple
Object Access Protocol (SOAP) in order to expose the business
functionality.SOAP defines a standardized format in XML which can be
exchanged between two entities over standard protocols such as HTTP. SOAP
is platform independent so the consumer of a Web Service is therefore
completely shielded from any implementation details about the platform
exposing the Web Service. For the consumer it is simply a black box of send
and receive XML over HTTP. So any web service hosted on windows can also
be consumed by UNIX and LINUX platform.
(B) What is UDDI ?

Full form of UDDI is Universal Description, Discovery and Integration. It is a


directory that can be used to publish and discover public Web Services. If you
want to see more details you can visit the http://www.UDDI.org .
(B) What is DISCO ?

DISCO is the abbreviated form of Discovery. It is basically used to club or


group common services together on a server and provides links to the
schema documents of the services it describes may require.
(B) What is WSDL?

Web Service Description Language (WSDL)is a W3C specification which


defines XML grammar for describing Web Services.XML grammar describes
details such as: Where we can find the Web Service (its URI)?
What are the methods and properties that service supports?
Data type support.
Supported protocols

In short its a bible of what the webservice can do.Clients can consume this
WSDL and build proxy objects that clients use to communicate with the Web
Services. Full WSDL specification is available at http://www.w3.org/TR/wsdl.

(B)What is file extension of Webservices ?

.ASMX is extension for Webservices.


(B) Which class does the remote object has to inherit ?

All remote objects should inherit from System.MarshalbyRefObject.

(B) Which attribute is used in order that the method can be used as WebService ?

WebMethod attribute has to be specified in order that the method and


property can be treated as WebService.

(I) What are two different types of remote object creation mode in .NET ?

There are two different ways in which object can be created using Remoting : SAO (Server Activated Objects) also called as Well-Known call
mode.
CAO (Client Activated Objects) SAO has two modes Single Call
and Singleton.
With Single Call object the object is created with every method call thus
making the object stateless. With Singleton the object is created only once
and the object is shared with all clients. CAO are stateful as compared to
SAO. In CAO the creation request is sent from client side. Client holds a proxy
to the server object created on server.
(I) How can we call methods in remoting Asynchronously ?

All previous examples are a synchronous method calls that means client has
to wait until the method completes the process. By using Delegates we can
make Asynchronous method calls.

(I) What are the situations you will use a Web Service and Remoting in projects?

Well Web services uses remoting concepts internally. But the major
difference between web service and remoting is that web service can
be consumed by clients who are not .NET platform. While remoting you need
the client to be .NET compliant. Regarding the speed issue Remoting is
faster than Web Services. So I think when deciding the architecture side of
choosing between Web services and Remoting keep the cross platform
issue and the speed issue in mind.
(A) What is marshalling and what are different kinds of marshalling ?

Marshaling is used when an object is converted so that it can be sent across


the network or across application domains. Unmarshaling creates an object
from the marshaled data. There are two ways to do marshalling : Marshal-by-value (MBV) :- In this the object is serialized into the
channel, and a copy of the object is created on the other side of the
network. The object to marshal is stored into a stream, and the stream
is used to build a copy of the object on the other side with the
unmarshalling sequence.
Marshaling-by-reference (MBR):- Here it creates a proxy on the client
that is used to communicate with the remote object. The marshaling
sequence of a remote object creates an ObjRef instance that itself can
be serialized across the network.
Objects that are derived from MarshalByRefObject are always marshaled by
reference. All our previous samples have classes inherited from
MarshalByRefObject

(A) How can we implement singleton pattern in .NET?

Singleton pattern mainly focuses on having one and only one instance of the
object running. Example a windows directory service which has multiple
entries but you can only have single instance of it through out the network.
Note:- May of developers would jump to a conclusion saying using the
STATIC keyword we can have a single instance of object. But thats not the
real case there is something more that has to be done. But please note we
can not define a class as STATIC, so this will not serve our actual purpose of
implementing singleton pattern.
Following are the three steps needed to implement singleton pattern in .NET:264

First create your class with static members.

Public class ClsStaticClass Private shared objCustomer as clsCustomer End


class
This ensures that there is actually only one Customer object throughout the
project.
Second define a private constructor to your class.
Note: - defining a private constructor to class does not allow a client to create
objects directly.
Finally provide a static method to get access to your singleton object.

CASHING
(B) What is an application object ?

Application object ca be n used in situation where we want data to be shared


across users globally.
(B) What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be
transmitted to and displayed in a Web browser:
Page Output Caching Page output caching adds the response of page to
cache object. Later when page is requested page is displayed from cache
rather than creating the page object and displaying it. Page output caching is
good if the site is fairly static.
Page Fragment Caching If parts of the page are changing, you can wrap
the static sections as user controls and cache the user controls using page
fragment caching.
(B) How can you cache different version of same page using ASP.NET cache
object ?

Output cache functionality is achieved by using OutputCache attribute on


ASP.NET page header. Below is the syntax <%@ OutputCache Duration="20"
Location="Server" VaryByParam="state" VaryByCustom="minorversion"
VaryByHeader="Accept-Language"%>
VaryByParam :- Caches different version depending on input
parameters send through HTTP POST/GET.
VaryByHeader:- Caches different version depending on the contents
of the page header.181

VaryByCustom:-Lets you customize the way the cache handles page


variations by declaring the attribute and overriding the
GetVaryByCustomString handler.
VaryByControl:-Caches different versions of a user control based on
the value of properties of ASP objects in the control.

(B) What are ASP.NET session and compare ASP.NET session with classic ASP
session variables?

ASP.NET session caches per user session state. It basically uses


HttpSessionState class. Following are the limitations in classic ASP
sessions : ASP session state is dependent on IIS process very heavily. So if IIS
restarts ASP session variables are also recycled.ASP.NET session can be
independent of the hosting environment thus ASP.NET session can
maintained even if IIS reboots.
ASP session state has no inherent solution to work with Web
Farms.ASP.NET session can be stored in state server and SQL SERVER
which can support multiple server.
ASP session only functions when browser supports cookies.ASP.NET
session can be used with browser side cookies or independent of it.
(B) Which various modes of storing ASP.NET session ?

InProc:- In this mode Session state is stored in the memory space of the
Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web
application restarts then session state is lost. 182
StateServer:-In this mode Session state is serialized and stored in a
separate process (Aspnet_state.exe); therefore, the state can be stored on a
separate computer(a state server).
SQL SERVER:- In this mode Session state is serialized and stored in a SQL
Server database. Session state can be specified in <sessionState> element
of application configuration file. Using State Server and SQL SERVER session
state can be shared across web farms but note this comes at speed cost as
ASP.NET needs to serialize and deserialize data over network again and
again.
(B) What are the other ways you can maintain state ?

Other than session variables you can use the following technique to store
state : Hidden fields View state Hidden frames Cookies Query
strings
(B) What are benefits and Limitation of using Hidden fields ?

Following are the benefits of using Hidden fields : They are simple to implement.
As data is cached on client side they work with Web Farms.
All browsers support hidden field.
No server resources are required. Following are limitations of Hidden field :184

They can be tampered creating a security hole.


Page performance decreases if you store large data, as the data are stored
in pages itself.
Hidden fields do not support rich structures as HTML hidden fields are only
single valued. Then you have to work around with delimiters etc to handle
complex structures. Below is how you will actually implement hidden field in
a project <input id="HiddenValue" type="hidden" value="Initial Value"
runat="server"NAME="HiddenValue">
(B) What is ViewState ?

Viewstate is a built-in structure for automatically retaining values amongst


the multiple requests for the same page. The viewstate is internally
maintained as a hidden field on the page but is hashed, providing greater
security than developer-implemented hidden fields do.
(B) What are benefits and Limitation of using Viewstate for state management?

Following are the benefits of using Viewstate : No server resources are required because state is in a structure in the page
code.
Simplicity.
States are retained automatically.185
The values in view state are hashed, compressed, and encoded, thus
representing a higher state of security than hidden fields.
View state is good for caching data in Web frame configurations because
the data is cached on the client.

Following are limitation of using Viewstate: Page loading and posting performance decreases when large values are
stored because view state is stored in the page.
Although view state stores data in a hashed format, it can still be tampered
because it is stored in a hidden field on the page. The information in the
hidden field can also be seen if the page output source is viewed directly,
creating a potential security risk.
Below is sample of storing values in view state. this.ViewState["EnterTime"]
= DateTime.Now.ToString();
(B) What is SQL Cache Dependency in ASP.NET 2.0?

SQL cache dependencies is a new feature in ASP.NET 2.0 which can


automatically invalidate a cached data object (such as a Dataset) when the
related data is modified in the database. So for instance if you have a dataset
which is tied up to a database tables any changes in the database table will
invalidate the cached data object which can be a dataset or a data source.

(B) What is cross page posting?

Note :- This is a new feature in ASP.NET 2.0 By default, button controls in


ASP.NET pages post back to the same page that contains the button, where
you can write an event handler for the post. In most cases this is the desired
behavior, but occasionaly you will also want to be able to post to another
page in your application. The Server.Transfer method can be used to move
between pages, however the URL doesn't change. Instead, the cross page
posting feature in ASP.NET 2.0 allows you to fire a normal post back to a
different page in the application. In the target page, you can then access the
values of server controls in the source page that initiated the post back. To
use cross page posting, you can set the PostBackUrl property of a Button,
LinkButton or ImageButton control, which specifies the target page. In the
target page, you can then access the PreviousPage property to retrieve
values from the source page.
(B) What is Query String and What are benefits and limitations of using Query
Strings?

A query string is information sent to the server appended to the end of a


page URL.
Following are the benefits of using query string for state management:-

No server resources are required. The query string containing in the HTTP
requests for a specific URL.
All browsers support query strings. Following are limitations of query
string : Query string data is directly visible to user thus leading to security
problems. Most browsers and client devices impose a 255-character limit on URL
length. Below is a sample Login query string passed in URL
http://www.querystring.com/ login.asp?login=testing. This query string data
can then be requested later by using Request.QueryString(login).
(I) Whats the difference between Cache object and application object ?

The main difference between the Cache and Application objects is that the
Cache object provides cache-specific features, such as dependencies and
expiration policies.
(I) How can get access to cache object ?

The Cache object is defined in the System.Web.Caching namespace. You can


get a reference to the Cache object by using the Cache property of the
HttpContext class in the System.Web namespace or by using the Cache
property of the Page object.
(I) What are benefits and limitations of using Cookies?

Following are benefits of using cookies for state management : No server resources are required as they are stored in client.
They are light weight and simple to use Following are limitation of using
cookies : Most browsers place a 4096-byte limit on the size of a cookie, although
support for 8192-byte cookies is becoming more common in the new browser
and client-device versions available today.
Some users disable their browser or client devices ability to receive
cookies, thereby limiting the use of cookies.
Cookies can be tampered and thus creating a security hole.
Cookies can expire thus leading to inconsistency. Below is sample code of
implementing cookies Request.Cookies.Add(New HttpCookie(name, user1))
(A) What are dependencies in cache and types of dependencies ?

When you add an item to the cache, you can define dependency
relationships that can force that item to be removed from the cache under
specific activities of dependenci es.Example if the cache object is dependent
on file and when the file data changes you want the cache object to be
update. Following are the supported dependency : File dependency :- Allows you to invalidate a specific cache item when a
disk based file or files change.
Time-based expiration :- Allows you to invalidate a specific cache item
depending on predefined time.
Key dependency :-Allows you to invalidate a specific cache item depending
when another cached item changes.
(A) Is Session_End event supported in all session modes ?

Session_End event occurs only in Inproc mode.State Server and SQL


SERVER do not have Session_End event.

XML
(B) What is XML?

XML (Extensible markup language) is all about describing data. Below is a


XML which describes invoice data.
An XML tag is not something predefined but it is something you have to
define according to your needs. For instance in the above example of invoice
all tags are defined according to business needs. The XML document is self
explanatory, any one can easily understand looking at the XML data what
exactly it means
(B) What is ROOT element in XML?

In our XML sample given previously <invoice></invoice> tag is the root


element. Root element is the top most elements for a XML.
(B) If XML does not have closing tag will it work?

No, every tag in XML which is opened should have a closing tag. For instance
in the top if I remove </discount> tag that XML will not be understood by lot
of application.427
(B) Is XML case sensitive?

Yes, they are case sensitive.

(B) What is the difference between XML and HTML?

XML describes data while HTML describes how the data should be displayed.
So HTML is about displaying information while XML is about describing
information.
(B) Is XML meant to replace HTML?

No, they both go together one is for describing data while other is for
displaying data.
(B) What is DTD (Document Type definition)?

It defines how your XML should structure. For instance in the above XML we
want to make it compulsory to provide qty and totalcost, also that these
two elements can only contain numeric. So you can define the DTD document
and use that DTD document with in that XML.
(B) What is well formed XML?

If a XML document is confirming to XML rules (all tags started are closed,
there is a root element etc) then its a well formed XML. 428
(B) What is a valid XML?

If XML is confirming to DTD rules then its a valid XML.


(B) What is CDATA section in XML?

All data is normally parsed in XML but if you want to exclude some elements
you will need to put those elements in CDATA.
(B) What is CSS?

With CSS you can format a XML document.

(B) What is XSL?

XSL (the eXtensible Stylesheet Language) is used to transform XML document


to some other document. So its transformation document which can convert
XML to some other document. For instance you can apply XSL to XML and
convert it to HTML document or probably CSV files.
(B) What is element and attributes in XML?

In the below example invoice is the element and the invnumber the attribute.
<invoice invnumber=1002></invoice>

(B) Which are the namespaces in .NET used for XML?

System.xml.dll is the actual physical file which has all XML implementation.
Below are the commonly used namespaces:- System.Xml
System.Xml.Schema System.Xml.XPath System.Xml.Xsl
(B) What are the core functionalities in XML .NET framework? Can you explain in
detail those functionalities?

The XML API for the .NET Framework comprises the following set of
functionalities:434
XML readers With XML readers the client application get reference to
instance of reader class. Reader class allows you to scroll forward through the
contents like moving from node to node or element to element. You can
compare it with the SqlDataReader object in ADO.NET which is forward only.
In short XML reader allows you to browse through the XML document.
XML writers Using XML writers you can store the XML contents to any other
storage media. For instance you want to store the whole in memory XML to a
physical file or any other media.
XML document classes XML documents provides a in memory
representation for the data in an XMLDOM structure as defined by W3C. It
also supports browsing and editing of the document. So it gives you a
complete memory tree structure representation of your XML document.
(B) What is XSLT?

XSLT is a rule based language used to transform XML documents in to other


file formats. XSLT are nothing but generic transformation rules which can be
applied to transform XML document to HTML, CS, Rich text etc.
(B) What is an XMLReader Class?

It is an abstract class available from System.XML namespace. XML reader


works on a read-only stream browsing from one node to other in a forward
direction. It maintains only a pointer to the current node but has no idea of
the previous and the next node. You can not modify the XML document, you
can only move forward.
(B) What is XMLTextReader?

The XmlTextReader class helps to provide fast access to streams of XML


data in a forward-only and read-only manner. It also checks if the XML is wellformed. But XMLTextReader does not validate against a schema or DTD for
that you will need XmlNodeReader or XmlValidatingReader class.

(I) What are XML namespaces for?


They're for allowing multiple markup languages to be combined, without having to worry about
conflicts of element and attribute names.
For example, look at any bit of XSLT code, and then think what would happen if you didn't use
namespaces and were trying to write an XSLT where the output has to contain "template", "foreach", etc, elements. Syntax errors, is what.
I'll leave the advice and pitfalls to others with more experience than I.

(A) Can you explain why your project needed XML?

Note: - This is an interview question where the interviewer wants to know


why you have chosen XML. Remember XML was meant to exchange data
between two entities as you can define your user friendly tags with ease. In
real world scenarios XML is meant to exchange data. For instance you have
two applications who want to exchange information. But because they work
in two complete opposite technologies its difficult to do it technically. For
instance one application is made in JAVA and the other in .NET. But both
languages understand XML so one of the applications will spit XML file which
will be consumed and parsed by other applications You can give a scenario of
two applications which are working separately and how you chose XML as the
data transport medium.

SILVERLIGHT

1. What is Microsoft Silverlight?

Silverlight is a web based technology, launched by Microsoft in April 2007.


Silverlight is considered as a competitor to Adobe's Flash.
Silverlight is Microsoft's implementation of a cross-browser, cross-platform
client framework that allows designers and developers to deliver Rich Internet
Applications (RIA) embedded in Web pages.
Silverlight is a browser plug-in approximately 6MB in size; it is client-side free
software, with an easy and fast (less than 10 sec) one time installation available for
any client side browser.
It supports advanced data integration, multithreading, HD video using IIS
Smooth Streaming, and built-in content protection. Silverlight enables online and
offline applications for a broad range of business and consumer scenarios.
One of the design goals of the Silverlight technology is to fill the gap between
Windows applications and Web applications in terms of creating Graphical User
Interfaces (GUI).
Silverlight applications are run as client-side applications without the need to
refresh the browser to update the UI. However, because of the built-in .NET

framework, Silverlight applications can easily integrate with server-side controls and
services. Using Silverlight's implementation of the .NET framework, developers can
easily integrate existing libraries and code into Silverlight applications.

2. Why use Silverlight?

Support for the .NET Framework if you are already a .NET developer, it is
easy to start programming on Silverlight.
Support for managed code you can write programs in your favorite language
which .NET CLR supports like C#, VB.NET, dynamic languages (IronPython,
IronRuby).
Better development tools -Visual Studio 2010, Expression Blend.
Large community- More learning resources available compared to Flash.
Integration with Enterprise based technologies like WPF, LINQ etc
Silverlight integrates the XAML declarative language with the .NET framework.
It is a cross-browser, cross-platform technology which provides a consistent
user experience everywhere it runs.
The Silverlight plug-in installs in seconds, and leaves a very small footprint.
After you install the plug-in, users no longer need to install anything on their
workstations to run Silverlight applications. The applications are available to them
from whatever browser they are accessing.
It runs a client-side application that can read data and update the UI without
interrupting the user by refreshing the whole page.
It can run asynchronous communications with the server, allowing the UI to
continue to function while waiting for the server response.
It delivers rich video, audio, and graphics.

3. Which platforms does Silverlight


support?

Mac OS
Windows Vista
Windows XP SP2
Windows 2000
Windows Server 2003
Linux (Moonlight)

4. Which browsers does Silverlight


support?

Microsoft - Internet Explorer 6, 7, 8


Mozilla - Firefox 2 and 3
Apple - Safari 3 and 4
Google - Chrome

5. What are the system requirements


for Silverlight?
The system requirements for Microsoft Silverlight and associated technologies are
listed below.

Windows
Operating System: Windows 7, Windows Vista, Windows XP Service Pack 2
Intel Pentium III 450MHz or faster processor (or equivalent)
128MB of RAM

Mac OS
Operating System: Apple Mac OS X 10.4.8 or above
Intel Core Duo 1.83GHz or faster processor
128MB of RAM
Linux

Moonlight

6. What is Moonlight?
Moonlight is an Open Source implementation of Silverlight, primarily for Linux and
other Unix/X11 based Operating Systems. In September of 2007, Microsoft and
Novell announced a technical collaboration that includes access to Microsoft's test
suites for Silverlight and the distribution of a Media Pack for Linux users that will
contain licensed media codecs for video and audio.
Moonlight 2 was released December 17, 2009

7. What are the goals of Moonlight?

To run Silverlight applications on Linux.


To provide a Linux SDK to build Silverlight applications.
To reuse the Silverlight engine built for desktop applications.

8. Is Silverlight free?
Yes, Microsoft has made the Silverlight browser plug-in freely available for all
supported platforms and browsers.

9. What is the difference between


Silverlight 1.0 and 2?

Silverlight 1 is purely AJAX and JavaScript based. All the code has to be written
in JavaScript and XAML.
Silverlight 2 supports managed code. When the Silverlight 2 runtime is
installed, it installs a limited version of the .NET runtime on the client machine. This
allows .NET programmers to write managed code to be executed on the client PC,
and provides a better user experience to users. Of course, there is security
restrictions built in to it so that the code has limited access to the client computer.
The biggest change is the implementation of the .NET Framework. If you are
familiar with Silverlight 1.0, then you will be used to coding the application
functionality in JavaScript. You can still implement functionality using JavaScript;
however, you can now also implement functionality using C#, Visual Basic, Python,
Ruby, and managed JavaScript.
Another major change is the introduction of the XAP package. In Silverlight
1.0, the XAML code was referenced directly by the Silverlight object embedded in the
browser. In Silverlight 2, however, the embedded object references an XAP package
that contains the XAP file, assemblies, and resources necessary to run the Silverlight
application.

10. What is the Silverlight plug-in?

The Silverlight plug-in is a very lightweight component that is necessary for


users to access Silverlight applications. The plug-in download and install takes only a
few moments, and do not take up much hard drive space.
The Silverlight plug-in is responsible for accessing the Silverlight object in the
Web page, downloading and accessing the XAP package, setting up the program
environment, and beginning execution of the application.
When a Web page containing a Silverlight application is displayed, the user
should be given a link to download the plug-in from Microsoft if the plug-in is not
already installed.

11. What is Silverlight Runtime?


Silverlight Runtime is a browser plug-in to support Silverlight enabled applications. If
the Silverlight runtime is not installed, browsers will not be able to run Silverlight
elements in the browser. You can set up your Silverlight tags in such a way that your
browser will automatically prompt the user to download and install the Silverlight
plug-in when your application is launched in the browser.
Installing the run time is a onetime operation on the client. Once installed, it will be
automatically launched when any Silverlight application is loaded in the browser.
Note: Silverlight plug-in and the runtime, both are the same; however, I am giving
two definitions here.

12. What is Silverlight SDK?


Silverlight SDK is a set of tools, documentation, samples, and templates for web
developers to enable them to easily develop Silverlight enabled applications. The

SDK is not really mandatory to develop Silverlight applications; however, the SDK will
make development much easier.

13. What are the tools required to


develop Silverlight applications?
To run Silverlight applications in a web browser, you need to have the Silverlight
runtime installed on the client browser as a plug-in. This is a light-weight version of
the .NET runtime.
However, to develop a Silverlight application, you need something more.
Silverlight SDK: This includes a set of tools required to compile and build Silverlight
controls.
If you are comfortable writing HTML using Notepad and compiling .NET applications
from console tools, then you just need the Silverlight SDK to develop Silverlight
applications.
However, most people use some kind of IDE to develop applications faster.
Microsoft offers two separate tools to develop Silverlight applications:

Microsoft Expression Studio - This tool is meant for web designers to


create rich visual elements for Silverlight applications. Expression Studio is
recommended for web designers who create rich internet applications with enhanced
visual content and graphics. There are several features provided for creating
enhanced graphics elements, with lot of options to pick color, font, etc.
Microsoft Visual Studio - This is the integrated development environment
from Microsoft to develop .NET applications. Programmers can use Visual Studio to
develop Silverlight applications which require programming. Visual Studio allows
programmers to develop sophisticated Silverlight applications in any .NET language
(like C#, VB.NET etc).
Here are some other tools that you can use:
Install Deep Zoom Composer - This tool allows you to prepare your images
for use with the Deep Zoom feature in Silverlight 3.
Download Silverlight Toolkit - This toolkit is a Microsoft project containing
Silverlight controls, components, and utilities that can be downloaded and used in
your Silverlight applications. It includes full source code, samples, and tests.
Download .NET RIA Services - Microsoft .NET RIA Services simplifies the
traditional n-tier application pattern by bringing together the ASP.NET and Silverlight
platforms. RIA Services provides a pattern to write application logic that runs on the
mid-tier and controls access to data for queries, changes, and custom operations.

14. Which tool to use - Expression


Studio or Visual Studio?
If your Silverlight application includes just graphics and visual elements, then you
can use Expression Studio. However, if you are a programmer and if your Silverlight

application includes programming logic, then you might want to choose Visual
Studio.

15. What are the Silverlight versions


available so far?

Silverlight 1.0: Silverlight 1.0, which was developed under the codename
Windows Presentation Foundation/Everywhere (WPF/E), consists of the core
presentation framework which is responsible for the user interface (UI), interactivity,
and user input, basic UI controls, graphics and animation, media playback, Digital
Restrictions Management (DRM), and DOM integration
Silverlight 2: Silverlight 2 (previously referred to as version 1.1) includes a
version of the .NET Framework, implementing the same full Common Language
Runtime (CLR) version as .NET Framework 3.0. The XAML markup as well as the code
is compiled into .NET assemblies which are then compressed using Zip and stored in
a .xap file.
Silverlight 3: Silverlight version 3 was released in July 9, 2009, which is an
extension to Silverlight 2.0, and mainly provides improvements in graphics
capabilities, media management, application development areas (additional controls,
enhanced binding support, and out-of-browser functionality), and integration in the
designers' Expression Blend 3 tools.
Silverlight 4: Silverlight version 4 was released on April 15, 2010 (along
with Silverlight 4 tools for developers).

16. What is a .xap file?

A .xap file is a Silverlight-based application package (.xap) that is generated when


the Silverlight project is built. A.xap file is the compressed output file for a Silverlight
application. The .xap file includes AppManifest.xaml, the compiled output assembly
of the Silverlight project (.dll), and the resource files referred to by the Silverlight
application:
Web pages like .aspx files and .html files use Silverlight components by
loading .xap files using the<object> tag in HTML or by using the <asp:Silverlight> tag
in ASP.NET pages.
".xap" files (pronounced "zap") use the standard Zip compression algorithm to
minimize client download size.
Rename this file to SilverlightTest.zip and open it using any decompression tool. You
can see that this is just like any other zip file, and it includes the project's output DLL
and another file called "AppManifest.xaml".

17. How does XAP work?


Once you have created the .xap file (explained below), the Silverlight 2 plug-in
downloads the file and runs it in a separate work space.

18. How do I use a .xap file?

A .xap file is used to contain and transfer the assemblies and resources of a
managed code application. This managed code application must be run within the
Silverlight 2 browser plug-in.

19. Can we add a reference to a Class


Library project in a Silverlight
application project?
No, you can't add a reference to a Class Library project to a Silverlight application
project. You can only add the reference of another Silverlight application project
inside a Silverlight application project.
However, you can add a reference to a Web Service or WCF Service.

20. What is a Silverlight.js file?


Silverlight.js is a helper file which enables websites to create advanced Silverlight
installation and instantiation experiences. You can call
the createObject and createObjectEx functions defined in this file to embed the
Silverlight plug-in in a web page.

21. What is the use of the ClientBin


folder?
The ClientBin folder is used to place the .xap file of a Silverlight application. You can
keep it anywhere in your web application, but this is the default location used by
Silverlight.

22. How to change the default page of


a Silverlight application?
To change the default page of a Silverlight application, you need to set
the RootVisual property inside theApplication_Startup event of the App.xaml file.
Collapse | Copy Code

private void Application_Startup(object sender, StartupEventArgs e)


{
this.RootVisual = new MainPage();
}

23. What is XAML?


XAML stands for eXtended Application Markup Language. XAML contains XML that is
used to declaratively specify the user interface for Silverlight or WPF applications.
For example, if you need to display a rectangle, this is the XAML you need to use:
Collapse | Copy Code

<UserControl x:Class="SilverlightApplication1.SilverlightControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas Width="500" Height="500" Background="White">
<Rectangle Canvas.Left="75" Canvas.Top="90"
Fill="red" Width="100" Height="100" />
</Canvas>
</UserControl>
Output:

When the above XAML is executed, it will display a rectangle filled with red color. You
may notice that XAML is very similar to HTML in nature.
XAML stands for eXtensible Application Markup Language, and is a declarative
markup language that follows the XML rule and is used for developing User
Interfaces in WPF and Silverlight technology. XAML files are XML files that generally
have the .xaml extension, and separates the UI definition from the run-time logic by
using code-behind files, joined to the markup through partial class definitions.
XAML has a set of rules that map object elements into classes or structures,
attributes into properties or events, and XML namespaces to CLR namespaces. XAML
elements map to Microsoft .NET types as defined in referenced assemblies, and the
attributes map to members of those types.

24. What is the AppManifest.xml file?


First, lets look at an example AppManifest.xaml file:
Collapse | Copy Code

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
EntryPointAssembly="SilverlightApplication1"
EntryPointType="SilverlightApplication1.App"
RuntimeVersion="2.0.30226.2">
<Deployment.Parts>
<AssemblyPart x:Name="SilverlightApplication1"
Source="SilverlightApplication1.dll" />

<AssemblyPart x:Name="System.Windows.Controls"
Source="System.Windows.Controls.dll" />
<AssemblyPart x:Name="System.Windows.Controls.Extended"
Source="System.Windows.Controls.Extended.dll" />
</Deployment.Parts>
</Deploymnt>

The first element in AppManifest.xaml is a Deployment node. This node defines the
application, and contains the child AssemblyPart nodes.
As you can see the AssemblyPart nodes define what assemblies (DLLs) are
contained within the .xap file, and give each of them a name.
Now, if you look back up to the top, you'll see the Deployment node has
the EntryPointAssembly andEntryPointType attributes.
The EntryPointAssembly attribute defines which assembly defined below (as a
child AssemblyPart node) is the main assembly (DLL) for the application. And,
the EntryPointType attribute specifies the class contained within the assembly (DLL),
defined in the EntryPointAssembly attribute, is the main class that will be
instantiated to start the application.
The Deployment node also has a RuntimeVersion attribute that defines the version
of Silverlight the application is built for.

25. What files are contained within


the .xap file?
The .xap file contains an application manifest (AppManifest.xaml) file and all the
necessary DLLs that are required by the application. The first DLL contained is the
compiled version of your application and has the same name of your application. In
my test, I created an application named "SilverlightApplication1", so the DLL is
named "SilverlightApplication1.dll". The rest of the DLLs are the dependencies the
application requires.

26. What is app.xaml?


App.xaml is a file used by Silverlight applications to declare shared resources like
brushes, various style objects, templates etc. Also, the code-behind file
of app.xaml.cs is used to handle global application level events
likeApplication_Startup, Application_Exit,
and Application_UnhandledException (similar to theGlobal.asax file for ASP.NET
applications).
When Visual Studio creates the app.xaml file automatically, it creates a few event
handlers with some default code. You can change the code appropriately.
Collapse | Copy Code

private void Application_Startup(object sender, StartupEventArgs e)


{
}
private void Application_Exit(object sender, EventArgs e)

{
}
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{
}

For ASP.NET developers, the above code will look familiar. This is similar to the
application level event handlers inGlobal.asax.

27. What is the Silverlight official


name?
Silverlight was formerly code-named "WPF/E".

28. What are the main features and


benefits of Silverlight?

Compelling cross-platform user experiences.


Flexible programming model with collaboration tools.
High-quality media, low-cost delivery.
Connected to data, servers, and services.

29. What is MainPage.xaml?


When you create a Silverlight project using Visual Studio, it creates a default XAML
file called "MainPage.xaml". This is just a dummy start page created by Visual Studio,
and it does not contain any visible UI elements. The default contents of
the MainPage.xaml file looks like this:
Collapse | Copy Code

<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>

30. Which language is Silverlight


developed in?
It was developed using a combination of C# and C++.

31. Can I consume WCF and ASP.NET


Web Services in Silverlight?
Yes, you can.

32. What are Deep Zoom and Deep


Zoom Composer?
Deep Zoom provides the ability to interactively view high-resolution images in
Silverlight. You can zoom in and out of images rapidly without affecting the
performance of your application. Deep Zoom provides smooth in-place zooming and
panning.
DeepZoom Composer allows you to create high resolution image compositions which
are built for smooth zooming and panning. DeepZoom Composer is absolutely free,
and is simple to use - just loads in all your high resolution images and makes your
composition on screen.
Deep Zoom Composer is a tool that allows preparing of images for use with the Deep
Zoom feature in Silverlight 3.

33. What is the difference between


WPF and Silverlight?
Silverlight and Windows Presentation Foundation (WPF) are two different products
from Microsoft, but have lot of overlap. Silverlight is a subset of WPF in terms of
features and functionality.
Silverlight is a Microsoft technology, competing with Adobe's Flash, and is meant for
developing rich browser based internet applications.
WPF is a Microsoft technology meant for developing enhanced graphics applications
for the desktop platform. In addition, WPF applications can be hosted on web
browsers which offer rich graphics features for web applications. Web Browser
Applications (WBA) developed on the WPF technology uses XAML to host user
interfaces for browser applications. XAML stands for eXtended Application Markup
Language, which is a new declarative programming model from Microsoft. XAML files
are hosted as discrete files in the Web server, but are downloaded to the browsers
and converted to a user interface by the .NET runtime in the client browsers.

WPF runs on the .NET runtime, and developers can take advantage of the rich .NET
Framework and WPF libraries to build really cool Windows applications. WPF supports
3-D graphics, complex animations, hardware acceleration etc.
Silverlight uses a particular implementation of a XAML parser, with that parser being
part of the Silverlight core installation. In some cases, the parsing behavior differs
from the parsing behavior in Windows Presentation Foundation (WPF), which also has
a particular implementation.
In table format:
Silverlight

WPF

Definition

Silverlight is Microsofts latest


development platform for building
next-generation Web client
applications.

Windows Presentation
Foundation (WPF) is Microsofts
latest development platform
for building next-generation
Windows client applications.

Subset of

Silverlight is generally considered to


be a subset of WPF, and is a XAMLbased technology that runs within
the sandbox of a browser plug-in.

WPF is generally considered to


be a subset of .NET
Framework, and is a XAML
based technology.

GUI

Silverlight will be used in the


development of Rich Internet
Applications (RIA) for web client
users.

WPF will be used in the


development of Rich Windows
Graphical User Interfaces (GUI)
for Windows client users.

Support

Cross OS, cross browser, cross


device.

Windows only.

Software
Required

Silverlight is the add-on mechanism


available for most browsers; in order
to run Silverlight applications at
client machines, we need to install
Silverlight software on the client
machine once.

WPF, on the other hand, does


not support any plug-in
mechanism; instead, we need
to install a completed WPF
client application in order to
use the WPF application at the
client place.

Framework
support

Silverlight has a very small, its own


rich base class library to make the
plug-in as small as possible. It is
highly optimized for size, and is a
small subset of the full .NET
Framework, to be embedded within

WPF, on the other hand, has


full access to the main .NET
Framework and all its
associated assemblies.

Silverlight

WPF

an application.
Deployment Silverlight applications are hosted
within a web server and a web page.
To minimize client download size,
Silverlight uses a XAP archive. A XAP
archive is a zip-compressed archive
of the Silverlight application, plus a
manifest file describing the content.
Visual Studio automatically
generates the XAP archive when
using the Silverlight project
template.

WPF applications can be


deployed as standalone
applications, ClickOnce
applications, or XAML browser
applications.

34. What is the difference between


Silverlight and Flash?
Adobe Flash is the most popular competitor to Silverlight, supporting browser plugins and enabling the execution of rich content for the Web. Flash is not a new
technology, and already has had a long life span as compared to Silverlight. But it
does not have a huge community as expected; it may be because of the limited
development tools which are not known to most developers. Flash
uses ActionScript as the programming language and Flex as the programming
environment, and most developers are far from these technologies.
For ASP.NET developers, to extend their websites using Flash content is not so
simple. They need to learn a development environment like ActionScript and Flex.
Apart from that, there is no way to generate Flash content using server-side .NET
code, which means its difficult to integrate ASP.NET content and Flash content.
Silverlight aims to give .NET developers a better option for creating rich web content.
Silverlight provides a browser plug-in with many similar features to Flash, but one
thats designed from the ground up for .NET. Silverlight natively supports the C#
language, and uses a range of .NET concepts. As a result, developers can write
client-side code for Silverlight in the same language they use for server-side code
(such as C# and VB), and use many of the same abstractions (including streams,
controls, collections, generics, and LINQ).

35. What is the difference between


Silverlight and ASP.NET AJAX?
Microsoft ASP.NET AJAX, a set of JavaScript libraries built into ASP.NET 3.5, is
available as a separate download for ASP.NET 2.0. Being an integral part of ASP.NET

3.5 and the AJAX Controls Toolkit for ASP.NET 3.5, now ASP.NET AJAX client-and
server-side libraries are more integrated with Visual Studio 2008. The client-side
library allows you to implement client-level processing such as processing and
validating information entered by the end user, refreshing a portion of the web page,
and developing rich, interactive user interfaces. You can also efficiently integrate the
client-side library components with the server-side ASP.NET controls library in
asynchronous mode. The key technology driver of ASP.NET AJAX is scripting. In
general, script-based web applications face several challenges due to different
browser settings (e.g., JavaScript is not enabled by default) on PCs and mobile
devices. As a result, scripting is often not always the best strategy for enterprises to
use to develop secure and scalable RIAs.
ASP.NET AJAX supports limited features of RIAs, and does not support effective
multimedia integration, managed code-behind integration, or metadata and
information management. Microsoft ASP.NET AJAX is a widely accepted model for
building RIAs, but it is very likely that, having Silverlight as an option, .NET
developers will migrate ASP.NET AJAX applications to Silverlight RIAs.
Visit www.asp.net/ajax/ if you want to learn more about Microsoft ASP.NET AJAX.

36. What are the different Layout


controls available in Silverlight?
There are three different types of Layout controls provided by Silverlight:

Canvas - Position child elements absolutely in x, y space.


StackPanel - Position child elements relative to one another in horizontal or

vertical stacks.
Grid - Position child elements in rows and columns.
You have to add a layout panel to every XAML page you create. All other UI elements
must be added inside one of the layout panels. Each page can have exactly one
layout panel control.

37. Are XAML files compiled or built at


runtime?
XAML files are usually compiled rather than parsed at runtime. But it also supports
parsing during runtime. When we build a XAML based project, you will see it creates
a g.cs extension in the obi\Debug folder. Therefore, for every XAML file, you will find
a g.cs file. For instance, a MainPage.XAML will have a MainPage.g.cs file in
theobi\Debug folder. In short, at run time, you actually do not see the XAML file. But
if you want to do runtime parsing of the XAML file, it also allows that to be done.

38. What is the long-term goal or vision


for Silverlight?

Microsoft Silverlight is a cross-browser, cross-platform, and cross-device plugin for delivering the next generation of .NET based media experiences and rich
interactive applications for the Web.
Silverlight offers a flexible programming model that supports AJAX, VB, C#,
IronPython, and IronRuby, and integrates with existing Web applications.
By using Expression Studio and Visual Studio, designers and developers can
collaborate more effectively using the skills they have today to light up the Web of
tomorrow.
By leveraging Silverlight's support for .NET, High Definition video, costeffective advanced streaming, unparalleled high-resolution interactivity with Deep
Zoom technology, and controls, businesses can reach out to new markets across the
Web, desktop, and devices.

39. Do I need to have the .NET


Framework installed in order to use
Silverlight?
The answer to this is no - a cross platform version of the .NET Framework is included
in the 6 MB Silverlight 4 download, which means you do not need to have anything
extra installed on the client in order to access Silverlight applications in the browser.
The Silverlight version of the .NET framework includes the same CLR engine (same
GC, type-system, JIT engine) that ships with the full .NET Framework, and a subset of
the .NET Framework namespace libraries. You can see the full list of all
classes/namespaces that are included by opening up the Object Browser when you
create a new Silverlight application using Visual Studio.

40. What are the other RIA


technologies besides Silverlight?
Adobe Flex, Java FX, Adobe Flash are some of the other RIA technologies besides
Silverlight.

41. What is meant by RIA?


RIA stands for Rich Internet Applications, which are Web applications with rich user
interfaces including media elements such as audio, video etc. You can think of them
as being similar to powerful and rich desktop applications, except that RIA
applications are Web based.

42. What is .NET RIA Services?


Microsoft .NET RIA Services helps to simplify the n-tier application pattern by
combining the ASP.NET and Silverlight platforms. RIA Services provides a pattern
using which you can write application logic that can run on the mid-tier and controls
access to data for queries, changes, and custom operations. It also provides support
for data validation, authentication, and roles by integrating with Silverlight
components on the client and ASP.NET on the middle tier.

43. What are the design files and the


code-behind files in Silverlight?
The user interface elements of Silverlight applications are defined in XAML files. The
logic and functionality of Silverlight applications is implemented using managed NET
code-behind files that share the same class with the XAML file.

44. Who is using Silverlight?


Yahoo! Japan, NBC, Continental Airlines, NASA, Indian Premier League, and National
Instruments are some of the organizations currently using Silverlight to enhance
their businesses.

45. What features are missing from


Silverlight presentation markup that
will be supported in WPF?
Some high-end Windows specific features of WPF, such as real 3D, hardware-based
video acceleration, and full document support, will not be supported in Silverlight.
This is by design in order to serve Silverlights cross-browser, cross-platform reach
scenario that demands a light weight plug-in. That being said, Silverlight will offer a
uniform runtime that can render identical experiences across browsers on both Mac
OS and Windows.

46. Will I need more memory, a faster


processor, or a better Graphics
Processing Unit (GPU)?

Microsoft designed Silverlight with the ability to deliver high-fidelity experiences on


the broadest set of system configurations. Some features, such as HD video, may
benefit from the power contained in newer personal computers.

47. How does Silverlight make the


Microsoft development system better?
Silverlight is a cross-browser, cross-platform plug-in for delivering the next
generation of media experiences and rich interactive applications (RIAs) for the Web.
Examples include:

For ASP.NET-based Web applications, Silverlight provides a rich UI front-end


that, with a consistent programming model, adds support for richer interactivity,
media, and audio.
For Microsoft SharePointbased content, Silverlight offers the ability to create
rich Web Parts.
For Windows Live services, Silverlight offers the ability to consume services
and APIs more effectively.

48. What is the relationship and


difference between Silverlight and
ASP.NET?
Technically, Silverlight and ASP.NET are completely different. The major differences
are listed below:

Silverlight runs completely on the client, while ASP.NET mainly runs on the
server, but also has a few parts running on the client.
When an event fires, Silverlight handles the event on the client, but in
ASP.NET, the browser will make an HTTP POST to the server, and after the server
handles the request, it sends a new HTML page to the client.
A Silverlight application sends rendering commands to the Silverlight
rendering engine by either writing XAML or code, and the Silverlight rendering
engine will handle the rendering task. On the other hand, ASP.NET doesnt have a
rendering engine. It generates an HTML file on the server, sends it to the client, and
allows the browser to parse the HTML file and render the content.
Silverlight cant work with a database directly; instead, it consumes data from
Web Services, while ASP.NET has strong support for working with databases directly.
The most important thing to note is what runs on the client and what runs on the
server, since this will affect almost every part of your system. Silverlight runs on the
client, and ASP.NET runs on the server. They can work together and are compatible
with each other, but this requires some time and effort.

49. When to use Silverlight, ASP.NET, or


both?
This depends on different scenarios. Below are some common approaches:

Pure Silverlight
One approach is to completely remove ASP.NET. This solution works best if youre
working on a new development. You only need to work on Silverlight, without any
worry about integration problems. If you need to communicate with the server, you
write Web Services, such as WCF. It will also help you when you need to port part or
whole of your system to another hosting or even another platform, since the client
and the server are completely separate.

Major ASP.NET, plus a Silverlight island


This approach is generally used when the Silverlight content and the ASP.NET
content have little relationship. For example, an ASP.NET blog engine with a
Silverlight media player in a blog post. This approach is very easy to implement, and
allows you to reach the broadest audience. For example, if a user hasnt installed
Silverlight, he can still read the blog posts, but he cant watch the videos.

Use ASP.NET AJAX instead of Silverlight


ASP.NET AJAX is designed to work with ASP.NET. It is mainly an extension to ASP.NET.
While AJAX cant provide you the advanced user experience that Silverlight can, for
many scenarios, it should be sufficient. This approach also helps if you have strong
ASP.NET experience, but are still quite new to Silverlight.

Within this approach, there are two branches. One is to mix the client and server
code by using theUpdatePanel, AJAX Control Toolkit, and etc. The other method is to
take the pure AJAX approach, where you write HTML and JavaScript instead of using
server controls, and call Web Services to communicate with the server. The former
branch is easier to implement, especially if you have strong ASP.NET experience but
lack JavaScript knowledge. The latter branch proves to be better in an architecture
when you want to port an AJAX application to other technologies such as Silverlight,
especially since you only need to rewrite the client side code, and can keep the Web
Services as they are. The programming model for the latter branch is similar to
Silverlight. Therefore, this approach is rarely taken if youre experienced in
Silverlight.
Mix Silverlight with ASP.NET
More often, you may want to port an existing ASP.NET application to Silverlight, but
you dont want to completely rewrite the entire application. This is the most difficult
approach since youre mixing client side and server side technologies.
Before going with this approach, please consider if the above approaches can solve
your problem. Ask yourself the following questions:

1.

Do you really need a rich interactive user experience?

This is normally a requirement for consumer oriented applications, but for most
business applications, you only need a good user experience, which AJAX is
sufficient to provide.
2.

Can you add Silverlight islands to your existing ASP.NET application


instead of mixing the contents?
This should work for most scenarios. For example, Windows Live Mail is built in
ASP.NET, with a few Silverlight islands, such as a slideshow program that allows you
to view photo attachments with enhanced experience (actually, most Microsoft
created web applications take this approach).

3.

Will this be a good chance to revise your architecture?


Most traditional ASP.NET applications use the B/S or three tire architecture in which
the application works with a database either directly or through a business logic
layer. When porting applications to other platforms, these architectures will introduce
many problems. When investigating Silverlight, it is also a good chance to adopt
SOA. Add a service facade layer on top of the business logic layer, and you can work
with the services from almost any client, such as an ASP.NET application and a
Silverlight application. If you are already on SOA, it should be trivial to port to
Silverlight, since you only need to rewrite a client application. With SOA, the ASP.NET
AJAX approach and the Silverlight island approach will also be much easier to
implement.
If none of the above approaches is suitable, you may have to mix Silverlight content
with ASP.NET. When using this approach, keep in mind that Silverlight cant call
ASP.NET server-side event handlers, and each post back (either partial or complete)
will cause the Silverlight application to reload.

50. What are the new features of


Silverlight 4?

Support for Google's Chrome browser.


Web cam and microphone support.
Printing support.
Full keyboard access while running in full-screen mode.
Programmatic access to a user's local document folder.
Improved mouse support, including right button support and mouse wheel
support.
Elevated trust and support for local Component Object Model (COM) objects.
New notification support to display messages to end users.
New and enhanced controls such as a RichTextBox and an
enhanced DataGrid control.
New support for implicit theming of controls.
New hosted browser support for rendering HTML inside Silverlight.
WCF data layer enhancements.
Localization enhancements with bi-directional text.
Support for Managed Extensibility Framework.
Enhanced data binding support.

Enhanced animation effects.


Clipboard and drag and drop support.
Deep Zoom performance enhancements.
WCF Rich Internet Application (RIA) Services.
Content protection for H.264, and support for playing offline DRM protected
media.

WCF

What is service ?
A service is a unit of functionality exposed to the world. Service orientation (SO) is an
abstract set of principles and best practices for building service-oriented
applications.

What do you mean by client ?


The client of a service is the program unit consuming its functionality. The client can
be literally anythingfor instance, Console application, Windows Forms, WPF, or
Silverlight class, anASP.NET page, or another service.

What is WCF ?

Stands for Windows Communication Foundation.


Its code name is Indigo.
It is a framework for building, configuring and deploying interoperable
distributed services.
It enables you to write more secure flexible services without any code change
(using configuration).
It also provide built-in support for logging. You can enable/disable logging
using configuration.
WCF = Web Service + Remoting + MSMQ + COM+
or
WCF = ASMX + .Net Remoting + WSE + Messaging + Enterprise Services

What are the transport schemes


supported by WCF ? Give example of
address for each scheme.

Following are the transport schemes supported by WCF:

HTTP/HTTPS - http://localhost:8001/MyService
TCP - net.tcp://localhost:8002/MyService
IPC - net.pipe://localhost/MyPipe
Peer network
MSMQ - net.msmq://localhost/private/MyQueue
Service bus - sb://MyNamespace.servicebus.windows.net/

What is Contract ? What are the types


of Contract ?
It is the agreement between client and service which specifies:

[ServiceContract] - which services are exposed to the client.


[OperationContract] - which operations the client can perform on the service.
[DataContract] which data types are passed to and from the service.
[MessageContract] - allow the service to interact directly with messages.
Message contracts can be typed or untyped and are useful in interoperability cases
when another party has alreadydictated some explicit (typically proprietary)
message format.
[FaultContract] -which errors are raised by the service and how the service
handles andpropagates errors to its clients.

What is the difference between Web


Service and WCF Service ?
Features

Web Service

WCF

Hosting

It can be hosted in IIS.

It can be hosted in IIS, WAS (windows


activation service), Self-hosting or Windows
service

Programming

Apply [WebService] attribute to the


class to be exposed as a service.

Apply [ServiceContract] attribute to the class


to be exposed as a service.

Model

Apply [WebMethod] attribute to the


method exposed to client.

Apply [OperationContract] attribute to the


method exposed to client.

Supported
Operations

One-way and Request- Response.

One-Way, Request-Response and Duplex.

Logging

Needs custom implementation.

No custom implementation needed. Can be


configured in service config file.

Serialization

System.Xml.serialization namespace System.Runtime.Serialization namespace is


is used.
used.

Supported
Encoding

XML 1.0, MTOM(Message


Transmission Optimization
Mechanism), DIME, Custom.

Supported
Transports

Can be accessed through HTTP, TCP Can be accessed through HTTP, TCP, Named
and Custom.
pipes, MSMQ,P2P(Peer to Peer) and Custom.

XML 1.0, MTOM, Binary, Custom.

Service Types ASMX, .Net Remoting

.ASMX, .Net Remoting, WSE(WS* Protocols),


MSMQ and Enterprise Services

Supported
Protocols

Security, Reliable messaging, Transactions

Security

How can we host WCF service ?


Every WCF service needs to be hosted in a windows process called the host process.
A single host process can host multiple services, and the same service type can be
hosted in multiple host processes.
WCF services can be hosted in many ways:
IIS 5/6 Hosting
WCF services can be hosted in IIS. It is similar to hosting a ASMX web service. To host
a WCF service, you need to create a .svc file similar to this example and put it in
virtual directory of IIS:
Collapse | Copy Code

<%@ ServiceHost Language = "C#" Debug = "true" CodeBehind = "/App_Code/MyService.cs"


Service = "MyService" %>

Instead of defining a .svc file, you can create and host the service in .config file as
below:
Collapse | Copy Code

<system.serviceModel>
<serviceHostingEnvironment>
<serviceActivations>
<add relativeAddress = "MyService.svc" service = "WcfService.MyService"/>
<add relativeAddress = "MyOtherService.svc" service = "MyOtherService"/>
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service name = "WcfService.MyService">
...
</service>
<service name = "MyOtherService">
...
</service>
</services>
</system.serviceModel>

Self Hosting

Self-hosting is the technique in which the developer is responsible for providing and
managing the lifecycle of the host process. You can host WCF service inside any
Windows process, such as a Windows Forms application, a WPF application, a
Console application, or a Windows NT Service.
You can also host your WCF service as in-proc. In-process (or in-proc) hosting is the
hosting technique where the service resides in the same process as the client. By
definition, the developer provides the host for the in-proc hosting.
Collapse | Copy Code

var host = new ServiceHost(typeof(MyService));


host.Open();
Console.WriteLine("Press any key to stop service");
Console.ReadKey();
host.Close();

WAS (Windows Activation Service) Hosting


Microsoft provides a generalpurpose hosting engine called the Windows Activation
Service (WAS). WAS is a system service available with Windows Vista, Windows
Server 2008, and Windows 7 (or later). The WAS is a true general-purpose hosting
engine. It can host websites (in fact, IIS 7 will host its websites in the WAS by
default), but it can just as easily host your services, allowing you to use any
transport, such as TCP, IPC, or MSMQ. You can install and configure the WAS
separately from IIS 7. Hosting a WCF service in the WAS is designed to look just like
hosting in IIS 5/6. You need to either supply an .svc file, just as with IIS 5/6, or
provide the equivalent information in the config file.
Custom Hosting in IIS/WAS
When using IIS 5/6 or WAS, you have no direct access to the host. To overcome this
hurdle, WCF provides a hook called a host factory. Using the Factory tag in the .svc
file, you can specify a class you provide that creates the host instance.
Collapse | Copy Code

<%@ ServiceHost Language = "C#" Debug = "true" CodeBehind = "/App_Code/MyService.cs"


Service = "MyService" Factory = "MyServiceFactory" %>

You can also specify the host factory in the config file when not using an .svc file
explicitly:
Collapse | Copy Code

<serviceActivations>
<add relativeAddress = "MyService.svc" service = "MyService" factory = "MyServiceFactory" />
</serviceActivations>

Note: The host factory class must derive from the ServiceHostFactory class and
override the CreateServiceHost() virtual method.
Windows Server AppFabric
AppFabric is an extension to the WAS. It is geared more toward WF services, which
require support for persistence and state management correlation. Windows Server
AppFabric adds items for managing and monitoring the services, as well as WCF and
WF configuration items, to the IIS 7 management console. Windows Server AppFabric

provides a dashboard for monitoring the running instances of WCF or WF services,


and is reminiscent of the MTS or COM+ Component Services Explorer of old.
Windows Server AppFabric provides health monitoring and custom diagnostics, as
well as some troubleshooting features for analyzing why a service call has failed.
Windows Server AppFabric also supports scripting of all the options available in the
user interface. Windows Server AppFabric offers its own events collecting system
service, which stores the events in a SQL Server database. You can provide Windows
Server AppFabric with tracing and tracking profiles at various verbosity levels.

How do you choose the hosting for WCF


internet service ?

What are the protocols supported by


WCF hosting environment ? What are
their advantages and disadvantages ?
WCF support multiple ways in which you can host your WCF service.
Hosting Environment

Supported protocol

IIS6

http, wshttps

IIS7 WAS (Windows Process


Activation Service)

http,net.tcp,net.pipe,net.msmq

Windows console and form


application

http,net.tcp,net.pipe,net.msmq

Windows service application


http,net.tcp,net.pipe,net.msmq
(formerly known as NT services)
Below is the feature summary of hosting environments:

Feature

Self-Hosting

IIS Hosting

WAS Hosting

Executable Process/
App Domain

Yes

Yes

Yes

Configuration

App.config

Web.config

Web.config

Activation

Manual at
startup

Messagebased

Messagebased

Idle-Time
Management

No

Yes

Yes

Health Monitoring

No

Yes

Yes

Process Recycling

No

Yes

Yes

Management Tools

No

Yes

Yes

What is binding ?
A binding is the set of configurations regarding the transport protocol, message
encoding, communication pattern, reliability, security, transaction propagation, and
interoperability.

What are the types of bindings


supported by WCF ? What are their
advantages and disadvantages ?
Transport

M
e

HTTP

Te

HTTP

Te

Duplex service
contracts or
Secure, Interoperable.
HTTP
communication through
SOAP intermediaries.

Te

Binding

Feature

Suitable For

BasicHttpBinding

Communication with
WS-Basic Profile
Not secure by default.
conformant Web
Services like ASMX.

WSHttpBinding

Secure, Interoperable.

WSDualHttpBinding

Non-duplex service
contracts.

WSFederationHttpBinding

Supports the WSFederation protocol,


enabling organizations
Secure, Interoperable. that are in a federation HTTP
to efficiently
authenticate and
authorize users.

Te

NetTcpBinding

Secure, Optimized.

Cross-machine
communication
between WCF
applications.

NetPeerTcpBinding

Secure.

Multi-machine
communication.

P2P

NetNamedPipesBinding

Secure, Reliable,
Optimized.

On-machine
communication
between WCF
applications.

Named Pipes B

Cross-machine
communication
between WCF
applications.

MSMQ

Cross-machine
communication
between a WCF
MSMQ
application and existing
MSMQ applications.

P
fo

NetMsmqBinding

MsmqIntegrationBinding

Does not use a WCF


message encoding
instead it lets you
choose a pre-WCF
serialization format.

TCP

What is Endpoint in WCF ? or What is ABC in WCF ?


Endpoint = Address (A) + Binding (B) + Contract (C)
Address specifies where the services is hosted.
Binding specifies how to access the hosted service. It specifies the transport,
encoding, protocol etc.
Contract specifies what type of data can be sent to or received from the service.
Eg:
Collapse | Copy Code

<endpoint name="BasicHttpGreetingService"
address="http://localhost:5487/MyService/GreetingService.svc" binding="basicHttpBinding"
contract="MyNamespace.MyService.IGreetingService" />

Can you explain Address in detail ?


It is the url which specifies the location of the service. Client can use this url to
connect to the service and invoke the service methods.

Eg: http://localhost:5487/MyService/GreetingService.svc

Can you explain Binding in detail ?


It specifies how to access the hosted service. There are following characteristics of
binding:
Transport defines the communication protocol to be used to communicate between
service and client. It may be HTTP, TCP, MSMQ, NamedPipes etc. It is mandatory to
define transport.
Encoding defines the technique used to encode the data before communicating it
from one end to the other.
Protocol defines the configurations like reliability, security, transaction, timouts,
message size etc.

What is binding configuration ?


You can customize the binding used by endpoint using config file. For example, you
can enable/disable transaction for the binding used by endpoint. All you need is to
configure binding element in config file similar as below:
Collapse | Copy Code

<bindings>
<netTcpBinding>
<binding name = "TransactionalTCP" transactionFlow = "true" />
</netTcpBinding>
</bindings>

What is default endpoints ?


If the service host does not define any endpoints (neither in config nor
programmatically) but does provide at least one base address, WCF will by default
add endpoints to the service. These are called the default endpoints. WCF will add an
endpoint per base address per contract, using the base address as the endpoints
address. WCF will infer the binding from the scheme of the base address. For HTTP,
WCF will use the basic binding. Note that the default bindings will affect the default
endpoints. WCF will also name the endpoint by concatenating the binding name and
the contract name.

How can we enable/disable metadata publishing of our WCF service ?


You can enable enable meta data publishing for a WCF service two ways:

Configure metadata publishing for a service that uses default endpoints.


Specify the ServiceMetadataBehavior in the configuration file but do not specify any
endpoints.

Collapse | Copy Code

<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CustomServiceBehavior">
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

Configure metadata publishing for a service that uses explicit endpoints.


Specify the ServiceMetadataBehavior in the configuration file and a mex endpoint.
Collapse | Copy Code

<configuration>
<system.serviceModel>
<services>
<service name="MyNamespace.MyService.GreetingService"
behaviorConfiguration="CustomServiceBehavior">
<endpoint address="" binding="wsHttpBinding"
contract="MyNamespace.MyService.IGreetingService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CustomServiceBehavior">
<serviceMetadata httpGetEnabled="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

Supported bindings for mex endpoint


are mexHttpBinding, mexHttpsBinding, mexNamedPipeBinding andmexTcpBinding.

How can you generate proxy class and


configuration file for WCF service ?
WCF provides an utility svcutil.exe which can be used to generate proxy class and
configuration file. Eg:
SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /noconfig

Is there any tool provided by Microsoft


for editing configuration file ?
Yes. Microsoft provides an utility SvcConfigEditor.exe that can edit any
configuration file.

How can you test your new WCF


service without writing any client
application ?
Microsoft provides a tool which can be used to test any WCF service. To use this tool,
open visual studio command prompt and execute the command
wcftestclient.exe. It will open a window where you can add many WCF services
and test. You can also provide values for input parameters of WCF methods.

Which bindings support reliability and


message ordering ?
Supports
reliability

Default
reliability

Supports
ordered
delivery

Default Ordered
delivery

BasicHttpBinding

No

N/A

No

N/A

NetTcpBinding

Yes

Off

Yes

On

NetNamedPipeBinding

No

N/A(On)

Yes

N/A(On)

WSHttpBinding

Yes

Off

Yes

On

NetMsmqBinding

No

N/A

No

N/A

Binding name

How can you configure reliability


using .config file ?
Collapse | Copy Code

<bindings>
<netTcpBinding>
<binding name = "ReliableTCP">
<reliableSession enabled = "true"/>
</binding>
</netTcpBinding>
</bindings>

How can you implement operation


overloading in WCF service ?

We can implement operation overloading using Name property of


OperationContract attribute. For eg:
Collapse | Copy Code

[ServiceContract]
interface ICalculator
{
[OperationContract(Name = "AddInt")]
int Add(int arg1,int arg2);
[OperationContract(Name = "AddDouble")]
double Add(double arg1,double arg2);
}

What is Known Types ?


By default, you can not use a subclass of a data contract class instead of its base
class. You need to explicitly tell WCF about the subclass using the
KnownTypeAttribute. For eg
Collapse | Copy Code

[DataContract]
[KnownType(typeof(SubClass))]
class BaseClass
{...}
[DataContract]
class SubClass : BaseClass
{...}

What is ServiceKnownType ?
Instead of using the KnownType attribute on the base data contract, you can apply
the
ServiceKnownType attribute on a specific operation on the service side. Then, only
that
operation (across all supporting services) can accept the known subclass.
Collapse | Copy Code

[OperationContract]
[ServiceKnownType(typeof(SubClass))]
void AddContact(BaseClass baseObject);

How can we create and host a WCF


service in IIS ?
Please read Create RESTful WCF Service API Using GET & POST: Step By Step Guide

How to create a service contract and


operation contract ? Can you give an
example ?
We can create a contract using an interface by applying [ServiceContract] and
[OperationContract] attributes on Interface and Methods respectively.
Collapse | Copy Code

[ServiceContract]
public interface IGreetingService
{
[OperationContract]
string GreetMe(string userName);
}
public class GreetingService : IGreetingService
{
public string GreetMe(string userName)
{
return string.Format("Welcome {0}", userName);
}
}

If we do not want to create interface then we can apply the attributes on a class
itself.
Collapse | Copy Code

[ServiceContract]
public class GreetingService
{
[OperationContract]
public string GreetMe(string userName)
{
return string.Format("Welcome {0}", userName);
}
}

Can you give an example of


DataContract ?
Collapse | Copy Code

[DataContract]
public enum Color
{
[EnumMember]
Red,

[EnumMember]
Green,
[EnumMember]
Blue
}
[DataContract]
public class Shape
{
[DataMember]
public string Name { get; set; }
[DataMember]
public Color FillColor { get; set; }
[DataMember]
public double Area { get; set; }
}

What is MessageContract ? Can you


give an example ?
WCF uses SOAP messages to transfer information from client to server and viceversa. It converts data contract to SOAP messages. SOAP message contains
Envelope, Header and Body. SOAP envelope contains name, namespace, header and
body element. SOAP Header contains important information which are related to
communication but not directly related to message. SOAP body contains information
which is used by the target.
Collapse | Copy Code

SOAP Envelope = Name + Namespace + Header + Body

However there are some cases when you want to have control over the SOAP
messages. You can achieve this using MessageContract.
Collapse | Copy Code

[MessageContract]
public class Shape
{
[MessageHeader]
public string ID;
[MessageBodyMember]
public string Name;
[MessageBodyMember]
public double Area;
}

In above example, ID will be added as header, Name and Area as body in SOAP
envelope.
When you use MessageContract then you have control over the SOAP message.
However some restrictions are imposed as below:

You can have only one parameter for a service operation if you are using
MessageContract.
You can return either void or MessageContract type from service operation.
Service operation can not return DataContract type.
Service operation can accept and return only MessageContract type.
Some important points about MessageContract:
You can mention the MessageHeader or MessageBodyMember to be signed or
Encrypted using ProtectionLevel property.
The order of the body elements are alphabetical by default. But you can
control the order, using Order property in the MessageBody attribute.

What is FaultContract ?
In most of the cases you would like to convey the details about any error which
occurred at service end. By default, WCF exceptions do not reach client. However
you can use FaultContract to send the exception details to client.
Collapse | Copy Code

[DataContract()]
public class CustomError
{
[DataMember()]
public string ErrorCode;
[DataMember()]
public string Title;
[DataMember()]
public string ErrorDetail;
}
[ServiceContract()]
public interface IGreetingService
{
[OperationContract()]
[FaultContract(typeof(CustomError))]
string Greet(string userName);
}
public class GreetingService : IGreetingService
{
public string Greet(string userName)
{
if (string.IsNullOrWhiteSpace(userName))
{
var exception = new CustomError()
{
ErrorCode = "401",
Title = "Null or empty",
ErrorDetail = "Null or empty user name has been provided"
};
throw new FaultException<CustomError>(exception, "Reason : Input error");
}
return string.Format("Welcome {0}", userName);
}
}

How is the service instance created ?


How can you manage or control WCF
service instance creation ?
Client request can be served by using single service instance for all users, one
service instance for one client, or one instance for one client request. You can control
this behavior by using the technique called Instance Management in WCF.
There are three instance modes supported by WCF:

Per-Call: Service instance is created for each client request. This Service
instance is disposed after response is sent back to client.
Per-Session (default): Service instance is created for each client. Same
instance is used to serve all the requests from that client for a session. When a client
creates a proxy to particular service, a service instance is created at server for that
client only. When session starts, context is created and when it closes, context is
terminated. This dedicated service instance will be used to serve all requests from
that client for a session. This service instance is disposed when the session ends.
Singleton: All client requests are served by the same single instance. When
the service is hosted, it creates a service instance. This service instance is disposed
when host shuts down.
You can configure instance mode using [ServiceBehavior] attribute as below:
Collapse | Copy Code

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService:IGreetingService

Can you control when the service


instance is recycled ?

Yes, we can control when the service instance is recycled using


the ReleaseInstanceMode property of theOperationBehavior attribute. You can
control the lifespan of your WCF service. You can set the value
ofReleaseInstanceMode property as one of the following:
RealeaseInstanceMode.None: No recycling behavior.
RealeaseInstanceMode.BeforeCall: Recycle a service object before an
operation is called.
RealeaseInstanceMode.AfterCall: Recycle a service object after an
operation is called.
RealeaseInstanceMode.BeforeAndAfterCall: Recycle a service object
both before and after an operation is called.

Can you limit how many instances or


sessions are created at the application
level ?
Yes, you can limit how many instances or sessions are created at the application
level. For this, you need to configure throttling behavior for the service in its
configuration file. Some of these important properties are:

maxConcurrentCalls limits the total number of calls that can currently be in


progress across all service instances. The default is 16.
maxConcurrentInstances limits the number of InstanceContext objects that
execute at one time across a ServiceHost. The default is Int32.MaxValue.
maxConcurrentSessions limits the number of sessions a ServiceHost object
can accept. It is a positive integer that is 10 by default.
Collapse | Copy Code

<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100"
maxConcurrentSessions ="200"/>
</behavior>
</serviceBehaviors>
</behaviors>

What are session modes in WCF ? How


can you make a service as sessionful ?
ServiceContract attribute offers the property SessionMode which is used to specify
the session mode. There are three session modes supported by WCF:

Session.Allowed(default): Transport sessions are allowed, but not enforced.


Service will behave as a per-session service only if the binding used maintains a
transport-level session.
Session.Required: Mandates the use of a transport-level session, but not
necessarily an application-level session.
Session.NotAllowed: Disallows the use of a transport-level session, which
precludes an application-level session. Regardless of the service configuration, the
service will always behave as a per-call service.
Collapse | Copy Code

[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{...}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract

{...}

What is the instance mode as a product


of the binding, contract configuration,
and service behavior ?
Binding

Session mode Context mode Instance mode

Basic

Allowed/
NotAllowed

PerCall/
PerSession

PerCall

TCP, IPC

Allowed/
Required

PerCall

PerCall

TCP, IPC

Allowed/
Required

PerSession

PerSession

WS
(no Message security, no reliability)

NotAllowed/
Allowed

PerCall/
PerSession

PerCall

WS
(with Message security or reliability)

Allowed/
Required

PerSession

PerSession

WS
(with Message security or reliability)

NotAllowed

PerCall/
PerSession

PerCall

What is MEP (Message Exception


Pattern) in WCF ?
MEP describes the way in which Client and Server communicates. It describes how
client and server would be exchanging messages to each other. There are three
types of message exchange patterns:

Request- Replay (default): When client makes a request to the WCF


service, it waits to get response from service till receiveTimeout expires. If client
does not get any response from the service before receiveTimeout expires,
TimeoutException is thrown.
One-Way: When client makes a request to the WCF service, it does not wait
for reply from the service. Service does not send any response to the sender, even if
any error occurs in the communication. It does not support out or ref parameters. It
does not return value to an operation.
Duplex/Callback: Client and service can sends messages to each other by
using One-way or request-reply messaging. This MEP is supported by only
bidirectional-capable bindings like as WS Dual, TCP and IPC bindings.To make a
duplex contract, you must also define a callback contract and assign the typeof that

callback contract to the CallbackContract property of your service contracts


ServiceContract attribute.
Collapse | Copy Code

public interface IMyDuplexServiceCallback


{
[OperationContract(IsOneWay = true)]
void Progress(string status);
}
[ServiceContract(CallbackContract = typeof(IMyDuplexServiceCallback))]
public interface IMyDuplexService
{
[OperationContract(IsOneWay = true)] //One-Way
void SaveData();
[OperationContract] //Request-Reply.
string GetData();
}

For Duplex MEP, you need to specify the one of the binding which supports bidirectional like wsDualHttpBinding as in below example:
Collapse | Copy Code

<services>
<service name="MyWCFServices.DuplexService">
<endpoint address ="" binding="wsDualHttpBinding" contract="MyWCFServices.IDuplexService">
</endpoint>
</service>
</services>

You can configure MEP using IsOneWay property of OperationContract attribute


as below:
Collapse | Copy Code

[OperationContract(IsOneWay = true)]

What is transaction and committed


transaction in WCF ?
A transaction is a collection or group of one or more units of operation executed as a
whole. It provides way to logically group multiple pieces of single work and execute
them as a single unit. In addition, WCF allows client applications to create
transactions and to propagate transactions across service boundaries.
A transaction that executes successfully and manages to transfer the system from
the consistent state A to the consistent state B is called a committed transaction.

What is Two-phase commit protocol in


WCF ? Why is it needed ?
Consider for example client calling multiple service or service itself calling another
service, this type of system are called as Distributed Service-oriented application.
Now the questions arise that which service will begin the transaction? Which service
will take responsibility of committing the transaction? How would one service know
what the rest of the service feels about the transaction? Service could also be
deployed in different machine and site. Any network failure or machine crash also
increases the complexity for managing the transaction. This problem is resolved by
using two phase protocol.
All the transactions in WCF complete using two phase commit protocol. It is the
protocol which enables transactions in a distributed environment. This protocol
mainly consist of two phases:

Prepare phase: In this phase the client application performs the operations
of a WCF service. WCF service determines whether the requested operation will be
successful or not and notify the client about the same.
Commit Phase: In the commit phase the client checks for the responses it
got from the prepare phase and if all the responses are indicating that the operation
can be carried out successfully the transaction is committed. If the response from
any one of the operations indicates failure then the transaction will be rolled back.
The actual operation on the service end will happen in the commit phase.
WCF service will have to send the notification of whether the operation will succeed
or fail to the client application. It means that the One way operations can never
support transactions. The operations that support transactions have to follow
the Request-Response MEP. Also the applied binding should support WS-Atomic
Transaction protocol like wsHttpBinding.

What is Transaction Propagation in WCF


? Explain with example.
Suppose that there are two services CreditService and DebitService. CreditService
has operation Credit(int accountId, double amount) and DebitService has operation
Debit(int accountId, double amount). If you want to transfer amount from one
account to another account, you need to call both the services. You also need to
ensure that both the services should either succeed or fail together. You can achieve
this by propagating the transaction of first service call to the second service call.
Transaction Propagation is supported by WCF. You can propagate transaction across
the service boundaries. It enables multiple services to participate in same
transaction.
You can enable/disable transaction propagation using configuration as below:
Collapse | Copy Code

<bindings>
<netTcpBinding>
<binding transactionFlow="true"></binding>
</netTcpBinding>
</bindings>

Above configuration ensures that transaction can be propagated. However it does


not force the transaction propagation until you specify for particular operation. You
need to enable transaction flow for the operations whom you want to be part of
transaction as below:
Collapse | Copy Code

[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Credit(int accountId, double amount);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);

Note: You can have single operation as which can do credit and debit. However I
have separated as two for illustrating about transaction.
transactionFlow and TransactionFlowOption together enables the transaction flow for
particular operation. If you enable only one of these two, transaction flow can not be
enabled.

There are 3 possible values for TransactionFlowOption:


TransactionFlowOption.Mandatory: specifies that this function can only be
called within a transaction.
TransactionFlowOption.Allowed: specifies that this operation can be called
within a transaction but its not mandatory.
TransactionFlowOption.NotAllowed: specifies that this operation can not be
called within a transaction.

How to create WCF transaction ?


There are some steps you need to follow to enable transaction for a WCF service as
below:
Step 1: Decorate the operation contract with TransactionFlow attribute for enabling
the transaction.
Collapse | Copy Code

<code>[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);

Step 2: Create the service class which implements the service contract and set the
operation behavior withTransactionScopeRequired = true. This attribute is used to
enable the service transaction when the client transaction is not available.
Collapse | Copy Code

<code>[OperationBehavior(TransactionScopeRequired = true)]

public bool Debit(int accountId, double amount)


{
// Debit logic goes here
}

Step 3: Enable transaction flow in configuration file.


Collapse | Copy Code

<bindings>
<wsHttpBinding>
<binding name="myTransactionBinding" transactionFlow="true" ></binding>
</wsHttpBinding>
</bindings>

What is Restful service ?

REST stands for Representational State Transfer.


REST is an architectural style for building distributed applications. It involves
building Resource Oriented Architecture (ROA) by definding resources that
implement uniform interfaces using standard HTTP verbs (GET, POST, PUT, and
DELETE), and that can be located/identified by a Uniform Resource Identifier (URI).
Any Service which follows the REST architecture style is called as RESTful service.
Characteristics of RESTful services:
We can load the server information using web url in the browser.
We can access/modify the server resource using Url.
It allows the client, written in different language, to access or modify the
resource in the server using URL.
It uses the http protocol for its communication and it is stateless.
It can transfer the data in XML,JSON,RSS,ATOM.

How can you control if and when


concurrent calls are allowed ?
Or
What is concurrency modes in WCF ?
Why do we use it ?
We can use Concurrency Modes in WCF to control if concurrent calls to the context
are allowed or not and if yes then when concurrent calls to the instance/context
should be allowed.
There are three possible values for Concurrency Modes:
ConcurrencyMode.Single(default)- only one caller at a time is allowed.
WCF will provide automatic synchronization to the service context and disallow
concurrent calls by associating the context containing the service instance with a

synchronization lock. If there are multiple concurrent callers to the same context
while the lock is locked, all the callers are placed in a queue. Once the context is
unlocked waiting callers are allowed to lock the context in the order of queue. If a
call times out while blocked, WCF will remove the caller from the queue and the
client will get a TimeoutException.
ConcurrencyMode.Multiple - multiple callers at a time are allowed.
WCF will not synchronize access to the service context. It means that the service
context is not associated with any synchronization lock. In this case, you must
manually synchronize access to the service instance state using .NET locks such as
Monitor or a WaitHandle-derived class.
ConcurrencyMode.Reentrant - multiple callers at a time are allowed only if it is
reentrant.
WCF associates the service context with a synchronization lock, so concurrent calls
on the same instance are never allowed. However, if the reentrant service calls
another service or a callback, and that call chain somehow winds its way back to the
service instance that call is allowed to reenter the service instance. For example,
suppose there are three services A, B and C. Service A calls service B, service B calls
service C, and service C calls service A then service C is allowed to call service A
because it is reentrant service.
You can set the concurrency mode for the service by setting the ConcurrencyMode
property of ServiceBehavior attribute.
Collapse | Copy Code

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode =


ConcurrencyMode.Multiple)]

WWF

What is Windows Workflow Foundation?


WWF is a programming model for building workflow-enabled applications on
Windows. The System.Workflownamespace has all the necessary modules to
develop any type of workflow.

What is a workflow?
A workflow is a set of activities which is stored as a model and they depict a process.
The figure below clearly depicts the difference between a Workflow and an Activity.

Every task is an activity and a group of activities depicts a complete workflow. A


workflow is run by the workflow runtime engine.

Figure 1: Workflow Foundation Architecture

The workflow model can be written in pure .NET code, pure XAML, or a mix of XAML
and .NET code. A workflow model is compiled and can execute under Windows,
ASP.NET, Web Services, or Windows Services application.

What are the different types of


workflows in Windows Workflow
Foundation?
There are two basic types of workflows: sequential workflow and state machine
workflow. A sequential workflow has clear start and finish boundaries. The workflow
controls the execution in sequential workflow. In sequential execution, one task is
executed after another. A sequential workflow is more rigid in format and the
execution path has a deterministic nature. A state machine workflow is more
dynamic in nature. The workflow has states and the states wait for events to help
them move to the next state. In state machine, execution path is indeterministic in
nature. The figure below shows the visual conceptualization of the fundamentals. You
can see in the sequential workflow that the execution path is very deterministic. Shiv

performs the entire tasks sequentially and these tasks are very deterministic. Now
have a look at the second workflow. Every state goes to another state when it
receives some external events. For instance, when Shiv is seeing Star Trek, there is
an event of flashing news which triggers him to see the flashing news.

Figure 2: Sequential and state machine workflow

When should we use a sequential


workflow and when should we use state
machines?
If the workflow is very rigid, then you go for sequential workflow, and if the workflow
is dynamic, then go for state machine workflow. For instance, you have placed an
order and the order will not pass until your supervisor approves it is a rigid flow.
Because your order has to be approved by a supervisor, or else it will not be
approved. But what if your order moves from one place to another? For instance, it
moves from approval to waiting, then clarification of the state machine workflow
model is more appropriate. Below is a simple code snippet which shows practically

how to use a sequential workflow. Let us try to understand step by step, what is
marked in the figure:

1 - First you need to select the System.Workflow namespace.


2, 3, and 4 - In these three steps, we create the code objects and link them
with activities.
5, 6, 7, and 8 - We start the workflow and create a workflow instance object to
run the sequential workflow. You can see the output in 8. Depending on how you add
the activity in section 3, it executes sequentially. Because we have added
codeactivity1, first it executes the first activity first. The sequence on how you add
the activity to the activities collection is how the activities are run.

Figure: 3: Code Snippet for Workflow

Note: The above code snippet was developed without using a designer. The whole
point was to make you understand what happens behind the scenes. In real projects,
you will be dependent on a designer rather than coding manually. You can find the
above code in the SimpleWorkFlowSampleManual folder.

How do we create workflows using a


designer?

As said previously, it is very easy to design workflows using a designer. We will


answer this question by actually doing a small sample. Below is a code snippet and
image snapshot which shows how we can use a designer to create workflows. Let's
understand the snapshot below.
1.

First select a sequential workflow project. In this case, we have selected a


sequential workflow console application to keep the sample simple.
2.
When you are done with creating the project, you will see the Solution
Explorer as shown in the second snapshot. There are two
files: WorkFlow1.cs and Workflow1.designer.cs. If you click on WorkFlow1.cs, you will
get a designer pane as shown in snapshot 3. If you double click
on Workflow1.designer.cs, you will get behind the code as shown in snapshot 4.
3.
Let us drag drop a code activity on the workflow designer and associate this
activity with a method calledMyActivity1. This association is done by entering the
method name in the ExecuteCode property. InMyActivity1, we have displayed in the
console that this is my first activity. Again, we have added one more code activity
which points to MyActivity2. If you see the designer pane, we have sequenced code1
first and code2 next. In short, code1 will execute first and then code2. This is clear
from the output displayed below.
4.
This is the code behind the workflow:

Figure 4: Sequential Workflow Using Designer

How do we specify conditions in a


workflow?

1.
2.

3.
4.

Yes, you can define conditions in a workflow using a conditionedActivitygroup.


Below is the numbered snapshot which shows how to use
a conditionedActivitygroup.
You can see in this snapshot that we have defined
a conditionedActivitygroup with two conditions. The two boxes inside the group define
the two conditions.
You can select one of the condition boxes and define the condition using
the WhenConditions property. If this condition is true, you need to specify in the
execute code which method to execute. For instance, in the current snapshot, we
have said that the old1 method should execute if age > 21. The same procedure we
need to follow for the second condition box. In the second condition box, we have
specified to executeyoung1 method if age < 21. Currently, the second condition is
not visible in the below snapshot.
The workflow editor also provides a cool interface called as Rule Condition
Editor, which can be used to specify conditions. Age is a public property in the behind
code. You can also get Age in the intelligence of the rule condition editor.
Both the conditions will execute inside the condition activity group. We need
to specify when thisconditionactivitygroup should exit. Therefore, we have a function
called exit. If the user inputs age as -1, it will exit from the loop or it will take inputs
from the user and continue evaluating depending on the two conditions.

Figure 5: Sequential Workflow with Conditions

How do you handle exceptions in a


workflow?

Exception handling in a workflow is somewhat different from how we do in normal


.NET applications. Below is the numbered snapshot of how we can handle exceptions
in a workflow.
1.

We have a small tab which says View Exceptions. If you click on View
Exceptions, you will be redirected to a workflow design only for the exception as
shown in the numbered snapshot 2.
2.
This is the workflow which will execute in case we have exceptions. We have
put a code activity which points to a method called as raiseException. In case of
exceptions in the workflow, this path will be followed.

Figure 6: Workflow With Exception Handling

What is the use of XOML files?


Twist: How can we serialize workflows?
Windows Workflow Foundation gives developers a declarative way to create
workflows using XAML. See the WPF chapter for more details about XAML. These
markup files are stored with a XOML (Extensible Object Markup Language) extension.
In the below snapshot you can see a Workflow1.xoml file created by the designer.
The markup file can also have a code behind. The whole concept of having a code
behind for a XOML file is to separate the presentation from the logic files. In the
below code snapshot, we have made a simple XOML sample. Below is the
explanation number wise:

1.

In order to create a XOML file, you need to add a sequential workflow with
separation. Which means that the XOML file will be created with a behind code.
2.
Currently we have two activities: code3 and code1. Below is the XOML file
contents:
Collapse | Copy Code

<?Mapping XmlNamespace="ComponentModel"
ClrNamespace="System.Workflow.ComponentModel"
Assembly="System.Workflow.ComponentModel" ?>
<?Mapping XmlNamespace="Compiler"
ClrNamespace="System.Workflow.ComponentModel.Compiler"
Assembly="System.Workflow.ComponentModel" ?>
<?Mapping XmlNamespace="Activities"
ClrNamespace="System.Workflow.Activities"
Assembly="System.Workflow.Activities" ?>
<?Mapping XmlNamespace="RuleConditions"
ClrNamespace="System.Workflow.Activities.Rules"
Assembly="System.Workflow.Activities" ?>
<SequentialWorkflow x:Class="WorkflowSeq.Workflow1"
x:CompileWith="Workflow1.xoml.cs" ID="Workflow1"
xmlns:x="Definition" xmlns="Activities">
<Code ExecuteCode="Mycode3" ID="code3" />
<Code ExecuteCode="Mycode1" ID="code1" />
</SequentialWorkflow>

See the above snippet of the XOML file. You can see how the behind code is linked
using the CompileWithattribute. Code forms the element of
the SequentialWorkflow tag. One of the best things with markup is we can change
the sequence just by changing the XOML file, we do not need to compile the whole
application again.

Figure 7: XOML in Action

In the above snapshot, one of the things to know is the 3, 4, and 5 numbered
sections. These sections are not linked with the sample. But just to make you aware,
you can create and serialize any workflow and deserialize them again using the text
writer object.

How can we pass parameters to a


workflow?
When you call the start workflow function, you can pass as name / value pairs using
the dictionary object.

Figure 8: Passing a Value to a Workflow

DTSX
1) What is SSIS?

SSIS was first introduced with SQL Server 2005, which was the next
generation of SQL Server software after SQL Server 2000. SSIS is a form
of ETL (extraction, transformation and load), which is a database term
that integrates data scheduling and tasks. The SSIS engine automation
many data maintenance tasks, so you can update data without manually
firing procedures and imports.
2) How is SSIS different from DTS?

Older versions of SQL Server used DTS, which was similar to SSIS. DTS let
you create steps that you would then assign a priority order. With SSIS,
you can separate data from work flow, and SSIS has significantly better
performance than older DTS packages. While performance isnt always an
issue when running jobs during off-peak hours, its a problem when you
must run jobs during normal business hours. You can run SSIS during
business hours without too much performance degradation.
3) What is SSIS control flow integration?

When you create a package, you usually need some tasks to complete
before you can move on to the next task. SSIS lets you control the order in
which each data task is performed. This is important, because the wrong
data flow can cause major issues with your data and sometimes cause
severe data corruption.
4) What is data transformation?

Data transformation is a vague term, because you can pull data from any
format and transform it to any other format. That is the goal of data
transformation. In many database jobs, youll have data listed in a simple
file such as a CSV or Excel file. Your job is to automatically pull data from
this file and import it into your database tables. You can sometimes
perform data updates and do scrubbing to the data to clean it up,
because these flat files can contain raw data that needs to be better
formatted. All of this can be accomplished using an SSIS package.
5) What can you do in an SSIS task?

A task is one step in your SSIS job. A task can be almost database
transformation step. It can be connection to another database, importing
data from a file or database table or running a stored procedure against
your database tables. You can also customize tasks with the Microsoft
.NET language, which makes SSIS a very powerful tool with your
database.

6) What are the result statuses for your tasks?

There are three statuses after a task attempts to complete. The first status
is Success, which allows the next task to perform. You set what happens
after a task is successfully run. The next status is Failure. This status
seems self explanatory, but its very vague. A failure can be a number of
problems, and you must view your server logs and investigate the issues. A
failure will stop the rest of the SSIS job from running, so you must fix the
failed task to allow the rest of your transformation steps to run. Its not
always easy figuring out the problem, but you can run each task one by
one to help identify the issue.
The final status is Complete. This status tells you if the task is
completed, which means all steps within that task were fully completed.
7) What kind of containers can you use with SSIS packages?

There are three types of containers: sequence, for loops and for each
loops. A sequence container is a simple way to group similar tasks
together. Think of a sequence container as an organization container for
more complex SSIS packages.
A for loop contain is what you can use to repeat steps a certain number of
times. Perhaps you need to update records ten times. You can use this for
loop container to complete a number of tasks 10 times before moving on
to another step.
A for each loop can only be used in a collection. A collection is an
enumerated object. For instance, you can use the for each loop to a
specific number of records in a record set or a certain number of files in a
directory. The for each loop is better than the standard for loop, because
you dont accidentally make a mistake of looping through numerical
values too many times and causing an error in your SSIS package.
8) What kind of variables can you create?

You can create global variables and task level variables in SSIS. For
programmers, these variables are the same as global and function level
variables. A global variable is available to all tasks across the entire job.
Variables created in tasks are only available within that task.

LinQ
What is Language Integrated Query (LINQ)?
LINQ is a programming model that is the composition of general-purpose standard query operators
that allow you to work with data, regardless of the data source in any .NET based programming
language. It is the name given to a set of technologies based on the integration of query
capabilities into any .NET language.

What are LINQ query expressions?


A LINQ query, also known as a query expression, consists of a combination of query clauses that
identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or
joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL
syntax. It specifies what information should be retrieved from the data source.

Write the basic steps to execute a LINQ query.


The following are the three basic steps to execute a LINQ query:

Obtain the data source (The data source can be either an SQL database or an XML file)

Create a query

Execute the query

Write the basic syntax of a LINQ query in Visual Basic as well as in C#.
In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with
the Select or Group Byclause. In addition, you can use the Where, Order By, and Order By
Descending clauses to perform additional functions, such as filtering data and generating the
data in a specific order.
In C#, the basic syntax of a LINQ query starts with the From clause and ends with
the Select or group by clause. In addition, you can use the where, orderby, and Orderby
descending clauses to perform additional functions, such as filtering data and generating the data
in a specific order.

In which statement the LINQ query is executed?

A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement
in C#.

In LINQ, lambda expressions underlie many of the standard query operators. Is it


True or False?
It is true.

What is PLINQ?
PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in
which a query can be executed by using multiple processors. PLINQ ensures the scalability of
software on parallel processors in the execution environment. It is used where data grows rapidly,
such as in telecom industry or where data is heterogeneous.
PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using
PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on
the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries
quickly. Parallel execution provides a major performance improvement to PLINQ over certain types
of legacy code, which takes too much time to execute.

What are the different Visual Basic features that support LINQ?
Visual Basic includes the following features that support LINQ:

Anonymous types - Enables you to create a new type based on a query result.

Implicitly typed variables - Enables the compiler to infer and assign a type when you
declare and initialize a variable.

Extension method - Enables you to extend an existing type with your own methods
without modifying the type itself.

What is the function of the DISTINCT clause in a LINQ query?


The DISTINCT clause returns the result set without the duplicate values.

What is the DataContext class and how is it related to LINQ?


After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty
design surface represents an empty DataContext class ready to be configured.
The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server
database and the LINQ to SQL entity classes mapped to that database. This class contains the
connection string information and the methods for connecting to a database and manipulating the
data in the database. It is configured with connection information provided by the first item that is
dragged onto the design surface.

What is the difference between the Take and Skip clauses?


The Take clause returns a specified number of elements. For example, you can use
the Take clause to return two values from an array of numbers. The Skip clause skips the
specified number of elements in the query and returns the rest. For example, you can use

the Skip clause to skip the first four strings in an array of strings and return the remaining array
of string.

What is Object Relational Designer (0/R Designer)?


The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and
associations (relationships) that are based on objects in a database.

Which interface implements the standard query operators in LINQ?


The standard query operators implement the IEnumerable<T> or the IQueryable<T> interface
in C# and theIEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.

What are standard query operators in LINQ?


The standard query operators in LINQ are the extension methods that form the LINQ pattern.
These operators form an API that enables querying of any .NET array or collection. It operates on
sequences and allows you to perform operations, such as determining if a value exists in the
sequence and performing an aggregated function, such as a summation over a sequence.

On what parameter does the GroupBy clause group the data?


The GroupBy clause groups the elements that share a common attribute.

What is a LinqDataSource control?


The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the
properties in the markup text. You can use the control retrieve or modify data. It is similar to
the SqIDataSource andObjectDataSource controls in the sense that it can be used to
declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead
of binding directly to a database or to a generic class, the LinqDataSource control is designed to
bind a LINQ enabled data model.

How can you open the O/R Designer?


You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.

The standard query operators are themselves a set of extension methods that
provide the LINQ query functionality for any type that implements
the IEnumerable<T> interface in Visual Basic. Is it True or False?
False, as it implements the IEnumerable(T) interface in Visual Basic and
the IEnumerable<T> interface is implemented in C#.

What are lambda expressions in LINQ?


A lambda expression is a function without a name that calculates and returns a single value. All
lambda expressions use the lambda operator =>, which read as goes to. The left side of the
lambda operator specifies the input parameters and the right side holds the expression or
statement block.

Before you query a DataSet object by using LINQ to DataSet, you must first
populate the dataset How can you do this?

You can load the data into the dataset by using different methods, such as:

Using the DataAdapter class

Using LINQ to SQL

What are the different implementations of LINQ?


The different implementations of LINQ are:

LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a runtime infrastructure to manage relational data as objects.

LINQ to DataSet - Refers to a component that makes it easier and faster to query over
data cached in a DataSet object.

LINQ to XML - Provides an in-memory XML programming interface.

LINQ to Objects - Refers to the use of LINQ queries with


any IEnumerable or IEnumerable(T) collection directly, without the use of an
intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.

Which command-line tool generates code and mapping for the LINQ to SQL
component of .NET Framework?
The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.

Name the control that exposes the LINQ features to Web developers through the
ASP.NET data-source control architecture.
The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET
data-source control architecture.

What is the difference between the Select clause and SelectMany() method in
LINQ?
Both the Select clause and SelectMany() method are used to produce a result value from a
source of values. The difference lies in the result set. The Select clause is used to produce one
result value for every source value. The result value is a collection that has the same number of
elements from the query. In contrast, the SelectMany() method produces a single result that
contains a concatenated collection from the query.

Which extension method do you need to run a parallel query in PLINQ?


The AsParallel extension method is required to run a parallel query in PLINQ.

[QUESTIONS]
Now that we have talked about my qualifications, do you have any concerns
about me fulfilling the responsibilities of this position?

[Does it seem counter-intuitive to ask the interviewer to articulate his or her


concerns? Many candidates think so. But they are being shortsighted, Upton
argues. Once objections are stated, the candidate can usually address them in a
way that is satisfactory. Unstated objections will doom the candidate every time.
]

As my direct report in this position, what are the three top priorities you would
first like to see accomplished?

[This question, she says, effectively identifies the hot buttons of the hiring
manager, demonstrates that the candidate understands the priorities, and
underscores the candidates commitment to action by the final word in the
question. Remember, accomplish is a term dear to the heart of every hiring
manager.]

[Ask open-ended questions.

Keep it short.

Dont Interrupt

Getting to Yes

Use Inclusive Language

Ask Questions the Interviewer Can Answer

Avoid Questions that are Obvious or Easy to Determine

Avoid Why Questions

Avoid Asking Questions that Call for a Superlative

Avoid Leading or Loaded Questions

Avoid Veiled Threats

Avoid Questions that Hint of Desperation

Asking Questions that Focus on What the Company Can Do for You

Don't Ask Questions that are irrelevant to the job or organization.

Relax and smile.


]

Reelaborate:

[
Whats the makeup of the team as far as experience? Am I going to be a mentor
or will I be mentored?

What does this company value the most and how do you think my work for you
will further these values?

What kinds of processes are in place to help me work collaboratively?

What can I bring Company XYZ to round out the team?

Do team members typically eat lunch together or do they typically eat at their
desk?

Whats the most important thing I can do to help within the first 90 days of my
employment?

Do you have any questions or concerns about my ability to perform this job?

When top performers leave the company why do they leave and where do they
usually go?

What do you see in me? What are my strongest assets and possible weaknesses?
Do you have any concerns that I need to clear up in order to be the top
candidate?

Who are the coolest people on my team? What makes him or her cool? Can I
meet them?
]

+ Company info
+ Training programs? What? How etc..
+ Career info
+ How would yo describe your ideal candidate?

EXERCISE
I think it usually helps to ask your applicants to complete a simple coding exercise such as:

Write your own linked list class without using the built-in classes.
Write your own hashtable class without using the built-in classes.
Write a class that represents a binary tree. Write a method that traverses all nodes of the
tree.

Write a method to perform a binary search on an array without using built-in methods.

Draw a database schema for a blog. Each user only has one blog, each blog has many
categories, each category has many posts, and each post can belong to more than one
category. Ask your applicant to write queries to pull specific information out.
Next, look for specific technical know-how:

(Event handlers) Create a class with a custom event handler, create another class which
hooks onto the custom event handler.
(XML) Load an XML document and select all of the nodes with properties x, y, and z.
(Functional programming) Create a function that accepts another function as a
parameter. A Map or Fold function works really good for this.
(Reflection) Write a function which determines if a class has a particular attribute.
(Regex) Write a regular expression which removes all tags from a block of HTML.

S-ar putea să vă placă și