File

advertisement
COMPLILED INTERVIEW QUESTIONS
C#
What are namespaces, and how they are used?
Namespaces are used to organize classes within the .NET Framework. They dictate the
logical structure of the code. They are analogous to Java packages; with the key
difference being Java packages define the physical layout of source files (directory
structure) while .NET namespaces do not. However, many developers follow this
approach and organize their C# source files in directories that correlate with namespaces.
The .NET Framework has namespaces defined for its many classes, such as System.Xml-these are utilized via the using statement. Namespaces are assigned to classes via the
namespace keyword.
WHAT IS SERIALIZATION
Serialization is the process of converting complex objects into stream of bytes for
storage. Deserialization is its reverse process, that is unpacking stream of bytes to their
original form. The namespace which is used to read and write files is System.IO. For
Serialization we are going to look at the System.Runtime.Serialization namespace.
The ISerializable interface allows you to make any class Serializable.
What is it ?
When you create an object in a .Net framework application, you don't need to think about
how the data is stored in memory. Because .Net framework takes care of that for you.
However, if you want to store the contents of an object to a file, send an object to another
process or transmit it across the network, you do have to think about how the object is
represented because you will need to convert it to a different format. This conversion is
called SERIALIZATION.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate it as needed,
providing storage of objects as well as data exchange. Through serialization, a developer
can perform actions like sending the object to a remote application by means of a Web
Service, passing an object from one domain to another, passing an object through a
firewall as an XML string, or maintaining security or user-specific information across
applications.
Apply the SerializableAttribute attribute to a type to indicate that instances of this type
can be serialized. Apply the SerializableAttribute attribute even if the class also
implements theISerializable interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute are
serialized by default, unless the type implements the ISerializable interface to override
the serialization process. The default serialization process excludes fields that are marked
with theNonSerializedAttribute attribute. If a field of a serializable type contains a
pointer, a handle, or some other data structure that is specific to a particular environment,
and cannot be meaningfully reconstituted in a different environment, then you might
want to apply the NonSerializedAttributeattribute to that field.
What is a constructor?
A constructor is a class member executed when an instance of the class is created. The
constructor has the same name as the class, and it can be overloaded via different
signatures. Constructors are used for initialization chores.
Early and Late Binding
Calling a non-virtual method, decided at a compile time is known as early binding.
Calling a virtual method (Pure Polymorphism), decided at a runtime is known as late
binding.
This Object
This pointer is a pointer which points to the current object of a class. this is actually a
keyword which is used as a pointer which differentiate the current object with global
object.
Server.tranfer vs response.redirect
Server.Transfer, transfers the control of a web page, posting a form data, while
Response.Redirect simply redirects a page to another page, it can not post a form data to
another page.
Server.Transfer is more efficient over the Response.Redirect, because Response.Redirect
causes a round trip to server as the page is processed once again on the client and a
request is made to server there after.
But the browser url is not changed in case of Server.Transfer i.e. Browser history is not
modified in using it.
What is the GAC, and where is it located?
The GAC is the Global Assembly Cache. Shared assemblies reside in the GAC; this
allows applications to share assemblies instead of having the assembly distributed with
each application. Versioning allows multiple assembly versions to exist in the GAC--
applications can specify version numbers in the config file. The gacutil command line
tool is used to manage the GAC.
What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of
parameters.
Why are strings in C# immutable?
Immutable means string values cannot be changed once they have been created. Any
modification to a string value results in a completely new string instance, thus an
inefficient use of memory and extraneous garbage collection. The mutable
System.Text.StringBuilder class should be used when string values will change.
What is DLL Hell, and how does .NET solve it?
DLL Hell describes the difficulty in managing DLLs on a system; this includes multiple
copies of a DLL, different versions, and so forth. When a DLL (or assembly) is loaded in
.NET, it is loaded by name, version, and certificate. The assembly contains all of this
information via its metadata. The GAC provides the solution, as you can have multiple
versions of a DLL side-by-side.
How are methods overloaded?
Methods are overloaded via different signatures (number of parameters and types). Thus,
you can overload a method by having different data types, different number of
parameters, or a different order of parameters.
How do you prevent a class from being inherited?
The sealed keyword prohibits a class from being inherited.
What is the execution entry point for a C# console application?
The Main method.
How do you initiate a string without escaping each backslash?
You put an @ sign in front of the double-quoted string.
String ex = @"This has a carriage return\r\n"
What is the difference between a struct and a class?
Structs cannot be inherited. Structs are passed by value and not by reference. Structs are
stored on the stack not the heap. The result is better performance with Structs.
What is a singleton?
A singleton is a design pattern used when only one instance of an object is created and
shared; that is, it only allows one instance of itself to be created. Any attempt to create
another instance simply returns a reference to the first one. Singleton classes are created
by defining all class constructors as private. In addition, a private static member is
created as the same type of the class, along with a public static member that returns an
instance of the class. Here is a basic example:
public class SingletonExample {
private static SingletonExample _Instance;
private SingletonExample () { }
public static SingletonExample GetInstance() {
if (_Instance == null) {
_Instance = new SingletonExample ();
}
return _Instance;
}
}
What is boxing?
Boxing is the process of explicitly converting a value type into a corresponding reference
type. Basically, this involves creating a new object on the heap and placing the value
there. Reversing the process is just as easy with unboxing, which converts the value in an
object reference on the heap into a corresponding value type on the stack. The unboxing
process begins by verifying that the recipient value type is equivalent to the boxed type.
If the operation is permitted, the value is copied to the stack.
Difference between DataSet and DataReader
DataReader
===========
DataReader is like a forward only recordset. It fetches one row at a time so very less
network cost compare to DataSet(Fethces all the rows at a time). DataReader is readonly
so we can't do any transaction on them. DataReader will be the best choice where we
need to show the data to the user which requires no transaction. As DataReader is
forward only so we can't fetch data randomly. .NET Data Providers optimizes the
datareader to handle huge amount of data.
DataSet
=======
DataSet is an in memory representation of a collection of Database objects including
tables of a relational database schemas.
DataSet is always a bulky object that requires a lot of memory space compare to
DataReader. We can say that the DataSet is a small database because it stores the schema
and data in the application memory area. DataSet fetches all data from the datasource at a
time to its memory area. So we can traverse through the object to get the required data
like querying database.
USE OF GLOBAL.ASAX CONFIG
Global.asax is a file that resides in the root directory of your application. It is inaccessible
over the web but is used by the ASP.NET application if it is there. It is a collection of
event handlers that you can use to change and set settings in your site. The events can
come from one of two places - The HTTPApplication object and any HTTPModule
object that is specified in web.confg or machine.config.
ASP.NET provides three ways to authenticate a user:
* Windows authentication,
* Forms authentication, and
* Passport au
DIRECTIVES in C#
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler.
Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control: Defines control-specific attributes used by the ASP.NET page parser and
compiler. Can be included only in .ascx files. <%@ Control Language="VB"
EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import
directive cannot have more than one namespace attribute. To import multiple
namespaces, use multiple @Import directives. <% @ Import Namespace="System.web"
%>
@Implements: Indicates that the current page or user control implements the specified
.NET framework interface.<%@ Implements
Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in
custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator"
Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the
assembly's classes and interfaces available for use on the page. <%@ Assembly
Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page
or a user control contained in a page<%@ OutputCache Duration="#ofseconds"
Location="Any | Client | Downstream | Server | None" Shared="True | False"
VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should
be dynamically compiled and linked against the page in which this directive is declared.
CACHING in c#
Caching is a technique widely used in computing to increase performance by keeping
frequently accessed or expensive data in memory. In context of web application, caching
is used to retain the pages or data across HTTP requests and reuse them without the
expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput
CachingFragment CachingData
CachingOutput Caching: Caches the dynamic output generated by a request. Some
times it is useful to cache the output of a website even for a minute, which will result in a
better performance. For caching the whole page the page should have OutputCache
directive.<%@ OutputCache Duration="60" VaryByParam="state" %>
Fragment Caching: Caches the portion of the page generated by the request. Some times
it is not practical to cache the entire page, in such cases we can cache a portion of
page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching asp.net provides a
cache object for eg: cache["States"] = dsStates;
VALIDATION IN C#
There are 5 validation control in asp.net
1. RequiredFieldValidator
2. RangeValidator
3. RegularExpressionValidator
4. CompareValidator
5. CustomValidator
We have two common properties for every validation controls
1. ControlToValidate
2. ErrorMessage.
SYSTEM.String vs SYSTEM.Stringbulder
System.String is immutable; System.StringBuilder was designed with the purpose of
having a mutable string where a variety of operations can be performed.Append Keyword
is used in System.StringBuilder but not in System.String.
System.Text.StringBuilder strTest=new System.Text.StringBuilder();
Strings are immutable. immutable means every time we alter the string a new object is
created. hence lower the performance. while stringBuilder are mutable. so it increase the
performance where we need to perform altered, insert and remove operations. But it is
not recommended to use StringBuilder always. for small string where you need to
perform less operation then use string
and in case of large string and more operation use StringBuilder.
USER CONTROL VS CUSTOM CONTROL
User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx
Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll
GLOBALIZATION and Localization
Globalization is process of identifying how many resources needs to be localized to
adopt a multiple culture support, while Localization is actual process of translating
resource to a specific culture. So Localization is the part of Globalization.
KILLING A SESSION
Session.abandon()
Difference between Hashtable and HAshmap
1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for
non-threaded applications, as unsynchronized Objects typically perform better than
synchronized ones.
2. Hashtable does not allow null keys or values. HashMap allows one null key and any
number ofnull values.
3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want
predictable iteration order (which is insertion order by default), you could easily
swap out the HashMap for aLinkedHashMap. This wouldn't be as easy if you were
using Hashtable.
Since synchronization is not an issue for you, I'd recommend HashMap. If
synchronization becomes an issue, you may also look at ConcurrentHashMap.
1. The HashMap class is roughly equivalent to Hashtable, except that it is non
synchronized and permits nulls. (HashMap allows null values as key and value
whereas Hashtable doesn't allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over
time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and
throw ConcurrentModificationException if any other Thread modifies the map
structurally by adding or removing any element except Iterator's own remove()
method. But this is not a guaranteed behavior and will be done by JVM on best
effort.
Asp.net interview question:
How does PostBack work?
PostBack is basically the ASP.NET submitting a form to it -- it posts back to the current
URL. The JavaScript __doPostBack function is placed on the page (look at the source
within the browser) to facilitate. PostBack uses ViewState to remember controls and data.
The IsPostBack property of the ASP.NET page allows you to determine if the loading of
the page is the result of a postback event; this is done in the Page_Load event.
What are ASP.NET Server controls?
ASP.NET includes a number of built-in server controls that are the foundation of its Web
programming model. They have various properties to control their behavior and
appearance. These controls provide an event model where events are handled on the
server (whereas HTML controls are handled in the client). Server controls have the
ability to maintain state (via ViewState) across requests, and they can automatically
detect the browser. With these controls, you will see the RunAt attribute
(RunAt="Server") that signals its processing will be done on the server. A good example
of these controls is the basic TextBox control (<ASP:TextBox RunAt="Server" .... >.
What is View State?
Basically, View State is how ASP.NET Web pages persists data across requests. It
handles data that must be preserved between postbacks, and you can use it to store pagespecific data. By default, View State is enabled on a page and its controls. This can be a
problem as the amount of data and controls on a page increases resulting in more data for
ASP.NET to maintain. This is accomplished via the hidden __VIEWSTATE field on a
form (look at the page source in a browser), so more data in this field means a slower
load time and slower overall processing, as it has to be posted to the server each time.
You can limit the size of the data in View State by disabling controls that do not need to
be persisted via the EnableViewState property. View State can be encrypted to address
security concerns.
How can you loop through all controls on an ASP.NET Web form?
You can easily traverse all controls on a form via the Web Form's Controls collection.
The GetType method can be used on each control to determine its type and how to work
with it. Now, it gets tricky because the form contains a tree of controls; that is, some
controls are contained within others (think of a Table). You would have to recursively
loop through the controls to make sure everything is processed.
What is a web.config file? Machine.config?
The web.config is the basic configuration file for ASP.NET applications. It utilizes an
XML format. It is used to define application settings, connection strings, and much more.
These files can appear in multiple directories, and they are applied in a top-down
approach; that is, configuration files apply to their container directory as well as all
directories below it, but the configuration files in lower directories can override those in
parent directories. This provides a way to granularly apply settings. The machine.config
file contains ASP.NET settings for all of the applications on the server -- it is at the top of
the configuration file hierarchy, thus web.configs can override it.
What is the global.asax file?
The global.asax file is an optional piece of an ASP.NET application. It is located in the
root of the application directory structure. It cannot be directly loaded or requested by
users. It provides a place to define application- and session-wide events. You can define
your own events, but it does contain default Application events like when the application
starts Application_Start and ends with Application_End. The same is true for Session
events (Session_Start and Session_End).
How can you pass values between ASP.NET pages?
There are numerous ways to accomplish this task; the option you choose depends on the
environment. The oldest way to approach it is via the QueryString (i.e., passing values
via URL); this is also one of the least secure ways because users can easily see the data
and could possibly hack the site/page by changing parameter values. Next, you can use
HTTP POST to pass values; these are available via a collection within the ASP.NET
page. More specific to ASP.NET is the use of Session state, which makes information
available to all pages within the ASP.NET application. Another approach is using public
properties on the source page and accessing these properties on the target page. Also, you
can use the PreviousPage property of the current page to access control information on
the referring page. The last two require the source, and target pages are within the same
ASP.NET application.
What are ASHX files?
ASP.NET Web handler files have an .ashx file extension. Web handlers work just like
.aspx files except you don't have to deal with the browser interface, thus no worrying
about presentation. Web handlers are generally used to generate content dynamically like
returning XML or an image. Web handlers use the IHttpHandler interface with the
ProcessRequest() method invoked when the handler is requested. Web handlers are
simpler than pages (fewer events and wiring), so they are ideal for performance-critical
applications.
What is a master page?
A master page is a template for one or more Web Forms. The master page defines how
the page will be laid out when presented to the user, with placeholders for content. The
MasterPageFile Page Directive in a content page's header is one way to assign a master
page. The content pages rely solely on content and leave layout to the master page.
ASP.NET merges the content with the master page layout when the content page is
requested by a user.
What is the code behind feature of ASP.NET?
The code behind feature divides ASP.NET page files into two files where one defines the
user interface (.aspx), while the other contains all of the logic or code (.aspx.cs for C#
and .aspx.vb for VB.NET). These two files are glued together with page directives like
the following line, which ties the page to the specific code behind class.
What are page directives?
The first line of an ASP.NET page is the page directive; you will find it on all ASP.NET
pages. These directives are instructions for the page. It begins with the @Page directive
and continues with the various attributes available to this directive.
It's unreasonable to expect a candidate to know all of these attributes, but a few popular
ones include the following.








AutoEventWireup: Indicates whether page events are autowired.
CodeBehind: The name of the compiled class associated with the page.
Debug: Indicates whether the page is compiled in debug mode (includes debug
symbols).
EnableTheming: Indicates whether themes are used on the page.
EnableViewState: Indicates whether view state is maintained across pages.
ErrorPage: Specifies a target URL to be used when unhandled exceptions occur.
Language: Indicates the language used when compiling inline code on the page.
Trace: Signals whether tracing is enabled on the page.
1. What is C#?
C# is an object oriented, type safe and managed language that is compiled by .Net
framework to generate Microsoft Intermediate Language.
What is the difference between public, static and void?
All these are access modifiers in C#. Public declared variables or methods are accessible
anywhere in the application. Static declared variables or methods are globally accessible
without creating an instance of the class. The compiler stores the address of the method
as the entry point and uses this information to begin execution before any objects are
created. And Void is a type modifier that states that the method or variable does not
return any value
What is an object?
An object is an instance of a class through which we access the methods of that class.
“New” keyword is used to create an object. A class that creates an object in memory will
contain the information about the methods, variables and behavior of that class.
10. What is serialization?
When we want to transport an object through network then we have to convert the object
into a stream of bytes. The process of converting an object into a stream of bytes is called
Serialization. For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.
12. What is difference between constants and read-only?
Constant variables are declared and initialized at compile time. The value can’t be
changed after wards. Read-only variables will be initialized only from the Static
constructor of the class. Read only is used only when we want to assign the value at run
time.
14. What are value types and reference types?
Value types are stored in the Stack whereas reference types stored on heap.
Value types:
20. Describe the accessibility modifier “protected internal”.
Protected Internal variables/methods are accessible within the same assembly and also
from the classes that are derived from this parent class.
21. What are the differences between System.String and System.Text.StringBuilder
classes?
System.String is immutable. When we modify the value of a string variable then a new
memory is allocated to the new value and the previous memory allocation released.
System.StringBuilder was designed to have concept of a mutable string where a variety
of operations can be performed without allocation separate memory location for the
modified string.
28. What are generics in C#.NET?
Generics are used to make reusable code classes to decrease the code redundancy,
increase type safety and performance. Using generics, we can create collection classes.
To create generic collection, System.Collections.Generic namespace should be used
instead of classes such as ArrayList in the System.Collections namespace. Generics
promotes the usage of parameterized types.
30. List down the commonly used types of exceptions in .Net?
ArgumentException, ArgumentNullException , ArgumentOutOfRangeException,
ArithmeticException, DivideByZeroException ,OverflowException ,
IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException ,
IOEndOfStreamException , NullReferenceException , OutOfMemoryException ,
StackOverflowException etc.
35. What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes
the method behavior. Method overloading is creating a method with the same name
within the same class having different signatures.
What is the difference between Server.Transfer and Response.Redirect?
In Server.Transfer page processing transfers from one page to the other page without
making a round-trip back to the client’s browser. This provides a faster response with a
little less overhead on the server. The clients url history list or current url Server does not
update in case of Server.Transfer.
Response.Redirect is used to redirect the user’s browser to another page or site. It
performs trip back to the client where the client’s browser is redirected to the new
page. The user’s browser history list is updated to reflect the new address.
5. From which base class all Web Forms are inherited?
Page class.
38. How can we set class to be inherited, but prevent the method from being overridden?
Declare the class as public and make the method sealed to prevent it from being
overridden.
40. What is the difference between a Struct and a Class?
Structs are value-type variables and classes are reference types. Structs stored on the
stack, causes additional overhead but faster retrieval. Structs cannot be inherited.
44. What’s a multicast delegate?
A delegate having multiple handlers assigned to it is called multicast delegate. Each
handler is assigned to a method.
45. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed
in the same way as array.
CType(expression, typename)
What is the difference between directcast and ctype?
DirectCast is used to convert the type of an object that requires the run-time type to be
the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and
the type.
50. Is C# code is managed or unmanaged code?
C# is managed code because Common language runtime can compile C# code to
Intermediate language.

can you explain how ASP.NET application life cycle and page life cycle events fire?
 what's the difference between delegates and events?
6. What are the different validators in ASP.NET?
1.
2.
3.
4.
5.
6.
Required field Validator
Range Validator
Compare Validator
Custom Validator
Regular expression Validator
Summary Validator
Which validator control you use if you need to make sure the values in two different
controls matched?
Compare Validator control.
40. How we can force all the validation controls to run?
The Page.Validate() method is used to force all the validation controls to run and to
perform validation.
8. What is ViewState?
ViewState is used to retain the state of server-side objects between page post backs
ViewState is stored in a hidden field on the page at client side. ViewState is transported
to the client and back to the server, and is not stored on the server or any other external
source.
13. What is caching?
Caching is a technique used to increase performance by keeping frequently accessed data
or files in memory. The request for a cached file/data will be accessed from cache instead
of actual location of that file.
1. Output Caching,
2. Fragment Caching,
3. Data Caching.
16. List the events in page life cycle.
4.
1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render
23. What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the
network traffic and saves server resources.
42. List the major built-in objects in ASP.NET?







Application
Request
Response
Server
Session
Context
Trace
49. What are the components of ADO.NET?

The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command,
connection.
Different Collections class in Asp.net
Can you explain the complete flow of MVC?
Below are the steps how control flows in MVC (Model, view and controller)
architecture:


All end user requests are first sent to the controller.
The controller depending on the request decides which model to load. The controller
loads the model and attaches the model with the appropriate view.
The final view is then attached with the model data and sent as a response to the end user
on the browser.
What is the difference between DataSet and DataReader?
Following are some major differences between DataSet and DataReader:



DataReader provides forward-only and read-only access to data, while the DataSet object
can hold more than one table (in other words, more than one row set) from the same data
source as well as the relationships between them.
DataSet is a disconnected architecture while DataReader is a connected architecture.
DataSet can persist contents while DataReader cannot persist contents, they are forward
only.
WHAT IS REFLECTION?
What is CTS(Common type systems)
Difference between static and constant
Serialization and deserialization
Automation
Mobile development/Card development technology
XML namespace
Delegates
Accessmodifiers
Satelite assembly
Threading which namespace has threading diff between threads and process
Difference between Abstract class and interfaces
Events and delegates
Nested class
Event bubbling
Global.asax, Web.congif,machine.config…
Command and connection object
Difference between having and where clause
C# interview questions and answers
By admin | December 7, 2003
1. What’s the advantage of using System.Text.StringBuilder over
System.String?StringBuilder is more efficient in the cases, where a lot of
manipulation is done to the text. Strings are immutable, so each time it’s being
operated on, a new instance is created.
2. Can you store multiple data types in System.Array? No.
3. What’s the difference between the System.Array.CopyTo() and
System.Array.Clone()? The first one performs a deep copy of the array, the
second one is shallow.
4. How can you sort the elements of the array in descending order? By calling
Sort() and then Reverse() methods.
5. What’s the .NET datatype that allows the retrieval of data by a unique
key?HashTable.
6. What’s class SortedList underneath? A sorted HashTable.
7. Will finally block get executed if the exception had not occurred? Yes.
8. What’s the C# equivalent of C++ catch (…), which was a catch-all statement
for any possible exception? A catch block that catches the exception of type
System.Exception. You can also omit the parameter data type in this case and just
write catch {}.
9. Can multiple catch blocks be executed? No, once the proper catch code fires
off, the control is transferred to the finally block (if there are any), and then
whatever follows the finally block.
10. Why is it a bad idea to throw your own exceptions? Well, if at that point you
know that an error has occurred, then why not write the proper code to handle that
error instead of passing a new Exception object to the catch block? Throwing
your own exceptions signifies some design flaws in the project.
11. What’s a delegate? A delegate object encapsulates a reference to a method. In
C++ they were referred to as function pointers.
12. What’s a multicast delegate? It’s a delegate that points to and eventually fires
off several methods.
13. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the
application to specify not only the library it needs to run (which was available
under Win32), but also the version of the assembly.
14. What are the ways to deploy an assembly? An MSI installer, a CAB archive,
and XCOPY command.
15. What’s a satellite assembly? When you write a multilingual or multi-cultural
application in .NET, and want to distribute the core application separately from
the localized modules, the localized assemblies that modify the core application
are called satellite assemblies.
16. What namespaces are necessary to create a localized
application?System.Globalization, System.Resources.
17. What’s the difference between // comments, /* */ comments and ///
comments?Single-line, multi-line and XML documentation comments.
18. How do you generate documentation from the C# file commented properly
with a command-line compiler? Compile it with a /doc switch.
19. What’s the difference between <c> and <code> XML documentation
tag? Single line code example and multiple-line code example.
20. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
21. What debugging tools come with the .NET SDK? CorDBG – command-line
debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the
DbgCLR. To use CorDbg, you must compile the original C# file using the /debug
switch.
22. What does the This window show in the debugger? It points to the object that’s
pointed to by this reference. Object’s instance data is shown.
23. What does assert() do? In debug compilation, assert takes in a Boolean condition
as a parameter, and shows the error dialog if the condition is false. The program
proceeds without any interruption if the condition is true.
24. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace
class for both debug and release builds.
25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The
tracing dumps can be quite verbose and for some applications that are constantly
running you run the risk of overloading the machine and the hard drive there. Five
levels range from None to Verbose, allowing to fine-tune the tracing activities.
26. Where is the output of TextWriterTraceListener redirected? To the Console
or a text file depending on the parameter passed to the constructor.
27. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe
process to the DbgClr debugger.
28. What are three test cases you should go through in unit testing? Positive test
cases (correct data, correct output), negative test cases (broken or missing data,
proper handling), exception test cases (exceptions are thrown and caught
properly).
29. Can you change the value of a variable while debugging a C#
application? Yes, if you are debugging via Visual Studio.NET, just go to
Immediate window.
30. Explain the three services model (three-tier application). Presentation (UI),
business (logic and underlying code) and data (from storage or other sources).
31. What are advantages and disadvantages of Microsoft-provided data provider
classes in ADO.NET? SQLServer.NET data provider is high-speed and robust,
but requires SQL Server license purchased from Microsoft. OLE-DB.NET is
universal for accessing other sources, like Oracle, DB2, Microsoft Access and
Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the
world. ODBC.NET is a deprecated layer provided for backward compatibility to
ODBC engines.
32. What’s the role of the DataReader class in ADO.NET connections? It returns
a read-only dataset from the data source when the command is executed.
33. What is the wildcard character in SQL? Let’s say you want to query
database with LIKE for all employees whose name starts with La. The
wildcard character is %, the proper query with LIKE would involve ‘La%’.
34. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it
is one unit of work and does not dependent on previous and following
transactions), Consistent (data is either committed or roll back, no “in-between”
case where something has been updated and something hasn’t), Isolated (no
transaction sees the intermediate results of the current transaction), Durable (the
values persist if the data had been committed even if the system crashes right
after).
35. What connections does Microsoft SQL Server support? Windows
Authentication (via Active Directory) and SQL Server authentication (via
Microsoft SQL Server username and passwords).
36. Which one is trusted and which one is untrusted? Windows Authentication is
trusted because the username and password are checked with the Active
Directory, the SQL Server authentication is untrusted, since SQL Server is the
only verifier participating in the transaction.
37. Why would you use untrusted verificaion? Web Services might use it, as well
as non-Windows applications.
38. What does the parameter Initial Catalog define inside Connection
String? The database name to connect to.
39. What’s the data provider name to connect to Access
database? Microsoft.Access.
40. What does Dispose method do with the connection object? Deletes it from the
memory.
41. What is a pre-requisite for connection pooling? Multiple processes must agree
that they will share the same connection, where every parameter is the same,
including the security settings.
3. What is a constructor?
A constructor is the method of a class that is called when an object of that class is
created. The constructor initializes class parameters and has the same name as the class.
5. How are methods overloaded in C#?
You can overload methods in C# by specifying different numbers or types of parameters
in the method definition. Overloading can help to give your program the flexibility it
needs to operate with different types of data input.
What is the top .NET class that everything is derived from?
System.Objects - See more at: http://www.aired.in/2009/10/c-realtime-interviewquestions-and_16.html#sthash.H1Dl7Cxx.dpuf
WHAT IS THE ADVANTAGE OF SERIALIZATION?
Serialization is the process of maintaing object in the form stream. it is useful in case of
remoting.
Serialization is the process of converting object into byte stream which is useful to
transport object(i.e remoting),persisting object(i.e files,database) - See more at:
http://www.aired.in/2009/10/c-realtime-interview-questionsand_16.html#sthash.H1Dl7Cxx.dpuf
What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting
class, and of course, within the class itself. - See more at: http://www.aired.in/2009/10/csharp-realtime-interview-questions.html#sthash.IQQU563w.dpuf
How to declare a constant variable in C#? What is the use of the const keyword?
If a variable needs to have a fixed value, that may not be changed across the application's
life, then it may be declared with the const keyword. The value assigned to a constant
variable (using the const keyword) must be known at the time of compilation
- See more at: http://www.aired.in/2009/11/c-realtime-interview-questionsand.html#sthash.PpQwUrKk.dpuf
Common classes and namespaces that are used



System
System.Collections
System.Data









System.Drawing
System.IO
System.Text
System.Threading
System.Timers
System.Web
System.Web.Services
System.Windows.Forms
System.Xml
SYSTEM.COLLECTION CLASSES







ArrayList: An ArrayList is a type of collection to which you can add items and
have it automatically grow. You can move through the items using a MoveNext
on the enumerator of the class. The ArrayList can have a maximum capacity and a
fixed size.
CollectionBase: This class is the base for a strongly-typed collection, critical for
creating collection classes, which are described below.
DictionaryBase: This class is the base for a strongly-typed collection utilizing
associated keys and values. This is similar to the Dictionaryobject found in
VBScript and used by many ASP developers.
SortedList: This class represents a collection of keys and values, and is
automatically sorted by the key. You can still access the values with either the key
or the index number.
Hashtable: This class represents a collection of keys and values, but the keys and
values are hashed using a hashing algorithm. Searching based on key is very fast,
and is moderately fast when based on value. The order of the items cannot be
determined, but if you need searching capabilities, this is the best collection to
use.
Queue: This class represents a collection that is to be used on a first-in, firstout or FIFO basis. This unsorted list lets you add items to the end and read (and
optionally remove) the items from the top.
Stack: In contrast to the FIFO nature of the Queue class, the Stack class
represents a collection for last-in, first-out or LIFO.
SYSTEM.DATA NAMESPACE


Connection: In the first version of ADO.NET, this will be either SqlConnection
or OleDbConnection. This class is responsible for making the actual connection to
the database, and it also handles starting a transaction.
Command: This will be either SqlCommand or OleDbCommand. This class
allows you to issue SQL statements or call stored procedures. It is the object that
will actually execute the command, and may return data.



DataReader: Either SqlDataReader or OleDbDataReader, this object is used to
read data in a forward-only manner. This is the firehose cursor with which most
ADO developers are familiar.
DataAdapters: Either SqlDataAdapter or OleDbDataAdapter, this object
encapsulates a connection and one or more commands. It gets data and fills a
DataSet object with data.
DataSets: Either SqlDataSet or OleDbDataSet, this is the ADO.NET
disconnected data cache. It stores data in memory in a schema, and applications
can use it like a database, accessing and updating data.SYS
SYSTEM.IO
there are Exists, Open, OpenRead, OpenText, andOpenWrite shared methods
for performing file IO.
The System.Threading Namespace
Thread object
MAxCount, dostuffs
The System.Web Namespace
Windows forms, server controls,
SYSTEM.WEBSERVICES
XML Web services are one of the newest and most exciting additions to the world of
development. XML Web services have been available for some time on the Microsoft
platform, thanks to the SOAP Toolkit.
The System.Windows.Forms
here are classes such as Button, Label, and TextBox.
ADO.NET
object
Description
DataReader
Provides a forward-only, read-only stream of data from a data source.
The DataReader is similar to a Recordset with CursorType =
adOpenForwardOnly and LockType = adLockReadOnly.
DataSet
Provides in-memory access to relational data.
The DataSet is independent of any specific data source and therefore can be populated from
multiple and differing data sources including relational databases and XML, or can be populated
with data local to the application. Data is stored in a collection of one or more tables, and can be
accessed non-sequentially and without limits to availability, unlike ADO in which data must be
accessed a single row at a time. A DataSet can contain relationships between tables, similar to
the ADO Recordset in which a single result set is created from a JOIN. A DataSet can also
contain unique, primary key, and foreign key constraints on its tables.
The DataSet is similar to a Recordset with CursorLocation = adUseClient, CursorType =
adOpenStatic, and LockType = adLockOptimistic. However, the DataSet has extended
capabilities over the Recordset for managing application data.
DataAdapter
Populates a DataSet with data from a relational database and resolves changes in
the DataSet back to the data source.
The DataAdapter enables you to explicitly specify behavior that the Recordset performs
implicitly.
System.Collections Classes
The classes in the System.Collections namespace do not store elements as specifically
typed objects, but as objects of type Object.
Whenever possible, you should use the generic collections in
the System.Collections.Generic namespace or
the System.Collections.Concurrentnamespace instead of the legacy types in
the System.Collections namespace.
Class
Description
ArrayList
Represents an array of objects whose size is dynamically increased as required.
Hashtable
Represents a collection of key/value pairs that are organized based on the hash code of the key.
Queue
Represents a first in, first out (FIFO) collection of objects.
Stack
Represents a last in, first out (LIFO) collection of objects.
The following table lists some of the frequently used classes in
the System.Collections namespace:
The System.Collections.Specialized namespace provides specialized and strongly typed
collection classes, such as string-only collections and linked-list and hybrid dictionaries.
Many common collections are provided by the .NET Framework. Each type of collection
is designed for a specific purpose.
The following groups of collection classes are described in this section:
 System.Collections.Generic classes
 System.Collections.Concurrent classes
 System.Collections classes
 Visual Basic Collection class

System.Collections.Generic Classes



You can create a generic collection by using one of the classes in
the System.Collections.Generic namespace. A generic collection is useful when
every item in the collection has the same data type. A generic collection enforces
strong typing by allowing only the desired data type to be added.
The following table lists some of the frequently used classes of
the System.Collections.Generic namespace:
Class
Description
Dictionary<TKey,
TValue>
Represents a collection of key/value pairs that are organized based on the key.
List<T>
Represents a list of objects that can be accessed by index. Provides methods to search, sort,
lists.
Queue<T>
Represents a first in, first out (FIFO) collection of objects.
SortedList<TKey,
TValue>
Represents a collection of key/value pairs that are sorted by key based on the
associated IComparer<T>implementation.
Stack<T>
Represents a last in, first out (LIFO) collection of objects.

For additional information, see Commonly Used Collection Types, Selecting a
Collection Class, and System.Collections.Generic.
SQL
What are DMVs?
Dynamic management views (DMVs) and functions return server state information that
can be used to monitor the health of a server instance, diagnose problems, and tune
performance; that is, they let you see what is going on inside SQL Server. They were
introduced in SQL Server 2005 as an alternative to system tables. One example is
viewing operating system wait statistics via this query:
SELECT * FROM sys.dm_os_wait_stats;
Another example is examining current sessions, much like the sp_who2 command:
SELECT * FROM sys.dm_exec_sessions;
What are temp tables? What is the difference between global and local temp tables?
Temporary tables are temporary storage structures. You may use temporary tables as
buckets to store data that you will manipulate before arriving at a final format. The hash
(#) character is used to declare a temporary table as it is prepended to the table name. A
single hash (#) specifies a local temporary table.
CREATE TABLE #tempLocal ( nameid int, fname varchar(50), lname varchar(50) )
Local temporary tables are available to the current connection for the user, so they
disappear when the user disconnects.
Global temporary tables may be created with double hashes (##). These are available to
all users via all connections, and they are deleted only when all connections are closed.
CREATE TABLE ##tempGlobal ( nameid int, fname varchar(50), lname varchar(50) )
Once created, these tables are used just like permanent tables; they should be deleted
when you are finished with them. Within SQL Server, temporary tables are stored in the
Temporary Tables folder of the tempdb database.
How are transactions used?
Transactions allow you to group SQL commands into a single unit. The transaction
begins with a certain task and ends when all tasks within it are complete. The transaction
completes successfully only if all commands within it complete successfully. The whole
thing fails if one command fails. The BEGIN TRANSACTION, ROLLBACK
TRANSACTION, and COMMIT TRANSACTION statements are used to work with
transactions. A group of tasks starts with the begin statement. If any problems occur, the
rollback command is executed to abort. If everything goes well, all commands are
permanently executed via the commit statement.
What is the difference between a clustered and a nonclustered index?
A clustered index affects the way the rows of data in a table are stored on disk. When a
clustered index is used, rows are stored in sequential order according to the index column
value; for this reason, a table can contain only one clustered index, which is usually used
on the primary index value.
A nonclustered index does not affect the way data is physically stored; it creates a new
object for the index and stores the column(s) designated for indexing with a pointer back
to the row containing the indexed values.
You can think of a clustered index as a dictionary in alphabetical order, and a
nonclustered index as a book's index.
What are DBCC commands?
Basically, the Database Consistency Checker (DBCC) provides a set of commands (many
of which are undocumented) to maintain databases -- maintenance, validation, and status
checks. The syntax is DBCC followed by the command name. Here are three examples:
DBCC CHECKALLOC -- Check disk allocation consistency.
DBCC OPENTRAN -- Display information about recent transactions.
DBCC HELP -- Display Help for DBCC commands.
What is the difference between truncate and delete?
Truncate is a quick way to empty a table. It removes everything without logging each
row. Truncate will fail if there are foreign key relationships on the table. Conversely, the
delete command removes rows from a table, while logging each deletion and triggering
any delete triggers that may be present.
What does the NOLOCK query hint do?
Table hints allow you to override the default behavior of the query optimizer for
statements. They are specified in the FROM clause of the statement. While overriding the
query optimizer is not always suggested, it can be useful when many users or processes
are touching data. The NOLOCK query hint is a good example because it allows you to
read data regardless of who else is working with the data; that is, it allows a dirty read of
data -- you read data no matter if other users are manipulating it. A hint like NOLOCK
increases concurrency with large data stores.
SELECT * FROM table_name (NOLOCK)
Microsoft advises against using NOLOCK, as it is being replaced by the
READUNCOMMITTED query hint. There are lots more query hints with plenty of
information online.
What is a CTE?
A common table expression (CTE) is a temporary named result set that can be used
within other statements like SELECT, INSERT, UPDATE, and DELETE. It is not stored
as an object and its lifetime is limited to the query. It is defined using the WITH
statement as the following example shows:
WITH ExampleCTE (id, fname, lname)
AS
(
SELECT id, firstname, lastname FROM table
)
SELECT * FROM ExampleCTE
A CTE can be used in place of a view in some instances.
What is a view? What is the WITH CHECK OPTION clause for a view?
A view is a virtual table that consists of fields from one or more real tables. Views are
often used to join multiple tables or to control access to the underlying tables.
The WITH CHECK OPTION for a view prevents data modifications (to the data) that do
not confirm to the WHERE clause of the view definition. This allows data to be updated
via the view, but only if it belongs in the view.
What is a query execution plan?
SQL Server has an optimizer that usually does a great job of optimizing code for the most
effective execution. A query execution plan is the breakdown of how the optimizer will
run (or ran) a query. There are several ways to view a query execution plan. This includes
using the Show Execution Plan option within Query Analyzer; Display Estimated
Execution Plan on the query dropdown menu; or use the SET SHOWPLAN_TEXT ON
command before running a query and capturing the execution plan event in a SQL Server
Profiler trace.
What does the SQL Server Agent Windows service do?
SQL Server Agent is a Windows service that handles scheduled tasks within the SQL
Server environment (aka jobs). The jobs are stored/defined within SQL Server, and they
contain one or more steps that define what happens when the job runs. These jobs may
run on demand, as well as via a trigger or predefined schedule. This service is very
important when determining why a certain job did not run as planned -- often it is as
simple as the SQL Server Agent service not running.
What is the default port number for SQL Server?
If enabled, the default instance of Microsoft SQL Server listens on TCP port 1433.
Named instances are configured for dynamic ports, so an available port is chosen when
SQL Server starts. When connecting to a named instance through a firewall, configure
the Database Engine to listen on a specific port, so that the appropriate port can be
opened in the firewall.
The list of possible questions is endless. I am sure these questions will spawn debate and
discussion.
s
OTHERS TO KEEP in MIND
GENERAL SQL
1. What are the differences between an Abstract class and Interface?
2. What are the differences between Inner and outer joins?
InnerJoin: Inner join is the most common type of Join which is used to combine the
rows from two tables and create a result set containing only such records that are
present in both the tables based on the joining condition (predicate).
Exmaple:
SELECT dept.name DEPARTMENT, emp.name EMPLOYEE FROM DEPT dept,
EMPLOYEE emp WHERE emp.dept_id = dept.id
Outer Join, on the other hand, will return matching rows from both tables as well as any
unmatched rows from one or both the tables (based on whether it is single outer or full
outer join respectively).
3. What two ways you can use using statement?
4. What is on the top of the .net class library?
5. What is the difference between JOIN and UNION?
1.SQL JOIN allows us to “lookup” records on other table based on the given
conditions between two tables. For example, if we have the department ID of
each employee, then we can use this department ID of the employee table to
join with the department ID of department table to lookup department
names.
2.UNION operation allows us to add 2 similar data sets to create resulting
data set that contains all the data from the source data sets. Union does not
require any condition for joining. For example, if you have 2 employee tables
with same structure, you can UNION them to create one result set that will
contain all the employees from both of the tables.
UNION AND UNION ALLL
UNION operation returns only the unique records from the resulting data set whereas
UNION ALL will return all the rows, even if one or more rows are duplicated to
each other.
HAVING AND WHERE CLAUSE
WHERE and HAVING both filters out records based on one or more conditions. The
difference is, WHERE clause can only be applied on a static non-aggregated column
whereas we will need to use HAVING for aggregated columns.
The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.
UNION combines the results from 2 tables and eliminates duplicate records from the
result set.
MINUS operator when used between 2 tables, gives us all the rows from the first
table except the rows which are present in the second table.
INTERSECT operator returns us only the matching or common rows between 2
result sets.
SELF JOIN Self Join is the act of joining one table with itself.
Self Join is often very useful to convert a hierarchical structure into a flat structure
Types of Joins
1. Inner: returns the common records between two tables
2. Outer: Matching records and any unmatched records as well
3. left join:
4. right join
5. full join
6. self join
An SQL JOIN clause is used to combine rows from two or more tables, based on a
common field between them.
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the
matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the
matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the
tables
How do you select the first 5 rows
SELECT TOP 5 * FROM EMP;
CREATE
PROCEDURE GetDBNames
AS
SELECT name, database_id
FROM sys.databases
GO
We can execute this stored procedure using the following script.
EXEC GetDBNames
WHAT ARE INDEXES? Difference between clustered and non clustered index..
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
WHAT IS CTE? –common table expression
A common table expression (CTE) can be thought of as a temporary result set that is
defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE,
or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored
as an object and lasts only for the duration of the query. Unlike a derived table, a CTE
can be self-referencing and can be referenced multiple times in the same query.
A CTE can be used to:
 Create a recursive query. For more information, see Recursive Queries Using
Common Table Expressions.
 Substitute for a view when the general use of a view is not required; that is, you
do not have to store the definition in metadata.
 Enable grouping by a column that is derived from a scalar subselect, or a function
that is either not deterministic or has external access.
 Reference the resulting table multiple times in the same statement.
Recursive function – is a function that is partially defined by itself and consists of some
simple case with a known answer. Example: Fibonacci number sequence, factorial
function, quick sort and more.
Some of the algorithms/functions can be represented in an iterative way and some may
not.
Iterative functions – are loop based imperative repetitions of a process (in contrast to
recursion which has a more declarative approach).
SQL FUNCTIONS
SQL has many built-in functions for performing calculations on data.
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:







AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:







UCASE() - Converts a field to upper case
LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LEN() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of decimals specified
NOW() - Returns the current system date and time
FORMAT() - Formats how a field is to be displayed
Tip: The aggregate functions and the scalar functions will be explained in details in the
next chapters.
INDEX
With a clustered index the rows are stored physically on the disk in the same order as
the index. There can therefore be only one clustered index.
With a non clustered index there is a second list that has pointers to the physical rows.
You can have many non clustered indexes, although each new index will increase the
time it takes to write new records.
It is generally faster to read from a clustered index if you want to get back all the
columns. You do not have to go first to the index and then to the table.
Writing to a table with a clustered index can be slower, if there is a need to rearrange the
data.
A clustered index is a special type of index that reorders the way 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.
In general, there are three types of transactions that you can use in the SQL Server
environment: BEGIN TRANSACTION, ROLL BACK TRANSACTION and COMMIT
TRANSACTION. The gist behind deploying transactions is that they allow you to group
multiple SQL commands into a single unit. From there, each transaction begins with a
certain task, and ends when all the tasks within the transaction are complete. BEGIN
TRANSACTION gets the ball rolling. ROLLBACK TRANSACTION functions a lot like
an “undo” command, and COMMIT TRANSACTION completes all of the tasks within
that transaction.
ASP.NET
Asp.net interview question:
How does PostBack work?
PostBack is basically the ASP.NET submitting a form to it -- it posts back to the current
URL. The JavaScript __doPostBack function is placed on the page (look at the source
within the browser) to facilitate. PostBack uses ViewState to remember controls and data.
The IsPostBack property of the ASP.NET page allows you to determine if the loading of
the page is the result of a postback event; this is done in the Page_Load event.
What are ASP.NET Server controls?
ASP.NET includes a number of built-in server controls that are the foundation of its Web
programming model. They have various properties to control their behavior and
appearance. These controls provide an event model where events are handled on the
server (whereas HTML controls are handled in the client). Server controls have the
ability to maintain state (via ViewState) across requests, and they can automatically
detect the browser. With these controls, you will see the RunAt attribute
(RunAt="Server") that signals its processing will be done on the server. A good example
of these controls is the basic TextBox control (<ASP:TextBox RunAt="Server" .... >.
What is View State?
Basically, View State is how ASP.NET Web pages persists data across requests. It
handles data that must be preserved between postbacks, and you can use it to store pagespecific data. By default, View State is enabled on a page and its controls. This can be a
problem as the amount of data and controls on a page increases resulting in more data for
ASP.NET to maintain. This is accomplished via the hidden __VIEWSTATE field on a
form (look at the page source in a browser), so more data in this field means a slower
load time and slower overall processing, as it has to be posted to the server each time.
You can limit the size of the data in View State by disabling controls that do not need to
be persisted via the EnableViewState property. View State can be encrypted to address
security concerns.
How can you loop through all controls on an ASP.NET Web form?
You can easily traverse all controls on a form via the Web Form's Controls collection.
The GetType method can be used on each control to determine its type and how to work
with it. Now, it gets tricky because the form contains a tree of controls; that is, some
controls are contained within others (think of a Table). You would have to recursively
loop through the controls to make sure everything is processed.
What is a web.config file? Machine.config?
The web.config is the basic configuration file for ASP.NET applications. It utilizes an
XML format. It is used to define application settings, connection strings, and much more.
These files can appear in multiple directories, and they are applied in a top-down
approach; that is, configuration files apply to their container directory as well as all
directories below it, but the configuration files in lower directories can override those in
parent directories. This provides a way to granularly apply settings. The machine.config
file contains ASP.NET settings for all of the applications on the server -- it is at the top of
the configuration file hierarchy, thus web.configs can override it.
What is the global.asax file?
The global.asax file is an optional piece of an ASP.NET application. It is located in the
root of the application directory structure. It cannot be directly loaded or requested by
users. It provides a place to define application- and session-wide events. You can define
your own events, but it does contain default Application events like when the application
starts Application_Start and ends with Application_End. The same is true for Session
events (Session_Start and Session_End).
How can you pass values between ASP.NET pages?
There are numerous ways to accomplish this task; the option you choose depends on the
environment. The oldest way to approach it is via the QueryString (i.e., passing values
via URL); this is also one of the least secure ways because users can easily see the data
and could possibly hack the site/page by changing parameter values. Next, you can use
HTTP POST to pass values; these are available via a collection within the ASP.NET
page. More specific to ASP.NET is the use of Session state, which makes information
available to all pages within the ASP.NET application. Another approach is using public
properties on the source page and accessing these properties on the target page. Also, you
can use the PreviousPage property of the current page to access control information on
the referring page. The last two require the source, and target pages are within the same
ASP.NET application.
What are ASHX files?
ASP.NET Web handler files have an .ashx file extension. Web handlers work just like
.aspx files except you don't have to deal with the browser interface, thus no worrying
about presentation. Web handlers are generally used to generate content dynamically like
returning XML or an image. Web handlers use the IHttpHandler interface with the
ProcessRequest() method invoked when the handler is requested. Web handlers are
simpler than pages (fewer events and wiring), so they are ideal for performance-critical
applications.
What is a master page?
A master page is a template for one or more Web Forms. The master page defines how
the page will be laid out when presented to the user, with placeholders for content. The
MasterPageFile Page Directive in a content page's header is one way to assign a master
page. The content pages rely solely on content and leave layout to the master page.
ASP.NET merges the content with the master page layout when the content page is
requested by a user.
What is the code behind feature of ASP.NET?
The code behind feature divides ASP.NET page files into two files where one defines the
user interface (.aspx), while the other contains all of the logic or code (.aspx.cs for C#
and .aspx.vb for VB.NET). These two files are glued together with page directives like
the following line, which ties the page to the specific code behind class.
What are page directives?
The first line of an ASP.NET page is the page directive; you will find it on all ASP.NET
pages. These directives are instructions for the page. It begins with the @Page directive
and continues with the various attributes available to this directive.
It's unreasonable to expect a candidate to know all of these attributes, but a few popular
ones include the following.


AutoEventWireup: Indicates whether page events are autowired.
CodeBehind: The name of the compiled class associated with the page.






Debug: Indicates whether the page is compiled in debug mode (includes debug
symbols).
EnableTheming: Indicates whether themes are used on the page.
EnableViewState: Indicates whether view state is maintained across pages.
ErrorPage: Specifies a target URL to be used when unhandled exceptions occur.
Language: Indicates the language used when compiling inline code on the page.
Trace: Signals whether tracing is enabled on the page.
1. What is C#?
C# is an object oriented, type safe and managed language that is compiled by .Net
framework to generate Microsoft Intermediate Language.
What is the difference between public, static and void?
All these are access modifiers in C#. Public declared variables or methods are accessible
anywhere in the application. Static declared variables or methods are globally accessible
without creating an instance of the class. The compiler stores the address of the method
as the entry point and uses this information to begin execution before any objects are
created. And Void is a type modifier that states that the method or variable does not
return any value
What is an object?
An object is an instance of a class through which we access the methods of that class.
“New” keyword is used to create an object. A class that creates an object in memory will
contain the information about the methods, variables and behavior of that class.
10. What is serialization?
When we want to transport an object through network then we have to convert the object
into a stream of bytes. The process of converting an object into a stream of bytes is called
Serialization. For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.
12. What is difference between constants and read-only?
Constant variables are declared and initialized at compile time. The value can’t be
changed after wards. Read-only variables will be initialized only from the Static
constructor of the class. Read only is used only when we want to assign the value at run
time.
14. What are value types and reference types?
Value types are stored in the Stack whereas reference types stored on heap.
Value types:
20. Describe the accessibility modifier “protected internal”.
Protected Internal variables/methods are accessible within the same assembly and also
from the classes that are derived from this parent class.
21. What are the differences between System.String and System.Text.StringBuilder
classes?
System.String is immutable. When we modify the value of a string variable then a new
memory is allocated to the new value and the previous memory allocation released.
System.StringBuilder was designed to have concept of a mutable string where a variety
of operations can be performed without allocation separate memory location for the
modified string.
28. What are generics in C#.NET?
Generics are used to make reusable code classes to decrease the code redundancy,
increase type safety and performance. Using generics, we can create collection classes.
To create generic collection, System.Collections.Generic namespace should be used
instead of classes such as ArrayList in the System.Collections namespace. Generics
promotes the usage of parameterized types.
30. List down the commonly used types of exceptions in .Net?
ArgumentException, ArgumentNullException , ArgumentOutOfRangeException,
ArithmeticException, DivideByZeroException ,OverflowException ,
IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException ,
IOEndOfStreamException , NullReferenceException , OutOfMemoryException ,
StackOverflowException etc.
35. What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes
the method behavior. Method overloading is creating a method with the same name
within the same class having different signatures.
What is the difference between Server.Transfer and Response.Redirect?
In Server.Transfer page processing transfers from one page to the other page without
making a round-trip back to the client’s browser. This provides a faster response with a
little less overhead on the server. The clients url history list or current url Server does not
update in case of Server.Transfer.
Response.Redirect is used to redirect the user’s browser to another page or site. It
performs trip back to the client where the client’s browser is redirected to the new
page. The user’s browser history list is updated to reflect the new address.
5. From which base class all Web Forms are inherited?
Page class.
38. How can we set class to be inherited, but prevent the method from being overridden?
Declare the class as public and make the method sealed to prevent it from being
overridden.
40. What is the difference between a Struct and a Class?
Structs are value-type variables and classes are reference types. Structs stored on the
stack, causes additional overhead but faster retrieval. Structs cannot be inherited.
44. What’s a multicast delegate?
A delegate having multiple handlers assigned to it is called multicast delegate. Each
handler is assigned to a method.
45. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed
in the same way as array.
CType(expression, typename)
What is the difference between directcast and ctype?
DirectCast is used to convert the type of an object that requires the run-time type to be
the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and
the type.
50. Is C# code is managed or unmanaged code?
C# is managed code because Common language runtime can compile C# code to
Intermediate language.

can you explain how ASP.NET application life cycle and page life cycle events fire?
 what's the difference between delegates and events?
6. What are the different validators in ASP.NET?
7. Required field Validator
8. Range Validator
9. Compare Validator
10. Custom Validator
11. Regular expression Validator
12. Summary Validator
Which validator control you use if you need to make sure the values in two different
controls matched?
Compare Validator control.
40. How we can force all the validation controls to run?
The Page.Validate() method is used to force all the validation controls to run and to
perform validation.
8. What is ViewState?
ViewState is used to retain the state of server-side objects between page post backs
ViewState is stored in a hidden field on the page at client side. ViewState is transported
to the client and back to the server, and is not stored on the server or any other external
source.
13. What is caching?
Caching is a technique used to increase performance by keeping frequently accessed data
or files in memory. The request for a cached file/data will be accessed from cache instead
of actual location of that file.
5. Output Caching,
6. Fragment Caching,
7. Data Caching.
16. List the events in page life cycle.
8.
1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render
23. What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the
network traffic and saves server resources.
42. List the major built-in objects in ASP.NET?







Application
Request
Response
Server
Session
Context
Trace
49. What are the components of ADO.NET?

The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command,
connection.
Different Collections class in Asp.net
Can you explain the complete flow of MVC?
Below are the steps how control flows in MVC (Model, view and controller)
architecture:-



All end user requests are first sent to the controller.
The controller depending on the request decides which model to load. The controller
loads the model and attaches the model with the appropriate view.
The final view is then attached with the model data and sent as a response to the end user
on the browser.
What is the difference between DataSet and DataReader?
Following are some major differences between DataSet and DataReader:



DataReader provides forward-only and read-only access to data, while the DataSet object
can hold more than one table (in other words, more than one row set) from the same data
source as well as the relationships between them.
DataSet is a disconnected architecture while DataReader is a connected architecture.
DataSet can persist contents while DataReader cannot persist contents, they are forward
only.
WHAT IS REFLECTION?
What is CTS(Common type systems)
Difference between static and constant
Serialization and deserialization
Automation
Mobile development/Card development technology
XML namespace
Delegates
Accessmodifiers
Satelite assembly
Threading which namespace has threading diff between threads and process
Difference between Abstract class and interfaces
Events and delegates
Nested class
Event bubbling
Global.asax, Web.congif,machine.config…
Command and connection object
Difference between having and where clause
C# interview questions and answers
By admin | December 7, 2003
42. What’s the advantage of using System.Text.StringBuilder over
System.String?StringBuilder is more efficient in the cases, where a lot of
manipulation is done to the text. Strings are immutable, so each time it’s being
operated on, a new instance is created.
43. Can you store multiple data types in System.Array? No.
44. What’s the difference between the System.Array.CopyTo() and
System.Array.Clone()? The first one performs a deep copy of the array, the
second one is shallow.
45. How can you sort the elements of the array in descending order? By calling
Sort() and then Reverse() methods.
46. What’s the .NET datatype that allows the retrieval of data by a unique
key?HashTable.
47. What’s class SortedList underneath? A sorted HashTable.
48. Will finally block get executed if the exception had not occurred? Yes.
49. What’s the C# equivalent of C++ catch (…), which was a catch-all statement
for any possible exception? A catch block that catches the exception of type
System.Exception. You can also omit the parameter data type in this case and just
write catch {}.
50. Can multiple catch blocks be executed? No, once the proper catch code fires
off, the control is transferred to the finally block (if there are any), and then
whatever follows the finally block.
51. Why is it a bad idea to throw your own exceptions? Well, if at that point you
know that an error has occurred, then why not write the proper code to handle that
error instead of passing a new Exception object to the catch block? Throwing
your own exceptions signifies some design flaws in the project.
52. What’s a delegate? A delegate object encapsulates a reference to a method. In
C++ they were referred to as function pointers.
53. What’s a multicast delegate? It’s a delegate that points to and eventually fires
off several methods.
54. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the
application to specify not only the library it needs to run (which was available
under Win32), but also the version of the assembly.
55. What are the ways to deploy an assembly? An MSI installer, a CAB archive,
and XCOPY command.
56. What’s a satellite assembly? When you write a multilingual or multi-cultural
application in .NET, and want to distribute the core application separately from
the localized modules, the localized assemblies that modify the core application
are called satellite assemblies.
57. What namespaces are necessary to create a localized
application?System.Globalization, System.Resources.
58. What’s the difference between // comments, /* */ comments and ///
comments?Single-line, multi-line and XML documentation comments.
59. How do you generate documentation from the C# file commented properly
with a command-line compiler? Compile it with a /doc switch.
60. What’s the difference between <c> and <code> XML documentation
tag? Single line code example and multiple-line code example.
61. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
62. What debugging tools come with the .NET SDK? CorDBG – command-line
debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the
DbgCLR. To use CorDbg, you must compile the original C# file using the /debug
switch.
63. What does the This window show in the debugger? It points to the object that’s
pointed to by this reference. Object’s instance data is shown.
64. What does assert() do? In debug compilation, assert takes in a Boolean condition
as a parameter, and shows the error dialog if the condition is false. The program
proceeds without any interruption if the condition is true.
65. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace
class for both debug and release builds.
66. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The
tracing dumps can be quite verbose and for some applications that are constantly
running you run the risk of overloading the machine and the hard drive there. Five
levels range from None to Verbose, allowing to fine-tune the tracing activities.
67. Where is the output of TextWriterTraceListener redirected? To the Console
or a text file depending on the parameter passed to the constructor.
68. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe
process to the DbgClr debugger.
69. What are three test cases you should go through in unit testing? Positive test
cases (correct data, correct output), negative test cases (broken or missing data,
proper handling), exception test cases (exceptions are thrown and caught
properly).
70. Can you change the value of a variable while debugging a C#
application? Yes, if you are debugging via Visual Studio.NET, just go to
Immediate window.
71. Explain the three services model (three-tier application). Presentation (UI),
business (logic and underlying code) and data (from storage or other sources).
72. What are advantages and disadvantages of Microsoft-provided data provider
classes in ADO.NET? SQLServer.NET data provider is high-speed and robust,
but requires SQL Server license purchased from Microsoft. OLE-DB.NET is
universal for accessing other sources, like Oracle, DB2, Microsoft Access and
Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the
world. ODBC.NET is a deprecated layer provided for backward compatibility to
ODBC engines.
73. What’s the role of the DataReader class in ADO.NET connections? It returns
a read-only dataset from the data source when the command is executed.
74. What is the wildcard character in SQL? Let’s say you want to query
database with LIKE for all employees whose name starts with La. The
wildcard character is %, the proper query with LIKE would involve ‘La%’.
75. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it
is one unit of work and does not dependent on previous and following
transactions), Consistent (data is either committed or roll back, no “in-between”
case where something has been updated and something hasn’t), Isolated (no
transaction sees the intermediate results of the current transaction), Durable (the
values persist if the data had been committed even if the system crashes right
after).
76. What connections does Microsoft SQL Server support? Windows
Authentication (via Active Directory) and SQL Server authentication (via
Microsoft SQL Server username and passwords).
77. Which one is trusted and which one is untrusted? Windows Authentication is
trusted because the username and password are checked with the Active
Directory, the SQL Server authentication is untrusted, since SQL Server is the
only verifier participating in the transaction.
78. Why would you use untrusted verificaion? Web Services might use it, as well
as non-Windows applications.
79. What does the parameter Initial Catalog define inside Connection
String? The database name to connect to.
80. What’s the data provider name to connect to Access
database? Microsoft.Access.
81. What does Dispose method do with the connection object? Deletes it from the
memory.
82. What is a pre-requisite for connection pooling? Multiple processes must agree
that they will share the same connection, where every parameter is the same,
including the security settings.
3. What is a constructor?
A constructor is the method of a class that is called when an object of that class is
created. The constructor initializes class parameters and has the same name as the class.
5. How are methods overloaded in C#?
You can overload methods in C# by specifying different numbers or types of parameters
in the method definition. Overloading can help to give your program the flexibility it
needs to operate with different types of data input.
What is the top .NET class that everything is derived from?
System.Objects - See more at: http://www.aired.in/2009/10/c-realtime-interviewquestions-and_16.html#sthash.H1Dl7Cxx.dpuf
WHAT IS THE ADVANTAGE OF SERIALIZATION?
Serialization is the process of maintaing object in the form stream. it is useful in case of
remoting.
Serialization is the process of converting object into byte stream which is useful to
transport object(i.e remoting),persisting object(i.e files,database) - See more at:
http://www.aired.in/2009/10/c-realtime-interview-questionsand_16.html#sthash.H1Dl7Cxx.dpuf
What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting
class, and of course, within the class itself. - See more at: http://www.aired.in/2009/10/csharp-realtime-interview-questions.html#sthash.IQQU563w.dpuf
How to declare a constant variable in C#? What is the use of the const keyword?
If a variable needs to have a fixed value, that may not be changed across the application's
life, then it may be declared with the const keyword. The value assigned to a constant
variable (using the const keyword) must be known at the time of compilation
- See more at: http://www.aired.in/2009/11/c-realtime-interview-questionsand.html#sthash.PpQwUrKk.dpuf
Common classes and namespaces that are used












System
System.Collections
System.Data
System.Drawing
System.IO
System.Text
System.Threading
System.Timers
System.Web
System.Web.Services
System.Windows.Forms
System.Xml
SYSTEM.COLLECTION CLASSES







ArrayList: An ArrayList is a type of collection to which you can add items and
have it automatically grow. You can move through the items using a MoveNext
on the enumerator of the class. The ArrayList can have a maximum capacity and a
fixed size.
CollectionBase: This class is the base for a strongly-typed collection, critical for
creating collection classes, which are described below.
DictionaryBase: This class is the base for a strongly-typed collection utilizing
associated keys and values. This is similar to the Dictionaryobject found in
VBScript and used by many ASP developers.
SortedList: This class represents a collection of keys and values, and is
automatically sorted by the key. You can still access the values with either the key
or the index number.
Hashtable: This class represents a collection of keys and values, but the keys and
values are hashed using a hashing algorithm. Searching based on key is very fast,
and is moderately fast when based on value. The order of the items cannot be
determined, but if you need searching capabilities, this is the best collection to
use.
Queue: This class represents a collection that is to be used on a first-in, firstout or FIFO basis. This unsorted list lets you add items to the end and read (and
optionally remove) the items from the top.
Stack: In contrast to the FIFO nature of the Queue class, the Stack class
represents a collection for last-in, first-out or LIFO.
SYSTEM.DATA NAMESPACE





Connection: In the first version of ADO.NET, this will be either SqlConnection
or OleDbConnection. This class is responsible for making the actual connection to
the database, and it also handles starting a transaction.
Command: This will be either SqlCommand or OleDbCommand. This class
allows you to issue SQL statements or call stored procedures. It is the object that
will actually execute the command, and may return data.
DataReader: Either SqlDataReader or OleDbDataReader, this object is used to
read data in a forward-only manner. This is the firehose cursor with which most
ADO developers are familiar.
DataAdapters: Either SqlDataAdapter or OleDbDataAdapter, this object
encapsulates a connection and one or more commands. It gets data and fills a
DataSet object with data.
DataSets: Either SqlDataSet or OleDbDataSet, this is the ADO.NET
disconnected data cache. It stores data in memory in a schema, and applications
can use it like a database, accessing and updating data.SYS
SYSTEM.IO
there are Exists, Open, OpenRead, OpenText, andOpenWrite shared methods
for performing file IO.
The System.Threading Namespace
Thread object
MAxCount, dostuffs
The System.Web Namespace
Windows forms, server controls,
SYSTEM.WEBSERVICES
XML Web services are one of the newest and most exciting additions to the world of
development. XML Web services have been available for some time on the Microsoft
platform, thanks to the SOAP Toolkit.
The System.Windows.Forms
here are classes such as Button, Label, and TextBox.
ADO.NET
object
Description
DataReader
Provides a forward-only, read-only stream of data from a data source.
The DataReader is similar to a Recordset with CursorType =
adOpenForwardOnly and LockType = adLockReadOnly.
DataSet
Provides in-memory access to relational data.
The DataSet is independent of any specific data source and therefore can be populated from
multiple and differing data sources including relational databases and XML, or can be populated
with data local to the application. Data is stored in a collection of one or more tables, and can be
accessed non-sequentially and without limits to availability, unlike ADO in which data must be
accessed a single row at a time. A DataSet can contain relationships between tables, similar to
the ADO Recordset in which a single result set is created from a JOIN. A DataSet can also
contain unique, primary key, and foreign key constraints on its tables.
The DataSet is similar to a Recordset with CursorLocation = adUseClient, CursorType =
adOpenStatic, and LockType = adLockOptimistic. However, the DataSet has extended
capabilities over the Recordset for managing application data.
DataAdapter
Populates a DataSet with data from a relational database and resolves changes in
the DataSet back to the data source.
The DataAdapter enables you to explicitly specify behavior that the Recordset performs
implicitly.
System.Collections Classes
The classes in the System.Collections namespace do not store elements as specifically
typed objects, but as objects of type Object.
Whenever possible, you should use the generic collections in
the System.Collections.Generic namespace or
the System.Collections.Concurrentnamespace instead of the legacy types in
the System.Collections namespace.
Class
Description
ArrayList
Represents an array of objects whose size is dynamically increased as required.
Hashtable
Represents a collection of key/value pairs that are organized based on the hash code of the key.
Queue
Represents a first in, first out (FIFO) collection of objects.
Stack
Represents a last in, first out (LIFO) collection of objects.
The following table lists some of the frequently used classes in
the System.Collections namespace:
The System.Collections.Specialized namespace provides specialized and strongly typed
collection classes, such as string-only collections and linked-list and hybrid dictionaries.
Many common collections are provided by the .NET Framework. Each type of collection
is designed for a specific purpose.
The following groups of collection classes are described in this section:
 System.Collections.Generic classes
 System.Collections.Concurrent classes
 System.Collections classes
 Visual Basic Collection class

System.Collections.Generic Classes



You can create a generic collection by using one of the classes in
the System.Collections.Generic namespace. A generic collection is useful when
every item in the collection has the same data type. A generic collection enforces
strong typing by allowing only the desired data type to be added.
The following table lists some of the frequently used classes of
the System.Collections.Generic namespace:
Class
Description
Dictionary<TKey,
TValue>
Represents a collection of key/value pairs that are organized based on the key.
List<T>
Represents a list of objects that can be accessed by index. Provides methods to search, sort,
lists.
Queue<T>
Represents a first in, first out (FIFO) collection of objects.
SortedList<TKey,
TValue>
Represents a collection of key/value pairs that are sorted by key based on the
associated IComparer<T>implementation.
Stack<T>
Represents a last in, first out (LIFO) collection of objects.

For additional information, see Commonly Used Collection Types, Selecting a
Collection Class, and System.Collections.Generic.
MVC INTERVIEW QUESTIONS
Asp.net interview question:
How does PostBack work?
PostBack is basically the ASP.NET submitting a form to it -- it posts back to the current
URL. The JavaScript __doPostBack function is placed on the page (look at the source
within the browser) to facilitate. PostBack uses ViewState to remember controls and data.
The IsPostBack property of the ASP.NET page allows you to determine if the loading of
the page is the result of a postback event; this is done in the Page_Load event.
What are ASP.NET Server controls?
ASP.NET includes a number of built-in server controls that are the foundation of its Web
programming model. They have various properties to control their behavior and
appearance. These controls provide an event model where events are handled on the
server (whereas HTML controls are handled in the client). Server controls have the
ability to maintain state (via ViewState) across requests, and they can automatically
detect the browser. With these controls, you will see the RunAt attribute
(RunAt="Server") that signals its processing will be done on the server. A good example
of these controls is the basic TextBox control (<ASP:TextBox RunAt="Server" .... >.
What is View State?
Basically, View State is how ASP.NET Web pages persists data across requests. It
handles data that must be preserved between postbacks, and you can use it to store pagespecific data. By default, View State is enabled on a page and its controls. This can be a
problem as the amount of data and controls on a page increases resulting in more data for
ASP.NET to maintain. This is accomplished via the hidden __VIEWSTATE field on a
form (look at the page source in a browser), so more data in this field means a slower
load time and slower overall processing, as it has to be posted to the server each time.
You can limit the size of the data in View State by disabling controls that do not need to
be persisted via the EnableViewState property. View State can be encrypted to address
security concerns.
How can you loop through all controls on an ASP.NET Web form?
You can easily traverse all controls on a form via the Web Form's Controls collection.
The GetType method can be used on each control to determine its type and how to work
with it. Now, it gets tricky because the form contains a tree of controls; that is, some
controls are contained within others (think of a Table). You would have to recursively
loop through the controls to make sure everything is processed.
What is a web.config file? Machine.config?
The web.config is the basic configuration file for ASP.NET applications. It utilizes an
XML format. It is used to define application settings, connection strings, and much more.
These files can appear in multiple directories, and they are applied in a top-down
approach; that is, configuration files apply to their container directory as well as all
directories below it, but the configuration files in lower directories can override those in
parent directories. This provides a way to granularly apply settings. The machine.config
file contains ASP.NET settings for all of the applications on the server -- it is at the top of
the configuration file hierarchy, thus web.configs can override it.
What is the global.asax file?
The global.asax file is an optional piece of an ASP.NET application. It is located in the
root of the application directory structure. It cannot be directly loaded or requested by
users. It provides a place to define application- and session-wide events. You can define
your own events, but it does contain default Application events like when the application
starts Application_Start and ends with Application_End. The same is true for Session
events (Session_Start and Session_End).
How can you pass values between ASP.NET pages?
There are numerous ways to accomplish this task; the option you choose depends on the
environment. The oldest way to approach it is via the QueryString (i.e., passing values
via URL); this is also one of the least secure ways because users can easily see the data
and could possibly hack the site/page by changing parameter values. Next, you can use
HTTP POST to pass values; these are available via a collection within the ASP.NET
page. More specific to ASP.NET is the use of Session state, which makes information
available to all pages within the ASP.NET application. Another approach is using public
properties on the source page and accessing these properties on the target page. Also, you
can use the PreviousPage property of the current page to access control information on
the referring page. The last two require the source, and target pages are within the same
ASP.NET application.
What are ASHX files?
ASP.NET Web handler files have an .ashx file extension. Web handlers work just like
.aspx files except you don't have to deal with the browser interface, thus no worrying
about presentation. Web handlers are generally used to generate content dynamically like
returning XML or an image. Web handlers use the IHttpHandler interface with the
ProcessRequest() method invoked when the handler is requested. Web handlers are
simpler than pages (fewer events and wiring), so they are ideal for performance-critical
applications.
What is a master page?
A master page is a template for one or more Web Forms. The master page defines how
the page will be laid out when presented to the user, with placeholders for content. The
MasterPageFile Page Directive in a content page's header is one way to assign a master
page. The content pages rely solely on content and leave layout to the master page.
ASP.NET merges the content with the master page layout when the content page is
requested by a user.
What is the code behind feature of ASP.NET?
The code behind feature divides ASP.NET page files into two files where one defines the
user interface (.aspx), while the other contains all of the logic or code (.aspx.cs for C#
and .aspx.vb for VB.NET). These two files are glued together with page directives like
the following line, which ties the page to the specific code behind class.
What are page directives?
The first line of an ASP.NET page is the page directive; you will find it on all ASP.NET
pages. These directives are instructions for the page. It begins with the @Page directive
and continues with the various attributes available to this directive.
It's unreasonable to expect a candidate to know all of these attributes, but a few popular
ones include the following.








AutoEventWireup: Indicates whether page events are autowired.
CodeBehind: The name of the compiled class associated with the page.
Debug: Indicates whether the page is compiled in debug mode (includes debug
symbols).
EnableTheming: Indicates whether themes are used on the page.
EnableViewState: Indicates whether view state is maintained across pages.
ErrorPage: Specifies a target URL to be used when unhandled exceptions occur.
Language: Indicates the language used when compiling inline code on the page.
Trace: Signals whether tracing is enabled on the page.
1. What is C#?
C# is an object oriented, type safe and managed language that is compiled by .Net
framework to generate Microsoft Intermediate Language.
What is the difference between public, static and void?
All these are access modifiers in C#. Public declared variables or methods are accessible
anywhere in the application. Static declared variables or methods are globally accessible
without creating an instance of the class. The compiler stores the address of the method
as the entry point and uses this information to begin execution before any objects are
created. And Void is a type modifier that states that the method or variable does not
return any value
What is an object?
An object is an instance of a class through which we access the methods of that class.
“New” keyword is used to create an object. A class that creates an object in memory will
contain the information about the methods, variables and behavior of that class.
10. What is serialization?
When we want to transport an object through network then we have to convert the object
into a stream of bytes. The process of converting an object into a stream of bytes is called
Serialization. For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.
12. What is difference between constants and read-only?
Constant variables are declared and initialized at compile time. The value can’t be
changed after wards. Read-only variables will be initialized only from the Static
constructor of the class. Read only is used only when we want to assign the value at run
time.
14. What are value types and reference types?
Value types are stored in the Stack whereas reference types stored on heap.
Value types:
20. Describe the accessibility modifier “protected internal”.
Protected Internal variables/methods are accessible within the same assembly and also
from the classes that are derived from this parent class.
21. What are the differences between System.String and System.Text.StringBuilder
classes?
System.String is immutable. When we modify the value of a string variable then a new
memory is allocated to the new value and the previous memory allocation released.
System.StringBuilder was designed to have concept of a mutable string where a variety
of operations can be performed without allocation separate memory location for the
modified string.
28. What are generics in C#.NET?
Generics are used to make reusable code classes to decrease the code redundancy,
increase type safety and performance. Using generics, we can create collection classes.
To create generic collection, System.Collections.Generic namespace should be used
instead of classes such as ArrayList in the System.Collections namespace. Generics
promotes the usage of parameterized types.
30. List down the commonly used types of exceptions in .Net?
ArgumentException, ArgumentNullException , ArgumentOutOfRangeException,
ArithmeticException, DivideByZeroException ,OverflowException ,
IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException ,
IOEndOfStreamException , NullReferenceException , OutOfMemoryException ,
StackOverflowException etc.
35. What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes
the method behavior. Method overloading is creating a method with the same name
within the same class having different signatures.
What is the difference between Server.Transfer and Response.Redirect?
In Server.Transfer page processing transfers from one page to the other page without
making a round-trip back to the client’s browser. This provides a faster response with a
little less overhead on the server. The clients url history list or current url Server does not
update in case of Server.Transfer.
Response.Redirect is used to redirect the user’s browser to another page or site. It
performs trip back to the client where the client’s browser is redirected to the new
page. The user’s browser history list is updated to reflect the new address.
5. From which base class all Web Forms are inherited?
Page class.
38. How can we set class to be inherited, but prevent the method from being overridden?
Declare the class as public and make the method sealed to prevent it from being
overridden.
40. What is the difference between a Struct and a Class?
Structs are value-type variables and classes are reference types. Structs stored on the
stack, causes additional overhead but faster retrieval. Structs cannot be inherited.
44. What’s a multicast delegate?
A delegate having multiple handlers assigned to it is called multicast delegate. Each
handler is assigned to a method.
45. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed
in the same way as array.
CType(expression, typename)
What is the difference between directcast and ctype?
DirectCast is used to convert the type of an object that requires the run-time type to be
the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and
the type.
50. Is C# code is managed or unmanaged code?
C# is managed code because Common language runtime can compile C# code to
Intermediate language.

can you explain how ASP.NET application life cycle and page life cycle events fire?
 what's the difference between delegates and events?
6. What are the different validators in ASP.NET?
13. Required field Validator
14. Range Validator
15. Compare Validator
16. Custom Validator
17. Regular expression Validator
18. Summary Validator
Which validator control you use if you need to make sure the values in two different
controls matched?
Compare Validator control.
40. How we can force all the validation controls to run?
The Page.Validate() method is used to force all the validation controls to run and to
perform validation.
8. What is ViewState?
ViewState is used to retain the state of server-side objects between page post backs
ViewState is stored in a hidden field on the page at client side. ViewState is transported
to the client and back to the server, and is not stored on the server or any other external
source.
13. What is caching?
Caching is a technique used to increase performance by keeping frequently accessed data
or files in memory. The request for a cached file/data will be accessed from cache instead
of actual location of that file.
9. Output Caching,
10. Fragment Caching,
11. Data Caching.
16. List the events in page life cycle.
12. 1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render
23. What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the
network traffic and saves server resources.
42. List the major built-in objects in ASP.NET?







Application
Request
Response
Server
Session
Context
Trace
49. What are the components of ADO.NET?

The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command,
connection.
Different Collections class in Asp.net
Can you explain the complete flow of MVC?
Below are the steps how control flows in MVC (Model, view and controller)
architecture:


All end user requests are first sent to the controller.
The controller depending on the request decides which model to load. The controller
loads the model and attaches the model with the appropriate view.
The final view is then attached with the model data and sent as a response to the end user
on the browser.
What is the difference between DataSet and DataReader?
Following are some major differences between DataSet and DataReader:



DataReader provides forward-only and read-only access to data, while the DataSet object
can hold more than one table (in other words, more than one row set) from the same data
source as well as the relationships between them.
DataSet is a disconnected architecture while DataReader is a connected architecture.
DataSet can persist contents while DataReader cannot persist contents, they are forward
only.
WHAT IS REFLECTION?
What is CTS(Common type systems)
Difference between static and constant
Serialization and deserialization
Automation
Mobile development/Card development technology
XML namespace
Delegates
Accessmodifiers
Satelite assembly
Threading which namespace has threading diff between threads and process
Difference between Abstract class and interfaces
Events and delegates
Nested class
Event bubbling
Global.asax, Web.congif,machine.config…
Command and connection object
Difference between having and where clause
C# interview questions and answers
By admin | December 7, 2003
83. What’s the advantage of using System.Text.StringBuilder over
System.String?StringBuilder is more efficient in the cases, where a lot of
manipulation is done to the text. Strings are immutable, so each time it’s being
operated on, a new instance is created.
84. Can you store multiple data types in System.Array? No.
85. What’s the difference between the System.Array.CopyTo() and
System.Array.Clone()? The first one performs a deep copy of the array, the
second one is shallow.
86. How can you sort the elements of the array in descending order? By calling
Sort() and then Reverse() methods.
87. What’s the .NET datatype that allows the retrieval of data by a unique
key?HashTable.
88. What’s class SortedList underneath? A sorted HashTable.
89. Will finally block get executed if the exception had not occurred? Yes.
90. What’s the C# equivalent of C++ catch (…), which was a catch-all statement
for any possible exception? A catch block that catches the exception of type
System.Exception. You can also omit the parameter data type in this case and just
write catch {}.
91. Can multiple catch blocks be executed? No, once the proper catch code fires
off, the control is transferred to the finally block (if there are any), and then
whatever follows the finally block.
92. Why is it a bad idea to throw your own exceptions? Well, if at that point you
know that an error has occurred, then why not write the proper code to handle that
error instead of passing a new Exception object to the catch block? Throwing
your own exceptions signifies some design flaws in the project.
93. What’s a delegate? A delegate object encapsulates a reference to a method. In
C++ they were referred to as function pointers.
94. What’s a multicast delegate? It’s a delegate that points to and eventually fires
off several methods.
95. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the
application to specify not only the library it needs to run (which was available
under Win32), but also the version of the assembly.
96. What are the ways to deploy an assembly? An MSI installer, a CAB archive,
and XCOPY command.
97. What’s a satellite assembly? When you write a multilingual or multi-cultural
application in .NET, and want to distribute the core application separately from
the localized modules, the localized assemblies that modify the core application
are called satellite assemblies.
98. What namespaces are necessary to create a localized
application?System.Globalization, System.Resources.
99. What’s the difference between // comments, /* */ comments and ///
comments?Single-line, multi-line and XML documentation comments.
100.
How do you generate documentation from the C# file commented
properly with a command-line compiler? Compile it with a /doc switch.
101.
What’s the difference between <c> and <code> XML documentation
tag? Single line code example and multiple-line code example.
102.
Is XML case-sensitive? Yes, so <Student> and <student> are different
elements.
103.
What debugging tools come with the .NET SDK? CorDBG –
command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET
uses the DbgCLR. To use CorDbg, you must compile the original C# file using
the /debug switch.
104.
What does the This window show in the debugger? It points to the
object that’s pointed to by this reference. Object’s instance data is shown.
105.
What does assert() do? In debug compilation, assert takes in a Boolean
condition as a parameter, and shows the error dialog if the condition is false. The
program proceeds without any interruption if the condition is true.
106.
What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace
class for both debug and release builds.
107.
Why are there five tracing levels in
System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose
and for some applications that are constantly running you run the risk of
overloading the machine and the hard drive there. Five levels range from None to
Verbose, allowing to fine-tune the tracing activities.
108.
Where is the output of TextWriterTraceListener redirected? To the
Console or a text file depending on the parameter passed to the constructor.
109.
How do you debug an ASP.NET Web application? Attach the
aspnet_wp.exe process to the DbgClr debugger.
110.
What are three test cases you should go through in unit
testing? Positive test cases (correct data, correct output), negative test cases
(broken or missing data, proper handling), exception test cases (exceptions are
thrown and caught properly).
111.
Can you change the value of a variable while debugging a C#
application? Yes, if you are debugging via Visual Studio.NET, just go to
Immediate window.
112.
Explain the three services model (three-tier application). Presentation
(UI), business (logic and underlying code) and data (from storage or other
sources).
113.
What are advantages and disadvantages of Microsoft-provided data
provider classes in ADO.NET? SQLServer.NET data provider is high-speed and
robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET
is universal for accessing other sources, like Oracle, DB2, Microsoft Access and
Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the
world. ODBC.NET is a deprecated layer provided for backward compatibility to
ODBC engines.
114.
What’s the role of the DataReader class in ADO.NET connections? It
returns a read-only dataset from the data source when the command is executed.
115.
What is the wildcard character in SQL? Let’s say you want to query
database with LIKE for all employees whose name starts with La. The
wildcard character is %, the proper query with LIKE would involve ‘La%’.
116.
Explain ACID rule of thumb for transactions. Transaction must be
Atomic (it is one unit of work and does not dependent on previous and following
transactions), Consistent (data is either committed or roll back, no “in-between”
case where something has been updated and something hasn’t), Isolated (no
transaction sees the intermediate results of the current transaction), Durable (the
values persist if the data had been committed even if the system crashes right
after).
117.
What connections does Microsoft SQL Server support? Windows
Authentication (via Active Directory) and SQL Server authentication (via
Microsoft SQL Server username and passwords).
118.
Which one is trusted and which one is untrusted? Windows
Authentication is trusted because the username and password are checked with
the Active Directory, the SQL Server authentication is untrusted, since SQL
Server is the only verifier participating in the transaction.
119.
Why would you use untrusted verificaion? Web Services might use it,
as well as non-Windows applications.
120.
What does the parameter Initial Catalog define inside Connection
String? The database name to connect to.
121.
What’s the data provider name to connect to Access
database? Microsoft.Access.
122.
What does Dispose method do with the connection object? Deletes it
from the memory.
123.
What is a pre-requisite for connection pooling? Multiple processes
must agree that they will share the same connection, where every parameter is the
same, including the security settings.
3. What is a constructor?
A constructor is the method of a class that is called when an object of that class is
created. The constructor initializes class parameters and has the same name as the class.
5. How are methods overloaded in C#?
You can overload methods in C# by specifying different numbers or types of parameters
in the method definition. Overloading can help to give your program the flexibility it
needs to operate with different types of data input.
What is the top .NET class that everything is derived from?
System.Objects - See more at: http://www.aired.in/2009/10/c-realtime-interviewquestions-and_16.html#sthash.H1Dl7Cxx.dpuf
WHAT IS THE ADVANTAGE OF SERIALIZATION?
Serialization is the process of maintaing object in the form stream. it is useful in case of
remoting.
Serialization is the process of converting object into byte stream which is useful to
transport object(i.e remoting),persisting object(i.e files,database) - See more at:
http://www.aired.in/2009/10/c-realtime-interview-questionsand_16.html#sthash.H1Dl7Cxx.dpuf
What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting
class, and of course, within the class itself. - See more at: http://www.aired.in/2009/10/csharp-realtime-interview-questions.html#sthash.IQQU563w.dpuf
How to declare a constant variable in C#? What is the use of the const keyword?
If a variable needs to have a fixed value, that may not be changed across the application's
life, then it may be declared with the const keyword. The value assigned to a constant
variable (using the const keyword) must be known at the time of compilation
- See more at: http://www.aired.in/2009/11/c-realtime-interview-questionsand.html#sthash.PpQwUrKk.dpuf
Common classes and namespaces that are used









System
System.Collections
System.Data
System.Drawing
System.IO
System.Text
System.Threading
System.Timers
System.Web



System.Web.Services
System.Windows.Forms
System.Xml
SYSTEM.COLLECTION CLASSES







ArrayList: An ArrayList is a type of collection to which you can add items and
have it automatically grow. You can move through the items using a MoveNext
on the enumerator of the class. The ArrayList can have a maximum capacity and a
fixed size.
CollectionBase: This class is the base for a strongly-typed collection, critical for
creating collection classes, which are described below.
DictionaryBase: This class is the base for a strongly-typed collection utilizing
associated keys and values. This is similar to the Dictionaryobject found in
VBScript and used by many ASP developers.
SortedList: This class represents a collection of keys and values, and is
automatically sorted by the key. You can still access the values with either the key
or the index number.
Hashtable: This class represents a collection of keys and values, but the keys and
values are hashed using a hashing algorithm. Searching based on key is very fast,
and is moderately fast when based on value. The order of the items cannot be
determined, but if you need searching capabilities, this is the best collection to
use.
Queue: This class represents a collection that is to be used on a first-in, firstout or FIFO basis. This unsorted list lets you add items to the end and read (and
optionally remove) the items from the top.
Stack: In contrast to the FIFO nature of the Queue class, the Stack class
represents a collection for last-in, first-out or LIFO.
SYSTEM.DATA NAMESPACE




Connection: In the first version of ADO.NET, this will be either SqlConnection
or OleDbConnection. This class is responsible for making the actual connection to
the database, and it also handles starting a transaction.
Command: This will be either SqlCommand or OleDbCommand. This class
allows you to issue SQL statements or call stored procedures. It is the object that
will actually execute the command, and may return data.
DataReader: Either SqlDataReader or OleDbDataReader, this object is used to
read data in a forward-only manner. This is the firehose cursor with which most
ADO developers are familiar.
DataAdapters: Either SqlDataAdapter or OleDbDataAdapter, this object
encapsulates a connection and one or more commands. It gets data and fills a
DataSet object with data.

DataSets: Either SqlDataSet or OleDbDataSet, this is the ADO.NET
disconnected data cache. It stores data in memory in a schema, and applications
can use it like a database, accessing and updating data.SYS
SYSTEM.IO
there are Exists, Open, OpenRead, OpenText, andOpenWrite shared methods
for performing file IO.
The System.Threading Namespace
Thread object
MAxCount, dostuffs
The System.Web Namespace
Windows forms, server controls,
SYSTEM.WEBSERVICES
XML Web services are one of the newest and most exciting additions to the world of
development. XML Web services have been available for some time on the Microsoft
platform, thanks to the SOAP Toolkit.
The System.Windows.Forms
here are classes such as Button, Label, and TextBox.
ADO.NET
object
Description
DataReader
Provides a forward-only, read-only stream of data from a data source.
The DataReader is similar to a Recordset with CursorType =
adOpenForwardOnly and LockType = adLockReadOnly.
DataSet
Provides in-memory access to relational data.
The DataSet is independent of any specific data source and therefore can be populated from
multiple and differing data sources including relational databases and XML, or can be populated
with data local to the application. Data is stored in a collection of one or more tables, and can be
accessed non-sequentially and without limits to availability, unlike ADO in which data must be
accessed a single row at a time. A DataSet can contain relationships between tables, similar to
the ADO Recordset in which a single result set is created from a JOIN. A DataSet can also
contain unique, primary key, and foreign key constraints on its tables.
The DataSet is similar to a Recordset with CursorLocation = adUseClient, CursorType =
adOpenStatic, and LockType = adLockOptimistic. However, the DataSet has extended
capabilities over the Recordset for managing application data.
DataAdapter
Populates a DataSet with data from a relational database and resolves changes in
the DataSet back to the data source.
The DataAdapter enables you to explicitly specify behavior that the Recordset performs
implicitly.
System.Collections Classes
The classes in the System.Collections namespace do not store elements as specifically
typed objects, but as objects of type Object.
Whenever possible, you should use the generic collections in
the System.Collections.Generic namespace or
the System.Collections.Concurrentnamespace instead of the legacy types in
the System.Collections namespace.
Class
Description
ArrayList
Represents an array of objects whose size is dynamically increased as required.
Hashtable
Represents a collection of key/value pairs that are organized based on the hash code of the key.
Queue
Represents a first in, first out (FIFO) collection of objects.
Stack
Represents a last in, first out (LIFO) collection of objects.
The following table lists some of the frequently used classes in
the System.Collections namespace:
The System.Collections.Specialized namespace provides specialized and strongly typed
collection classes, such as string-only collections and linked-list and hybrid dictionaries.
Many common collections are provided by the .NET Framework. Each type of collection
is designed for a specific purpose.
The following groups of collection classes are described in this section:
 System.Collections.Generic classes
 System.Collections.Concurrent classes
 System.Collections classes
 Visual Basic Collection class

System.Collections.Generic Classes



You can create a generic collection by using one of the classes in
the System.Collections.Generic namespace. A generic collection is useful when
every item in the collection has the same data type. A generic collection enforces
strong typing by allowing only the desired data type to be added.
The following table lists some of the frequently used classes of
the System.Collections.Generic namespace:
Class
Description
Dictionary<TKey,
TValue>
Represents a collection of key/value pairs that are organized based on the key.
List<T>
Represents a list of objects that can be accessed by index. Provides methods to search, sort,
lists.
Queue<T>
Represents a first in, first out (FIFO) collection of objects.
SortedList<TKey,
TValue>
Represents a collection of key/value pairs that are sorted by key based on the
associated IComparer<T>implementation.
Stack<T>
Represents a last in, first out (LIFO) collection of objects.

For additional information, see Commonly Used Collection Types, Selecting a
Collection Class, and System.Collections.Generic.
WCF Interview Questions
(A very good tool SVCutil.exe: to generate and register the proxy)
What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying
services on Windows. WCF provides a runtime environment for services, enabling you to
expose CLR types as services, and to consume other services as CLR types.
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that
support it.
The main components of WCF are
1. Service class
2. Hosting environment
3. End point
Following bindings supports the streaming in WCF:
1. basicHttpBinding
2. netTcpBinding
3. netNamedPipeBinding
ADVANTATAGES
(1) Inter-operability with applications built on differnet technologies.
(2) Unification of the original Dotnet Framework communication Technologies.
(3) Support for Service Oriented Architecture (SOA).
DIFFERENCE BETWEEN WEB SERVICES AND WCF
Web Services
1.It Can be accessed only over HTTP
2.It works in stateless environment
WCF
WCF is flexible because its services can be hosted in different types of applications. The
following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service
What is Bindings?
Mechanism specifying transport encoding and protocol is called binding
What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
What are contracts in WCF?
 In WCF, all services expose contracts. The contract is a platform-neutral and
standard way of describing what the service does.
WCF defines four types of contracts.
Service contracts
Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.
 Data contracts
Define which data types are passed to and from the service. WCF defines implicit
contracts for built-in types such as int and string, but we can easily define explicit
opt-in data contracts for custom types.
There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.
 If DataMember attributes are not specified for a properties in the class, that
property can't be passed to-from web service.
Fault contracts
Define which errors are raised by the service, and how the service handles and
propagates errors to its clients.
Message contracts
Allow the service to interact directly with messages. Message contracts can be
typed or untyped, and are useful in interoperability cases and when there is an
existing message format we have to comply with.
Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF
services.
They are 1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)
What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the
transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A
binding can contain binding elements that specify details like the security mechanisms
used to secure messages, or the message pattern used by an endpoint.
WCF
supports
nine
types
of
bindings.
Basicbinding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a
legacy ASMX web service, so that old clients can work with new services. When used by
the client, this binding enables new WCF clients to work with old ASMX services.
TCPbinding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on
the intranet. It supports a variety of features, including reliability, transactions, and
security, and is optimized for WCF-to-WCF communication. As a result, it requires both
the
client
and
the
service
to
use
WCF.
Peernetworkbinding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The
peer network-enabled client and services all subscribe to the same grid and
broadcastmessagestoit.
IPCbinding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for
same-machine communication. It is the most secure binding since it cannot accept calls
from outside the machine and it supports a variety of features similar to the TCPbinding.
WebService(WS)binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is
designed to offer a variety of features such as reliability, transactions, and security
overtheInternet.
FederatedWSbinding
Offered by the WSFederationHttpBinding class, this is a specialization of the binding,
offering
support
for
federated
security.
DuplexWSbinding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also
supports bidirectional communication from the service to the client.
MSMQbinding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to
offer
support
for
disconnected
queued
calls.
MSMQintegrationbinding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from
MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that
defines what the service does and a Binding that defines how to communicate with the
service. In WCF the relationship between Address, Contract and Binding is
calledEndpoint.
The Endpoint is the fusion of Address, Contract and Binding.
How to define a service as REST based service in WCF?
WCF 3.5 provides explicit support for RESTful communication using a new binding
named
sWebHttpBinding.
The
below
code
shows
how
to
expose
a
RESTful
service
[ServiceContract]
interface
{
[OperationContract]
[WebGet]
int
}
IStock
GetStock(string
StockId);
WHAT IS PROXY AND HOW THEY ARE GENERATED
It is a class by which a service client can interact with the service. The client will make
an object of the proxy class and by the help of it will call different methods exposed by
the service.
The proxy is a CLR class that exposes a single CLR interface representing the service
contract. The proxy provides the same operations as service's contract, but also has
additional methods for managing the proxy life cycle and the connection to the service.
The proxy completely encapsulates every aspect of the service: its location, its
implementation technology and runtime platform, and the communication transport.
The proxy can be generated using Visual Studio by right clicking Reference and
clicking on Add Service Reference. This brings up the Add Service Reference dialog
box, where you need to supply the base address of the service (or a base address and a
MEX URI) and the namespace to contain the proxy.
Proxy can also be generated by using SvcUtil.exe command-line utility. We need to
provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address
and, optionally, with a proxy filename. The default proxy filename is output.cs but you
can also use the /out switch to indicate a different name.
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we
must provide that port number as part of the base address:
SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
SOA is Service Oriented Architecture. SOA service is the encapsulation of a high level
business concept. A SOA service is composed of three parts.
1. A service class implementing the service to be provided.
2. An environment to host the service.
3. One or more endpoints to which clients will connect.
What is .svc file in WCF?
Posted by: Prasham
.svc file is a text file. This file is similar to our .asmx file in web services.
This file contains the details required for WCF service to run it successfully.
This file contains following details :
1. Language (C# / VB)
2. Name of the service
3. Where the service code resides
Example of .svc file
<%@ ServiceHost Language="C#/VB" Debug="true/false" CodeBehind="Service code
files path" Service="ServiceName"
We can also write our service code inside but this is not the best practice.
What is DataContractSerializer in WCF?
Posted by: Prasham
DataContractSerializer
is
new
WCF
serializer.
This is serialization engine in WCF. DataContractSerializer translate the .NET
framework objects into XML and vice-versa.
DIFFERENCE
from
XMLSERIALIZER
By default WCF uses DataContractSeriazer.
a. DataContractSerializer is the default serializer fot the WCF
b. DataContractSerializer is very fast.
c. DataContractSerializer is basically for very small, simple subset of the XML
infoset.
d. XMLSerializer is used for complex schemas
System.runtime.serialization Namespace:
WCF uses the class to convert objects into a stream of data suitable for transmitting over
the network (this process is known as Serialization). It also uses them to convert a stream
of data received from the network back into objects (De-Serialization).
What is the difference between a web-garden and a web-farm?
Web-garden - An IIS6.0 feature where you can configure an application pool as a webgarden and also specify the number of worker processes for that pool. It can help improve
performance in some cases.
Web-farm - a general term referring to a cluster of physically separate machines, each
running a web-server for scalability and performance (contrast this with web-garden
which refers to multiple processes on one single physical machine).
JAVASCRIPT
What can javascript programs do?
Generation of HTML pages on-the-fly without accessing the Web server. The user can be
given control over the browser like User input validation Simple computations can be
performed on the client's machine The user's browser, OS, screen size, etc. can be
detected Date and Time Handling
What is the difference between undefined value and null value?
(i)Undefined value cannot be explicitly stated that is there is no keyword called
undefined whereas null value has keyword called null
(ii)typeof undefined variable or property returns undefined whereas typeof null value
returns object
What looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.
How to comment javascript code?
Use // for line comments and
/*
*/ for block comments
What is this keyword?
It refers to the current object.
What does javascript null mean?
The null value is a unique value representing no value or no object.
It implies no object,or null string,no valid boolean value,no number and no array object.
How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};
What is === operator ?
==== is strict equality operator ,it returns true only when the two operands are having the
same value without any type conversion.
How to create arrays in JavaScript?
We can declare an array like this
var scripts = new Array();
We can add elements to this array like this
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
How do you target a specific frame from a hyperlink?
Include the name of the frame in the target attribute of the hyperlink. <a
href=”mypage.htm” target=”myframe”>>My Page</a>
Where are cookies actually stored on the hard disk?
This depends on the user's browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called
cookies.txt
How to add Buttons in JavaScript?
The most basic and ancient use of buttons are the "submit" and "clear",
What does isNaN function do?
Return true if the argument is not a number.
What is negative infinity?
It’s a number in JavaScript, derived by dividing negative number by zero.
What is the data type of variables of in JavaScript?
All variables are of object type in JavaScript.
Methods GET and POST in HTML forms - what's the difference?
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent
via the GET method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data
that can be transferred using POST. However, there are limits on the maximum amount
of data that can be transferred in one name/value pair.
Is a javascript script faster than an ASP script?
Yes.Since javascript is a client-side script it does require the web server's help for its
computation,so it is always faster than any server-side script like ASP,PHP,etc..
What Boolean operators does JavaScript support?
&&, || and !
How to set the focus in an element using Javascript?
<script> function setFocus() { if(focusElement != null) {
document.forms[0].elements["myelementname"].focus(); } } </script>
What is the difference between SessionState and ViewState?
ViewState is specific to a page in a session. Session state refers to user specific data that
can be accessed across all pages in the web application.
How to create a popup warning box
alert('Warning: Please enter an integer between 0 and 100.');
How to create a confirmation box?
confirm("Do you really want to launch the missile?");
How to create an input box?
prompt("What is your temperature?");
how to force a page to go to another page using JavaScript ?
<script language="JavaScript" type="text/javascript" ><!-location.href="http://newhost/newpath/newfile.html"; //--></script>
What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.
Download