Top Banner
Good List of Questions with Answers Describe the difference between a Thread and a Process? The main difference between processes and threads is each process has its own address space where as thread don't. If a process creates multiple threads, all the threads will be contained in its address space. This is why they share resources so easily and interthread communication is so simple. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes. Threads have almost no overhead; processes have considerable overhead. New threads are easily created; new processes require duplication of the parent process. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes. Eg What is a Windows Service and how does its lifecycle differ from a "standard" EXE? Windows services are long running process (applications) that are ideal for use in server environments. These applications do not have user interface and they do not produce any visual output. Its lifecycle is managed by “Service Control Manager” which is responsible for starting and stopping the service. They do not require a logged in user in order to execute and can run under the context of any user including the system. On the other hand, a “Standard executable” doesn’t require Control Manager and is directly related to the visual output.
250
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Good+List+of+Questions+With+Answers

Good List of Questions with Answers

Describe the difference between a Thread and a Process?The main difference between processes and threads is each process has its own address space

where as thread don't. If a process creates multiple threads, all the threads will be contained in its

address space. This is why they share resources so easily and interthread communication is so

simple.

Threads have direct access to the data segment of its process; processes have their own copy of

the data segment of the parent process. Threads can directly communicate with other threads of

its process; processes must use interprocess communication to communicate with sibling

processes.

Threads have almost no overhead; processes have considerable overhead. New threads are

easily created; new processes require duplication of the parent process. Threads can exercise

considerable control over threads of the same process; processes can only exercise control over

child processes.

Eg

What is a Windows Service and how does its lifecycle differ from a "standard" EXE?Windows services are long running process (applications) that are ideal for use in server

environments. These applications do not have user interface and they do not produce any visual

output. Its lifecycle is managed by “Service Control Manager” which is responsible for starting and

stopping the service. They do not require a logged in user in order to execute and can run under

the context of any user including the system. On the other hand, a “Standard executable” doesn’t

require Control Manager and is directly related to the visual output.

What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?Windows provides a page-based virtual memory management scheme that allows applications to

realize a 32-bit linear address space for 4 gigabytes (GB) of memory. As a result, each

application has its own private address space from which it can use the lower 2 GB—the system

reserves the upper 2 GB of every process's address space for its own use.

What is the difference between an EXE and a DLL?DLL is An abbreviation for dynamic link library, a file containing a collection of Windows functions

designed to perform a specific class of operations. An EXE contains an entry point to start

Page 2: Good+List+of+Questions+With+Answers

execution { main() in C/C++ and Public Static Void Main() in .Net } whereas functions within

DLLs are called (invoked) by applications (EXEs) as necessary to perform the desired operation.

What is strong-typing versus weak-typing? Which is preferred? Why?Strict enforcement of type rules with no exceptions is strong-typing. In a strongly typed language,

type usage can be detected at compile time rather then run-time. In these languages, conversion

between types requires use of explicit conversion functions as opposed to implicit type coercion

in weak-typed (batter called run-typed) languages.

As a common assumption, strong typing catches more errors at compile time than weak typing,

resulting in fewer run-time exceptions (but still is a disputable point when it comes to "which one

to use").

Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.Microsoft first announced C# and the .NET Framework in summer 2000, calling C# 'The first

component-oriented language in the C/C++ family.' The essence of component development is

not to build what you can buy, on the basis that snapping together pre-tested parts is faster,

cheaper and probably more reliable than coding everything for yourself.

As a definition, almost any class file is a component. Moreover, it can easily be compiled to a

DLL, it benefits from .NET versioning, and it can be reused. The existence of components also

implies the existence of containers, which again may be visual or non-visual. The container plays

an important role in component management. In particular, all containers implement IDisposable,

which means they have a Dispose method for releasing unmanaged resources such as window

handles or open files. In their Dispose method, containers must also call Dispose on all the

components they host. In the .NET Framework both ASP.NET Web Forms and rich client

Windows Forms are visual component containers. System.Web.UI.Page,

System.Windows.Forms.Form and System.ComponentModel.Container are few other component

containers which ship with Windows Server Family.

What is a PID? How is it useful when troubleshooting a system?PID stands for Process Identifier, a uniquely assigned integer that identifies a process in the

operating system. In any system, applications use PID to identify the process uniquely. Also, it is

used in diagnosing the problems with the process in Multi-Tasking systems.

How many processes can listen on a single TCP/IP port?One. If you need to create another TCP/IP listener, you need to set-up a different port.

Page 3: Good+List+of+Questions+With+Answers

What is the GAC? What problem does it solve?Each computer on which the common language runtime is installed has a machine-wide code

cache called the global assembly cache (GAC). Assemblies deployed in the global assembly

cache must have a strong name. A developer tool named "Global Assembly Cache tool"

(Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC.

The global assembly cache stores assemblies specifically designated to be shared by several

applications on the computer. It provides us the way to overcome “DLL Hell” problem also.

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.Interface Oriented ProgrammingAn interface oriented programming language (IOPL) is similar to an object oriented programming

language (OOPL) but differs in one subtle but very significant way: in an IOPL dynamic function

dispatch occurs in the interface, not in the class itself. This means there are no "virtual" or

"abstract" functions. As a result of this a class will always the same behaviour, no matter how it is

inherited. This is a substantial deviatiaion from an OOPL where behaviour of a class can change

depending on how it is inherited.

In many OOPL's objects contain a pointer to a function table for dispatching virtual functions at

runtime. In an IOPL, a function table pointer would be associated with an interface reference. So

in an IOPL the abstraction penalty (in space and speed) occurs only when using an object in a

polymorphic context. This can be significant in some designs where dynamic function dispatching

is required rarely.

Another benefit of the IOPL approach is that classes can be more easily optimized by a compiler

since intra-method calls (calls from one member function to another), can be resolved at compile-

time.

Object Orient ProgrammingA type of programming in which programmers define not only the data type of a data structure,

but also the types of operations (functions) that can be applied to the data structure. In this way,

the data structure becomes an object that includes both data and functions. In addition,

programmers can create relationships between one object and another. For example, objects can

inherit characteristics from other objects.

One of the principal advantages of object-oriented programming techniques over procedural

programming techniques is that they enable programmers to create modules that do not need to

be changed when a new type of object is added. A programmer can simply create a new object

that inherits many of its features from existing objects. This makes object-oriented programs

easier to modify.

Page 4: Good+List+of+Questions+With+Answers

Aspect Oriented ProgrammingAspect-Oriented Programming (AOP) complements OO programming by allowing the developer

to dynamically modify the static OO model to create a system that can grow to meet new

requirements. Just as objects in the real world can change their states during their lifecycles, an

application can adopt new characteristics as it develops.

Consider an example: many of you have developed simple web applications that use servlets as

the entry point, where a servlet accepts the values of a HTML form, binds them to an object,

passes them into the application to be processed, and then returns a response to the user. The

first cut of the servlet may be very simple, with only the minimum amount of code required to fulfill

the use case being modeled. The code, however, often inflates to three to four times its original

size by the time secondary requirements such as exception handling, security, and logging have

been implemented. I use the term "secondary requirements" because a servlet should not need

to know about the logging or security mechanisms being used; its primary function is to accept

input and process it.

AOP allows us to dynamically modify our static model to include the code required to fulfill the

secondary requirements without having to modify the original static model (in fact, we don't even

need to have the original code). Better still, we can often keep this additional code in a single

location rather than having to scatter it across the existing model, as we would have to if we were

using OO on its own.

Describe what an Interface is and how it’s different from a Class?An Interface is a reference type and it contains only abstract members. Interface's members can

be Events, Methods, Properties and Indexers. But the interface contains only declaration for its

members. Any implementation must be placed in class that realizes them. The interface can't

contain constants, data fields, constructors, destructors and static members. All the member

declarations inside interface are implicitly public.

Difference between an Interface and Abstract Class are as under

Interfaces are closely related to abstract classes that have all members abstract.

For an abstract class, at least one method of the class must be an abstract method that

means it may have concrete methods.

For an interface, all the methods must be abstract

Class that implements an interface much provide concrete implementation of all the

methods definition in an interface or else must be declare an abstract class

In C#, multiple inheritance is possible only through implementation of multiple interfaces.

Abstract class can only be derived once.

Page 5: Good+List+of+Questions+With+Answers

An interface defines a contract and can only contains four entities viz methods,

properties, events and indexes. An interface thus cannot contain constants, fields,

operators, constructors, destructors, static constructors, or types.

Also an interface cannot contain static members of any kind. The modifiers abstract,

public, protected, internal, private, virtual, override is disallowed, as they make no sense

in this context.

Class members that implement the interface members must be publicly accessible.

What is Reflection?Reflection is the process of walking the metadata about a type and finding out things; for

instance, how many constructors a type has, and what the parameters are. It also allows you to

dynamically create and invoke types.

Refelction is the mechanism of discovering class information solely at run time.

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?XML web services work only over HTTP+SOAP, Remoting is a flexible architecture, it works over

TCP/can be implemented for other protocols as well.

.NET remoting using SOAP lets you use client-activated objects and other such like remoting

features which Web Services doesn't. On the other hand, Web Services can at least theoretically

- if written really amazingly carefully - be cross-platform, which .NET Remoting isn't.

Web services are generally stateless, using a standard HTTP interface, while remoting is highly

customizable and extensible, varying by the specific application that uses it.

Are the type system represented by XmlSchema and the CLS isomorphic?Informally, an isomorphism is a kind of mapping between objects, which shows a relationship

between two properties or operations. If there exists an isomorphism between two structures, we

call the two structures isomorphic. In a certain sense, Isomorphic sets are structurally identical, if

you choose to ignore finer-grained differences that may arise from how they are defined.

Type system represented by XML Schema and CLS are not isomorphic

Conceptually, what is the difference between early-binding and late-binding?Binding refers the object type definition. You are using Early Binding if the object type is specified

when declaring your object. Eg if you Dim myObject as ADODB.Recordset that is early binding.

If on the other hand you declare your object as a generic type you are late binding. Eg if you Dim

myObject as Object.

Page 6: Good+List+of+Questions+With+Answers

On should note that binding is determined at object declaration and not at object instantiation.

Therefore it does not matter if you later go on to Set myObject = New ADODB.Recordset or Set

myObject = CreateObject(”ADODB.Recordset”).

Early binding allows developers to interact with the object’s properties and methods during

coding. You can enjoy the benefits of intellisense. Also, early binding permits the compiler to

check your code. Errors are caught at compile time. Early binding also results in faster code. It’s

disadvantage is that you cannot create a generic object which may be bound to different types of

objects.

Late binding on the other hand permits defining generic objects which may be bound to different

objects. Eg you could declare myControl as Control without knowing which control you will

encounter. You could then query the Controls collection and determine which control you are

working on using the TypeOf method and branch to the section of your code that provides for that

type. This is the only benefit of late binding. It’s disadvantages are that it is error prone and you

will not enjoy much intellisense whilst coding.

There are two ways to use Automation (or OLE Automation) to programmatically control another

application.

Late binding uses CreateObject to create and instance of the application object, which you can

then control. For example, to create a new instance of Excel using late binding:

Dim oXL As Object

Set oXL = CreateObject("Excel.Application")

On the other hand, to manipulate an existing instance of Excel (if Excel is already open) you

would use GetObject (regardless whether you're using early or late binding):

Dim oXL As Object

Set oXL = GetObject(, "Excel.Application")

To use early binding, you first need to set a reference in your project to the application you want

to manipulate. In the VB Editor of any Office application, or in VB itself, you do this by selecting

Tools + References, and selecting the application you want from the list (e.g. “Microsoft Excel 8.0

Object Library”).

Page 7: Good+List+of+Questions+With+Answers

To create a new instance of Excel using early binding:

Dim oXL As Excel.Application

Set oXL = New Excel.Application

In either case, incidentally, you can first try to get an existing instance of Excel, and if that returns

an error, you can create a new instance in your error handler.

Advantages of Early Binding

Your code will run considerably faster, because it can all be compiled up front. With late binding,

the code relating to an application you declared as an object has to, in effect, be compiled as it

runs.

Because your code can all be compiled up front, debugging is far easier – select Debug +

Compile, and the compiler will be able to spot syntax errors which would have been missed had

you used late binding.

You have full access in your project to intellisense (type a keyword and a dot to get a popup list of

properties and methods supported by that keyword, select one to insert it; type a keyword and

press F1 to launch the Help topic on that keyword).

You have full access to the application's object model via the Object Browser and VBA Help.

You have access to the application's built-in constants. For instance, if you are automating Word

from Excel, you can use:

Dim objWord As Word.Application

Set objWord = New Word.Application

With objWord

.Visible = True

.Activate

.WindowState = wdWindowStateMaximize

.Documents.Open ("c:\temp\temp.doc")

End With

Furthermore, when you type

.WindowState =

Page 8: Good+List+of+Questions+With+Answers

you'll get a pop-up list of the supported constants, and can simply pick

“wdWindowStateMaximize” from the list.

If you used late binding, you would need to use:

.WindowState = 1

.. and you would need to know (by looking it up in Word's Object Browser) that the value of the

constant “wdWindowStateMaximize” happens to be 1.

All this makes programming using early binding immeasurably easier than using late binding.

Advantages of Late Binding

The main advantage is that code which uses late binding is more certain to be version-

independent

If you set a reference in a Word 97 project to “Microsoft Excel 8.0 Object Library”, then the project

will run OK on a machine which has Office 2000 installed. Word 2000 changes the reference on

the fly to the “Microsoft Excel 9.0 Object Library”.

But as they famously say, YMMV. Problems have been found in certain circumstances. For

instance, if you run a Word 97 project containing a reference to the Excel 8.0 object library on a

machine with Office 2000 installed, it will run OK, but you may get the occasional “cannot open

macro storage” error unless you save the project in Word 2000. If you do save it in Word 2000,

the reference will change to the Excel 9.0 object library. So if you use early binding and support a

mixed environment, it may be safest to create separate Word 97 and Word 2000 versions of your

addins, despite the maintenance overhead.

The more references your project contains, the larger the file size and the longer it takes to

compile.

Some programming environments don't allow you to create references to another application.

Is using Assembly.Load a static reference or dynamic reference?Firstly lets understand what static and dynamic references are

Below is the example of static and dynamic reference.

Static Reference :

[System.Diagnostics.DebuggerStepThroughAttribute()]

Page 9: Good+List+of+Questions+With+Answers

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Web.Services.WebServiceBindingAttribute(Name="WSSoap",

Namespace=http://tempuri.org/)]

public class WS : System.Web.Services.Protocols.SoapHttpClientProtocol {

///

public WS() {

this.Url = http://localhost:81/MyWebService/WS.asmx;

}

Dynamic Reference:

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Web.Services.WebServiceBindingAttribute(Name="WSSoap",

Namespace=http://tempuri.org/)]

public class WS : System.Web.Services.Protocols.SoapHttpClientProtocol {

///

public WS() {

string urlSetting =

System.Configuration.ConfigurationSettings.AppSettings["WebServiceKey"];

if ((urlSetting != null)) {

this.Url = string.Concat(urlSetting, "");

}

else {

this.Url = http://localhost:81/MyWebService/WS.asmx;

}

}

Assembly.Load is a dynamic reference.

When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate? Use the System.Reflection.Assembly.LoadFile method to load and examine assemblies that have

the same identity, but are located in different paths. System.Reflection.Assembly.LoadFile does

not load files into the System.Reflection.Assembly.LoadFrom context, and does not resolve

dependencies using the load path, as the System.Reflection.Assembly.LoadFrom method does.

System.Reflection.Assembly.LoadFile is useful in this limited scenario because

System.Reflection.Assembly.LoadFrom cannot be used to load assemblies that have the same

identities but different paths; it will load only the first such assembly.

Page 10: Good+List+of+Questions+With+Answers

What is an Asssembly Qualified Name? Is it a filename? How is it different?An assembly qualified name isn't the filename of the assembly; it's the internal name of the

assembly combined with the assembly version, culture, and public key, thus making it unique. It

is a type reference qualified by the name of the assembly it is referenced from.

Is this valid? Assembly.Load("foo.dll");No because "foo.dll" is not an assembly qualified name. Assembly.Load(string) takes the full

name of the assembly (as contained in the GAC), not the name of the file.

Eg. Assembly.Load("System.Data, Version=1.0.3300.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089")

How is a strongly-named assembly different from one that isn’t strongly-named?A strongly named assembly gives it a unique identity. For example, consider a weakly named

assembly - anyone with access can replace it with a similarly named (same namespace/type info)

assembly ! Having a strongly named assembly doesn't let that happen.

Unlike the other, Strongly-named assemblies can be loaded into the GAC and use key pairs to

insure non-collision and authorship verification. This is because a strongly-named assembly is

signed with a public key; this prevents tampering and enables it to be placed in the GAC

alongside other assemblies of the same name.

Can DateTimes be null?No. DateTime is a structure and not an object. Hence we cannot assign new values to DateTime.

What is the JIT? What is NGEN? What are limitations and benefits of each?A Microsoft.NET application can be run only after the MSIL code is translated into native machine

code. In .NET Framework, the intermediate language is complied "just in time" (JIT) into native

code when the application or component is run instead of compiling the application at

development time. The Microsoft.NET runtime consists of two JIT compilers. They are standard

JIT compiler and the EconoJIT compiler. The EconoJIT compiler compiles faster than the

standard JIT compiler, but the code it produces is not as optimized as the code obtained from the

standard JIT compiler.

NGEN tool is used to create a native Image from an .NET assembly and installs it into the native

image cache on that computer. Since assembly image is present on the local machine cache

loading of the assembly becomes faster because .NET reads data from the native image than

generating them dynamically (JIT).

Page 11: Good+List+of+Questions+With+Answers

JIT is Just-in-Time compiling, which natively compiles .NET code as it needs to be executed,

allowing more flexibility in platform optimization. NGEN is the Native Image Generator, a tool

which precompiles native code for assemblies and caches it for execution, pre-empting JIT.

NGEN saves time at execution in exchange for potentially slowing execution on platforms other

than the one it was originally executed for.

The principle advantage of JITted code is that it can be compiled with optimisation for the CPU

and processor on which it is finally running, which in practice seems to be more efficient than

precompilation. NGEN improves load time at the price of losing this optimisation at run-time.

NGENed assemblies also have some restrictions on how certain features can be used that are

sufficiently obscure I haven't run into them yet, not being an NGENer.

How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?The garbage collector defines objects into multiple generations based upon their expected

lifecycle, and collects each generation with different frequency. Non-deterministic finalization

means that the Finalize() method of objects is not guaranteed to be called as soon as the object

falls out of scope; it is executed when the garbage collector has time to prioritize it.

What is the difference between Finalize() and Dispose()?Finalize() is called by the garbage collector before destroying an object, allowing it to clean up

resources it may have allocated. Dispose() is a method the programmer can call on an object to

force resource deallocation (and pre-empt costly finalization).

One important difference is that finalize will called by the runtime while dispose is called by the user.Dispose() is called by the user of an object to indicate that he is finished with it, enabling that

object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow

an object which has not had Dispose() called on it to do the same. However, Dispose() operates

determinalistically, whereas there is no guarantee that Finalize() will be called immediately when

an object goes out of scope - or indeed at all, if the program ends before that object is GCed -

and as such Dispose() is generally preferred.

How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?The using() construct allows you to mark a resource which is guaranteed to be disposed when

the block exits. IDisposable provides an interface for the Dispose() method, which allows a

Page 12: Good+List+of+Questions+With+Answers

programmer to forcibly finalize an object while still placing a Finalize() method in it as a means of

security in case another programmer neglects to use Dispose().

In C# the following code

using ( expression )

statement

will be converted to

ExpressionType temp = expression;

try {

statement

} finally {

if (temp != null) {

((IDisposable)temp).Dispose();

}

}

What does this useful command line do? tasklist /m "mscor*"?This command allows you to see which processes currently running have loaded a specific library

-- in this case, anything beginning with "MSCOR".

What is the difference between in-proc and out-of-proc?In-process communication is that between threads in a particular application space, as defined by

the operating system. Out-of-process communication is that between non-shared memory and

process spaces. Out-of-proc requires marshaling between two processes and thus slower.

What technology enables out-of-proc communication in .NET?Remoting using Serialization - Most usually Remoting;.NET remoting enables client applications

to use objects in other processes on the same computer or on any other computer available on its

network.While you could implement an out-of-proc component in any number of other ways,

someone using the term almost always means Remoting.

When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?XP & 2003: aspnet_wp.exe, 2000: inetinfo.exe

What’s wrong with a line like this? DateTime.Parse(myString);The above line doesn't specify a locale or format.

Page 13: Good+List+of+Questions+With+Answers

Eg. DateTime dt = DateTime.ParseExact(dateString, "r");

Formats supported are:

Standard Format Example Date

RFC1123 rSun, 06 Nov 1994 08:49:37 GMT

ISO 8601 (almost) s 1993-02-14T13:10:30

Universal Sortable u 2004-04-30 04:30:00Z

What are PDBs? Where must they be located for debugging to work?PDB stands for Program Database files. They contain references that connect the uncompiled

code to the compiled code for debugging. They must be located either in the same place as the

EXE/DLL, or in your VS.NET specified symbols path.

What is cyclomatic complexity and why is it important?It's a measure of the number of independent linearly executed paths through a program. It's

important for judging the complexity of software and assisting in determinations of which modules

should be refactored into smaller components.

Write a standard lock() plus “double check” to create a critical section around a variable access.

--- bool notLocked = true;

--- if (notLocked)--- {--- --- lock (typeof(lockingObject))--- --- {--- --- --- if (notLocked)--- --- --- {--- --- --- --- notLocked = false;--- --- --- --- foo = lockingObject;--- --- --- --- notLocked = true;

Page 14: Good+List+of+Questions+With+Answers

--- --- --- }--- --- }--- }

What is FullTrust? Do GAC’ed assemblies have FullTrust?FullTrust means all .NET security permissions are granted to the assembly. GAC assemblies

have FullTrust by default, but that can be changed by the user's security policy. Your code is

allowed to do anything in the framework, meaning that all (.Net) permissions are granted. The

GAC has FullTrust because it's on the local HD, and that has FullTrust by default, you can

change that using caspol

What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?Allows administrators to see exactly which permissions your application needs to run; prevents

your code from being exploited beyond what permissions it absolutely needs; allows your

application to forcibly fail instead of having to manually handle situations where it might be denied

permissions it requires.

What does this do? gacutil /l | find /i "Corillian"?Lists all assemblies in the GAC, searching for those whose names contain "Corillian".

What does this do? sn -t foo.dllThis shows token for foo.dll

What ports must be open for DCOM over a firewall? What is the purpose of Port 135?135 for the service control manager, 1024-65535 (or whatever range the administrator has

restricted DCOM to) for applications.

Contrast OOP and SOA. What are tenets of each?OOP tries to encapsulate functionality required to operate on data with the data structure itself,

making objects "self-reliant". SOA aims to decouple functionality from data entirely, using

interfaces to allow functional components to operate blindly with as little understanding of the

precise nature of the data they're fed as possible, allowing many types of data sets to be fed into

them for the same operation.

Page 15: Good+List+of+Questions+With+Answers

What is SOA - Service Oriented Architecture (SOA) is an architectural style whose goal is to

achieve loose coupling among interacting software agents. A service is a unit of work done by a

service provider to achieve desired end results for a service consumer. Both provider and

consumer are roles played by software agents on behalf of their owners.

This sounds a bit too abstract, but SOA is actually everywhere. Let's look at an example of SOA

which is likely to be found in your living room. Take a CD for instance. If you want to play it, you

put your CD into a CD player and the player plays it for you. The CD player offers a CD playing

service. Which is nice because you can replace one CD player with another. You can play the

same CD on a portable player or on your expensive stereo. They both offer the same CD playing

service, but the quality of service is different.

The idea of SOA departs significantly from that of object oriented programming, which strongly

suggests that you should bind data and its processing together. So, in object oriented

programming style, every CD would come with its own player and they are not supposed to be

separated. This sounds odd, but it's the way we have built many software systems.

The results of a service are usually the change of state for the consumer but can also be a

change of state for the provider or for both. After listening to the music played by your CD player,

your mood has changed, say, from "depressed" to "happy". If you want an example that involves

the change of states for both, dining out in a restaurant is a good one.

The reason that we want someone else to do the work for us is that they are experts. Consuming

a service is usually cheaper and more effective than doing the work ourselves. Most of us are

smart enough to realize that we are not smart enough to be expert in everything. The same rule

applies to building software systems. We call it "separation of concerns", and it is regarded as a

principle of software engineering.

How does SOA achieve loose coupling among interacting software agents? It does so by

employing two architectural constraints:

A small set of simple and ubiquitous interfaces to all participating software agents. Only

generic semantics are encoded at the interfaces. The interfaces should be universally

available for all providers and consumers.

Descriptive messages constrained by an extensible schema delivered through the

interfaces. No, or only minimal, system behavior is prescribed by messages. A schema

limits the vocabulary and structure of messages. An extensible schema allows new

versions of services to be introduced without breaking existing services.

Page 16: Good+List+of+Questions+With+Answers

As illustrated in the power adapter example, interfacing is fundamentally important. If interfaces

do not work, systems do not work. Interfacing is also expensive and error-prone for distributed

applications. An interface needs to prescribe system behavior, and this is very difficult to

implement correctly across different platforms and languages. Remote interfaces are also the

slowest part of most distributed applications. Instead of building new interfaces for each

application, it makes sense to reuse a few generic ones for all applications.

Since we have only a few generic interfaces available, we must express application-specific

semantics in messages. We can send any kind of message over our interfaces, but there are a

few rules to follow before we can say that an architecture is service oriented.

First, the messages must be descriptive, rather than instructive, because the service provider is

responsible for solving the problem. This is like going to a restaurant: you tell your waiter what

you would like to order and your preferences but you don't tell their cook how to cook your dish

step by step.

Second, service providers will be unable to understand your request if your messages are not

written in a format, structure, and vocabulary that is understood by all parties. Limiting the

vocabulary and structure of messages is a necessity for any efficient communication. The more

restricted a message is, the easier it is to understand the message, although it comes at the

expense of reduced extensibility.

Third, extensibility is vitally important. It is not difficult to understand why. The world is an ever-

changing place and so is any environment in which a software system lives. Those changes

demand corresponding changes in the software system, service consumers, providers, and the

messages they exchange. If messages are not extensible, consumers and providers will be

locked into one particular version of a service. Despite the importance of extensibility, it has been

traditionally overlooked. At best, it was regarded simply as a good practice rather than something

fundamental. Restriction and extensibility are deeply entwined. You need both, and increasing

one comes at the expense of reducing the other. The trick is to have a right balance.

Fourth, an SOA must have a mechanism that enables a consumer to discover a service provider

under the context of a service sought by the consumer. The mechanism can be really flexible,

and it does not have to be a centralized registry.

Page 17: Good+List+of+Questions+With+Answers

In SOA you create an abstract layer that your applications use to access various “services” and can aggregate the services. These services could be databases, web services, message queues or other sources. The Service Layer provides a way to access these services that the applications do not need to know how the access is done. For example, to get a full customer record, I might need to get data from a SGL Server database, a web service and a message queue. The Service layer hides this from the calling application. All the application knows is that it asked for a full customer record. It doesn’t know what system or systems it came from or how it was retrieved.

How does the XmlSerializer work? What ACL permissions does a process using it require?The primary purpose of XML serialization in the .NET Framework is to enable the conversion of

XML documents and streams to common language runtime objects and vice versa. Serialization

of XML to common language runtime objects enables one to convert XML documents into a form

where they are easier to process using conventional programming languages. On the other hand,

serialization of objects to XML facilitates persisting or transporting the state of such objects in an

open, standards compliant and platform agnostic manner.

XML serialization in the .NET Framework supports serializing objects as either XML that

conforms to a specified W3C XML Schema Definition (XSD) schema or that is conformant to the

serialization format defined in section five of the SOAP specification. During XML serialization,

only the public properties and fields of an object are serialized. Also, type fidelity is not always

preserved during XML serialization. This means that if, for instance, you have a Book object that

exists in the Library namespace, there is no guarantee that it will be deserialized into an object of

the same type. However, this means that objects serialized using the XML serialization in

the .NET Framework can be shipped from one machine to the other without requiring that the

original type be present on the target machine or that the XML is even processed using the .NET

Framework. XML serialization of objects is a useful mechanism for those who want to provide or

consume data using platform agnostic technologies such as XML and SOAP.

XML documents converted to objects by the XML serialization process are strongly typed. Data

type information is associated with the elements and attributes in an XML document through a

schema written in the W3C XML Schema Definition (XSD) Language. The data type information

in the schema allows the XmlSerializer to convert XML documents to strongly typed classes.

Thus you can define Serialization & Deserialization as - Serialization is the process of taking

an object and converting it to a format in which it can be transported across a network or

Page 18: Good+List+of+Questions+With+Answers

persisted to a storage location. The storage location could be as simple as using a file or a

database. The serialized format contains the object's state information. Deserialization is the

process of using the serialized state information to reconstruct the object from the serialized state

to its original state. In essence, the process of serialization allows an object to be serialized,

shipped across the network for remoting or persisted in a storage location such as the ASP.NET

cache, and then be reconstructed for use at a later point in time.

Working of an XML Serializer Class – You instantiate an XmlSerializer for the class you want

to serialize. Then you called the Serialize() method with an XmlTextWriter object and the object

to serialize and that was it! The XmlTextWriter controls where and how the output of the method

is written. The Serialize() method makes use of the pluggable architecture we have seen

throughout the discussion of the System.Xml namespace. It accepts any classes derived from

System.IO.Stream, System.Xml.XmlWriter or System.IO.TextWriter, thus allowing a great

deal of flexibility where to persist objects to. The following listing shows the class and the XML

document of a serialized instance side-by-side.

ACL Permissions - .Net Reflection permissions are required.

Why is catch(Exception) almost always a bad idea?Because it swallows an exception without doing anything with it. The only time this should really

be used is when trying risky casts that you expect to have a reasonable likelihood of failure, but

always of a very specific type.

Well, it's not _always_ a bad idea. As with all such rules, there are exceptions. However, the short

answer is that you almost never want to catch every possible exception that a method or property

might throw. OutOfMemoryException is one example of an exception that many methods /

properties may throw that you definitely don't want to catch, because there's nothing you can do

about it.

You should catch only those exceptions that you can handle in some intelligent way, so it's almost

never a good idea to catch _all_exceptions, because you can never deal intelligently with any

possible exception.

The only exception to the rule (no pun intended) is when you're dealing with a method for which

you have no documentation about which exceptions it can throw, and for which you want to

continue if it fails. In that case you don't have much choice but to catch all of them, since you

don't know which specific ones to catch.

What is the difference between Debug.Write and Trace.Write? When should each be used?

Page 19: Good+List+of+Questions+With+Answers

The Debug.Write call won’t be compiled when the DEBUG symbol is not defined (when doing a

release build). Trace.Write calls will be compiled. Debug.Write is for information you want only in

debug builds, Trace.Write is for when you want it in release build as well.

What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?Release builds don't contain debug symbols and are more compact and optimized.

Debug build contain debug symbols and can be debugged while Release build doesn’t contain

debug symbols and hence cannot be debugged. When an application is built using Debug build,

a .pdb file is generated in the bin folder while this does not happen in Release build. There will

be a speed difference, because of disabling debug methods.

To be simple, producing the application build in "Release" mode is optimized and in "debug"

mode lets you handle exceptions and view stack trace information.Performance of the application

degrades when you run it in "debug" mode for the same reason.

Building applications in Release mode allows inlining of methods thus increasing performance.

When using ASP.NET applications, you have an element in the web.config file as follows.

<compilation defaultLanguage="c#" debug="true" />

debug=true is used to allow the framework produce debug binaries

debug = false is used to produce release (retail) binaries

ASP.NET maintains a directory where it stores compiled code, be it debug or release code. The

debug switch determines the manner in which it compiles code. In the .NET 1.1 installation you

can find this folder in \Windows\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files.

ASP.NET creates a folder called "debugtest" for each web application root in there.

Does JITting occur per-assembly or per-method? How does this affect the working set?JITing occurs per method. This affects the working set because methods that aren't lined up for

calls aren't loaded, reducing its footprint.

Contrast the use of an abstract base class against an interface?Interfaces: An interface defines a set of properties, methods, and events. Unlike classes,

interfaces do not provide implementation. You define an interface as a separate entity from the

classes that implement it. When a class implements an interface, it must implement all the

methods that are declared in that interface. An interface must define the methods that set and get

Page 20: Good+List+of+Questions+With+Answers

data. However, the interface will not implement these methods. You use an interface to define a

protocol of behavior that any class can implement. Use interfaces to:

Capture similarities among unrelated classes without artificially forcing a class

relationship.

Declare the methods that one or more classes are expected to implement.

Reveal an object’s programming interface without revealing its class.

Abstract base classes: An abstract class has one or more abstract methods. Abstract classes

act as expressions of general concepts from which you can derive more classes that are specific.

An abstract class serves as a base class from which other classes can inherit properties and

methods. You cannot create an object of an abstract class type; however, you can pass

references to abstract class types. You use abstract base classes to provide default behavior or

to define families.

Thus An abstract class allows you to write code that will be inherited by derived classes. An

interface declares a contract, but does not allow inheritance of code. An abstract class forms part

of your class hierarchy, and so affects how you organize your code. Interfaces cut across the

class hierarchy and so place no restrictions on how you organize your classes.

Differences between Interface and Abstract Class are

Interfaces are closely related to abstract classes that have all members abstract.

For an abstract class, at least one method of the class must be an abstract method that

means it may have concrete methods.

For an interface, all the methods must be abstract

Class that implements an interface much provide concrete implementation of all the

methods definition in an interface or else must be declare an abstract class

In C#, multiple inheritance is possible only through implementation of multiple interfaces.

Abstract class can only be derived once.

An interface defines a contract and can only contains four entities viz methods,

properties, events and indexes. An interface thus cannot contain constants, fields,

operators, constructors, destructors, static constructors, or types.

Also an interface cannot contain static members of any kind. The modifiers abstract,

public, protected, internal, private, virtual, override is disallowed, as they make no sense

in this context.

Class members that implement the interface members must be publicly accessible.

What is the difference between a.Equals(b) and a == b?In value types (structs and native value types), there is no difference (assuming that a struct is

implemented properly and overrides == correctly). In reference types the standard is that .Equals

Page 21: Good+List+of+Questions+With+Answers

compares the contents of the types (typically comparing keys or other indicators of business-level

identity), while == determines whether the two object references point to the same object in

memory.

The first uses the object's equivalency constructor to see if it considers itself value-equal to the

the second object. The second construct compares their memory references to determine if they

are the SAME object.

In the context of a comparison, what is object identity versus object equivalence?Here is an interesting description of the differences between Object Identity and Object Equality

pertaining to objects in the .NET Framework. Generally speaking, two objects are identical if they

share the same address in memory. This means that they are both referring to the same instance

of a class. You can test if two objects are identical by using the ReferenceEquals static method of

System.Object: Object.ReferenceEquals(myFirstObject, mySecondObject).

On the other hand, two objects are equivalent if they are instances of the same type and if every

field of the first object matches the value of the same field of the second object. Being equivalent

does not imply that the objects are identical: they can be independent instances, but their fields

should have the same value. Because testing for equivalence can and probably will be different

for most types, there is no global solution. For this purpose System.Object provides the virtual

(overridable) method Equals to determine if two objects are equal. When implementing the

overridden method, you need to ensure that the operation is:

Reflexive:

myObject.Equals(myObject) must be true

Symmetric:

if myFirstObject.Equals(mySecondObject) is true then

mySecondObject.Equals(myFirstObject) must also be true

Transitive:

if myFirstObject.Equals(mySecondObject) is true and

mySecondObject.Equals(myThirdObject) is true then

myFirstObject.Equals(myThirdObject) must be true too.

The interesting thing is that if you don't override the virtual method Equals of System.Object when

creating your own objects, the virtual method Equals looks like this:

class Object {

public virtual Boolean Equals(Object obj) {

Page 22: Good+List+of+Questions+With+Answers

// If both references point to the same

// object, they must be equal.

if (this == obj) return (true);

// Assume that the objects are not equal.

return (false);

}

...

}

So really, the virtual method Equals of System.Object only tests if the two objects are identical

(share the same address in memory) not equivalent. You will need to override this method if you

want Equals to act any differently

How would one do a deep copy in .NET?Implement the IClonable interface, and define your implementation to execute deep copies on

your subobjects (possibly through IClonable interfaces). Alternatively, serialize the object and

then deserialize it into another object, but this is very slow compared to a dedicated cloning

interface..

A shallow copy creates a new instance of the same type as the original object, and then copies

the non-static fields of the original object. If the field is a value type, a bit-by-bit copy of the field is

performed. If the field is a reference type, the reference is copied but the referred object is not;

therefore, the reference in the original object and the reference in the clone point to the same

object. In contrast, a deep copy of an object duplicates everything directly or indirectly

referenced by the fields in the object."

The simplest way to create a generic deep copy routine, that is a procedure that can create a

true, distinct copy of an object and all its dependent object, is to rely on the serialization features

of the .NET framework.

Function CloneObject(ByVal obj As Object) As Object

' Create a memory stream and a formatter.

Dim ms As New MemoryStream(1000)

Dim bf As New BinaryFormatter()

' Serialize the object into the stream.

bf.Serialize(ms, obj)

' Position streem pointer back to first byte.

ms.Seek(0, SeekOrigin.Begin)

Page 23: Good+List+of+Questions+With+Answers

' Deserialize into another object.

CloneObject = bf.Deserialize(ms)

' Release memory.

ms.Close()

End Function

You can use this routine as follows:

Dim ar(100) As Person

' Fill the array.

' ...

' Create a copy of the array AND all the objects it contains.

ar = CType(CloneObject(ar), Person())

Explain current thinking around IClonable.Cloning is really required if setting up the state of an object is expensive and you just need a copy

of the object to do some changes to the existing state. Let's take a good example to understand

what I have just said. Consider the DataTable class. Building a DataTable can involve operations

like querying the database for the schema and data, adding constraints, setting the primary key

and so on. So, if you want a new copy of this DataTable, just for making minor changes to the

schema or adding a new row etc, it would be more wise just to clone an existing object and work

on that, rather than recreating a new DataTable, which can require more time and resources.

Cloning is also widely applicable to Arrays and Collections, where you need a copy of existing

elements many a time.

Types of CloningWe can classify two types of cloning based on "how much" is cloned: Deep and Shallow. A

shallow clone is a new instance of the same type as the original object, which contains a copy of

the value typed fields. But, if the field is a reference type, the reference is copied, not the referred

object. Hence, the reference in the original object and the reference in the clone point to the same

object. A deep clone of an object, on the other hand, contains a copy of everything directly or

indirectly referenced by the object. Let's take up an example.

X is an object with references to the object A and the object A also has a reference to an object

M. A shallow copy of X is an object Y, which also has references to object A. In contrast, a deep

copy of X is an object Y with direct reference to object B, and an indirect reference to object N,

Page 24: Good+List+of+Questions+With+Answers

where B is a copy of A, and N is a copy of M. This is visually depicted below to understand this

better.

Implementing CloningSystem.Object provides a protected method MemberwiseClone which can be used to implement

Shallow cloning. This method is marked as protected, so you can access this method in context

of a derived class or within that class itself.

.NET defines an interface called IClonable which has to be implemented by classes that need

functionality beyond the scope of shallow cloning (for deep cloning). We need to provide a

suitable implementation in the Clone method of the interface to do the same.

There are various ways to implement deep cloning. One method is to serialize the object into a

memory stream and deserialize it back into a new object. We would need to use a Binary

formatter or SOAP formatter which do a deep serialization. The problem with this approach is that

the class and its members (the entire object graph) have to be marked as serializable, else the

formatter would through an exception.

Reflection may be another method to achieve the same.

What is boxing?Boxing and unboxing is a essential concept in C#’s type system. With Boxing and unboxing one

can link between value-types and reference-types by allowing any value of a value-type to be

converted to and from type object. Boxing and unboxing enables a unified view of the type

system wherein a value of any type can ultimately be treated as an object. Converting a value

type to reference type is called Boxing. Unboxing is an explicit operation.

C# provides a unified type system. All types including value types derive from the type object. It is

possible to call object methods on any value, even values of primitive types such as int.

The example

using System;

class Test

{

static void Main() {

Console.WriteLine(3.ToString());

}

}

calls the object-defined ToString method on an integer literal.

Page 25: Good+List+of+Questions+With+Answers

The example

class Test

{

static void Main() {

int i = 1;

object o = i; // boxing

int j = (int) o; // unboxing

}

}

An int value can be converted to object and back again to int.

This example shows both boxing and unboxing. When a variable of a value type needs to be

converted to a reference type, an object box is allocated to hold the value, and the value is copied

into the box.

Unboxing is just the opposite. When an object box is cast back to its original value type, the value

is copied out of the box and into the appropriate storage location.

Boxing conversions

A boxing conversion permits any value-type to be implicitly converted to the type object or to any

interface-type implemented by the value-type. Boxing a value of a value-type consists of

allocating an object instance and copying the value-type value into that instance.

For example any value-type G, the boxing class would be declared as follows:

class vBox

{

G value;

G_Box(G g) {

value = g;

}

}

Boxing of a value v of type G now consists of executing the expression new G_Box(v), and

returning the resulting instance as a value of type object. Thus, the statements

Page 26: Good+List+of+Questions+With+Answers

int i = 12;

object box = i;

conceptually correspond to

int i = 12;

object box = new int_Box(i);

Boxing classes like G_Box and int_Box above don’t actually exist and the dynamic type of a

boxed value isn’t actually a class type. Instead, a boxed value of type G has the dynamic type G,

and a dynamic type check using the is operator can simply reference type G. For example,

int i = 12;

object box = i;

if (box is int) {

Console.Write("Box contains an int");

}

will output the string "Box contains an int" on the console.

A boxing conversion implies making a copy of the value being boxed. This is different from a

conversion of a reference-type to type object, in which the value continues to reference the same

instance and simply is regarded as the less derived type object.

For example, given the declaration

struct Point

{

public int x, y;

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

the following statements

Point p = new Point(10, 10);

object box = p;

p.x = 20;

Page 27: Good+List+of+Questions+With+Answers

Console.Write(((Point)box).x);

will output the value 10 on the console because the implicit boxing operation that occurs in the

assignment of p to box causes the value of p to be copied. Had Point instead been declared a

class, the value 20 would be output because p and box would reference the same instance.

Unboxing conversions

An unboxing conversion permits an explicit conversion from type object to any value-type or from

any interface-type to any value-type that implements the interface-type. An unboxing operation

consists of first checking that the object instance is a boxed value of the given value-type, and

then copying the value out of the instance. unboxing conversion of an object box to a value-type

G consists of executing the expression ((G_Box)box).value.

Thus, the statements object box = 12;

int i = (int)box;

conceptually correspond to

object box = new int_Box(12);

int i = ((int_Box)box).value;

For an unboxing conversion to a given value-type to succeed at run-time, the value of the source

argument must be a reference to an object that was previously created by boxing a value of that

value-type. If the source argument is null or a reference to an incompatible object, an

InvalidCastException is thrown.

Is string a value type or a reference type?It is an immutable reference type. Since it is immutable it acts like a value type in some ways. In

particular, String overrides == to do content comparisons instead of an identity comparison.

What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?Defines the specific parameters that .NET class members serialize into. Solves the issue of an

XML spec needing to have slightly different names for class members than the class itself does.

Page 28: Good+List+of+Questions+With+Answers

Why are out parameters a bad idea in .NET? Are they?The out method parameter keyword on a method parameter causes a method to refer to the

same variable that was passed into the method. Any changes made to the parameter in the

method will be reflected in that variable when control passes back to the calling method.

Declaring an out method is useful when you want a method to return multiple values. A method

that uses an out parameter can still return a value. A method can have more than one out

parameter.

To use an out parameter, the argument must explicitly be passed to the method as an out

argument. The value of an out argument will not be passed to the out parameter. A variable

passed as an out argument need not be initialized. However, the out parameter must be assigned

a value before the method returns. An overload will occur if declarations of two methods differ

only in their use of out.

A property is not a variable and cannot be passed as an out parameter.

out" parameters aren't a bad idea in .NET. FxCop warns you not to use them, but only because

other programmers might be unfamiliar with the concept. There are situations in which methods

return more than one result, in which out parameters are the way to go. However, they should

be rare in most programs, as most methods return only one result.

Can attributes be placed on specific parameters to a method? Why is this useful?Yes. This might be needed to specify remoting implementations or types for method parameters,

or to provide metadata for method parameters when exporting a code library.

What is the use of override with new?Override redefines an inherited method which was marked as virtual or abstract, and its access

level must be the same as the method it overrides. New allows you to completely hide an

inherited member and create a different implementation of it with whatever attributes you choose.

When a virtual method is called on a reference, the actual type of the object that the reference

refers to is used to decide which method implementation to use. When a method of a base class

is overridden in a derived class, the version in the derived class is used, even if the calling code

didn't "know" that the object was an instance of the derived class. will end up calling Derived.

Some \Method if that overrides Base.SomeMethod. Now, if you use the new keyword instead of

override, the method in the derived class doesn't override the method in the base class, it merely

hides it.

Explain the use of virtual, sealed, override, and abstract.Virtual: The virtual keyword allows polimorphism too. A virtual property or method has an

implementation in the base class, and can be overriden in the derived classes.

Page 29: Good+List+of+Questions+With+Answers

Sealed: A sealed class is a class that does not allow inheritance. Some object model designs

need to allow the creation of new instances but not inheritance, if this is the case, the class

should be declared as sealed.

Abstract: An abstract class is a parent class that allows inheritance but can never be instantiated.

Abstract classes contain one or more abstract methods that do not have implementation. Abstract

classes allow specialization of inherited classes.

Override: Overriding is the action of modifying or replacing the implementation of the parent class

with a new one. Parent classes with virtual or abstract members allow derived classes to override

them.

Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d?Foo.Bar – Assembly Name – This is used for loading the Assembly.

Version– Also is used for loading

Culture=neutral - defines culture settings used for string translation and other locale-specific

settings

PublicKeyToken - used to uniquely identify this assembly and prevent collisions.

Explain the differences between public, protected, private and internal.Public -- Anything that can create an instance of this object has access to this member.

Protected -- Only classes that are derived from this class have access to this member.

Private -- This member can only be accessed by other members within this specific class.

Internal - like public, but accessible only by code within the same assembly.

What benefit do you get from using a Primary Interop Assembly (PIA)?A primary interop assembly is a unique, vendor-supplied assembly that contains type definitions

(as metadata) of types implemented with COM. There can be only one primary interop assembly,

which must be signed with a strong name by the publisher of the COM type library. A single

primary interop assembly can wrap more than one version of the same type library.

A COM type library that is imported as an assembly and signed by someone other than the

publisher of the original type library cannot be a primary interop assembly. Only the publisher of a

type library can produce a true primary interop assembly, which becomes the unit of official type

definitions for interoperating with the underlying COM types.

Page 30: Good+List+of+Questions+With+Answers

Publishers of COM components produce primary interop assemblies and distribute them to

developers for use in .NET Framework applications. For publishers, this section provides

information about producing primary interop assemblies. For developers, this section describes

how to program with primary interop assemblies.

Because it is strongly-named, it can be loaded into the GAC and verified against the COM

component's own signature to give the component collision-protection and authorship-verification

benefits when interacing with .NET code.

By what mechanism does NUnit know what methods to test?NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit, the current

production release, version 2.2, is the fourth major release of this xUnit based unit testing tool for

Microsoft .NET. It is written entirely in C# and has been completely redesigned to take advantage

of many .NET language features, for example custom attributes and other reflection related

capabilities. NUnit brings xUnit to all .NET languages.

NUnit uses the "attribute" feature of .NET to identify tests. Test fixtures are identified by the

attribute [TestFixture] and individual tests by [Test]. This means that you can write tests that don't

inherit from a fixed TestCase superclass, and NUnit can still find them.

NUnit allows you to write tests in any .NET language. So even though NUnit itself is written in C#,

you can write your tests in Visual Basic or C++, or, I suppose, even in ML or Eiffel. Language

interoperation is a key characteristic of .NET, and one that I consider to be quite important.

When you write tests using NUnit, you can run the NUnit application, and it will run and report on

your tests.

What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;} ?Both statements will catch and throw exception, but the latter will preserve the original exception

stack.

What is the difference between typeof(foo) and myFoo.GetType()?Testing if an object is of a particular type, can be done with the TypeOf...Is operator:

If TypeOf obj Is TextBox Then...

Obtaining a System.Type object for a given type can be done with the GetType operator:

Dim t As System.Type

t = GetType(String)

MessageBox.Show(t.FullName)

Page 31: Good+List+of+Questions+With+Answers

Obtaining a System.Type object for a given object can be done with the GetType method:

Dim t as System.Type

t = obj.GetType()

MessageBox.Show(t.FullName)

Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?The first constructor invokes the base constructor in addition to its own functionality; this would be

useful if your base initialized basic field values or had other code that all other constructors would

utilize.

What is this? Can this be used within a static method?The "this" reference refers to the current object context. Static methods have no context, so it is

not valid.

Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.

What is a PostBack?Postback is a mechanism to provide that you can do server-side actions. Some actions can be

handled on the client side, meaning they don't require anything to be processed on the server

side. (For example showing a mouseover image effect.) On the other hand, sometimes you need

to do more complex things which you cannot do on the client side. (For example, changing a data

source on the server side.) Because of this need, there's the postback mechanism. The page

"posts" back the page to the server. (As the name implies, this is a POST, not a GET).

What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?ViewState is the mechanism by which page state (information) is maintained between page post

backs, i.e. a web form is submitted by the user, this same page performs some processing and

perhaps presents further information to the user.

The contents of ViewState is base64-encoded for safe transmission in a POST request.

In 1.1 they use a tuple format (a hierarchical collection of triplets and pairs) serialized using < and

> characters. The letter preceding the < symbol indicates the type of the object stored (t=triplet,

Page 32: Good+List+of+Questions+With+Answers

p=pair, i=integer, etc.). Each sub-element within the < and > characters is separated with a ';'

character. It's an interesting serialization format, sort of like a compressed XML.

Base64 is not an encryption algorithm. Base64 makes a string suitable for HTTP transfer plus it

makes it a little hard to read. Just a little. It's easy to decode this string and see what's inside. Can

this be a security issue? It sure can. We'll address your concern in due time. Stick around.

View state is simply text. It is an aggregate of values of controls on a page. It's a string that

contains values of page controls hashed and encoded in some manner. The view state contains

no information about the server or the client. It only comprises information about the page itself

and its controls. It lives along with the page in the user's browser.

Every server control ultimately derives from the Control class. Be it a WebControl, HtmlControl or

even LiteralControl it has a property called EnableViewState. When a page is built every control

that has this property enabled contributes to the view state by serializing its contents (in this case:

converting its contents into a string). Now, some controls are easy to serialize, while others might

give us grief.What manages the view state is the StateBag class. This class is like a dictionary—

you may store key/value pairs in it.

What is the <machinekey> element and what two ASP.NET technologies is it used for?<machinekey> element configures keys to use for encryption and decryption of forms authentication cookie data and view state data, and for verification of out-of-process session state identification. This section can be declared at the machine, site, and application

levels, but not at the subdirectory level.

<machineKey validationKey="AutoGenerate|value[,IsolateApps]"

decryptionKey="AutoGenerate|value[,IsolateApps]"

validation="SHA1|MD5|3DES"/>

Required Attributes

Attribute Option Description

validationKey     Specifies the key used for validation of encrypted data. validationKey is used when enableViewStateMAC is true to create a message authentication code (MAC) to ensure that view state has not been tampered with. validationKey is also used to generate out-of-process, application-specific session IDs to ensure that session state variables are

Page 33: Good+List+of+Questions+With+Answers

isolated between sessions.

    AutoGenerate Specifies that ASP.NET generates a random key and stores it in the Local Security Authority (LSA). The AutoGenerate option is the default value. If you add the IsolateApps modifier to the validationKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.

    value Specifies a manually assigned validation key. This value must be manually set to ensure consistent configuration across a network of Web servers (a Web farm). The key must be a minimum of 40 characters (20 bytes) and a maximum of 128 characters (64 bytes) long. If keys shorter than the maximum length are used, they should be created by a truly random means, such as by using RNGCryptoServiceProvider. The recommended key length is 128 hexadecimal characters. If you add the IsolateApps modifier to the validationKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.

decryptionKey     Specifies the key used to encrypt data. decryptionKey is used for Forms authentication encryption and decryption and for view state encryption when validation is 3DES.

    AutoGenerate Specifies that ASP.NET generates a random key and stores it in the LSA. The AutoGenerate option is the default value. If you add the IsolateApps modifier to the decryptionKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.

    value Specifies a manually assigned key. This value must be manually set to a string of hexadecimal characters to ensure consistent configuration across a Web farm. The key should be 16 characters in length when using DES encryption and 48 characters in length when using Triple DES encryption. If keys shorter than the maximum length are used, they should be created by a truly random means, such as by using RNGCryptoServiceProvider. ASP.NET can use Triple DES only on computers on which 128-bit encryption is available. If you add the IsolateApps modifier to the decryptionKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.

validation     Specifies the type of encryption used for validation of data.

    SHA1 Specifies that ASP.NET uses SHA1 encryption.

Page 34: Good+List+of+Questions+With+Answers

    MD5 Specifies that ASP.NET uses MD5 encryption.

    3DES Specifies that ASP.NET uses Triple-DES (3DES) encryption. When 3DES is specified, forms authentication defaults to SHA1. When the validation attribute is set to 3DES, the view state validation technique uses 3DES encryption.

Example

The following example sets both validationKey and decryptionKey to AutoGenerate. The

isolateApps option is specified to generate unique keys for each application on the server.

<machineKey validationKey="AutoGenerate,IsolateApps"

decryptionKey="AutoGenerate,IsolateApps"

validation="SHA1"/>

What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?ASP.NET provides three distinct ways to store session data for your application: in-process

session state, out-of-process session state as a Windows service, and out-of-process session

state in a SQL Server database. Each has it advantages.

1.In-process session-state modeLimitations:

When using the in-process session-state mode, session-state data is lost if

aspnet_wp.exe or the application domain restarts.

If you enable Web garden mode in the < processModel > element of the application's

Web.config file, do not use in-process session-state mode. Otherwise, random data loss

can occur.

Advantage:

in-process session state is by far the fastest solution. If you are storing only small

amounts of volatile data in session state, it is recommended that you use the in-process

provider.

2. The State Server simply stores session state in memory when in out-of-proc mode. In this mode the worker process talks directly to the State Server

3. SQL mode, session states are stored in a SQL Server database and the worker process talks directly to SQL. The ASP.NET worker processes are then able to take advantage of

Page 35: Good+List+of+Questions+With+Answers

this simple storage service by serializing and saving (using .NET serialization services) all objects within a client's Session collection at the end of each Web request Both these out-of-process solutions are useful primarily if you scale your application across multiple processors or multiple computers, or where data cannot be lost if a server or process is restarted.

What is Web Gardening? How would using it affect a design?The Web Garden ModelThe Web garden model is configurable through the section of the machine.config file. Notice that

the section is the only configuration section that cannot be placed in an application-specific

web.config file. This means that the Web garden mode applies to all applications running on the

machine. However, by using the node in the machine.config source, you can adapt machine-wide

settings on a per-application basis.

Two attributes in the section affect the Web garden model. They are webGarden and cpuMask.

The webGarden attribute takes a Boolean value that indicates whether or not multiple worker

processes (one per each affinitized CPU) have to be used. The attribute is set to false by default.

The cpuMask attribute stores a DWORD value whose binary representation provides a bit mask

for the CPUs that are eligible to run the ASP.NET worker process. The default value is -1

(0xFFFFFF), which means that all available CPUs can be used. The contents of the cpuMask

attribute is ignored when the webGarden attribute is false. The cpuMask attribute also sets an

upper bound to the number of copies of aspnet_wp.exe that are running.

Web gardening enables multiple worker processes to run at the same time. However, you should

note that all processes will have their own copy of application state, in-process session state,

ASP.NET cache, static data, and all that is needed to run applications. When the Web garden

mode is enabled, the ASP.NET ISAPI launches as many worker processes as there are CPUs,

each a full clone of the next (and each affinitized with the corresponding CPU). To balance the

workload, incoming requests are partitioned among running processes in a round-robin manner.

Worker processes get recycled as in the single processor case. Note that ASP.NET inherits any

CPU usage restriction from the operating system and doesn't include any custom semantics for

doing this.

All in all, the Web garden model is not necessarily a big win for all applications. The more stateful

applications are, the more they risk to pay in terms of real performance. Working data is stored in

blocks of shared memory so that any changes entered by a process are immediately visible to

Page 36: Good+List+of+Questions+With+Answers

others. However, for the time it takes to service a request, working data is copied in the context of

the process. Each worker process, therefore, will handle its own copy of working data, and the

more stateful the application, the higher the cost in performance. In this context, careful and

savvy application benchmarking is an absolute must.

Changes made to the section of the configuration file are effective only after IIS is restarted. In IIS

6, Web gardening parameters are stored in the IIS metabase; the webGarden and cpuMask

attributes are ignored.

Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?It would be great if some one can post this answer

Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?It would be great if some one can post this answer

Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?This is a class derived from a special base class, System.Attribute, and its proper class name is

ThreadStaticAttribute. If you're new to using attribute classes, both VB and C# allow you to drop

the Attribute suffix when you annotate a target element.

[ThreadStatic]

private static int someField;

is equivalent to

[ThreadStaticAttribute]

private static int someField;

Attributes provide a mechanism for declaring specific kinds of metadata in your compiled

assemblies. When applied properly, that metadata gives you better control of how a program

behaves at run time.

Page 37: Good+List+of+Questions+With+Answers

The [ThreadStatic] attribute is only useful when YOU control the ThreadPool (and the lifecycle of

the threads). It also reminds one to think about variable scope/lifetime especially in the context of

ASP.NET.

interesting things:

Don't slap a [ThreadStatic] attribute on a static member when you're operating within

ASP.NET as chances are you don't control the thread life...you inherit a worker thread.

ThreadStatic gives you thread local storage, not HttpContext local storage! If you need to

store something away to be used later in the same HTTP request, think about my favorite

ASP.NET class, the little-known and not-used-enough

System.Web.HttpContext.Current.Items In ASP.NET your code is run on a WorkerThread

from the 25 or so threads in the default ASP.NET worker thread pool and the variable

that you think is "personal private to your thread" is personal private...to you and every

other request that this worker thread has been with. Under load you may well find your

variable modified.

Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.An HTTP handler is a class that knows how to render content for a particular type of Web

content. For example, there is a different HTTP handler class in the .NET Framework for

rendering ASP.NET Web pages than there is for rendering Web services. Just as IIS relies on

external programs to serve dynamic content, the ASP.NET engine relies on different classes to

render the content for a certain type of content.

Advantages

It provides a nice division of labor. IIS can focus on excelling at serving static content,

and can leave the details for serving dynamic content to an external program. That is, IIS

can focus on efficiently serving HTML pages and images while the ASP.NET engine can

focus on efficiently rendering ASP.NET Web pages and Web services.

It allows for new dynamic server-side technologies to be added to IIS in a pluggable

manner. Imagine if IIS was responsible for rendering ASP.NET Web pages itself, rather

than relying on an external engine. In that case, each time a new version of ASP.NET

came out—or any dynamic server-side technology, for that matter—a new version of IIS

would need to be created that supported this new version. Those who wanted to use the

latest version would have to update the version of IIS.

Page 38: Good+List+of+Questions+With+Answers

What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?

An HTTP module can register for the following events exposed by the

System.Web.HttpApplication object.

Event Name Description

AcquireRequestStateThis event is raised when ASP.NET runtime is ready to acquire the

Session state of the current HTTP request.

AuthenticateRequestThis event is raised when ASP.NET runtime is ready to authenticate

the identity of the user.

AuthorizeRequestThis event is raised when ASP.NET runtime is ready to authorize

the user for the resources user is trying to access.

BeginRequestThis event is raised when ASP.NET runtime receives a new HTTP

request.

DisposedThis event is raised when ASP.NET completes the processing of

HTTP request.

EndRequestThis event is raised just before sending the response content to the

client.

ErrorThis event is raised when an unhandled exception occurs during the

processing of HTTP request.

PostRequestHandlerExecute This event is raised just after HTTP handler finishes execution.

PreRequestHandlerExecute

This event is raised just before ASP.NET begins executing a

handler for the HTTP request. After this event, ASP.NET will forward

the request to the appropriate HTTP handler.

PreSendRequestContent

This event is raised just before ASP.NET sends the response

contents to the client. This event allows us to change the contents

before it gets delivered to the client. We can use this event to add

the contents, which are common in all pages, to the page output.

For example, a common menu, header or footer.

PreSendRequestHeaders This event is raised just before ASP.NET sends the HTTP response

headers to the client. This event allows us to change the headers

Page 39: Good+List+of+Questions+With+Answers

before they get delivered to the client. We can use this event to add

cookies and custom data into headers.

ReleaseRequestStateThis event is raised after ASP.NET finishes executing all request

handlers.

ResolveRequestCache

This event is raised to determine whether the request can be fulfilled

by returning the contents from the Output Cache. This depends on

how the Output Caching has been setup for your web application.

UpdateRequestCache

This event is raised when ASP.NET has completed processing the

current HTTP request and the output contents are ready to be

added to the Output Cache. This depends on how the Output

Caching has been setup for your Web application.

Apart from these events, there are four more events that we can use. We can hook up to these

events by implementing the methods in the global.asax file of our Web application.

These events are as follows:

Application_OnStart

This event is raised when the very first request arrives to the Web application.

Application_OnEnd

This event is raised just before the application is going to terminate.

Session_OnStart

This event is raised for the very first request of the user's session.

Session_OnEnd

This event is raised when the session is abandoned or expired.

Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.

Explain how cookies work. Give an example of Cookie abuse.

Page 40: Good+List+of+Questions+With+Answers

A cookie is a small bit of text that accompanies requests and pages as they go between the Web

server and browser. The cookie contains information the Web application can read whenever the

user visits the site.

Imagine that when users request a page from your site, your application sends not just a page,

but a cookie containing the date and time. When the user's browser gets the page, the browser

also gets the cookie, which it stores in a folder on the user's hard disk. Later, the user requests a

page from your site again. When the user enters the URL, the browser looks on the local hard

disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to

your site along with the page request. Your application can then determine the date and time that

the user last visited the site. You might use the information to display a message to the user,

check an expiration date, or perform any other useful function.

Cookies are associated with a Web site, not with a specific page, so the browser and server will

exchange the www.contoso.com cookie information no matter what page the user requests from

your site. As the user visits different sites, each site might send a cookie to the user's browser as

well; the browser stores all the cookies separately.

That's the basics of how cookies work. But what are they good for? In essence, cookies help Web

sites store information about visitors. More generally, cookies are one way of maintaining

continuity in a Web application (formally, performing state management). Except for the brief time

when they are actually exchanging information, the browser and Web server are disconnected.

Each request you make to a Web server is treated independently of any other request. Many

times, however, it's useful for the Web server to recognize you when you request a page.

Cookie Abuse

Explain the importance of HttpRequest.ValidateInput()?The HttpRequest.ValidateInput method validates data submitted by a client browser and raises

an exception if potentially dangerous data is present.

If the validation feature is enabled by page directive or configuration, this method is called during

the Page's ProcessRequest processing phase. ValidateInput can be called by your code if the

validation feature is not enabled. Request validation works by checking all input data against a

hard-coded list of potentially dangerous data."

Input data is checked during request validation in the following members:

HttpRequest.Form

HttpRequest.QueryString

HttpRequest.Cookies

The HttpRequest.ValidateInput is enabled by default in ASP.NET 1.1

Page 41: Good+List+of+Questions+With+Answers

What kind of data is passed via HTTP Headers?Normally Textual data is passed through the http headers.

Juxtapose the HTTP verbs GET and POST. What is HEAD?In HTML, one can specify two different submission methods for a form. The method is specified

inside a FORM element, using the METHOD attribute. The difference between METHOD="GET"

(the default) and METHOD="POST" is primarily defined in terms of form data encoding. The

official recommendations say that "GET" should be used if and only if the form processing is

idempotent, which typically means a pure query form. Generally it is advisable to do so. There

are, however, problems related to long URLs and non-ASCII character repertoires which can

make it necessary to use "POST" even for idempotent processing.

The head element can contain information about the document. The browser does not display the

"head information" to the user. The following tags can be in the head section: <base>, <link>,

<meta>, <script>, <style>, and <title>.

Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.When a browser requests a service from a web server, an error might occur. This is a list of

HTTP status messages that might be returned:

1xx: Information

Message: Description:100 Continue Only a part of the request has been received by the server,

but as long as it has not been rejected, the client should continue with the request

101 Switching Protocols The server switches protocol

2xx: Successful

Message: Description:200 OK The request is OK201 Created The request is complete, and a new resource is created  202 Accepted The request is accepted for processing, but the processing

is not complete 203 Non-authoritative Information  204 No Content   205 Reset Content   206 Partial Content  

Page 42: Good+List+of+Questions+With+Answers

3xx: Redirection

Message: Description:300 Multiple Choices A link list. The user can select a link and go to that location.

Maximum five addresses  301 Moved Permanently The requested page has moved to a new url  302 Found The requested page has moved temporarily to a new url  303 See Other The requested page can be found under a different url  304 Not Modified   305 Use Proxy   306 Unused This code was used in a previous version. It is no longer

used, but the code is reserved 307 Temporary Redirect The requested page has moved temporarily to a new url

4xx: Client Error

Message: Description:400 Bad Request The server did not understand the request401 Unauthorized The requested page needs a username and a password 402 Payment Required You can not use this code yet 403 Forbidden Access is forbidden to the requested page 404 Not Found The server can not find the requested page 405 Method Not Allowed The method specified in the request is not allowed 406 Not Acceptable The server can only generate a response that is not

accepted by the client 407 Proxy Authentication Required You must authenticate with a proxy server before this

request can be served 408 Request Timeout The request took longer than the server was prepared to

wait 409 Conflict The request could not be completed because of a conflict 410 Gone The requested page is no longer available  411 Length Required The "Content-Length" is not defined. The server will not

accept the request without it  412 Precondition Failed The precondition given in the request evaluated to false by

the server 413 Request Entity Too Large The server will not accept the request, because the request

entity is too large 414 Request-url Too Long The server will not accept the request, because the url is

too long. Occurs when you convert a "post" request to a "get" request with a long query information 

415 Unsupported Media Type The server will not accept the request, because the media type is not supported 

416    417 Expectation Failed  

5xx: Server Error

Message: Description:500 Internal Server Error The request was not completed. The server met an

unexpected condition501 Not Implemented The request was not completed. The server did not support

the functionality required

Page 43: Good+List+of+Questions+With+Answers

502 Bad Gateway The request was not completed. The server received an invalid response from the upstream server

503 Service Unavailable The request was not completed. The server is temporarily overloading or down

504 Gateway Timeout The gateway has timed out 505 HTTP Version Not Supported The server does not support the "http protocol" version

How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?"If-Not-Modified-Since" is a header field to specify that the lock will occur only if the entity has not

been modified since the time specified in this field. This ensures that a user does not take out a

lock on an entity which has changes since they retrieved it. Typically, the time specified in the "If-

Not-Modified-Since" field is the time of the most recent retrieval of the entity being locked.

This field tells the server to send the document only if the timestamp has changed. This will help

ASP.Net to handle trips to the server side and page rendering.

Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.Page level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web

pages. The way ASP.NET implements this (roughly) is through an Output Cache engine. Each

time an incoming ASP.NET page request comes in, this engine checks to see if the page being

requested has a cached output entry. If it does, this cached HTML is sent as a response;

otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.

Output Caching is particularly useful when you have very static pages. Output caching is easy to

implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take

advantage of this powerful technique. The syntax looks like this:

<%@OutputCache Duration="60" VaryByParam="none" %>

The Duration parameter specifies how long, in seconds, the HTML output of the Web page

should be held in the cache. When the duration expires, the cache becomes invalid and, with the

next visit, the cached content is flushed, the ASP.NET Web page's HTML dynamically generated,

and the cache repopulated with this HTML.

The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a

form submit with method="POST") parameters should be used in varying what gets cached. In

other words, multiple versions of a page can be cached if the output used to generate the page is

different for different values passed in via either a GET or POST. The VaryByParam is a useful

setting that can be used to cache different "views" of a dynamic page whose content is generated

Page 44: Good+List+of+Questions+With+Answers

by GET or POST values. For example, you may have an ASP.NET Web page that reads in a Part

number from the QueryString and displays information about a particular widget whose part

number matches the QueryString Part number. Imagine for a moment that Output Caching

ignored the QueryString parameters altogether (which you can do by setting

VaryByParam="none"). If the first user visited the page with QueryString /ProductInfo.aspx?

PartNo=4, she would see information out widget #4. The HTML for this page would be cached.

The next user now visits and wished to see information on widget #8, a la /ProductInfo.aspx?

PartNo=8. If VaryByParam is set to VaryByParam="none", the Output Caching engine will

assume that the requests to the two pages are synonymous, and return the cached HTML for

widget #4 to the person wishing to see widget #8! To solve for this problem, you can specify that

the Output Caching engine should vary its caches based on the PartNo parameter by either

specifying it explicitly, like VaryByParam="PartNo", or by saying to vary on all GET/POST

parameters, like: VaryByParam="*".

A semicolon-separated list of HTTP headers used to vary the output cache. When this attribute is

set to multiple headers, the output cache contains a different version of the requested document

for each combination of specified headers. Setting the VaryByHeader attribute enables caching

items in all HTTP version 1.1 caches, not just the ASP.NET cache. This attribute is not supported

for @ OutputCache directives in user controls.

How does VaryByCustom work?VaryByCustom attribute contains the default setting Browser, which means that a different

instance of an item is cached for each browser version that requests it. For example, both

Microsoft Internet Explorer 5 and Internet Explorer 5.5 request the item. When VaryByCustom is

set to Browser, a cache entry exists for each browser version. You cannot provide a string to

control the caching for other custom scenarios. The string does not have any meaning unless you

provide code to override the HttpApplication.GetVaryByCustomString method in the Global.asax

file.

The following code illustrates the syntax for the VaryByCustom attribute:

<%@ OutputCache Duration="Seconds" VaryByCustom="string" %>

What is the purpose of XML Namespaces?XML Namespaces provide a method to avoid element name conflicts. Namespaces have been a

W3C standard since January 1999. The idea behind namespaces is simple: We need a way to

Page 45: Good+List+of+Questions+With+Answers

fully qualify XML element and attribute names to prevent from confusing two elements that have

the same name but mean different things.

For example, you might have an accounting application that uses an element called <schedule>

to mean an accounting schedule. A time management application might use the same element

<schedule> to mean a time schedule. You might need to put accounting and time management

data in one XML document. For example, you might be keeping track of all project information

including accounting and project timeline in the same document. Now each application would not

be able to tell which <schedule> element belongs to it. To solve this problem, you could prefix

each <schedule> element with a unique prefix that indicates to which application it belongs. For

example <accounting:schedule> and <time:schedule> would make things much clearer. In this

example accounting and time are namespaces.

Namespaces are simply a way to uniquely identify elements and attributes within a document.

When is the DOM appropriate for use? When is it not? Are there size limitations?The XML Document Object Model (XML DOM) defines a standard way for accessing and

manipulating XML documents.

The DOM presents an XML document as a tree structure, and gives access to the structure

through a set of objects. The W3C Document Object Model (DOM) is a platform and language

neutral interface that allows programs and scripts to dynamically access and update the content,

structure, and style of a document." The W3C DOM provides a standard set of objects for

representing HTML and XML documents, and a standard interface for accessing and

manipulating them. The DOM is separated into different parts (Core, XML, and HTML) and

different levels (DOM Level 1/2/3):

Core DOM - defines a standard set of objects for any structured document

XML DOM - defines a standard set of objects for XML documents

HTML DOM - defines a standard set of objects for HTML documents

What is the WS-I Basic Profile and why is it important?Don’t Know

What is the one fundamental difference between Elements and Attributes?The only substantial difference between attributes and element text is that the standard DOM

(and perhaps SAX) APIs optionally strip whitespace from element text. If you've edited HTML

documents by hand, you know that putting a carriage return in the middle of text doesn't

accomplish anything -- you have to use <BR> or <P> instead. Any sequence of spaces, tabs,

Page 46: Good+List+of+Questions+With+Answers

carriage returns is converted into a single space. Sometimes whitespace stripping is desirable

and sometimes it isn't. It depends entirely on the nature of the data and what you intend to do

with it.

What is the difference between Well-Formed XML and Valid XML?Well-formed – The XML code must be syntactically correct or the XML parser will raise an error.

Valid – If the XML file has an associated XML Schema, the elements must appear in the defined

structure and the content of the individual elements must conform to the declared data types

specified in the schema.

How would you validate XML using .NET?Validation of Xml Files can be achieved through the use of various Technologies ex. Visual

Studio Net. Also, there are many on-line Tools available for validating an input .xml File. Few of

them are mentioned below :

Xml Schema Validator : This is an online tool which is available at the site

http://www.gotdotnet.com/team/xmltools/

Xml Validator provided by W3C Schools on the following link

http://www.w3schools.com/dom/dom_validate.asp

Microsoft’s Visual Studio .Net provides a number of classes, shipped in as base class libraries of

the .Net Framework for dealing with Xml Files. Xml functionality in .Net is primarily handled by the

class code present in the following namespaces :

System.Xml

System.Xml.Schema

System.Xml.XPath

System.Xml.Xsl

Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)SAX is an event-based API, which means that it reports results back to the application (or calls

back) as the XML file is parsed. Conceptually, SAX parsers break an XML file into pieces, starting

from the beginning of the file, notifying your application after each piece has been parsed. This

differs from the DOM, which parses an XML file completely and then presents your application

with a complete node tree. SAX gives your application the opportunity to store only the

information it needs as the parse progresses and to discard the rest.

NET uses a proprietary class called XmlReader instead of SAX. The two are very similar, and

would be used in similar circumstances, but are not based on the same API. Both of them read

Page 47: Good+List+of+Questions+With+Answers

XML documents from start to finish, one piece at a time. The main difference between SAX and

XmlReader is in how the parsers handle the pieces as they get them.

SAX works on a "push" model. The parser reads through the XML document, and sends

messages to a handler class that must do something with them. XmlReader, however, uses a

"pull" model. The class requests pieces from the reader at its own pace, only when it needs them.

When it needs the next piece, it must "ask" for it, rather than simply receiving it automatically.

XmlReader is an abstract class, and you will generally work with one of its implementations.

XmlValidatingReader automatically validates against a DTD or schema if one is available),

whereas SAX only allows validation against DTDs. If you don't need validation, XmlTextReader is

probably the best choice; it simply reads forward through an XML document and has methods

that return data on content and node types.

The end result of these differences is that, as with the DOM, SAX-style processing in .NET is

much faster and easier to implement. The code has been simplified and hidden "under the hood"

to such an extent that nowhere near the amount of developer-designed code is needed to load

and parse documents using XmlReader.

What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.XmlDocument implements a document object model which allows reading out data from the

document and changing the document (changing the value of an attribute, changing the contents

of a text node, inserting nodes, removing nodes).

XPathDocument allows a read only access to an XML document.

XmlDocument and XPathDocument are based on different data models. XmlDocument is based

on W3C XML DOM, which is object model that basically covers all XML syntax, including low

level syntax sugar such as entities, CDATA sections, DTD, notations etc. That's document-centric

model and it allows for full fidelity when loading/saving XML documents.

XPathDocument is based on XPath 1.0 data model which is read-only XML Infoset-compatible

data-centric object model that covers only semantically significant parts of XML, leaving out

insignificant syntax details - no DTD, no entities, no CDATA, no adjacent text nodes, only

significant data expressed as a tree with seven types of nodes. Simple and lightweight.

That's why XPathDocument is preffered data store for read-only scenarios, especially with XPath

or XSLT involved.

What is the difference between an XML "Fragment" and an XML "Document."

Page 48: Good+List+of+Questions+With+Answers

XML fragment: A piece of well-formed XML, that may or may not have a root element. In the

parlance of the spec, it would probably be called a 'well-formed textual object'. Doesn't even

have to contain any elements. Colloquially synonymous with 'XML'.

XML document: A document fragment that, in the words of the spec, 'when taken as a whole

matches production labeled document'. In practice, some XML with a single root element.

Parsed entities must also be well formed.

What does it meant to say “the canonical” form of XML?Canonicalizing an XML documentThe canonical XML specification has defined an algorithm to author the canonical form of XML

documents. You will need to perform the following steps in order to canonicalize an XML

document:

1. Encoding Scheme

All XML documents are composed of human readable text, which is a sequence of characters.

Encoding schemes are meant to represent characters by octets. Therefore, the same XML file

can be represented by an entirely different octet stream just by changing the character encoding

of the XML file. The canonical XML specification dictates that the canonical form of XML

documents should be encoded in UTF-8 encoding. Therefore, if the XML file to be canonicalized

has any other encoding, it should be changed to UTF-8.

2. Line Breaks

Line breaks in text files are normally represented either by hexadecimal A (decimal 10) or

hexadecimal D (decimal 13) or a combination of these two octets. XML files are all simple text

files, therefore #xA and #xD are used as line breaks in all XML files. The canonical form of XML

requires that all line breaks (#xD or a combination of #xA and #xD) be replaced with #xA. This

should be done before starting to process the XML file.

3. Attribute values are normalized

All attributes are required to be normalized in canonical form, as if by a validating XML parser.

The process of attribute value normalization is stated in the XML 1.0 recommendation by W3C.

4. Double quotes for Attribute values

Only double quotes should be used to encapsulate attribute values in canonical form.

5. Special Characters in Attribute Values and Character Content

Page 49: Good+List+of+Questions+With+Answers

When we replaced single quotes with double quotes, we introduced a problem. It is no longer a

well formed XML file, as the string representing value of the name attribute already contained

double quotes as part of the string value. In order to solve this problem, the Canonical XML

specification requires that all special characters (e.g. double quotes) in attribute values and

element content be replaced with character entities (e.g. &quot; for double quotes).

6. Entity References

Canonical XML requires that all entity references be replaced with the content represented by the

entity

7. Default Attributes

The DTD declaration defines a default attribute named approved for each part element.

Canonical XML requires that default attributes should be included in the canonical XML form.

8. XML and DTD declarations

Canonical XML does not require XML and DTD declarations. Therefore XML and DTD

declarations should be removed in the canonical form. Although we have used the DTD

declaration while replacing entity references and adding default attributes, the actual XML and

DTD declarations need to be removed.

9. White Space outside the Document Element

A Canonical XML document starts with the '<' character. This means that there should be no

white space before the first node.

10. White Space in Start and End Elements

Start and End elements should have normalized white space in canonical form. This means there

should be:

No white space between the left angle bracket ('<') and the name of a start element.

Similarly there should be no space between a slash ('/') and the name of an end element.

A single #x20 character between the element name and the first attribute name, if

present.

No white space before and after the equality sign in attribute-value pairs.

A single #x20 character between attribute-value pairs.

No white space following the closing double quote of the last attribute's value.

If there are no attributes, there should be no white space between the element name and

the right angle bracket '>'.

Page 50: Good+List+of+Questions+With+Answers

11. Empty Elements

Canonical XML requires start-end tag pairs for all elements, which includes empty elements as

well. Therefore, all empty elements of the form <emptyElement/> need to be converted to

<emptyElement></emptyElement>.

12. Namespace Declarations

Canonical XML requires preserving all namespace declarations as such (along with the

namespace prefixes) except superfluous namespace declarations (those namespace

declarations that have no effect on the namespace context of any node in the XML file).

13. Ordering of Namespace Declarations and Attributes

Canonical XML requires the inclusion of namespace declarations and attributes in ascending

lexicographic order. Inside an opening element, all namespace declarations should appear first,

followed by the attribute-value pairs.

Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?The XML Information Set (or "Infoset") defines an abstract data set whose purpose is to

provide a consistent set of definitions for use in other specifications that need to refer to the

information in a well-formed XML document. This information set is defined in terms of

"information items", which is an abstract description of a part of an XML document that has

specific properties. For example, specifications refer to an "element information item" rather than

an "element", and an element information item has properties such as a namespace name,

attributes, parent, children, etc.

XML documents can vary in physical representation based on syntactic "options" that are

allowed in XML. For example, attribute order is not important, quotes can be single or double, etc.

Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?Document Type Definition (DTD) describes a model or set of rules for an XML document. XML

Schema Definition (XSD) also describes the structure of an XML document but XSDs are much

more powerful.

The disadvantage with the Document Type Definition is it doesn’t support data types beyond the

basic 10 primitive types. It cannot properly define the type of data contained by the tag.

Page 51: Good+List+of+Questions+With+Answers

An Xml Schema provides an Object Oriented approach to defining the format of an xml

document. The Xml schema support most basic programming types like integer, byte, string, float

etc., We can also define complex types of our own which can be used to define a xml document.

Xml Schemas are always preferred over DTDs as a document can be more precisely defined

using the XML Schemas because of its rich support for data representation.

Does System.Xml support DTDs? How?Don’t know the answer

Can any XML Schema be represented as an object graph? Vice versa?Don’t know

From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what the are events fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each?When you ask a web server for a web page (navigate to an aspx page), the asp.net engine will

execute the class for the web page (after being compiled if necessary). The following events will

fire, on a first call to a web page:

1. Init, which occurs when the page class is initialized. Note that Delphi automatically adds an

overridden OnInit method to your web form's code. This is NOT the event handler for the Page's

Init event. If you want to add code inside the Init event handling procedure you should create

using the Object Inspector (the same way you create event handling procedures for Win32

applications). Furthermore, you should not access server controls (in the page control hierarchy)

during this event; since the view state is not yet populated.

2. Load, this event is typically used for initializing controls, variables and other objects. You can

safely access page's server controls. Note: the Load event handling method's skeleton is auto-

created by the Delphi IDE when you add a new page to the web application.

3. PreRender, occurs when the page is ready to be rendered to the browser.

4. Unload and Disposed, occur as final events in a page life-cycle.

Note: on a second (third, ...) call for the same page (after a postback), numerous control-specific

events may also occur.

There are other events that you can handle for a web page, but the most interesting could be

Error and DataBinding. Error event is fired when any unhandled exception is raised in the web

Page 52: Good+List+of+Questions+With+Answers

form. You could you this event to redirect the user to a special page where you can display the

error in a more friendly way. Notice, however, that errors and exceptions inside the entire web

application can be handled using the web.config file. Again, this is something we'll discuss later.

Table 1. Key events in the life of an ASP.NET page

Stage Page Event Overridable method

Page initialization Init  

View state loading   LoadViewState

Postback data processing   LoadPostData method in any control that implements the IPostBackDataHandler interface

Page loading Load  

Postback change notification   RaisePostDataChangedEvent method in any control that implements the IPostBackDataHandler interface

Postback event handling Any postback event defined by controls

RaisePostBackEvent method in any control that implements the IPostBackEventHandler interface

Page pre-rendering phase PreRender  

View state saving   SaveViewState

Page rendering   Render

Page unloading Unload  

Some of the stages listed above are not visible at the page level and affect only authors of server

controls and developers who happen to create a class derived from Page. Init, Load,

PreRender, Unload, plus all postback events defined by embedded controls are the only signals

of life that a page sends to the external world.

Stages of Execution

The first stage in the page lifecycle is the initialization. This stage is characterized by the Init

event, which fires to the application after the page's control tree has been successfully created. In

other words, when the Init event arrives, all the controls statically declared in the .aspx source file

have been instantiated and hold their default values. Controls can hook up the Init event to

initialize any settings that will be needed during the lifetime of the incoming Web request. For

example, at this time controls can load external template files or set up the handler for the events.

You should notice that no view state information is available for use yet.

Page 53: Good+List+of+Questions+With+Answers

Immediately after initialization, the page framework loads the view state for the page. The view

state is a collection of name/value pairs, where controls and the page itself store any information

that must be persistent across Web requests. The view state represents the call context of the

page. Typically, it contains the state of the controls the last time the page was processed on the

server. The view state is empty the first time the page is requested in the session. By default, the

view state is stored in a hidden field silently added to the page. The name of this field is

__VIEWSTATE. By overriding the LoadViewState method—a protected overridable method on

the Control class—component developers can control how the view state is restored and how its

contents are mapped to the internal state.

Methods like LoadPageStateFromPersistenceMedium and its counterpart

SavePageStateToPersistenceMedium can be used to load and save the view state to an

alternative storage medium—for example, Session, databases, or a server-side file. Unlike

LoadViewState, the aforementioned methods are available only in classes derived from Page.

Once the view state has been restored, the controls in the page tree are in the same state they

were the last time the page was rendered to the browser. The next step consists of updating their

state to incorporate client-side changes. The postback data-processing stage gives controls a

chance to update their state so that it accurately reflects the state of the corresponding HTML

element on the client. For example, a server TextBox control has its HTML counterpart in an

<input type=text> element. In the postback data stage, the TextBox control will retrieve the

current value of <input> tag and use it to refresh its internal state. Each control is responsible for

extracting values from posted data and updating some of its properties. The TextBox control will

update its Text property whereas the CheckBox control will refresh its Checked property. The

match between a server control and a HTML element is found on the ID of both.

At the end of the postback data processing stage, all controls in the page reflect the previous

state updated with changes entered on the client. At this point, the Load event is fired to the

page.

There might be controls in the page that need to accomplish certain tasks if a sensitive property is

modified across two different requests. For example, if the text of a textbox control is modified on

the client, the control fires the TextChanged event. Each control can take the decision to fire an

appropriate event if one or more of its properties are modified with the values coming from the

client. Controls for which these changes are critical implement the IPostBackDataHandler

interface, whose LoadPostData method is invoked immediately after the Load event. By coding

the LoadPostData method, a control verifies if any critical change has occurred since last request

and fires its own change event.

Page 54: Good+List+of+Questions+With+Answers

The key event in the lifecycle of a page is when it is called to execute the server-side code

associated with an event triggered on the client. When the user clicks a button, the page posts

back. The collection of posted values contains the ID of the button that started the whole

operation. If the control is known to implement the IPostBackEventHandler interface (buttons and

link buttons will do), the page framework calls the RaisePostBackEvent method. What this

method does depends on the type of the control. With regard to buttons and link buttons, the

method looks up for a Click event handler and runs the associated delegate.

After handling the postback event, the page prepares for rendering. This stage is signaled by the

PreRender event. This is a good time for controls to perform any last minute update operations

that need to take place immediately before the view state is saved and the output rendered. The

next state is SaveViewState, in which all controls and the page itself are invited to flush the

contents of their own ViewState collection. The resultant view state is then serialized, hashed,

Base64 encoded, and associated with the __VIEWSTATE hidden field.

The rendering mechanism of individual controls can be altered by overriding the Render method.

The method takes an HTML writer object and uses it to accumulate all HTML text to be generated

for the control. The default implementation of the Render method for the Page class consists of a

recursive call to all constituent controls. For each control the page calls the Render method and

caches the HTML output.

The final sign of life of a page is the Unload event that arrives just before the page object is

dismissed. In this event you should release any critical resource you might have (for example,

files, graphical objects, database connections).

Finally, after this event the browser receives the HTTP response packet and displays the page.

What are ASHX files? What are HttpHandlers? Where can they be configured?ASHX file is a web handler file that works just like an aspx file except you are one step back

away from the messy browser level where HTML and code behind mix. One reason you would

write an .ashx file instead of an .aspx file is that your output is not going to a browser but to an

xml-consuming client of some kind. Working with .ashx keeps you away from all the browser

technology you don't need in this case. Notice that you have to include the IsReusable property.

<% @ webhandler language="C#" class="AverageHandler" %>

using System;

using System.Web;

Page 55: Good+List+of+Questions+With+Answers

public class AverageHandler : IHttpHandler

{

public bool IsReusable

{ get { return true; } }

public void ProcessRequest(HttpContext ctx)

{

ctx.Response.Write("hello");

}

}

ASP.NET uses HTTP handlers to process all requests.

All requests to IIS are handled through Internet Server Application Programming Interface (ISAPI)

extensions. ASP.NET has its own filter to ensure pages are processed appropriately. By default,

the ASP.NET ISAPI filter (aspnet_isapi.dll) only handles ASPX, ASMX, and all other non-display

file formats used by .NET and Visual Studio. However, this filter can be registered with other

extensions in order to handle requests to those file types, too, but that will be covered later.

Every request flows through a number of HTTP modules, which cover various areas of the

application (i.e. authentication and session intofmation). After passing through each module, the

request is assigned to a single HTTP handler, which determines how the system will respond to

the request. Upon completion of the request handler, the response flows back through the HTTP

modules to the user.

HTTP ModuleHTTP modules are executed before and after the handler and provide a method for interacting

with the request. Custom modules must implement the System.Web.IHttpModule interface.

Modules are typically synchronized with events of the System.Web.IHttpModule class

(implemented within the Global.asax.cs or .vb file). The following consists of a list of events that

should be considered when implementing your module:

BeginRequest

AuthenticateRequest

AuthorizeRequest

ResolveRequestCache

AcquireRequestState

PreRequestHandlerExecute

PostRequestHandlerExecute

ReleaseRequestState

UpdateRequestCache

Page 56: Good+List+of+Questions+With+Answers

EndRequest

PreSendRequestHeaders*

PreSendRequestContent*

Error*

The events identified by an asterisk (*) can occur at any time within the request; all others are

listed in their calling order.

HTTP HandlersHTTP handlers proces the request and are generally responsible for initiating necessary business

logic tied to the request. Custom handlers must implement the System.Web.IHttpHandler

interface. Additionally, a handler factory can be created which will analyze a request to determine

what HTTP handler is appropriate. Custom handler factories implement the

System.Web.IHttpHandlerFactory interface.

When to use Modules and HandlersWith all of the options available in ASP.NET, it is sometimes hard to determine what solution best

fits your needs. Of course, it's always best to keep things simple; but, you still need to take

evolutionary considerations and experience levels of current and future team members who have

a potential of working on teh project into account. Both modules and handlers add a layer of

indirection that can be daunting to beginners and/or programmers who are not used to

implementing quality designs (read: design patterns).

First, consider what it is that you want to do within your module or handler. Some functions, such

as authentication and intstrumentation can be added within modules. Modules should be

considered only when there is a need for pass-through and/or intercepting interaction with the

request. Alternatively, handlers should be put in place when there is a need to direct functional

actions to one or more parts of an application. Probably the most noted use of HTTP handlers is

to the FrontController pattern, which allows requests to be refactored and assigned to different

components within your application without implementing such changes in every page.

Second, is it worth it? Most applications do not require this level of indirection, which can be hard

to understand and/or implement when not documented properly. Some methods, such as the

PageController pattern, allow for common functionality to be reused across multiple pages by

including this logic in a base System.Web.UI.Page object, and inheriting from this for every web

page. When reviewing the PageController implementation, you should know and understand the

appropriate use of inheritence. Although certain things can be done this way (i.e. authorization

and instrumentation), this is not always the correct means. You should fully understand the

pros/cons of utilizing both modules and handlers before deciding on one implementation over the

other.

Page 57: Good+List+of+Questions+With+Answers

With each of these considerations, and more, the decision to implement modules and/or handlers

can be a daunting one. Such decisions should be led by an experienced .NET architect. In the

absense of a skilled architect, you will be looking at a lot of leg-work to determine the best

solution.

Most notably, HTTP handlers are beneficial because they provide a way to interact with HTTP

requests before they get to a web page. This can be very nice, depending on what you need to

do with the request. For instance, perhaps there is a need for logging actions taken by users or

controlling access to individual files (i.e. images, executables).

What events fire when binding data to a data grid? What are they good for?Data binding is a very common process in ASP.NET so its important you have some sort of idea

of what is going on. Data binding, like the name suggests, is the dynamic process where values

are assigned to the properties of a control during runtime.

OnItemDataBound - OnItemDataBound is fired for each row being bound to your datasource (in

addition to when other templates are bound (header, footer, pager, ..)). It not only exposes the

DataItem being used in binding, but also the complete template. OnItemDataBound starts to fire

as soon as the DataBind() method is called on the Repeater/DataList/DataGrid.

OnItemCreated - Another useful event exposed by these controls is OnItemCreated. The key

difference between the two is that OnItemDataBound only fires when the control is bound - that

is, when you are posting back and the control is recreated from the viewstate, OnItemDataBound

doesn't fire. OnItemCreated, on the other hand, fires when a control is bound as well as when the

control is recreated from the viewstate.

Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality?With ASP .Net, the whole model has changed. Each of the asp .net pages will be a separate

entity with ability to process its own posted data. That is, the values of the Form are posted to the

same page and the very same page can process the data. This model is called post back. Each

Asp .net page when loaded goes through a regular creation and destruction cycle like

Initialization, Page load etc., in the beginning and unload while closing it. This Postback is a read

only property with each Asp .Net Page (System.Web.UI.Page) class. This is false when the first

time the page is loaded and is true when the page is submitted and processed. This enables

users to write the code depending on if the PostBack is true or false (with the use of the function

Page.IsPostBack()).

Implementation of ASP.Net Post back on the Client side:

Page 58: Good+List+of+Questions+With+Answers

Post back is implemented with the use javascript in the client side. The HTML page generated for

each .aspx page will have the action property of the form tag set to the same page. This makes

the page to be posted on to itself. If we check the entry on the HTML file, it will look something

like this.

<form name="_ctl1" method="post" action="pagename.aspx?getparameter1=134" language="javascript" onsubmit="if (!ValidatorOnSubmit()) return false;" id="_ctl1" > Also, all the validation code that is written (Required Field Validation, Regular Expression

validation etc.,) will all be processed at the client side using the .js(javascript) file present in the

webserver_wwwroot/aspnet_client folder.

With this new ASP .Net model, even if the user wants to post the data to a different .aspx page,

the web server will check for the runat='server' tag in the form tag and post the web form to the

same .aspx page. A simple declaration as in the following code snippet will be enough to create

such a web form.

<form id="form1" runat="server" > <!-- place the controls inside --></form>

How does ViewState work and why is it either useful or evil?When the WebForm's HTML output is streamed to the browser, the hidden "__VIEWSTATE" field is added to the form. When the form is posted back to the server, the Request.Form Collection (same as ASP) contains the values of the posted form. The Server Control reads the form POST data, extracts the values, and updates (rewrites) the ViewState value to be sent back to the client. At the same time, the Server Control adds the appropriate HTML to the HTML object text to "set" it in it's proper (remembered) state, that is, the state the form field was in when the form was posted. In essence, ASP.Net is doing the same thing that ASP does, although you don't have to write all that code to make it so.

Page 59: Good+List+of+Questions+With+Answers

We can use the ViewState to store any type of object, if that object is serializable or is having

TypeConverter. ‘Serialization is the process of converting object’s data into a stream based

output, and using that output later we can construct the same object’. Here, we must be aware of

where this serialization plays its role in ViewState. As early, we seen that controls' data are stored

into a hidden field, before that the value or data is being serialized.

Viewstate has lots of advantages and as well as disadvantages, so you need to weigh carefully

before making the decision to use it. View state doesnt require any server resources for its

operation. It is passed to the client during every postback as an hidden element. Since it is added

with every page, it adds few Kbytes to the page. This effects the loading of the page in the client.

Other main problem with Viewstate is, since it is passed as plain text to the client. Anybody can

tamper this value, because of this you shouldnt store any important data in the viewstate. View

state is one of the most important features of ASP.NET, not so much because of its technical

relevance, but more because it makes the magic of the Web Forms model possible. However, if

used carelessly, view state can easily become a burden. Although ViewState is freely accessible

in a hidden field called __VIEWSTATE, the view state information is not clear text. By default, a

machine-specific authentication code is calculated on the data and appended to the view state

string. The resulting text is then Base64 encoded only, but not encrypted. In order to make the

view state more secure, the ASP.NET @Page directive supports an attribute called

EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original

data.

Page 60: Good+List+of+Questions+With+Answers

What is the OO relationship between an ASPX page and its CS/VB code behind file in ASP.NET 1.1? in 2.0?The code-behind file contains the code to display the time, whereas the ASPX file contains the

code to define the GUI. When a client requests an ASPX file, ASP.NET creates two classes

behind the scenes. The first file ASP.NET generates is another partial class containing the

remaining portion of class based on the markup in the ASPX file. For example, WebTime.aspx

contains a Label Web control with ID timeLabel, so the generated partial class would contain a

declaration for a Label variable named timeLabel. This partial class might look like

Partial Class WebTime

Protected timeLabel As System.Web.UI.WebControls.Label

End Class

Note that a Label is a Web control defined in namespace System.Web.UI.WebControls, which

contains Web controls for designing a page's user interface. Web controls in this namespace

derive from class WebControl. When compiled, this partial class declaration containing Web

control declarations combines with the code-behind file's partial class declaration to form class

WebTime.

The second class generated by ASP.NET is a class based on the ASPX file that is used to create

the visual aspect of the page. This new class inherits from class WebTime, which defines the

logic of the page. The first time the Web page is requested, this class is compiled, and an

instance is created. This instance represents our page-it creates the XHTML that is sent to the

client. The assembly created from our compiled classes is placed within a subdirectory of

C:\WINDOWS\Microsoft.NET\Framework\VersionNumber\

Temporary ASP.NET Files\WebTime

where VersionNumber is the version number of the .NET Framework (e.g., v2.0.50215) installed

on your computer.

Name 10 C# keywords.1. new

2. public

3. private

4. sealed

5. static

Page 61: Good+List+of+Questions+With+Answers

6. void

7. base

8. virtual

9. string

10. int

What is public accessibility?Allows access to the class member from any other class

What is protected accessibility? Allows access to the class member only within the same class and from inherited classes.

What is internal accessibility? Allows access to the class member only in the same assembly.

What is protected internal accessibility? Allows access to the class member only within the same class, from inherited classes, and other

classes in the same assembly.

What is private accessibility?Allows access to the class member only in the same class.

What is static accessibility?Indicates that the member can be called without first instantiating the class.

What is the default accessibility for a class?private

What is the default accessibility for members of an interface? Public

What is the default accessibility for members of a struct?Public

Can the members of an interface be private?No

Page 62: Good+List+of+Questions+With+Answers

In C# Methods must declare a return type, what is the keyword used when nothing is returned from the method?Void

Class methods to should be marked with what keyword?New

What are the two return types for main?Int and void

What is a reference parameter?Reference parameters don't pass the values of the variables used in the function member

invocation - they use the variables themselves. Rather than creating a new storage location for

the variable in the function member declaration, the same storage location is used, so the value

of the variable in the function member and the value of the reference parameter will always be the

same. Reference parameters need the ref modifier as part of both the declaration and the

invocation - that means it's always clear when you're passing something by reference.

What is an out parameter?Like reference parameters, output parameters don't create a new storage location, but use the

storage location of the variable specified on the invocation. Output parameters need the out

modifier as part of both the declaration and the invocation - that means it's always clear when

you're passing something as an output parameter.

Output parameters are very similar to reference parameters. The only differences are:

The variable specified on the invocation doesn't need to have been assigned a value

before it is passed to the function member. If the function member completes normally,

the variable is considered to be assigned afterwards (so you can then "read" it).

The parameter is considered initially unassigned (in other words, you must assign it a

value before you can "read" it in the function member).

The parameter must be assigned a value before the function member completes

normally.

Declaring an out method is useful when you want a method to return multiple values. A method

that uses an out parameter can still return a value. A method can have more than one out

parameter.

What is an overloaded method?

Page 63: Good+List+of+Questions+With+Answers

A method is considered to be an overloaded method, if it has two or more signatures for the same

method name. These methods will contain different parameters but the same return types.

A simple example for an overloaded methods are:

Public void functionName(int a, params int[] varParam);

Public void functionName(int a);

What is a constructor?A constructor can be used, where every time an object gets created and if we want some code to

be executed automatically. The code that we want to execute must be put in the constructor. The

general form of a C# constructor is as follows

modifier constructor_name (parameters)

{

//constructor body

}

The modifiers can be private, public, protected or internal. The name of a constructor must be the

name of the class, where it is defined. A constructor can take zero or more arguments. A

constructor with zero arguments (that is no-argument) is known as default constructor.

Remember that there is not return type for a constructor.

We can say that constructor is mainly used for initializing an object. Even it is possible to do very

complicated calculations inside a constructor. The statement inside a constructor can throw

exceptions also.

Just like member functions, constructors can also be overloaded in a class. The overloaded

constructor must differ in their number of arguments and/or type of arguments and/or order of

arguments.

If I have a constructor with a parameter, do I need to explicitly create a default constructor?No

What is a destructor?The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory

occupied by the un-used objects. The destructor implements the statements to be executed

during the garbage collection process. A destructor is a function with the same name as the name

of the class but starting with the character ~.

Page 64: Good+List+of+Questions+With+Answers

Example

class Complex

{

public Complex()

{

// constructor

}

~Complex()

{

// Destructor

}

}

Remember that a destructor can’t have any modifiers like private, public etc. If we declare a

destructor with a modifier, the compiler will show an error. Also destructor will come in only one

form, without any arguments. There is no parameterized destructor in C#.

Destructors are invoked automatically and can’t be invoked explicitly. An object becomes eligible

for garbage collection, when it is no longer used by the active part of the program. Execution of

destructor may occur at any time after the instance or object becomes eligible for destruction.

Can you use access modifiers with destructors?Destructor can’t have any modifiers like private, public etc. If we declare a destructor with a

modifier, the compiler will show an error. Also destructor will come in only one form, without any

arguments. There is no parameterized destructor in C#.

What is a delegate? Write some code to use a delegate. What is a delegate useful for?A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the

programmer to encapsulate a reference to a method inside a delegate object. The delegate

object can then be passed to code which can call the referenced method, without having to know

at compile time which method will be invoked.

The signature of a single cast delegate is shown below:

delegate result-type identifier ([parameters]);where:

result-type: The result type, which matches the return type of the function.

Page 65: Good+List+of+Questions+With+Answers

identifier: The delegate name.

parameters: The Parameters, that the function takes.

A delegate will allow us to specify what the function we'll be calling looks like without having to

specify which function to call. The declaration for a delegate looks just like the declaration for a

function, except that in this case, we're declaring the signature of functions that this delegate can

reference. There are three steps in defining and using delegates:

Declaration

Instantiation

Invocation

A very basic example (SimpleDelegate1.cs):

using System;

namespace Akadia.BasicDelegate

{

// Declaration

public delegate void SimpleDelegate();

class TestDelegate

{

public static void MyFunc()

{

Console.WriteLine("I was called by delegate ...");

}

public static void Main()

{

// Instantiation

SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

// Invocation

simpleDelegate();

}

}

}

Page 66: Good+List+of+Questions+With+Answers

What is an event? Events use a publisher/subscriber model. What is that?

The Event model in C# finds its roots in the event programming model that is popular in

asynchronous programming. The basic foundation behind this programming model is the

idea of "publisher and subscribers." In this model, you have publishers who will do some

logic and publish an "event." Publishers will then send out their event only to

subscribers who have subscribed to receive the specific event.

In C#, any object can publish a set of events to which other applications can subscribe.

When the publishing class raises an event, all the subscribed applications are notified.

The following figure shows this mechanism.

Conventions

The following important conventions are used with events:

o Event Handlers in the .NET Framework return void and take two parameters.

Page 67: Good+List+of+Questions+With+Answers

o The first paramter is the source of the event; that is the publishing object.

o The second parameter is an object derived from EventArgs.

o Events are properties of the class publishing the event.

o The keyword event controls how the event property is accessed by the

subscribing classes.

Are events synchronous of asynchronous? Asynchronous.

Can a subscriber subscribe to more than one publisher?Yes

What is a value type and a reference type?1] value types (example : structures,primitive type,enums)

2] reference types (example : Classes,interface,arrays,strings etc..,)

When a value-type object is created, C# allocates a single space in memory, and puts the

contents of the object into it. Primitive types such as int, float, bool or char are also value types,

and they are instantiated in the same way. When the runtime deals with a value type, it's dealing

directly with its underlying data and this can be very efficient, particularly with primitive types.

With reference types, however, an object is created in memory, and then handled through a

separate reference – rather like a pointer. Suppose Point is a struct, and Form is a class.

Name 5 built in types.

C# Type .NET Framework Type

bool System.Boolean

Byte System.Byte

Sbyte System.SByte

Char System.Char

Decimal System.Decimal

Page 68: Good+List+of+Questions+With+Answers

Double System.Double

Float System.Single

Int System.Int32

Uint System.UInt32

Long System.Int64

Ulong System.UInt64

Object System.Object

Short System.Int16

Ushort System.UInt16

String System.String

string is an alias for what? System.string

Is string Unicode, ASCII, or something else? Unicode

Strings are immutable, what does this mean?Strings are immutable--the contents of a string object cannot be changed after the object is

created.

Name a few string properties.trim, tolower, toupper, concat, copy, insert, equals, compare.

What is boxing and unboxing? Write some code to box and unbox a value type.

Page 69: Good+List+of+Questions+With+Answers

Boxing and unboxing is a essential concept in C#’s type system. With Boxing and unboxing one

can link between value-types and reference-types by allowing any value of a value-type to be

converted to and from type object. Boxing and unboxing enables a unified view of the type

system wherein a value of any type can ultimately be treated as an object.

Converting a value type to reference type is called Boxing. Unboxing is an explicit operation.

C# provides a “unified type system”. All types—including value types—derive from the type

object. It is possible to call object methods on any value, even values of “primitive” types such as

int.

The example

class Test

{

static void Main() {

int i = 1;

object o = i; // boxing

int j = (int) o; // unboxing

}

}

An int value can be converted to object and back again to int.

This example shows both boxing and unboxing. When a variable of a value type needs to be

converted to a reference type, an object box is allocated to hold the value, and the value is copied

into the box.

Unboxing is just the opposite. When an object box is cast back to its original value type, the value

is copied out of the box and into the appropriate storage location.

Boxing conversions A boxing conversion permits any value-type to be implicitly converted to the type object or to any

interface-type implemented by the value-type. Boxing a value of a value-type consists of

allocating an object instance and copying the value-type value into that instance.

For example any value-type G, the boxing class would be declared as follows:

class vBox

{

G value;

G_Box(G g) {

value = g;

}

Page 70: Good+List+of+Questions+With+Answers

}

Boxing of a value v of type G now consists of executing the expression new G_Box(v), and

returning the resulting instance as a value of type object. A boxing conversion implies making a

copy of the value being boxed. This is different from a conversion of a reference-type to type

object, in which the value continues to reference the same instance and simply is regarded as the

less derived type object.

Unboxing conversions An unboxing conversion permits an explicit conversion from type object to any value-type or from

any interface-type to any value-type that implements the interface-type. An unboxing operation

consists of first checking that the object instance is a boxed value of the given value-type, and

then copying the value out of the instance. unboxing conversion of an object box to a value-type

G consists of executing the expression ((G_Box)box).value.

For an unboxing conversion to a given value-type to succeed at run-time, the value of the source

argument must be a reference to an object that was previously created by boxing a value of that

value-type. If the source argument is null or a reference to an incompatible object, an

InvalidCastException is thrown.

What is a heap and a stack? The heap and the stack are the two places where programs store data (okay, there are a few

more, but they're the two most common ones). The heap is just a big chunk of memory that is

managed by a heap manager (or garbage collector, in C#'s case). When you write something like:

Employee e = new Employee();

(assuming Employee is a class), you get a chunk of memory allocated out of the heap to store the

information for that employee instance. This instance will be preserved until it isn't needed

anymore (in C#), or until it is explicitly deleted (in languages like C++).

The stack is used to hold local variables. So, when I write something like:

int i = 15;

as part of a method, that sets aside a chunk of space on the stack to hold the value "15". When I

enter a method, that space is used on the stack, and when I leave the method, that space is

reclaimed for later use.

To be strictly true, in my first example, I not only allocated an instance of Employee on the heap, I

allocated a reference to that on the stack.

Or, to be shorter, all local variables use up space on the stack. If they are value types, this space

is used to store the actual value. If they are references types, this space is used as a reference

(aka pointer) to the actual value, which is stored on the heap.

Page 71: Good+List+of+Questions+With+Answers

What is a pointer? Pointers are variables that hold the addresses of other variables. For example, if x contains the

address of y, then x is said to “point to” y. Once a pointer points to a variable, the value of that

variable can be obtained or changed through the pointer. Operations through pointers are often

referred to as indirection.

Declaring a PointerThe general form of a pointer variable declaration is:

type* var-name;

Here, type is the pointer’s base type, which must be a nonreference type. Thus you cannot

declare a pointer to a class object. Notice the placement of the *. It follows the type name. var-

name is the name of the pointer variable. To declare ip to be a pointer to an int, use this

declaration:

int* ip;

In general, in a declaration statement, following a type name with a * creates a pointer type. In

C#, the * is distributive and the declaration:

int* p, q;

creates two pointer variables.

The * and & Pointer OperatorsTwo operators are used with pointers: * and &. The & is a unary operator that returns the

memory address of its operand. For example,

int* ip;

int num = 10;

ip = &num;

put’s into ip the memory address of the variable num. This address is the location of the variable

in the computers internal memory. It has nothing to do with the value of num. thus ip does not

contain the value 10.It contains the address at which num is stored.

The operation of & can be remembered as returning “the address of” the variable it precedes.

The second operator is *, and it is the compliment of &. It is a unary operator that refers to the

value of the variable located at the address specified by its operand. So,

int val = *ip;

will place into val the value 10. The operation of * can be remembered as “at address.”

The * can also be used on the left side of an assignment statement. For example,

*ip = 100;

Page 72: Good+List+of+Questions+With+Answers

Thus, This statement can be read as “at address ip, put the value as 100.”

Using unsafeAny code that uses pointers must be marked as unsafe by using the unsafe keyword. You can

mark an individual statement or an entire method unsafe. For example here is a program that

uses pointers inside Main(), which is marked unsafe:

What does new do in terms of objects? The new keyword is used to create objects and invoke constructors, for example;

private Label label1 = new Label();

It is also used to invoke the default constructor for value types, for example:

int myInt = new int();

In the preceding statement, myInt is initialized to 0, which is the default value for the type int. The

statement has the same effect as:

int myInt = 0;

The new keyword cannot be overloaded.

How do you dereference an object?Set it equal to null

What is a struct? A structure in C# is simply a composite data type consisting of a number elements of other types.

A C# structure is a value type and the instances or objects of a structure are created in stack. The

structure in C# can contain fields, methods, constants, constructors, properties, indexers,

operators and even other structure types.

Structure Declaration & Object Creation The keyword struct can be used to declare a structure. The general form of a structure

declaration in C# is as follows.

<modifiers> struct <struct_name>

{

//Structure members

}

Where the modifier can be private, public, internal or public. The struct is the required keyword.

For example

struct MyStruct

{

Page 73: Good+List+of+Questions+With+Answers

public int x;

public int y;

}

The objects of a strcut can be created by using the new operator as follows.

MyStruct ms = new MyStruct();

The individual members of a struct can be accessed by using the dot (.) operator as showing

below.

ms.x = 10;

ms.y = 20;

Remember that unlike classes, the strcut object can also be created without using the new

operator.

MyStruct ms;

But in this case all fields of the struct will remain unassigned and the object can’t be used until all

of the fields are initialized.

Describe 5 numeric value types ranges. sbyte -128 to 127, byte 0 – 255, short -32,768 to 32,767, int -2,147,483,648 to 2,147,483,647,

ulong 0 to 18,446,744,073,709,551,615

What is the default value for a bool? False

Write code for an enumeration. An enumeration (enum) is a special form of value type, which inherits from System.Enum and

supplies alternate names for the values of an underlying primitive type. An enumeration type has

a name, an underlying type, and a set of fields. The underlying type must be one of the built-in

signed or unsigned integer types (such as Byte, Int32, or UInt64). The fields are static literal

fields, each of which represents a constant. The language you are using assigns a specific value

of the underlying type to each field. The same value can be assigned to multiple fields. When this

occurs, the language marks one of the values as the primary enumeration value for purposes of

reflection and string conversion. The boxing rules that apply to value types also apply to

enumerations. The general form of an enumeration declaration is as follows.

<modifier> enum <enum_name>

{

// Enumeration list

{

Page 74: Good+List+of+Questions+With+Answers

For example

enum Months

{

jan, feb, mar, apr

}

By default the first enumerator has the value of zero and the value of each successive

enumerator is increased by 1. For example in the above case the value jan is 0, feb is 1 and so

on. Remember that the modifier can be private, public, protected or internal.

In C# enums, it is possible to override the default values. For example

enum Months

{

jan = 10, feb = 20, mar = 30, apr=40

}

A complete example is shown below.

using System;

enum Months : long

{

jan = 10,feb = 20,mar

}

class MyClient

{

public static void Main()

{

long x = (long)Months.jan;

long y = (long)Months.feb;

long z = (long)Months.mar;

Console.WriteLine("JANUARY={0},FEbriary = {1},March={2}",x,y,z);

}

}

The following are the restrictions apply to an enum type in C#

They can’t define their own methods.

They can’t implement interfaces.

They can’t define properties or indexers.

The use of enum type is superior to the use of integer constants, because the use of

enum makes the code more readable and self-documenting.

Page 75: Good+List+of+Questions+With+Answers

Write code for a case statement. The switch statement is a control statement that handles multiple selections by passing control to

one of the case statements within its body. It takes the following form:

switch (expression)

{

case constant-expression:

statement

jump-statement

[default:

statement

jump-statement]

}

Where:

expression - An integral or string type expression.

statement - The embedded statement(s) to be executed if control is transferred to the

case or the default.

jump-statement - A jump statement that transfers control out of the case body.

constant-expression - Control is transferred to a specific case according to the value of

this expression.

Control is transferred to the case statement whose constant-expression matches expression. The

switch statement can include any number of case instances, but no two case constants within the

same switch statement can have the same value. Execution of the statement body begins at the

selected statement and proceeds until the jump-statement transfers control out of the case body.

Notice that the jump-statement is required after each block, including the last block whether it is a

case statement or a default statement. Unlike the C++ switch statement, C# does not support an

explicit fall through from one case label to another. If you want, you can use goto a switch-case,

or goto default.

If expression does not match any constant-expression, control is transferred to the statement(s)

that follow the optional default label. If there is no default label, control is transferred outside the

switch.

Example

// statements_switch.cs

using System;

class SwitchTest

{

public static void Main()

Page 76: Good+List+of+Questions+With+Answers

{

Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");

Console.Write("Please enter your selection: ");

string s = Console.ReadLine();

int n = int.Parse(s);

int cost = 0;

switch(n)

{

case 1:

cost += 25;

break;

case 2:

cost += 25;

goto case 1;

case 3:

cost += 50;

goto case 1;

default:

Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");

break;

}

if (cost != 0)

Console.WriteLine("Please insert {0} cents.", cost);

Console.WriteLine("Thank you for your business.");

}

}

Is a struct stored on the heap or stack? A C# structure is a value type and the instances or objects of a structure are created in stack

Can a struct have methods? The structure in C# can contain fields, methods, constants, constructors, properties, indexers,

operators and even other structure types.

What is checked { } and unchecked { }?

Page 77: Good+List+of+Questions+With+Answers

Checked allows you to force C# to raise an exception whenever stack overflow (or underflow)

occurs due to type conversion issues. Unchecked will allow you to ignore these exceptions when

the C# project is set to raise these types of exceptions. This video explains both of these

concepts thoroughly.

Can C# have global overflow checking? Yes

What is explicit vs. implicit conversion? Give examples of both of the above.Type conversion is a process of converting one type into another. Using C# type conversion

techniques, not only you can convert data types, you can also convert object types. The type

conversion in C# can be either implicit conversion or an explicit conversion.

If one type of data is automatically converted into another type of data, it is known as implicit

conversions. There is no data loss due to implicit conversion. But explicit conversion is a forced

conversion and there may be a data loss. Type conversions occur mainly when we pass

arguments to a function or mixing mode arithmetic etc.

Implicit Conversions in C#The implicit conversions can occur in a variety of situations like function invoking, cast

expressions, assignments etc. The implicit conversions can be further classified into different

categories.

Implicit Numerical Conversions

The possible implicit numerical conversions in C# are shown below.

uint , ulong, float, double, decimal, ushort, short, int, long, sbyte, byte, char

The implicit conversions in the direction of arrow are possible with basic data types of C#.

Remember that there are no implicit conversions to the char type from any other types. Also there

are no implicit or explicit conversions associated with bool type. The examples for implicit

numerical conversions are shown below.

long x;

int y = 25;

x = y; //implicit numerical conversion

Implicit Enumeration Conversion

An implicit enumeration conversion permits the decimal integer literal 0 to be converted to any

enum type.

Implicit Reference Conversion

Page 78: Good+List+of+Questions+With+Answers

The possible implicit reference conversions are:

From any reference type to object.

From any class type D to any class type B, provided D is inherited from B.

From any class type A to interface type I, provided A implements I.

From any interface type I2 to any other interface type I1, provided I2 inherits I1.

From any array type to System.Array.

From any array type A with element type a to an array type B with element type b

provided A & B differ only in element type (but the same number of elements) and both a

and b are reference types and an implicit reference conversion exists between a & b.

From any delegate type to System.Delegate type.

From any array type or delegate type to System.ICloneable

From null type to any reference type.

Boxing Conversions

Boxing is the conversion of any value type to object type. Remember that boxing is an implicit

conversion. Boxing a value of value type like int consists of allocating an object instance and

copying the value of the value type into that object instance. An example for boxing is shown

below.

int x = 10;

object o = x; //Boxing

if(o is int)

Console.WriteLine(“o contains int type”);

A boxing conversion making a copy of the value being boxed. But when we convert a reference

type to object type, the object continues to reference the same instance.

Explicit Conversions in C#The explicit conversions are forced conversions in C# by using the casting operator (). There may

be a data loss due to explicit conversions. For example when we explicitly convert a double type

to an int type as shown below

int x = (int) 26.45; //Explicit conversion

Console.WriteLine(x); // Displays only 26

Explicit Numerical Conversions

They are the conversions from a numeric type to another numeric type for which an implicit

conversion doesn’t already exist. It is possible to convert any numerical type to any other

numerical type explicitly. The explicit numerical conversions can result possibly a data loss or

OverflowException to be thrown.

Explicit Enumeration Conversions

The explicit enumeration conversions are:

Page 79: Good+List+of+Questions+With+Answers

From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double or decimal to any

enum type.

From any enum type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double

or decimal.

From any enum type to any other enum type.

Explicit Reference Conversions

The possible explicit reference conversions are:

From object to any reference type.

From any class type B to any class type D, provided B is the base class of D

From any class type A to any interface type I, provided S is not sealed and do not

implement I.

From any interface type I to any class type A, provided A is not sealed and implement I.

From any interface type I2 to any interface type I1, provided I2 is not derived from I1.

From System.Array to any array type.

From System.Delegate type to any delegate type.

From System.ICloneable to any array or delegate type.

Because of any reasons, if an explicit reference conversion fails, an InvalidCastException is

thrown.

Un-boxing Conversions

Un-boxing is the conversion of an object type to a value type. The casting operator () is

necessary for un-boxing. The example for un-boxing is shown below.

int x = 100;

object o = x; // Boxing

int I (int) o; // un-boxing

For an un-boxing conversion to a given value type to succeed at run-time , the value type of the

source argument must be reference type to an object that was previously created by boxing a

value of the value type. If the source argument is null or a reference type to an incompatible type,

an InvalidCastException is thrown.

Can assignment operators be overloaded directly?No.

What do operators is and as do?The as operator is used to perform conversions between compatible types. The as operator is

used in an expression of the form:

Page 80: Good+List+of+Questions+With+Answers

expression as type

where:

expression - An expression of a reference type.

type - A reference type.

The as operator is like a cast except that it yields null on conversion failure instead of raising an

exception. More formally, an expression of the form:

expression as type

is equivalent to:

expression is type ? (type)expression : (type)null

except that expression is evaluated only once.

Note that the as operator only performs reference conversions and boxing conversions. The as

operator cannot perform other conversions, such as user-defined conversions, which should

instead be performed using cast expressions

The is operator is used to check whether the run-time type of an object is compatible with a given

type. The is operator is used in an expression of the form:

expression is type

Where:

expression - An expression of a reference type.

type - A type.

An is expression evaluates to true if both of the following conditions are met:

expression is not null.

expression can be cast to type. That is, a cast expression of the form (type)(expression)

will complete without throwing an exception. For more information, see 7.6.6 Cast

expressions.

A compile-time warning will be issued if the expression expression is type is known to always be

true or always be false. The is operator cannot be overloaded.

Note that the is operator only considers reference conversions, boxing conversions, and unboxing

conversions. Other conversions, such as user-defined conversions, are not considered by the is

operator.

What is the difference between the new operator and modifier?In C#, the new keyword can be used as an operator or as a modifier.

new operator Used to create objects on the heap and invoke constructors.

new modifier Used to hide an inherited member from a base class member.

The new operator is used to create objects and invoke constructors, for example:

Page 81: Good+List+of+Questions+With+Answers

Class1 MyClass = new Class1();

It is also used to invoke the default constructor for value types, for example:

int myInt = new int();

Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited

member, declare it in the derived class using the same name, and modify it with the new modifier.

Consider the following class:

public class MyBaseC

{

public int x;

public void Invoke() {}

}

Declaring a member with the name Invoke in a derived class will hide the method Invoke in the

base class, that is:

public class MyDerivedC : MyBaseC

{

new public void Invoke() {}

}

Explain sizeof and typeof.The sizeof operator is used to obtain the size in bytes for a value type. A sizeof expression takes

the form:

sizeof(type)

where:

type - The value type for which the size is obtained.

The sizeof operator can be applied only to value types, not reference types. The sizeof operator

can only be used in the unsafe mode. The sizeof operator cannot be overloaded.

The typeof operator is used to obtain the System.Type object for a type. A typeof expression

takes the form:

typeof(type)

where:

type - The type for which the System.Type object is obtained.

The typeof operator cannot be overloaded. To obtain the run-time type of an expression, you can

use the .NET Framework method GetType.

Page 82: Good+List+of+Questions+With+Answers

What does the stackalloc operator do?Stackalloc Allocates a block of memory on the stack.

type * ptr = stackalloc type [ expr ];

where:

type - An unmanaged type.

ptr - A pointer name.

Expr - An integral expression.

A block of memory of sufficient size to contain expr elements of type type is allocated on the

stack, not the heap; the address of the block is stored in pointer ptr. This memory is not subject to

garbage collection and therefore does not have to be pinned (via fixed). The lifetime of the

memory block is limited to the lifetime of the method in which it is defined.

stackalloc is only valid in local variable initializers.

Contrast ++count vs. count++.Some operators have temporal properties depending on their placement. E.g.

double x;

x = 2;

Console.Write(++x);

x = 2;

Console.Write(x++);

Console.Write(x);

Returns 323

What are the names of the three types of operators?Unary, Binary and Conversion

An operator declaration must include a public and static modifier, can it have other modifiers? No

Can operator parameters be reference parameters? No

Page 83: Good+List+of+Questions+With+Answers

Describe an operator from each of these categories: Arithmetic, Logical (boolean and bitwise), String concatenation, Increment, decrement, Shift, Relational, Assignment, Member access, Indexing, Cast, Conditional, Delegate, Concatenation and removal, Object creation, Type information, Overflow exception control Indirection and Address

Operator category Operators

Arithmetic +   -   *   /   %

Logical (boolean and bitwise)

&   |   ^   !   ~   &&   ||   true   false

String concatenation +

Increment, decrement ++   --

Shift <<   >>

Relational ==   !=   <   >   <=   >=

Assignment =   +=   -=   *=   /=   %=   &=   |=   ^=   <<=   >>=

Member access .

Indexing []

Cast ()

Conditional ?:

Delegate concatenation and removal

+   -

Object creation new

Type information as   is   sizeof   typeof   

Overflow exception control checked   unchecked

Indirection and Address *   ->   []   &

What does operator order of precedence mean?

The process of the order of evaluation of operators is called operators precedence. If you don't

want to use the parentheses, and would rather rely on the second procedure, it is the default C#

operator precedence. The C# compiler evaluates operators based on the following table:

Page 84: Good+List+of+Questions+With+Answers

The IntelliSense Operator .

The Parentheses Operator ()

Array Index Operator []

The Post Increment Operator ++

The Post Decrement Operator --

The new Operator

The typeof Operator

The checked Operator

the unchecked Operator

The unary plus +

The unary minus -

the unary !

The unary ~

The Pre Increment Operator ++

The Pre Decrement Operator --

The multiplication Operator *

The division Operator /

The Module Operator %

The Addition Operator +

The Subtraction Operator -

The Shift-Left Operator <<

The Shift-Right Operator >>

The Less Than Operator <

The Less Than or Equal Operator <=

The Greater Than Operator >

The Greater Than or Equal Operator >=

The is Operator

The Equality Operator ==

Page 85: Good+List+of+Questions+With+Answers

The Is Not Equal Operator !=

The And Operator &

The XOR Operator ^

The Or Operator |

The Short-Circuit And Operator &&

The Short-Circuit Or Operator ||

The Ternary Operator ?:

The Assignment Operators as following

=,*=,/=,+=,-=,<<=,>>=,&=,^= and |=

What is special about the declaration of relational operators? Relational Operators must be declared in pair.

What operators cannot be overloaded? =, ., ?:, ->, new, is, sizeof, typeof

What is an exception? Practically any program including c# .net can have some amount of errors. They can be broadly

classified as compile-time errors and runtime errors. Compile-time errors are errors that can be

found during compilation process of source code. Most of them are syntax errors. Runtime errors

happen when program is running. It is very difficult to find and debug the run-time errors.

These errors also called exceptions.

Can C# have multiple catch blocks? Yes

Can break exit a finally block? No

Can continue exit a finally block? No

Page 86: Good+List+of+Questions+With+Answers

What are expression and declaration statements?

What is a dangling else? if (n>0)

if (n2>0)

Console.Write("Dangling Else")

else

Is switch case sensitive? Yes

Can you have multiple control variables in a for loop? Yes

Write some code for a collection class.using System;

using System.Collections;

public class Items : IEnumerable

{

private string[] contents;

public Items(string[] contents)

{

this.contents = contents;

}

public IEnumerator GetEnumerator()

{

return new ItemsEnumerator(this);

}

private class ItemsEnumerator : IEnumerator

{

private int location = -1;

private Items i;

public ItemsEnumerator(Items i)

{

Page 87: Good+List+of+Questions+With+Answers

this.i = i;

}

public bool MoveNext()

{

if (location < i.contents.Length - 1)

{

location++;

return true;

}

else

{

return false;

}

}

public void Reset()

{

location = -1;

}

public object Current

{

get

{

return i.contents[location];

}

}

}

static void Main()

{

// Test

string[] myArray = {"a","b","c"};

Items items = new Items(myArray);

foreach (string item in items)

{

Console.WriteLine(item);

}

Page 88: Good+List+of+Questions+With+Answers

Console.ReadLine();

}

}

Describe Jump statements: break, continue, and goto. Break terminates a loop or switch. Continue jumps to the next iteration of an enclosing iteration

statement. Goto jumps to a labelled statement

How do you declare a constant? public const int c1 = 5;

What is the default index of an array?0

What is array rank? Rank returns the number of dimensions of an array.

Can you resize an array at runtime? No

Does the size of an array need to be defined at compile time. No

Write some code to implement a multidimensional array. int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};

Write some code to implement a jagged array. Jagged arrrays are nothing but arrays of arrays. This is very clear from the 'Declaration' sysnatx.

See the [] appears more than once in the following declaration.

// Declare the array of two elements:

int[][] myArray = new int[2][];

// Initialize the elements:

myArray[0] = new int[5] {1,3,5,7,9};

myArray[1] = new int[4] {2,4,6,8};

Page 89: Good+List+of+Questions+With+Answers

What is an ArrayList? The main problem of traditional arrays is that their size is fixed by the number you specify when

declaring the array variable: you cannot add items beyond the specified dimension. Another

limitation is that you cannot insert an item inside the list. To overcome this, you can create a

linked list. Instead of working from scratch, the .NET Framework provides the ArrayList class.

With the ArrayList class, you can add new items to a list, insert items inside a list, arrange items

of a list, check the existence of an item in a list, remove an item from the list, inquire about the

list, or destroy the list. These operations are possible through various properties and methods.

The ArrayList class is defined in the System.Collections namespace. To use it, first declare a

pointer to ArrayList. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)

{

ArrayList lstNumbers = new ArrayList();

}

Can an ArrayList be ReadOnly? Yes

Can properties have an access modifier? Yes

Can properties hide base class members of the same name? Yes

What happens if you make a property static? They become class properties

Can a property be a ref or out parameter? No

What is an accessor? An accessor contains executable statements associated with getting or setting properties.

Can an interface have properties? Yes

Page 90: Good+List+of+Questions+With+Answers

What is polymorphism Polymorphism is possibility to change behavior with objects depending of object?s data type. In

C# polymorphism realizes through the using of keyword virtual and override. Let look on the

example of code:

public virtual void Out()

{

Console.WriteLine("Aperture virtual method called");

}

//This method is defined in Aperture class.

public override void Out()

{

Console.WriteLine("Door virtual method called");

}

What is a nested class? In C# it is possible to define one class inside another. A class defined inside another one is called

a nested class. Consider the following C# code fragment:

public class A

{

int y;

public static class B

{

int x;

void F() {}

}

}

This fragment defines the class A which contains the nested class B.

What is a namespace? A namespace declares a scope which is useful for organizing code and to distinguish one type

from another. Namespaces allow you to create a system to organize your code. A good way to

organize your namespaces is via a hierarchical system. You put the more general names at the

top of the hierarchy and get more specific as you go down. This hierarchical system can be

represented by nested namespaces.By placing code in different sub-namespaces, you can keep

your code organized.

Page 91: Good+List+of+Questions+With+Answers

Can nested classes use any of the 5 types of accessibility? Yes

Can base constructors can be private? Yes

object is an alias for what? System.object

What namespace would you use for reflection? System.Reflection

What does this do? Public Foo() : this(12, 0, 0) Calls another constructor in the list

Do local values get garbage collected? They automatically die when they go out of scope.

Is object destruction deterministic? No

How do you refer to a member in the base class? To refer to a member in the base class use:return base.NameOfMethod().

Can you derive from a struct?No

Does C# supports multiple inheritance? No

All classes derive from what? System.Object

Can different assemblies share internal access? No

Does C# have “friendship”?

Page 92: Good+List+of+Questions+With+Answers

No

Can you inherit from multiple interfaces? Yes

Can abstract methods override virtual methods? Yes

What keyword would you use for scope name clashes? This

Can you have nested namespaces? Yes

What are attributes?Attributes are declarative tags which can be used to mark certain entities (like methods for

example).

Name 3 categories of predefined attributes. COM Interop -

Transaction

Visual Designer Component Builder

What are the 2 global attributes. Assembly & Module

Why would you mark something as Serializable? The easiest way to make a class serializable is to mark it with the Serializable attribute as follows.

[Serializable]

public class MyObject {

public int n1 = 0;

public int n2 = 0;

public String str = null;

}

Write code to define and use your own custom attribute. // cs_attributes_retr.cs

Page 93: Good+List+of+Questions+With+Answers

using System;

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,

AllowMultiple=true)]

public class Author : Attribute

{

public Author(string name)

{

this.name = name; version = 1.0;

}

public double version;

string name;

public string GetName()

{

return name;

}

}

List some custom attribute scopes and possible targets. Assembly – assembly

Class – type

Delegate - type, return

List compiler directives? #if

#else

#elif

#endif

#define

#undef

#warning

#error

#line

#region

#endregion

Do you spin off or spawn a thread?

Page 94: Good+List+of+Questions+With+Answers

Spin

What is the volatile keyword used for? The volatile keyword indicates that a field can be modified in the program by something such as

the operating system, the hardware, or a concurrently executing thread.

volatile declaration

where:

declaration - The declaration of a field.

The system always reads the current value of a volatile object at the point it is requested, even if

the previous instruction asked for a value from the same object. Also, the value of the object is

written immediately on assignment. The volatile modifier is usually used for a field that is

accessed by multiple threads without using the lock statement to serialize access. Using the

volatile modifier ensures that one thread retrieves the most up-to-date value written by another

thread.

The type of a field marked as volatile is restricted to the following types:

Any reference type.

Any pointer type (in an unsafe context).

The types sbyte, byte, short, ushort, int, uint, char, float, bool.

An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

Write code to use threading and the lock keyword. using System;

using System.Threading;

namespace ConsoleApplication4

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

ThreadClass tc1 = new ThreadClass(1);

ThreadClass tc2 = new ThreadClass(2);

Thread oT1 = new Thread(new ThreadStart(tc1.ThreadMethod));

Page 95: Good+List+of+Questions+With+Answers

Thread oT2 = new Thread(new ThreadStart(tc2.ThreadMethod));

oT1.Start();

oT2.Start();

Console.ReadLine();

}

}

class ThreadClass

{

private static object lockValue = "dummy";

public int threadNumber;

public ThreadClass(int threadNumber)

{

this.threadNumber = threadNumber;

}

public void ThreadMethod()

{

for (;;)

{

lock(lockValue)

{

Console.WriteLine(threadNumber + " working");

Thread.Sleep(1000);

}

}

}

}

}

What is Monitor? The Monitor class controls access to objects by granting a lock for an object to a single thread.

Object locks provide the ability to restrict access to a block of code, commonly called a critical

section. While a thread owns the lock for an object, no other thread can acquire that lock. You

can also use Monitor to ensure that no other thread is allowed to access a section of application

Page 96: Good+List+of+Questions+With+Answers

code being executed by the lock owner, unless the other thread is executing the code using a

different locked object.

What is a semaphore? A semaphore is a protected variable (or abstract data type) and constitutes the classic method for

restricting access to shared resources (e.g. storage) in a multiprogramming environment. They

were invented by Edsger Dijkstra and first used in the THE operating system. Semaphores are

the classic solution to the dining philosophers problem, although they do not prevent all

deadlocks.

What mechanisms does C# have for the readers, writers problem? System.Threading.ReaderWriterLock which has methods AcquireReaderLock,

ReleaseReaderLock, AcquireWriterLock, and ReleaseWriterLock

What is Mutex? When two or more threads need to access a shared resource at the same time, the system needs

a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex

is a synchronization primitive that grants exclusive access to the shared resource to only one

thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is

suspended until the first thread releases the mutex.

What is an assembly? An assembly is a file that is automatically generated by the compiler upon successful compilation

of every .NET application. It can be either a Dynamic Link Library or an executable file. It is

generated only once for an application and upon each subsequent compilation the assembly gets

updated. The entire process will run in the background of your application; there is no need for

you to learn deeply about assemblies. However, a basic knowledge about this topic will help you

to understand the architecture behind a .NET application.

What is an assembly identity? Assembly identity is name, version number, and optional culture, and optional public key to

guarantee uniqueness

What does the assembly manifest contain? Assembly manifest lists all names of public types and resources and their locations in the

assembly.

Page 97: Good+List+of+Questions+With+Answers

What is IDLASM used for? Use IDLASM to see assembly internals. It disassembles into MSIL.

Where are private assemblies stored? Same folder as exe

Where are shared assemblies stored? GAC

What is DLL hell? DLLs, VBX or OCX files being unavailable or in the wrong versions. Applicatioins using say these

older DLLs expect some behaviour which is not present.

In terms of assemblies, what is side-by-side execution? Side-by-side execution is the ability to run multiple versions of an application or component on the

same computer. You can have multiple versions of the common language runtime, and multiple

versions of applications and components that use a version of the runtime, on the same computer

at the same time.

Name and describe 5 different documentation tags. /// <value></value>

/// <example></example>

/// <exception cref=""></exception>

/// <include file='' path='[@name=""]'/>

/// <param name="args"></param>

/// <paramref name=""/>

/// <permission cref=""></permission>

/// <remarks>

/// </remarks>

/// <summary>

/// <c></c>

/// <code></code>

/// <list type=""></list>

/// <see cref=""/>

Page 98: Good+List+of+Questions+With+Answers

/// <seealso cref=""/>

/// </summary>

What is unsafe code? Unsafe code bypasses type safety and memory management.

What does the fixed statement do? The fixed statement prevents the garbage collector from relocating a movable variable. The fixed

statement is only permitted in an unsafe context. Fixed can also be used to create fixed size

buffers. The fixed statement sets a pointer to a managed variable and "pins" that variable during

the execution of statement. Without fixed, pointers to movable managed variables would be of

little use since garbage collection could relocate the variables unpredictably. The C# compiler

only lets you assign a pointer to a managed variable in a fixed statement.

How would you read and write using the console? Console.Write, Console.WriteLine, Console.Readline

Give examples of hex, currency, and fixed point console formatting. Console.Write("{0:X}", 250); --> FA

Console.Write("{0:C}", 2.5); --> $2.50

Console.Write("{0:F2}", 25); --> 25.00

Given part of a stack trace: aspnet.debugging.BadForm.Page_Load(Object sender, EventArgs e) +34. What does the +34 mean? It is an actual offset (at the assembly language level) – not an offset into the IL instructions.

Are value types are slower to pass as method parameters? Yes

How can you implement a mutable string? Use System.Text.StringBuilder.

What is a thread pool? Provides a pool of threads that can be used to post work items, process asynchronous I/O, wait

on behalf of other threads, and process timers.

System.Object

Page 99: Good+List+of+Questions+With+Answers

System.Threading.ThreadPool

[Visual Basic]

NotInheritable Public Class ThreadPool

[C#]

public sealed class ThreadPool

[C++]

public __gc __sealed class ThreadPool

[JScript]

public class ThreadPool

Many applications create threads that spend a great deal of time in the sleeping state, waiting for

an event to occur. Other threads might enter a sleeping state only to be awakened periodically to

poll for a change or update status information. Thread pooling enables you to use threads more

efficiently by providing your application with a pool of worker threads that are managed by the

system. One thread monitors the status of several wait operations queued to the thread pool.

When a wait operation completes, a worker thread from the thread pool executes the

corresponding callback function. You can also queue work items that are not related to a wait

operation to the thread pool. To request that a work item be handled by a thread in the thread

pool, call the QueueUserWorkItem method. This method takes as a parameter a reference to the

method or delegate that will be called by the thread selected from the thread pool. There is no

way to cancel a work item after it has been queued.

Timer-queue timers and registered wait operations also use the thread pool. Their callback

functions are queued to the thread pool. The thread pool is created the first time you create an

instance of the ThreadPool class. The thread pool has a default limit of 25 threads per available

processor, which could be changed using CorSetMaxThreads as defined in the mscoree.h file.

Each thread uses the default stack size and runs at the default priority. Each process can have

only one operating system thread pool.

Describe the CLR security model.

What’s the difference between camel and pascal casing? They are written as follows

PascalCasing,

camelCasing

What does marshalling mean?

Page 100: Good+List+of+Questions+With+Answers

The process of packing one or more items of data into a message buffer, prior to transmitting that

message buffer over a communication channel. The packing process not only collects together

values which may be stored in non-consecutive memory locations but also converts data of

different types into a standard representation agreed with the recipient of the message

What is inlining? In-line expansion or inlining for short is a compiler optimization which "expands" a function call

site into the actual implementation of the function which is called, rather than each call

transferring control to a common piece of code. This reduces overhead associated with the

function call, which is especially important for small and frequently called functions, and it helps

call-site-specific compiler optimizations, especially constant propagation.

What are design patterns? Describe some common design patterns. (Need to expand these)Design patterns are recurring solutions to software design problems you find again and again in

real-world application development. Patterns are about design and interaction of objects, as well

as providing a communication platform concerning elegant, reusable solutions to commonly

encountered programming challenges.

Creational Patterns Abstract Factory Creates an instance of several families of classes

Builder Separates object construction from its representation

Factory Method Creates an instance of several derived classes

Prototype A fully initialized instance to be copied or cloned

Singleton A class of which only a single instance can exist

Structural Patterns Adapter Match interfaces of different classes

Bridge Separates an object’s interface from its implementation

Composite A tree structure of simple and composite objects

Decorator Add responsibilities to objects dynamically

Façade A single class that represents an entire subsystem

Flyweight A fine-grained instance used for efficient sharing

Proxy An object representing another object

Behavioral Patterns Chain of Resp. A way of passing a request between a chain of objects

Command Encapsulate a command request as an object

Page 101: Good+List+of+Questions+With+Answers

Interpreter A way to include language elements in a program

Iterator Sequentially access the elements of a collection

Mediator Defines simplified communication between classes

Memento Capture and restore an object's internal state

Observer A way of notifying change to a number of classes

State Alter an object's behavior when its state changes

Strategy Encapsulates an algorithm inside a class

Template Method Defer the exact steps of an algorithm to a subclass

Visitor Defines a new operation to a class without change

What are the different diagrams in UML? What are they used for? Use case diagram: The use case diagram is used to identify the primary elements and

processes that form the system. The primary elements are termed as "actors" and the

processes are called "use cases." The use case diagram shows which actors interact

with each use case.

Class diagram: The class diagram is used to refine the use case diagram and define a

detailed design of the system. The class diagram classifies the actors defined in the use

case diagram into a set of interrelated classes. The relationship or association between

the classes can be either an "is-a" or "has-a" relationship. Each class in the class

diagram may be capable of providing certain functionalities. These functionalities

provided by the class are termed "methods" of the class. Apart from this, each class may

have certain "attributes" that uniquely identify the class.

Object diagram: The object diagram is a special kind of class diagram. An object is an

instance of a class. This essentially means that an object represents the state of a class

at a given point of time while the system is running. The object diagram captures the

state of different classes in the system and their relationships or associations at a given

point of time.

State diagram: A state diagram, as the name suggests, represents the different states

that objects in the system undergo during their life cycle. Objects in the system change

states in response to events. In addition to this, a state diagram also captures the

transition of the object's state from an initial state to a final state in response to events

affecting the system.

Activity diagram: The process flows in the system are captured in the activity diagram.

Similar to a state diagram, an activity diagram also consists of activities, actions,

transitions, initial and final states, and guard conditions.

Page 102: Good+List+of+Questions+With+Answers

Sequence diagram: A sequence diagram represents the interaction between different

objects in the system. The important aspect of a sequence diagram is that it is time-

ordered. This means that the exact sequence of the interactions between the objects is

represented step by step. Different objects in the sequence diagram interact with each

other by passing "messages".

Collaboration diagram: A collaboration diagram groups together the interactions between

different objects. The interactions are listed as numbered interactions that help to trace

the sequence of the interactions. The collaboration diagram helps to identify all the

possible interactions that each object has with other objects.

Component diagram: The component diagram represents the high-level parts that make

up the system. This diagram depicts, at a high level, what components form part of the

system and how they are interrelated. A component diagram depicts the components

culled after the system has undergone the development or construction phase.

Deployment diagram: The deployment diagram captures the configuration of the runtime

elements of the application. This diagram is by far most useful when a system is built and

ready to be deployed.”

What is MSIL? Microsoft Intermediate Language (MSIL) is the CPU-independent instruction set generated

by .NET compilers from .NET languages such as J#, C# or Visual Basic. MSIL is compiled before

or during execution of the program by a Virtual Execution System (VES), which is part of the

Common Language Runtime module (CLR).

What is the CLR and how is it different from a JVM? Firstly CLR is referred to an Execution Engine rather than a virtual machine.

The .NET framework's Common Language Runtime (CLR) is much similar to Java Virtual

Machine (JVM), in terms of garbage collection, security, just in time compilation (JIT).

However, the fundamental difference arises from the variance in perception between the 2 teams.

The JVM executes bytecode, so it could technically support many different languages, too. Unlike

Java's bytecode, though, IL is never interpreted. Another conceptual difference between the two

infrastructures is that Java code runs on multiple platforms with a JVM, whereas .NET code runs

only on the Windows platforms with the CLR (at the time of this writing). Microsoft has submitted

the Common Language Infrastructure (CLI), which is functional a subset of the CLR, to ECMA, so

a third-party vendor could theoretically implement a CLR for a platform other than Windows.

CLR implements a contiguous (adjacent) memory allocation algorithm whereas JVM implements

a noncontiguous memory allocation algorithm.

CLR compiles the source code twice during the process of converting to native code. Compiling

works faster than interpreting. JVM compiles and interprets the source code once during the

process of converting it to native code.

Page 103: Good+List+of+Questions+With+Answers

What is WinFX? "WinFX" is the name of new managed API available for Longhorn. It can be thought as Win32

API available for current Windows operating system. Similar to Win32. The new Windows API

that will be released with the Microsoft Longhorn Operating System. This will include features for

Avalon, Indigo, and WinFS as well as a number of fundamental routines.

What is Indigo? Indigo is an umbrella that covers all the technologies used to build connected applications

in .NET. If you think about technologies used to build connected application in .NET, you will

see .NET Remoting, XML Web services, COM+ services, and MSMQ. In Longhorn model, all

these technologies are under a single name and that is Indigo. For developer, who do not use

Longhorn operating system, Indigo will be available as a separate download for Windows XP and

Windows Server 2003. Indigo, also supports smooth migration of existing connected applications

and services.

What is LongHorn SDK?For Longhorn developers, the Longhorn SDK can be thought as a .NET SDK for .NET

developers. It consists every component required to build, manage, and run Longhorn

applications. Longhorn SDK is a part of Longhorn operating system. Similar to .NET SDK, the

Longhorn SDK is available for a separate download for Windows XP and Windows Server 2003.

Describe AvalonUnder Longhorn programming model, the presentation layer development (client application

development) that used to be Windows Forms is called Avalon. Besides the capabilities exists in

Windows Forms, Avalon adds many new features to the system. A few of these features are

addition of a new markup language, Extensible Application Markup Language (XAML), and

support for both Windows and Web applications. The class model of Avalon is totally different

than Windows Forms. In the current version, the root namespace for Avalon development is

MSAvalon and then sub namespace are like MSAvalon.Windows and

MSAvalon.Windows.Controls. Again, Avalon is a part of Longhorn library which is common for all

programming language that supports Longhorn.

Describe XAMLXAML (Extensible Application Markup Language) is a new scripting language based on XML that

allows Longhorn developers to build and managed UI applications via scripting. If you remember

Windows Forms model, the settings of a Form and its child controls were used to store in a .cs

Page 104: Good+List+of+Questions+With+Answers

file with all the attributes of the Form and controls. Now, all these attributes can store in an xaml

file and that can run without any additional code. For example, the following code shows how to

create a Form with a button saying "Hello, C# Corner".

<?xml version="1.0" standalone="yes"?>

<Window>

<Button>Hello, C# Corner</Button>

</Window>

To run this code, simply type this code in a text editor, save as xaml extension and double click

on it. Of course you have to install Longhorn SDK on your machine if you are not working on

Longhorn.

Similar to the above sample code, XAML has tags and attributes for every possible Windows

control. You can also embed your code (C# or VB.NET) in an XAML file.

What is WinFSWinFS is the codename for new file system used in Longhorn. Unlike previous file systems

(FAT32 and NTFS), WinFS takes advantage of database and XML and stores files and their

metadata in a database. WinFS not only stores files but also stores metadata about the files

which is accessible to the users from the Windows interface as well as programmatically. By

having control on the file system metadata, the users and developers have more control on files.

For example, you can search for the files they were written by a particular user. Not only the

author, you can also query based on dates, file types, title, size and so on.

Explain the Remoting architecture. .NET Remoting Architecture.NET remoting enables objects in different application domains to talk to each other. The real

strength of remoting is in enabling the communication between objects when their application

domains are separated across the network. In this case, remoting transparently handles details

related to network communication.

How come remoting is able to establish cross-application domain communication when the

application domains do not allow direct calls across their boundaries?

Remoting takes an indirect approach to application domain communication by creating proxy

objects as shown in Figure 3.1.

Page 105: Good+List+of+Questions+With+Answers

Both application domains communicate with each other by following these steps:

When a client object requests an instance of the server object, the remoting system at

the client side instead creates a proxy of the server object. The proxy object lives at the

client but behaves just like the remote object; this leaves the client with the impression

that the server object is in the client's process.

When the client object calls a method on the server object, the proxy passes the call

information to the remoting system on the client. This remoting system in turn sends the

call over the channel to the remoting system on the server.

The remoting system on the server receives the call information and, on the basis of it,

invokes the method on the actual object on the server (creating the object if necessary).

The remoting system on the server collects the result of the method invocation and

passes it through the channel to the remoting system on the client.

The remoting system at the client receives the server's response and returns the results

to the client object through the proxy.

Page 106: Good+List+of+Questions+With+Answers

The process of packaging and sending method calls among objects, across application

boundaries, via serialization and deserialization, as shown in the preceding steps, is also known

as marshaling.

Object MarshalingRemotable objects are the objects that can be marshaled across the application domains. In

contrast, all other objects are known as non-remotable objects. There are two types of remotable

objects:

Marshal-by-value (MBV) Objects—These objects are copied and passed out of the server

application domain to the client application domain. MBV objects reside on the server. When a

client invokes a method on the MBV object, the MBV object is serialized, transferred over the

network, and restored on the client as an exact copy of the server-side object. Now, the MBV

object is locally available and therefore any method calls to the object do not require any proxy

object or marshaling. The MBV objects can provide faster performance by reducing the network

roundtrips, but in the case of large objects, the time taken to transfer the serialized object from

server to the client can be very significant. Furthermore, the MBV objects do not provide the

privilege of running the remote object in the server environment. You can create an MBV object

by declaring a class with the Serializable attribute. For example:

//define a MBV remoting object

[Serializable()]

public class MyMBVObject

{

//...

}

If a class needs to control its own serialization, it can do so by implementing the ISerializable

interface as follows:

//define a MBV remoting object

[Serializable()]

public class MyMBVObject : ISerializable

{

//...

//Implement custom serialization here

public void GetObjectData(

SerializationInfo info,

StreamingContext context)

{

//...

}

Page 107: Good+List+of+Questions+With+Answers

//...

}

The NonSerialized Attribute By default public and private fields of a class are serialized, if a

Serializable attribute is applied to the class. If you do not want to serialize a specific field in a

serializable class, apply the NonSerialized attribute on that field. For example, in the class

Sample, although field1 and field2 are serialized, field3 is not serialized because of the

NonSerialized attribute.

[Serializable()]

public class Sample

{

public int field1;

public string field2;

// A field that is not serialized.

[NonSerialized()]

public string field3;

.

.

.

}

Marshal-by-reference (MBR) Objects—A proxy is used to access these objects on the client

side. The clients hold just a reference to these objects. The MBR objects are remote objects.

They always reside on the server and all methods invoked on these objects are executed at the

server side. The client communicates with the MBR object on the server by using a local proxy

object that holds the reference to the MBR object.

Although the use of MBR objects increases the number of network roundtrips, they are a likely

choice when the objects are prohibitively large or when the functionality of the object is available

only in the server environment on which it is created. You can create an MBR object by deriving

the MBR class from the System.MarshalByRefObject class. For example:

//define a MBR remoting object

public class MyMBRObject : MarshalByRefObject

{

//...

}

Page 108: Good+List+of+Questions+With+Answers

How would you write an asynchronous webservice?

What is the Microsoft Enterprise Library? The patterns & practices Enterprise Library is a library of Application Blocks designed to assist

developers with common enterprise development challenges. Application Blocks are a type of

guidance, provided as source code, which can be used as-is, extended or modified by developers

for use on enterprise development projects. These include Caching Application Block,

Configuration Application Block, Data Access Application Block, Cryptography Application Block,

Exception Handling Application Block, Logging and Instrumentation Application Block, Security

Application Block etc.

Discuss System.Collections The System.Collections namespace contains interfaces and classes that define various

collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

ClassesClass Description

ArrayList Implements the IList interface using an array whose size is dynamically increased as required.

BitArray Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).

CaseInsensitiveComparer Compares two objects for equivalence, ignoring the case of strings.

CaseInsensitiveHashCodeProvider Supplies a hash code for an object, using a hashing algorithm that ignores the case of strings.

CollectionBase Provides the abstract (MustInherit in Visual Basic) base class for a strongly typed collection.

Comparer Compares two objects for equivalence, where string comparisons are case-sensitive.

DictionaryBase Provides the abstract (MustInherit in Visual Basic) base class for a strongly typed collection of key-and-value pairs.

Hashtable Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Queue Represents a first-in, first-out collection of objects.

Page 109: Good+List+of+Questions+With+Answers

ReadOnlyCollectionBase Provides the abstract (MustInherit in Visual Basic) base class for a strongly typed read-only collection.

SortedList Represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index.

Stack Represents a simple last-in-first-out collection of objects.

InterfacesInterface Description

ICollection Defines size, enumerators and synchronization methods for all collections.

IComparer Exposes a method that compares two objects.

IDictionary Represents a collection of key-and-value pairs.

IDictionaryEnumerator Enumerates the elements of a dictionary.

IEnumerable Exposes the enumerator, which supports a simple iteration over a collection.

IEnumerator Supports a simple iteration over a collection.

IHashCodeProvider Supplies a hash code for an object, using a custom hash function.

IList Represents a collection of objects that can be individually accessed by index.

StructuresStructure Description

DictionaryEntry Defines a dictionary key-and-value pair that can be set or retrieved.

Discuss System.Configuration The System.Configuration namespace provides classes and interfaces that allow you to

programmatically access .NET Framework configuration settings and handle errors in

configuration files (.config files).

ClassesClass Description

Page 110: Good+List+of+Questions+With+Answers

AppSettingsReader Provides a method for reading values of a particular type from the .config file.

ConfigurationException The exception that is thrown when an error occurs in a configuration setting.

ConfigurationSettings Provides access to configuration settings in a specified configuration section. This class cannot be inherited.

DictionarySectionHandler Reads key-value pair configuration information for a configuration section.

IgnoreSectionHandler Provides a section handler definition for configuration sections read and handled by systems other than System.Configuration.

NameValueSectionHandler Provides name-value pair configuration information from a configuration section.

SingleTagSectionHandler

InterfacesInterface Description

IConfigurationSectionHandler Defines the contract that all configuration section handlers must implement in order to participate in the resolution of configuration settings.

Discuss System.Data The System.Data namespace consists mostly of the classes that constitute the ADO.NET

architecture. The ADO.NET architecture enables you to build components that efficiently manage

data from multiple data sources. In a disconnected scenario (such as the Internet), ADO.NET

provides the tools to request, update, and reconcile data in multiple tier systems. The ADO.NET

architecture is also implemented in client applications, such as Windows Forms, or HTML pages

created by ASP.NET. The centerpiece of the ADO.NET architecture is the DataSet class. Each

DataSet can contain multiple DataTable objects, with each DataTable containing data from a

single data source, such as SQL Server.

Each DataTable contains a DataColumnCollection--a collection of DataColumn objects--that

determines the schema of each DataTable. The DataType property determines the type of data

held by the DataColumn. The ReadOnly and AllowDBNull properties allow you to further ensure

data integrity. The Expression property enables you to construct calculated columns.

If a DataTable participates in a parent/child relationship with another DataTable, the relationship

is constructed by adding a DataRelation to the DataSet object's DataRelationCollection. When

Page 111: Good+List+of+Questions+With+Answers

such a relation is added, a UniqueConstraint and a ForeignKeyConstraint are both created

automatically (depending on the parameter settings for the constructor). The UniqueConstraint

ensures that values contained in a column are unique. The ForeignKeyConstraint determines

what action will happen to the child row or column when a primary key value is changed or

deleted.

Using the System.Data.SqlClient namespace (the .NET Framework Data Provider for SQL

Server), the System.Data.Odbc namespace (the .NET Framework Data Provider for ODBC), or

the System.Data.OleDb namespace (the .NET Framework Data Provider for OLE DB), you can

access a data source to use in conjunction with a DataSet. Each .NET data provider has a

corresponding DataAdapter that you use as a bridge between a data source and a DataSet.

ClassesClass Description

Constraint Represents a constraint that can be enforced on one or more DataColumn objects.

ConstraintCollection Represents a collection of constraints for a DataTable.

ConstraintException Represents the exception that is thrown when attempting an action that violates a constraint.

DataColumn Represents the schema of a column in a DataTable.

DataColumnChangeEventArgs Provides data for the ColumnChanging event.

DataColumnCollection Represents a collection of DataColumn objects for a DataTable.

DataException Represents the exception that is thrown when errors are generated using ADO.NET components.

DataRelation Represents a parent/child relationship between two DataTable objects.

DataRelationCollection Represents the collection of DataRelation objects for this DataSet.

DataRow Represents a row of data in a DataTable.

DataRowChangeEventArgs Provides data for the RowChanged, RowChanging, OnRowDeleting, and OnRowDeleted events.

DataRowCollection Represents a collection of rows for a DataTable.

DataRowView Represents a customized view of a DataRow exposed as a fully featured Windows Forms control.

Page 112: Good+List+of+Questions+With+Answers

DataSet Represents an in-memory cache of data.

DataSysDescriptionAttribute Marks a property, event, or extender with a description. Visual designers can display this description when referencing the member.

DataTable Represents one table of in-memory data.

DataTableCollection Represents the collection of tables for the DataSet.

DataView Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.

DataViewManager Contains a default DataViewSettingCollection for each DataTable in a DataSet.

DataViewSetting Represents the default settings for ApplyDefaultSort, DataViewManager, RowFilter, RowStateFilter, Sort, and Table for DataViews created from the DataViewManager.

DataViewSettingCollection Contains a read-only collection of DataViewSetting objects for each DataTable in a DataSet.

DBConcurrencyException The exception that is thrown by the DataAdapter during the update operation if the number of rows affected equals zero.

DeletedRowInaccessibleException Represents the exception that is thrown when an action is attempted on a DataRow that has been deleted.

DuplicateNameException Represents the exception that is thrown when a duplicate database object name is encountered during an add operation in a DataSet-related object.

EvaluateException Represents the exception that is thrown when the Expression property of a DataColumn cannot be evaluated.

FillErrorEventArgs Provides data for the FillError event of a DbDataAdapter.

ForeignKeyConstraint Represents an action restriction enforced on a set of columns in a primary key/foreign key relationship when a value or row is either deleted or updated.

InRowChangingEventException Represents the exception that is thrown when calling the EndEdit method within the RowChanging event.

InternalDataCollectionBase Provides the base functionality for creating collections.

InvalidConstraintException Represents the exception that is thrown when incorrectly attempting to create or access a relation.

InvalidExpressionException Represents the exception that is thrown when attempting to add a DataColumn containing an invalid Expression to a

Page 113: Good+List+of+Questions+With+Answers

DataColumnCollection.

MergeFailedEventArgs Occurs when a target and source DataRow have the same primary key value, and the EnforceConstraints property is set to true.

MissingPrimaryKeyException Represents the exception that is thrown when attempting to access a row in a table that has no primary key.

NoNullAllowedException Represents the exception that is thrown when attempting to insert a null value into a column where AllowDBNull is set to false.

PropertyCollection Represents a collection of properties that can be added to DataColumn, DataSet, or DataTable.

ReadOnlyException Represents the exception that is thrown when attempting to change the value of a read-only column.

RowNotInTableException Represents the exception that is thrown when trying to perform an operation on a DataRow that is not in a DataTable.

StateChangeEventArgs Provides data for the state change event of a .NET Framework data provider.

StrongTypingException The exception that is thrown by a strongly-typed DataSet when the user accesses DBNull value.

SyntaxErrorException Represents the exception that is thrown when the Expression property of a DataColumn contains a syntax error.

TypedDataSetGenerator Used to create a strongly-typed DataSet.

TypedDataSetGeneratorException The exception that is thrown when a name conflict occurs while generating a strongly-typed DataSet.

UniqueConstraint Represents a restriction on a set of columns in which all values must be unique.

VersionNotFoundException Represents the exception that is thrown when attempting to return a version of a DataRow that has been deleted.

InterfacesInterface Description

IColumnMapping Associates a data source column with a DataSet column, and is implemented by the DataColumnMapping class, which is used in common by .NET Framework data providers.

Page 114: Good+List+of+Questions+With+Answers

IColumnMappingCollection Contains a collection of DataColumnMapping objects, and is implemented by the DataColumnMappingCollection, which is used in common by .NET Framework data providers.

IDataAdapter Allows an object to implement a DataAdapter, and represents a set of methods and mapping action-related properties used to fill and refresh a DataSet and update a data source.

IDataParameter Represents a parameter to a Command object, and optionally, its mapping to DataSet columns; and is implemented by .NET Framework data providers that access data sources.

IDataParameterCollection Collects all parameters relevant to a Command object and their mappings to DataSet columns, and is implemented by .NET Framework data providers that access data sources.

IDataReader Provides a means of reading one or more forward-only streams of result sets obtained by executing a command at a data source, and is implemented by .NET Framework data providers that access relational databases.

IDataRecord Provides access to the column values within each row for a DataReader, and is implemented by .NET Framework data providers that access relational databases.

IDbCommand Represents an SQL statement that is executed while connected to a data source, and is implemented by .NET Framework data providers that access relational databases.

IDbConnection Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases.

IDbDataAdapter Represents a set of command-related properties that are used to fill the DataSet and update a data source, and is implemented by .NET Framework data providers that access relational databases.

IDbDataParameter Used by the Visual Basic .NET Data Designers to represent a parameter to a Command object, and optionally, its mapping to DataSet columns.

IDbTransaction Represents a transaction to be performed at a data source, and is implemented by .NET Framework data providers that access relational databases.

ITableMapping Associates a source table with a table in a DataSet, and is implemented by the DataTableMapping class, which is used in common by .NET Framework data providers.

ITableMappingCollection Contains a collection of TableMapping objects, and is implemented by the DataTableMappingCollection, which is used in common by .NET Framework data providers.

Page 115: Good+List+of+Questions+With+Answers

DelegatesDelegate Description

DataColumnChangeEventHandler Represents the method that will handle the ColumnChanging event.

DataRowChangeEventHandler Represents the method that will handle the RowChanging, RowChanged, RowDeleting, and RowDeleted events of a DataTable.

FillErrorEventHandler Represents the method that will handle the FillError event.

MergeFailedEventHandler Represents the method that will handle the MergeFailed event.

StateChangeEventHandler Represents the method that will handle the StateChange event.

EnumerationsEnumeration Description

AcceptRejectRule Determines the action that occurs when the AcceptChanges or RejectChanges method is invoked on a DataTable with a ForeignKeyConstraint.

CommandBehavior Provides a description of the results of the query and its effect on the database.

CommandType Specifies how a command string is interpreted.

ConnectionState Describes the current state of the connection to a data source.

DataRowAction Describes an action performed on a DataRow.

DataRowState Gets the state of a DataRow object.

DataRowVersion Describes the version of a DataRow.

DataViewRowState Describes the version of data in a DataRow.

DbType Specifies the data type of a field, a property, or a Parameter object of a .NET Framework data provider.

IsolationLevel Specifies the transaction locking behavior for the connection.

KeyRestrictionBehavior Identifies a list of connection string parameters identified by the KeyRestrictions property that are either allowed or not allowed.

MappingType Specifies how a DataColumn is mapped.

Page 116: Good+List+of+Questions+With+Answers

MissingMappingAction Determines the action that occurs when a mapping is missing from a source table or a source column.

MissingSchemaAction Specifies the action to take when adding data to the DataSet and the required DataTable or DataColumn is missing.

ParameterDirection Specifies the type of a parameter within a query relative to the DataSet.

PropertyAttributes Specifies the attributes of a property.

Rule Indicates the action that occurs when a ForeignKeyConstraint is enforced.

SchemaType Specifies how to handle existing schema mappings when performing a FillSchema operation.

SqlDbType Specifies SQL Server-specific data type of a field, property, for use in a SqlParameter.

StatementType Specifies the type of SQL query to be used by the OleDbRowUpdatedEventArgs, OleDbRowUpdatingEventArgs, SqlRowUpdatedEventArgs, or SqlRowUpdatingEventArgs class.

UpdateRowSource Specifies how query command results are applied to the row being updated.

UpdateStatus Specifies the action to take with regard to the current and remaining rows during an Update.

XmlReadMode Specifies how to read XML data and a relational schema into a DataSet.

XmlWriteMode Specifies how to write XML data and a relational schema from a DataSet.

Discuss System.Diagnostics The System.Diagnostics namespace provides classes that allow you to interact with system

processes, event logs, and performance counters.

The EventLog component provides functionality to write to event logs, read event log entries, and

create and delete event logs and event sources on the network. The EntryWrittenEventHandler

provides a way to interact with event logs asynchronously. Supporting classes provide access to

more detailed control, including: permission restrictions, the ability to specify event log types

(which controls the type of default data that is written with an event log entry), and iterate through

collections of event log entries

Page 117: Good+List+of+Questions+With+Answers

The Process class provides functionality to monitor system processes across the network, and to

start and stop local system processes. In additional to retrieving lists of running processes (by

specifying either the computer, the process name, or the process id) or viewing information about

the process that currently has access to the processor, you can get detailed knowledge of

process threads and modules both through the Process class itself, and by interacting with the

ProcessThread and ProcessModule classes. The ProcessStartInfo class enables you to specify a

variety of elements with which to start a new process, such as input, output, and error streams,

working directories, and command line verbs and arguments. These give you fine control over the

behavior of your processes. Other related classes let you specify window styles, process and

thread priorities, and interact with collections of threads and modules.

The PerformanceCounter class enables you to monitor system performance, while the

PerformanceCounterCategory class provides a way to create new custom counters and

categories. You can write to local custom counters and read from both local and remote counters

(system as well as custom). You can sample counters using the PerformanceCounter class, and

calculate results from successive performance counter samples using the CounterSample class.

The CounterCreationData class enables you to create multiple counters in a category and specify

their types. Other classes associated with the performance counter component provide access to

collections of counters, counter permission, and counter types.

The System.Diagnostics namespace also provides classes that allow you to debug your

application and to trace the execution of your code. For more information, see the Trace and

Debug classes.

ClassesClass Description

BooleanSwitch Provides a simple on/off switch that controls debugging and tracing output.

ConditionalAttribute Indicates to compilers that a method is callable if a specified preprocessing identifier is applied to the method.

CounterCreationData Defines the counter type, name, and Help string for a custom counter.

CounterCreationDataCollection Provides a strongly typed collection of CounterCreationData objects.

CounterSampleCalculator Provides a set of utility functions for interpreting performance counter data.

Debug Provides a set of methods and properties that help debug your code. This class cannot be

Page 118: Good+List+of+Questions+With+Answers

inherited.

DebuggableAttribute Modifies code generation for runtime just-in-time (JIT) debugging. This class cannot be inherited.

Debugger Enables communication with a debugger. This class cannot be inherited.

DebuggerHiddenAttribute Specifies the DebuggerHiddenAttribute. This class cannot be inherited.

DebuggerStepThroughAttribute Specifies the DebuggerStepThroughAttribute. This class cannot be inherited.

DefaultTraceListener Provides the default output methods and behavior for tracing.

EntryWrittenEventArgs Provides data for the EntryWritten event.

EventLog Provides interaction with Windows event logs.

EventLogEntry Encapsulates a single record in the event log. This class cannot be inherited.

EventLogEntryCollection Defines size and enumerators for a collection of EventLogEntry instances.

EventLogInstaller Allows you to install and configure an event log that your application reads from or writes to when running. This class is called by the installation utility, for example, InstallUtil.exe, when installing an event log.

EventLogPermission Allows control of code access permissions for event logging.

EventLogPermissionAttribute Allows declaritive permission checks for event logging.

EventLogPermissionEntry Defines the smallest unit of a code access security permission that is set for an EventLog.

EventLogPermissionEntryCollection Contains a strongly typed collection of EventLogPermissionEntry objects.

EventLogTraceListener Provides a simple listener that directs tracing or debugging output to an EventLog.

FileVersionInfo Provides version information for a physical file on disk.

InstanceData Holds instance data associated with a

Page 119: Good+List+of+Questions+With+Answers

performance counter sample.

InstanceDataCollection Provides a strongly typed collection of InstanceData objects.

InstanceDataCollectionCollection Provides a strongly typed collection of InstanceDataCollection objects.

MonitoringDescriptionAttribute Specifies a description for a property or event.

PerformanceCounter Represents a Windows NT performance counter component.

PerformanceCounterCategory Represents a performance object, which defines a category of performance counters.

PerformanceCounterInstaller Specifies an installer for the PerformanceCounter component.

PerformanceCounterPermission Allows control of code access permissions for PerformanceCounter.

PerformanceCounterPermissionAttribute Allows declaritive performance counter permission checks.

PerformanceCounterPermissionEntry Defines the smallest unit of a code access security permission that is set for a PerformanceCounter.

PerformanceCounterPermissionEntryCollection Contains a strongly typed collection of PerformanceCounterPermissionEntry objects.

Process Provides access to local and remote processes and enables you to start and stop local system processes.

ProcessModule Represents a .dll or .exe file that is loaded into a particular process.

ProcessModuleCollection Provides a strongly typed collection of ProcessModule objects.

ProcessStartInfo Specifies a set of values used when starting a process.

ProcessThread Represents an operating system process thread.

ProcessThreadCollection Provides a strongly typed collection of ProcessThread objects.

StackFrame Provides information about a StackFrame, which represents a function call on the call stack

Page 120: Good+List+of+Questions+With+Answers

for the current thread.

StackTrace Represents a stack trace, which is an ordered collection of one or more stack frames.

Switch Provides an abstract (MustInherit in Visual Basic) base class to create new debugging and tracing switches.

TextWriterTraceListener Directs tracing or debugging output to a TextWriter or to a Stream, such as Console.Out or FileStream.

Trace Provides a set of methods and properties that help you trace the execution of your code. This class cannot be inherited.

TraceListener Provides the abstract (MustInherit in Visual Basic) base class for the listeners who monitor trace and debug output.

TraceListenerCollection Provides a thread-safe list of TraceListener objects.

TraceSwitch Provides a multilevel switch to control tracing and debug output without recompiling your code.

StructuresStructure Description

CounterSample Defines a structure holding the raw data for a performance counter.

DelegatesDelegate Description

EntryWrittenEventHandler Represents the method that will handle the EntryWritten event of an EventLog.

EnumerationsEnumeration Description

EventLogEntryType Specifies the event type of an event log entry.

EventLogPermissionAccess Defines access levels used by EventLog permission classes.

Page 121: Good+List+of+Questions+With+Answers

PerformanceCounterPermissionAccess Defines access levels used by PerformanceCounter permission classes.

PerformanceCounterType Specifies the formula used to calculate the NextValue method for a PerformanceCounter instance.

ProcessPriorityClass Indicates the priority that the system associates with a process. This value, together with the priority value of each thread of the process, determines each thread's base priority level.

ProcessWindowStyle Specified how a new window should appear when the system starts a process.

ThreadPriorityLevel Specifies the priority level of a thread.

ThreadState Specifies the current execution state of the thread.

ThreadWaitReason Specifies the reason a thread is waiting.

TraceLevel Specifies what messages to output for the Debug, Trace and TraceSwitch classes.

Discuss System.DirectoryServcies The System.DirectoryServices namespace provides easy access to Active Directory from

managed code. The namespace contains two component classes, DirectoryEntry and

DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is

the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network

providers. ADSI gives the administrator the ability to locate and manage resources on a network

with relative ease, regardless of the network's size.

The classes in this namespace can be used with any of the Active Directory service providers.

The current providers are: Internet Information Services (IIS), Lightweight Directory Access

Protocol (LDAP), Novell NetWare Directory Service (NDS), and WinNT.

ADSI is a programmatic interface for Microsoft Active Directory that enables your applications to

interact with diverse directories on a network, using a single interface. Using ADSI, you can

create applications that can perform common tasks, such as backing up databases, accessing

printers, and administering user accounts.

It is assumed that you have a general understanding of Active Directory before using these

classes. For more information on Active Directory, see Introduction to Active Directory Objects,

Active Directory Technology Backgrounder, and the Active Directory topics in the MSDN library

Page 122: Good+List+of+Questions+With+Answers

Active Directory is a tree structure. Each node in the tree contains a set of properties. Use this

namespace to traverse, search, and modify the tree, and read and write to the properties of a

node.

The DirectoryEntry class encapsulates a node or object in the Active Directory hierarchy. Use this

class for binding to objects, reading properties, and updating attributes. Together with helper

classes, DirectoryEntry provides support for life-cycle management and navigation methods,

including creating, deleting, renaming, moving a child node, and enumerating children.

Use the DirectorySearcher class to perform queries against the Active Directory hierarchy. LDAP

is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports

searching.

A search of the Active Directory hierarchy through DirectorySearcher returns instances of

SearchResult, which are contained in an instance of the SearchResultCollection class.

ClassesClass Description

DirectoryEntries Contains the children (child entries) of an entry in Active Directory.

DirectoryEntry Encapsulates a node or object in the Active Directory hierarchy.

DirectorySearcher Performs queries against Active Directory.

DirectoryServicesPermission Allows control of code access security permissions for System.DirectoryServices.

DirectoryServicesPermissionAttribute Allows declarative System.DirectoryServices permission checks.

DirectoryServicesPermissionEntry Defines the smallest unit of a code access security permission set for System.DirectoryServices.

DirectoryServicesPermissionEntryCollection Contains a strongly typed collection of DirectoryServicesPermissionEntry objects.

PropertyCollection Contains the properties of a DirectoryEntry.

PropertyValueCollection Contains the values of a DirectoryEntry property.

ResultPropertyCollection Contains the properties of a SearchResult instance.

ResultPropertyValueCollection Contains the values of a SearchResult property.

SchemaNameCollection Contains a list of the schema names that the

Page 123: Good+List+of+Questions+With+Answers

SchemaFilter property of a DirectoryEntries object can use.

SearchResult Encapsulates a node in the Active Directory hierarchy that is returned during a search through DirectorySearcher.

SearchResultCollection Contains the SearchResult instances that the Active Directory hierarchy returned during a DirectorySearcher query.

SortOption Specifies how to sort the results of a search.

EnumerationsEnumeration Description

AuthenticationTypes Specifies the types of authentication used in System.DirectoryServices.

DirectoryServicesPermissionAccess Defines access levels used by System.DirectoryServices permission classes.

ReferralChasingOption Specifies if and how referral chasing is pursued.

SearchScope Specifies the possible scopes for a directory search.

SortDirection Specifies how to sort the results of an Active Directory query.

Discuss System.Drawing The System.Drawing namespace provides access to GDI+ basic graphics functionality. More

advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging,

and System.Drawing.Text namespaces. The Graphics class provides methods for drawing to the

display device. Classes such as Rectangle and Point encapsulate GDI+ primitives. The Pen class

is used to draw lines and curves, while classes derrived from the abstract class Brush are used to

fill the interiors of shapes.

ClassesClass Description

Bitmap Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A Bitmap object is an

Page 124: Good+List+of+Questions+With+Answers

object used to work with images defined by pixel data.

Brush Classes derived from this abstract base class define objects used to fill the interiors of graphical shapes such as rectangles, ellipses, pies, polygons, and paths.

Brushes Brushes for all the standard colors. This class cannot be inherited.

ColorConverter Converts colors from one data type to another. Access this class through the TypeDescriptor.

ColorTranslator Translates colors to and from GDI+ Color structures. This class cannot be inherited.

Font Defines a particular format for text, including font face, size, and style attributes. This class cannot be inherited.

FontConverter Converts Font objects from one data type to another. Access the FontConverter class through the TypeDescriptor object.

FontFamily Defines a group of type faces having a similar basic design and certain variations in styles. This class cannot be inherited.

Graphics Encapsulates a GDI+ drawing surface. This class cannot be inherited.

Icon Represents a Windows icon, which is a small bitmap image used to represent an object. Icons can be thought of as transparent bitmaps, although their size is determined by the system.

IconConverter Converts an Icon object from one data type to another. Access this class through the TypeDescriptor object.

Image An abstract base class that provides functionality for the Bitmap and Metafile descended classes.

ImageAnimator Animates an image that has time-based frames.

ImageConverter ImageConverter is a class that can be used to convert Image objects from one data type to another. Access this class through the TypeDescriptor object.

ImageFormatConverter ImageFormatConverter is a class that can be used to convert colors from one data type to another. Access this class through the TypeDescriptor object.

Pen Defines an object used to draw lines and curves. This class

Page 125: Good+List+of+Questions+With+Answers

cannot be inherited.

Pens Pens for all the standard colors. This class cannot be inherited.

PointConverter Converts a Point object from one data type to another. Access this class through the TypeDescriptor object.

RectangleConverter Converts rectangles from one data type to another. Access this class through the TypeDescriptor.

Region Describes the interior of a graphics shape composed of rectangles and paths. This class cannot be inherited.

SizeConverter The SizeConverter class is used to convert from one data type to another. Access this class through the TypeDescriptor object.

SolidBrush Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths. This class cannot be inherited.

StringFormat Encapsulates text layout information (such as alignment and line spacing), display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features. This class cannot be inherited.

SystemBrushes Each property of the SystemBrushes class is a SolidBrush object that is the color of a Windows display element.

SystemColors Each property of the SystemColors class is a Color structure that is the color of a Windows display element.

SystemIcons Each property of the SystemIcons class is an Icon object for Windows system-wide icons. This class cannot be inherited.

SystemPens Each property of the SystemPens class is a Pen object that is the color of a Windows display element and that is a width of 1.

TextureBrush Each property of the TextureBrush class is a Brush object that uses an image to fill the interior of a shape. This class cannot be inherited.

ToolboxBitmapAttribute You can apply a ToolboxBitmapAttribute to a control so that containers, such as Microsoft Visual Studio Form Designer, can retrieve an icon that represents the control. The bitmap for the icon can be in a file by itself or embedded in the assembly that contains the control.

The size of the bitmap that you embed in the control's

Page 126: Good+List+of+Questions+With+Answers

assembly (or store in a separate file) should be 16 by 16. The GetImage method of a ToolboxBitmapAttribute object can return the small 16 by 16 image or a large 32 by 32 image that it creates by scaling the small image.

StructuresStructure Description

CharacterRange Specifies a range of character positions within a string.

Color Represents an ARGB color.

Point Represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensional plane.

PointF Represents an ordered pair of floating point x- and y-coordinates that defines a point in a two-dimensional plane.

Rectangle Stores a set of four integers that represent the location and size of a rectangle. For more advanced region functions, use a Region object.

RectangleF Stores a set of four floating-point numbers that represent the location and size of a rectangle. For more advanced region functions, use a Region object.

Size Stores an ordered pair of integers, typically the width and height of a rectangle.

SizeF Stores an ordered pair of floating-point numbers, typically the width and height of a rectangle.

DelegatesDelegate Description

Graphics.DrawImageAbort Provides a callback method for deciding when the DrawImage method should prematurely cancel execution and stop drawing an image.

Graphics.EnumerateMetafileProc Provides a callback method for the EnumerateMetafile method.

Image.GetThumbnailImageAbort Provides a callback method for determining when the GetThumbnailImage method should prematurely cancel execution.

Page 127: Good+List+of+Questions+With+Answers

EnumerationsEnumeration Description

ContentAlignment Specifies alignment of content on the drawing surface.

FontStyle Specifies style information applied to text.

GraphicsUnit Specifies the unit of measure for the given data.

KnownColor Specifies the known system colors.

RotateFlipType Specifies the direction of an image's rotation and the axis used to flip the image.

StringAlignment Specifies the alignment of a text string relative to its layout rectangle.

StringDigitSubstitute The StringDigitSubstitute enumeration specifies how to substitute digits in a string according to a user's locale or language.

StringFormatFlags Specifies the display and layout information for text strings.

StringTrimming Specifies how to trim characters from a string that does not completely fit into a layout shape.

StringUnit Specifies the units of measure for a text string.

Discuss System.EnterpriseServices The System.EnterpriseServices namespace provides an important infrastructure for enterprise

applications. COM+ provides a services architecture for component programming models

deployed in an enterprise environment. This namespace provides .NET objects with access to

COM+ services making the .NET Framework objects more practical for enterprise applications.

ClassesClass Description

Activity Creates an activity to do synchronous or asynchronous batch work that can use COM+ services without needing to create a COM+ component. This class cannot be inherited.

ApplicationAccessControlAttribute Allows security configuration for the library or server application housing the application. This class cannot be inherited.

Page 128: Good+List+of+Questions+With+Answers

ApplicationActivationAttribute Specifies whether components in the assembly run in the creator's process or in a system process.

ApplicationIDAttribute Specifies the application ID (as a GUID) for this assembly. This class cannot be inherited.

ApplicationNameAttribute Specifies the name of the COM+ application to be used for the install of the components in the assembly. This class cannot be inherited.

ApplicationQueuingAttribute Enables queuing support for the marked assembly and enables the application to read method calls from Message Queuing queues. This class cannot be inherited.

AutoCompleteAttribute Marks the attributed method as an AutoComplete object. This class cannot be inherited.

BYOT Wraps the COM+ ByotServerEx class and the COM+ DTC interfaces ICreateWithTransactionEx and ICreateWithTipTransactionEx. This class cannot be inherited.

ComponentAccessControlAttribute Enables security checking on calls to a component. This class cannot be inherited.

COMTIIntrinsicsAttribute Enables you to pass context properties from the COM Transaction Integrator (COMTI) into the COM+ context.

ConstructionEnabledAttribute Enables COM+ object construction support. This class cannot be inherited.

ContextUtil Obtains information about the COM+ object context. This class cannot be inherited.

DescriptionAttribute Sets the description on an assembly (application), component, method, or interface. This class cannot be inherited.

EventClassAttribute Marks the attributed class as an event class. This class cannot be inherited.

EventTrackingEnabledAttribute Enables event tracking for a component. This class cannot be inherited.

ExceptionClassAttribute Sets the queuing exception class for the queued class. This class cannot be inherited.

IISIntrinsicsAttribute Enables access to ASP intrinsic values from ContextUtil.GetNamedProperty. This class cannot be inherited.

InterfaceQueuingAttribute Enables queuing support for the marked interface. This class cannot be inherited.

Page 129: Good+List+of+Questions+With+Answers

JustInTimeActivationAttribute Turns just-in-time (JIT) activation on or off. This class cannot be inherited.

LoadBalancingSupportedAttribute Determines whether the component participates in load balancing, if the component load balancing service is installed and enabled on the server.

MustRunInClientContextAttribute Forces the attributed object to be created in the context of the creator, if possible. This class cannot be inherited.

ObjectPoolingAttribute Enables and configures object pooling for a component. This class cannot be inherited.

PrivateComponentAttribute Identifies a component as a private component that is only seen and activated by components in the same application. This class cannot be inherited.

RegistrationConfig Provides configuration information for installing assemblies into the COM+ catalog.

RegistrationErrorInfo Retrieves extended error information about methods related to multiple COM+ objects. This also includes methods that install, import, and export COM+ applications and components. This class cannot be inherited.

RegistrationException The exception that is thrown when a registration error is detected.

RegistrationHelper Installs and configures assemblies in the COM+ catalog. This class cannot be inherited.

ResourcePool Stores objects in the current transaction. This class cannot be inherited.

SecureMethodAttribute Ensures that the infrastructure calls through an interface for a method or for each method in a class when using the security service. Classes need to use interfaces to use security services. This class cannot be inherited.

SecurityCallContext Describes the chain of callers leading up to the current method call.

SecurityCallers Provides an ordered collection of identities in the current call chain.

SecurityIdentity Contains information regarding an identity in a COM+ call chain.

SecurityRoleAttribute Configures a role for an application or component. This class cannot be inherited.

ServiceConfig Specifies and configures the services that are to be active in the domain which is entered when calling Enter or creating

Page 130: Good+List+of+Questions+With+Answers

an Activity. This class cannot be inherited.

ServicedComponent Represents the base class of all classes using COM+ services.

ServicedComponentException The exception that is thrown when an error is detected in a serviced component.

ServiceDomain Allows a code segment identified by Enter and Leave to run in its own context and behave as if it were a method that is called on an object created within the context. This class cannot be inherited.

SharedProperty Accesses a shared property. This class cannot be inherited.

SharedPropertyGroup Represents a collection of shared properties. This class cannot be inherited.

SharedPropertyGroupManager Controls access to shared property groups. This class cannot be inherited.

SynchronizationAttribute Sets the synchronization value of the component. This class cannot be inherited.

TransactionAttribute Specifies the type of transaction that is available to the attributed object. Permissible values are members of the TransactionOption enumeration.

InterfacesInterface Description

IAsyncErrorNotify Implements error trapping on the asynchronous batch work that is submitted by the Activity object.

IPlaybackControl Functions in Queued Components in the abnormal handling of server-side playback errors and client-side failures of the Message Queuing delivery mechanism.

IProcessInitControl Supports setting the time-out for the Startup method.

IProcessInitializer Supports methods that can be called when a COM component starts up or shuts down.

IRegistrationHelper Installs and configures assemblies in the COM+ catalog.

IServiceCall Implements the batch work that is submitted through the activity created by Activity.

ITransaction Corresponds to the DTC ITransaction interface and is supported by objects obtained through ContextUtil.Transaction.

Page 131: Good+List+of+Questions+With+Answers

StructuresStructure Description

BOID Represents the unit of work associated with a transaction. This structure is used in XACTTRANSINFO.

XACTTRANSINFO Represents a structure used in the ITransaction interface.

DelegatesDelegate Description

ResourcePool.TransactionEndDelegate Represents the method that handles the ending of a transaction.

EnumerationsEnumeration Description

AccessChecksLevelOption Specifies the level of access checking for an application, either at the process level only or at all levels, including component, interface, and method levels.

ActivationOption Specifies the manner in which serviced components are activated in the application.

AuthenticationOption Specifies the remote procedure call (RPC) authentication mechanism. Applicable only when the ActivationOption is set to Server.

BindingOption Indicates whether all work submitted by Activity should be bound to only one single-threaded apartment (STA). This enumeration has no impact on the multithreaded apartment (MTA).

ImpersonationLevelOption Specifies the level of impersonation allowed when calling targets of a server application.

InheritanceOption Indicates whether to create a new context based on the current context or on the information in ServiceConfig.

InstallationFlags Flags used with the RegistrationHelper class.

PartitionOption Indicates the context in which to run the COM+ partition.

PropertyLockMode Specifies the mode for accessing shared properties in the shared property group manager.

PropertyReleaseMode Specifies the release mode for the properties in the new shared property group.

Page 132: Good+List+of+Questions+With+Answers

SxsOption Indicates how side-by-side assemblies are configured for ServiceConfig.

SynchronizationOption Specifies the type of automatic synchronization requested by the component.

ThreadPoolOption Indicates the thread pool in which the work, submitted by Activity, runs.

TransactionIsolationLevel Specifies the value of the TransactionAttribute.

TransactionOption Specifies the automatic transaction type requested by the component.

TransactionStatus Indicates the transaction status.

TransactionVote Specifies the values allowed for transaction outcome voting.

Discuss System.Globalization The System.Globalization namespace contains classes that define culture-related information,

including the language, the country/region, the calendars in use, the format patterns for dates,

currency, and numbers, and the sort order for strings. These classes are useful for writing

globalized (internationalized) applications. Classes like StringInfo and TextInfo provide advanced

globalization functionalities, such as surrogate support and text element processing.

ClassesClass Description

Calendar Represents time in divisions, such as weeks, months, and years.

CompareInfo Implements a set of methods for culture-sensitive string comparisons.

CultureInfo Represents information about a specific culture including the names of the culture, the writing system, and the calendar used, as well as access to culture-specific objects that provide information for common operations, such as formatting dates and sorting strings.

DateTimeFormatInfo Defines how DateTime values are formatted and displayed, depending on the culture.

DaylightTime Defines the period of daylight-saving time.

GregorianCalendar Represents the Gregorian calendar.

HebrewCalendar Represents the Hebrew calendar.

HijriCalendar Represents the Hijri calendar.

Page 133: Good+List+of+Questions+With+Answers

JapaneseCalendar Represents the Japanese calendar.

JulianCalendar Represents the Julian calendar.

KoreanCalendar Represents the Korean calendar.

NumberFormatInfo Defines how numeric values are formatted and displayed, depending on the culture.

RegionInfo Contains information about the country/region.

SortKey Represents the result of mapping a string to its sort key.

StringInfo Provides functionality to split a string into text elements and to iterate through those text elements.

TaiwanCalendar Represents the Taiwan Calendar.

TextElementEnumerator Enumerates the text elements of a string.

TextInfo Defines properties and behaviors, such as casing, that are specific to a writing system.

ThaiBuddhistCalendar Represents the Thai Buddhist calendar.

EnumerationsEnumeration Description

CalendarWeekRule Defines different rules for determining the first week of the year.

CompareOptions Defines the string comparison options to use with CompareInfo.

CultureTypes Defines the types of culture lists that can be retrieved using CultureInfo.GetCultures.

DateTimeStyles Defines the formatting options that customize how the DateTime.Parse and DateTime.ParseExact methods parse a string.

GregorianCalendarTypes Defines the different language versions of the Gregorian calendar.

NumberStyles Determines the styles permitted in numeric string arguments that are passed to the Parse methods of the numeric base type classes.

UnicodeCategory Defines the Unicode category of a character.

Discuss System.IO

Page 134: Good+List+of+Questions+With+Answers

The System.IO namespace contains types that allow reading and writing to files and data

streams, and types that provide basic file and directory support.

ClassesClass Description

BinaryReader Reads primitive data types as binary values in a specific encoding.

BinaryWriter Writes primitive types in binary to a stream and supports writing strings in a specific encoding.

BufferedStream Adds a buffering layer to read and write operations on another stream. This class cannot be inherited.

Directory Exposes static methods for creating, moving, and enumerating through directories and subdirectories.

DirectoryInfo Exposes instance methods for creating, moving, and enumerating through directories and subdirectories.

DirectoryNotFoundException The exception that is thrown when part of a file or directory cannot be found.

EndOfStreamException The exception that is thrown when reading is attempted past the end of a stream.

ErrorEventArgs Provides data for the Error event.

File Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

FileInfo Provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

FileLoadException The exception that is thrown when a managed assembly is found but cannot be loaded.

FileNotFoundException The exception that is thrown when an attempt to access a file that does not exist on disk fails.

FileStream Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.

FileSystemEventArgs Provides data for the directory events: Changed, Created, Deleted.

FileSystemInfo Provides the base class for both FileInfo and DirectoryInfo objects.

Page 135: Good+List+of+Questions+With+Answers

FileSystemWatcher Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.

InternalBufferOverflowException The exception thrown when the internal buffer overflows.

IODescriptionAttribute Sets the description visual designers can display when referencing an event, extender, or property.

IOException The exception that is thrown when an I/O error occurs.

MemoryStream Creates a stream whose backing store is memory.

Path Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.

PathTooLongException The exception that is thrown when a pathname or filename is longer than the system-defined maximum length .

RenamedEventArgs Provides data for the Renamed event.

Stream Provides a generic view of a sequence of bytes.

StreamReader Implements a TextReader that reads characters from a byte stream in a particular encoding.

StreamWriter Implements a TextWriter for writing characters to a stream in a particular encoding.

StringReader Implements a TextReader that reads from a string.

StringWriter Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.

TextReader Represents a reader that can read a sequential series of characters.

TextWriter Represents a writer that can write a sequential series of characters. This class is abstract.

StructuresStructure Description

WaitForChangedResult Contains information on the change that occurred.

DelegatesDelegate Description

ErrorEventHandler Represents the method that will handle the Error event of a

Page 136: Good+List+of+Questions+With+Answers

FileSystemWatcher.

FileSystemEventHandler Represents the method that will handle the Changed, Created, or Deleted event of a FileSystemWatcher class.

RenamedEventHandler Represents the method that will handle the Renamed event of a FileSystemWatcher class.

EnumerationsEnumeration Description

FileAccess Defines constants for read, write, or read/write access to a file.

FileAttributes Provides attributes for files and directories.

FileMode Specifies how the operating system should open a file.

FileShare Contains constants for controlling the kind of access other FileStreams can have to the same file.

NotifyFilters Specifies changes to watch for in a file or folder.

SeekOrigin Provides the fields that represent reference points in streams for seeking.

WatcherChangeTypes Changes that might occur to a file or directory.

Discuss System.Net The System.Net namespace provides a simple programming interface for many of the protocols

used on networks today. The WebRequest and WebResponse classes form the basis of what are

called pluggable protocols, an implementation of network services that enables you to develop

applications that use Internet resources without worrying about the specific details of the

individual protocols.

ClassesClass Description

AuthenticationManager Manages the authentication modules called during the client authentication process.

Authorization Contains an authentication message for an Internet server.

Cookie Provides a set of properties and methods used to manage cookies. This class cannot be inherited.

Page 137: Good+List+of+Questions+With+Answers

CookieCollection Provides a collection container for instances of the Cookie class.

CookieContainer Provides a container for a collection of CookieCollection objects.

CookieException The exception that is thrown when an error is made adding a Cookie to a CookieContainer.

CredentialCache Provides storage for multiple credentials.

Dns Provides simple domain name resolution functionality.

DnsPermission Controls rights to access Domain Name System (DNS) servers on the network.

DnsPermissionAttribute Specifies permission to request information from Domain Name Servers.

EndPoint Identifies a network address. This is an abstract (MustInherit in Visual Basic) class.

EndpointPermission Defines an endpoint that is authorized by a SocketPermission instance.

FileWebRequest Provides a file system implementation of the WebRequest class.

FileWebResponse Provides a file system implementation of the WebResponse class.

GlobalProxySelection Contains a global default proxy instance for all HTTP requests.

HttpVersion Defines the HTTP version numbers supported by the HttpWebRequest and HttpWebResponse classes.

HttpWebRequest Provides an HTTP-specific implementation of the WebRequest class.

HttpWebResponse Provides an HTTP-specific implementation of the WebResponse class.

IPAddress Provides an Internet Protocol (IP) address.

IPEndPoint Represents a network endpoint as an IP address and a port number.

IPHostEntry Provides a container class for Internet host address information.

IrDAEndPoint Establishes connections to a server and provides infrared port information.

NetworkCredential Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.

ProtocolViolationException The exception that is thrown when an error is made while using a network protocol.

Page 138: Good+List+of+Questions+With+Answers

ServicePoint Provides connection management for HTTP connections.

ServicePointManager Manages the collection of ServicePoint instances.

SocketAddress Stores serialized information from EndPoint derived classes.

SocketPermission Controls rights to make or accept connections on a transport address.

SocketPermissionAttribute Specifies security actions to control Socket connections. This class cannot be inherited.

WebClient Provides common methods for sending data to and receiving data from a resource identified by a URI. This class cannot be inherited.

WebException The exception that is thrown when an error occurs while accessing the network through a pluggable protocol.

WebHeaderCollection Contains protocol headers associated with a request or response.

WebPermission Controls rights to access HTTP Internet resources.

WebPermissionAttribute Specifies permission to access Internet resources. This class cannot be inherited.

WebProxy Contains HTTP proxy settings for the WebRequest class.

WebRequest Makes a request to a Uniform Resource Identifier (URI). This is an abstract (MustInherit in Visual Basic) class.

WebResponse Provides a response from a Uniform Resource Identifier (URI). This is an abstract (MustInherit in Visual Basic) class.

InterfacesInterface Description

IAuthenticationModule Provides the base authentication interface for Web client authentication modules.

ICertificatePolicy Validates a server certificate.

ICredentials Provides the base authentication interface for retrieving credentials for Web client authentication.

IWebProxy Provides the base interface for implementation of proxy access for the WebRequest class.

IWebRequestCreate Provides the base interface for creating WebRequest instances.

Delegates

Page 139: Good+List+of+Questions+With+Answers

Delegate Description

HttpContinueDelegate Represents the method that notifies callers when a continue response is received by the client.

EnumerationsEnumeration Description

HttpStatusCode Contains the values of status codes defined for HTTP.

NetworkAccess Specifies network access permissions.

SecurityProtocolType

TransportType Defines transport types for the SocketPermission and Socket classes.

WebExceptionStatus Defines status codes for the WebException class.

System.Runtime contains System.Runtime.CompilerServcies, what else? Apart from System.Runtime.CompilerServices, System.Runtime contains

System.Runtime.InteropServices, System.Runtime.Remoting, System.Runtime.Serialization.

Discuss System.Security The System.Security namespace provides the underlying structure of the common language

runtime security system, including base classes for permissions.

ClassesClass Description

AllowPartiallyTrustedCallersAttribute Allows strong-named assemblies to be called by partially trusted code. Without this declaration, only fully trusted callers are able to use such assemblies. This class cannot be inherited.

CodeAccessPermission Defines the underlying structure of all code access permissions.

NamedPermissionSet Defines a permission set that has a name and description associated with it. This class cannot be inherited.

PermissionSet Represents a collection that can contain many different types of permissions.

Page 140: Good+List+of+Questions+With+Answers

SecurityElement Represents the XML object model for encoding security objects. This class cannot be inherited.

SecurityException The exception that is thrown when a security error is detected.

SecurityManager Provides the main access point for classes interacting with the security system. This class cannot be inherited.

SuppressUnmanagedCodeSecurityAttribute Allows managed code to call into unmanaged code without a stack walk. This class cannot be inherited.

UnverifiableCodeAttribute Marks modules containing unverifiable code. This class cannot be inherited.

VerificationException The exception that is thrown when the security policy requires code to be type safe and the verification process is unable to verify that the code is type safe.

XmlSyntaxException The exception that is thrown when there is a syntax error in XML parsing. This class cannot be inherited.

InterfacesInterface Description

IEvidenceFactory Gets an object's Evidence.

IPermission Defines methods implemented by permission types.

ISecurityEncodable Defines the methods that convert permission object state to and from XML element representation.

ISecurityPolicyEncodable Supports the methods that convert permission object state to and from an XML element representation.

IStackWalk Manages the stack walk that determines whether all callers in the call stack have the required permissions to access a protected resource.

EnumerationsEnumeration Description

PolicyLevelType Specifies the type of a managed code policy level.

SecurityZone Defines the integer values corresponding to security zones used by security policy.

Page 141: Good+List+of+Questions+With+Answers

Discuss System.Text The System.Text namespace contains classes representing ASCII, Unicode, UTF-7, and UTF-8

character encodings; abstract base classes for converting blocks of characters to and from blocks

of bytes; and a helper class that manipulates and formats String objects without creating

intermediate instances of String.

ClassesClass Description

ASCIIEncoding Represents an ASCII character encoding of Unicode characters.

Decoder Converts encoded blocks of bytes into blocks of Unicode characters.

Encoder Converts blocks of characters into encoded blocks of bytes.

Encoding Represents a character encoding.

StringBuilder Represents a mutable string of characters. This class cannot be inherited.

UnicodeEncoding Represents a UTF-16 encoding of Unicode characters.

UTF7Encoding Represents a UTF-7 encoding of Unicode characters.

UTF8Encoding Represents a UTF-8 encoding of Unicode characters.

Discuss System.Threading The System.Threading namespace provides classes and interfaces that enable multithreaded

programming. In addition to classes for synchronizing thread activities and access to data (Mutex,

Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class

that allows you to use a pool of system-supplied threads, and a Timer class that executes

callback methods on thread pool threads.

ClassesClass Description

AutoResetEvent Notifies a waiting thread that an event has occurred. This class cannot be inherited.

Interlocked Provides atomic operations for variables that are shared by multiple threads.

ManualResetEvent Notifies one or more waiting threads that an event has occurred.

Page 142: Good+List+of+Questions+With+Answers

This class cannot be inherited.

Monitor Provides a mechanism that synchronizes access to objects.

Mutex A synchronization primitive than can also be used for interprocess synchronization.

ReaderWriterLock Defines a lock that supports single writers and multiple readers.

RegisteredWaitHandle Represents a handle that has been registered when calling RegisterWaitForSingleObject. This class cannot be inherited.

SynchronizationLockException The exception that is thrown when a method requires the caller to own the lock on a given Monitor, and the method is invoked by a caller that does not own that lock.

Thread Creates and controls a thread, sets its priority, and gets its status.

ThreadAbortException The exception that is thrown when a call is made to the Abort method. This class cannot be inherited.

ThreadExceptionEventArgs Provides data for the ThreadException event.

ThreadInterruptedException The exception that is thrown when a Thread is interrupted while it is in a waiting state.

ThreadPool Provides a pool of threads that can be used to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

ThreadStateException The exception that is thrown when a Thread is in an invalid ThreadState for the method call.

Timeout Contains a constant used to specify an infinite amount of time. This class cannot be inherited.

Timer Provides a mechanism for executing a method at specified intervals. This class cannot be inherited.

WaitHandle Encapsulates operating system-specific objects that wait for exclusive access to shared resources.

StructuresStructure Description

LockCookie Defines the lock that implements single-writer/multiple-reader semantics. This is a value type.

NativeOverlapped Provides an explicit layout that is visible from unmanaged code and that will have the same layout as the Win32 OVERLAPPED structure with additional

Page 143: Good+List+of+Questions+With+Answers

reserved fields at the end.

DelegatesDelegate Description

IOCompletionCallback Receives the error code, number of bytes, and overlapped value type when an I/O operation completes on the thread pool.

ThreadExceptionEventHandler Represents the method that will handle the ThreadException event of an Application.

ThreadStart Represents the method that executes on the Thread.

TimerCallback Represents the method that handles calls from a Timer.

WaitCallback Represents a callback method to be executed by a thread pool thread.

WaitOrTimerCallback Represents a method to be called when a WaitHandle is signaled or times out.

EnumerationsEnumeration Description

ApartmentState Specifies the apartment state of a Thread.

ThreadPriority Specifies the scheduling priority of a Thread.

ThreadState Specifies the execution states of a Thread.

Discuss System.Web The System.Web namespace supplies classes and interfaces that enable browser-server

communication. This namespace includes the HttpRequest class which provides extensive

information about the current HTTP request, the HttpResponse class which manages HTTP

output to the client, and the HttpServerUtility class which provides access to server-side utilities

and processes. System.Web also includes classes for cookie manipulation, file transfer,

exception information, and output cache control.

ClassesClass Description

AspNetHostingPermission Controls access permissions in ASP.NET hosted

Page 144: Good+List+of+Questions+With+Answers

environments.

AspNetHostingPermissionAttribute Allows security actions for AspNetHostingPermission to be applied to code using declarative security. This class cannot be inherited.

HttpApplication Defines the methods, properties, and events common to all application objects within an ASP.NET application. This class is the base class for applications defined by the user in the global.asax file.

HttpApplicationState Enables sharing of global information across multiple sessions and requests within an ASP.NET application.

HttpBrowserCapabilities Enables the server to gather information on the capabilities of the browser that is running on the client.

HttpCachePolicy Contains methods for setting cache-specific HTTP headers and for controlling the ASP.NET page output cache.

HttpCacheVaryByHeaders Provides a type-safe way to set the VaryByHeaders property that identifies the request headers that ASP.NET adds to the Vary HTTP header sent to the client.

HttpCacheVaryByParams Provides a type-safe way to set the VaryByParams property that identifies the HTTP Get or Post parameters that ASP.NET uses to choose a response from multiple cached responses.

HttpClientCertificate Provides the client certificate fields issued by the client in response to the server's request for the client's identity.

HttpCompileException The exception that is thrown when a compiler error occurs.

HttpContext Encapsulates all HTTP-specific information about an individual HTTP request.

HttpCookie Provides a type-safe way to create and manipulate individual HTTP cookies.

HttpCookieCollection Provides a type-safe way to manipulate HTTP cookies.

HttpException Provides a means of generating HTTP exceptions.

HttpFileCollection Provides access to and organizes files uploaded by a client.

HttpModuleCollection Provides a means of indexing and retrieving a collection of IHttpModule objects.

HttpParseException The exception that is thrown when a parse error occurs.

HttpPostedFile Provides a way to access individual files that have been

Page 145: Good+List+of+Questions+With+Answers

uploaded by a client.

HttpRequest Enables ASP.NET to read the HTTP values sent by a client during a Web request.

HttpRequestValidationException The exception that is thrown when a potentially dangerous input string is received from the client.

HttpResponse Encapsulates HTTP response information from an ASP.NET operation .

HttpRuntime Provides a set of ASP.NET run-time services for the current application.

HttpServerUtility Provides helper methods for processing Web requests.

HttpStaticObjectsCollection Provides a static objects collection for the StaticObjects property.

HttpUtility Provides methods for encoding and decoding URLs when processing Web requests.

HttpWorkerRequest This abstract class defines the base worker methods and enumerations used by ASP.NET managed code to process requests.

HttpWriter Provides a TextWriter object that is accessed through the intrinsic HttpResponse object.

ProcessInfo Provides information on processes currently executing.

ProcessModelInfo Contains methods that return information about worker processes.

TraceContext Captures and presents execution details about a Web request. This class cannot be inherited.

InterfacesInterface Description

IHttpAsyncHandler When implemented by a class, defines the contract that HTTP asynchronous handler objects must implement.

IHttpHandler Defines the contract that ASP.NET implements to synchronously process HTTP Web requests using custom HTTP handlers.

IHttpHandlerFactory Defines the contract that class factories must implement to create new IHttpHandler objects.

IHttpModule Provides module initialization and disposal events to the inheriting class.

Page 146: Good+List+of+Questions+With+Answers

DelegatesDelegate Description

BeginEventHandler Represents the method that handles asynchronous events such as application events. This delegate is called at the start of an asynchronous operation.

EndEventHandler Represents the method that handles asynchronous events such as application events. This delegate is called by the event source when completion of the asynchronous operation is signaled by a callback to the BeginEventHandler delegate.

HttpCacheValidateHandler Delegate method that is called when a cached item is validated. Cache items invalidated within the method are treated as cache misses.

HttpWorkerRequest.EndOfSendNotification

Represents the method that notifies callers when sending of the response is complete.

EnumerationsEnumeration Description

AspNetHostingPermissionLevel

HttpCacheability Provides enumerated values that are used to set the Cache-Control HTTP header.

HttpCacheRevalidation Provides enumerated values that are used to set revalidation-specific Cache-Control HTTP headers.

HttpValidationStatus Provides enumerated values that indicate cache validation status.

ProcessShutdownReason Provides enumerated values that indicate why a process has shut down.

ProcessStatus Provides enumerated values that indicate the current status of a process.

TraceMode Specifies in what order trace messages are emitted into the HTML output of a page.

Discuss System.Windows.Forms The System.Windows.Forms namespace contains classes for creating Windows-based

applications that take full advantage of the rich user interface features available in the Microsoft

Page 147: Good+List+of+Questions+With+Answers

Windows operating system. The classes in this namespace can be grouped into the following

categories:

Control, User Control, and Form. Most classes within the System.Windows.Forms namespace

derive from the Control class. The Control class provides the base functionality for all controls

that are displayed on a Form. The Form class represents a window within an application. This

includes dialog boxes, modeless windows, and Multiple Document Interface (MDI) client and

parent windows. To create a custom control that is a composite of other controls, use the

UserControl class.

Controls. The System.Windows.Forms namespace provides a variety of control classes that allow

you to create rich user interfaces. Some controls are designed for data entry within the

application, such as TextBox and ComboBox controls. Other controls display application data,

such as Label and ListView. The namespace also provides controls for invoking commands within

the application, such as Button and ToolBar. In addition, the PropertyGrid control can be used to

create your own Windows Forms designer that displays the designer-visible properties of the

controls.

Components. In addition to controls, the System.Windows.Forms namespace provides other

classes that do not derive from the Control class but still provide visual features to a Windows-

based application. Some classes, such as ToolTip and ErrorProvider, extend the capabilities or

provide information to the user. Other classes, such as Menu, MenuItem, and ContextMenu,

provide the ability display menus to the user to invoke commands within an application. The Help

and HelpProvider classes enable you to display help information to the user of your applications.

Common Dialog Boxes. Windows provides a number of common dialog boxes that can be used

to give your application a consistent user interface when performing tasks such as opening and

saving files, manipulating the font or text color, or printing. The OpenFileDialog and

SaveFileDialog classes provide the functionality to display a dialog box that allows the user to

browse to and enter the name of a file to open or save. The FontDialog class displays a dialog

box to change elements of the Font object used by your application. The PageSetupDialog,

PrintPreviewDialog, and PrintDialog classes display dialog boxes that allow the user to control

aspects of printing documents. For more information on printing from a Windows-based

application, see the System.Drawing.Printing namespace. In addition to the common dialog

boxes, the System.Windows.Forms namespace provides the MessageBox class for displaying a

message box that can display and retrieve data from the user.

There are a number of classes within the System.Windows.Forms namespace that provide

support to the classes mentioned in the preceding summary. Example of the supporting classes

are enumerations, event argument classes, and delegates used by events within controls and

components.

Page 148: Good+List+of+Questions+With+Answers

Discuss System.XML The System.Xml namespace provides standards-based support for processing XML. The

supported standards are:

XML 1.0 - http://www.w3.org/TR/1998/REC-xml-19980210 - including DTD support.

XML Namespaces - http://www.w3.org/TR/REC-xml-names/ - both stream level and

DOM.

XSD Schemas - http://www.w3.org/2001/XMLSchema

XPath expressions - http://www.w3.org/TR/xpath

XSLT transformations - http://www.w3.org/TR/xslt

DOM Level 1 Core - http://www.w3.org/TR/REC-DOM-Level-1/

DOM Level 2 Core - http://www.w3.org/TR/DOM-Level-2/

ClassesClass Description

NameTable Implements a single-threaded XmlNameTable.

XmlAttribute Represents an attribute. Valid and default values for the attribute are defined in a DTD or schema.

XmlAttributeCollection Represents a collection of attributes that can be accessed by name or index.

XmlCDataSection Represents a CDATA section.

XmlCharacterData Provides text manipulation methods that are used by several classes.

XmlComment Represents the content of an XML comment.

XmlConvert Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types the values returned are locale independent.

XmlDataDocument Allows structured data to be stored, retrieved, and manipulated through a relational DataSet.

XmlDeclaration Represents the XML declaration node: <?xml version='1.0' ...?>.

XmlDocument Represents an XML document.

XmlDocumentFragment Represents a lightweight object that is useful for tree insert operations.

Page 149: Good+List+of+Questions+With+Answers

XmlDocumentType Represents the document type declaration.

XmlElement Represents an element.

XmlEntity Represents an entity declaration: <!ENTITY ... >.

XmlEntityReference Represents an entity reference node.

XmlException Returns detailed information about the last exception.

XmlImplementation Defines the context for a set of XmlDocument objects.

XmlLinkedNode Gets the node immediately preceding or following this node.

XmlNamedNodeMap Represents a collection of nodes that can be accessed by name or index.

XmlNamespaceManager Resolves, adds and removes namespaces to a collection and provides scope management for these namespaces. This class is used by the XsltContext and XmlReader classes.

XmlNameTable Table of atomized string objects.

XmlNode Represents a single node in the XML document.

XmlNodeChangedEventArgs Provides data for the NodeChanged, NodeChanging, NodeInserted, NodeInserting, NodeRemoved and NodeRemoving events.

XmlNodeList Represents an ordered collection of nodes.

XmlNodeReader Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode .

XmlNotation Represents a notation declaration: <!NOTATION ... >.

XmlParserContext Provides all the context information required by XmlTextReader or XmlValidatingReader to parse an XML fragment.

XmlProcessingInstruction Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document.

XmlQualifiedName Represents an XML qualified name.

XmlReader Represents a reader that provides fast, non-cached, forward-only access to XML data.

XmlResolver Resolves external XML resources named by a URI.

XmlSecureResolver Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.

Page 150: Good+List+of+Questions+With+Answers

XmlSignificantWhitespace Represents white space between markup in a mixed content mode or white space within an xml:space= 'preserve' scope. This is also referred to as significant white space.

XmlText Represents the text content of an element or attribute.

XmlTextReader Represents a reader that provides fast, non-cached, forward-only access to XML data.

XmlTextWriter Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

XmlUrlResolver Resolves external XML resources named by a URI.

XmlValidatingReader Represents a reader that provides DTD, XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation.

XmlWhitespace Represents white space in element content.

XmlWriter Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

InterfacesInterface Description

IHasXmlNode Enables a class to return an XmlNode from the current context or position.

IXmlLineInfo Provides an interface to enable a class to return line and position information.

DelegatesDelegate Description

XmlNodeChangedEventHandler Represents the method that handles NodeChanged, NodeChanging, NodeInserted, NodeInserting, NodeRemoved and NodeRemoving events.

EnumerationsEnumeration Description

EntityHandling Specifies how entities are handled.

Formatting Specifies formatting options for the XmlTextWriter.

Page 151: Good+List+of+Questions+With+Answers

ReadState Specifies the state of the reader.

ValidationType Specifies the type of validation to perform.

WhitespaceHandling Specifies how white space is handled.

WriteState Specifies the state of the XmlWriter.

XmlNodeChangedAction Specifies the type of node change.

XmlNodeOrder Describes the document order of a node compared to a second node.

XmlNodeType Specifies the type of node.

XmlSpace Specifies the current xml:space scope.

XmlTokenizedType Represents the XML type for the string. This allows the string to be read as a particular XML type, for example a CDATA section type.

Does VS.NET 2003 have a web browser (think about it)? Yes. The web browser is the client.

How are VB.NET and C# different?

VB.NET

Program Structur

eC#

Imports System

Namespace Hello   Class HelloWorld       Overloads Shared Sub Main(ByVal args() As String)          Dim name As String = "VB.NET"

         'See if an argument was passed from the command line          If args.Length = 1 Then name = args(0)

          Console.WriteLine("Hello, " & name & "!")

using System;

namespace Hello {   public class HelloWorld {      public static void Main(string[] args) {         string name = "C#";

         // See if an argument was passed from the command line         if (args.Length == 1)            name = args[0];

         Console.WriteLine("Hello, " + name + "!");

Page 152: Good+List+of+Questions+With+Answers

      End Sub    End Class End Namespace

      }   }}

VB.NET Comments C#

' Single line onlyRem Single line only

// Single line/* Multiple    line  *//// XML comments on single line/** XML comments on multiple lines */

VB.NET Data Types C#

Value TypesBooleanByteChar   (example: "A"c)Short, Integer, LongSingle, DoubleDecimalDate

Reference TypesObjectString

Dim x As Integer Console.WriteLine(x.GetType())     ' Prints System.Int32 Console.WriteLine(TypeName(x))  ' Prints Integer

' Type conversionDim d As Single = 3.5 Dim i As Integer = CType(d, Integer)   ' set to 4 (Banker's rounding)i = CInt(d)  ' same result as CTypei = Int(d)    ' set to 3 (Int function truncates the decimal)

Value Typesboolbyte, sbytechar   (example: 'A')short, ushort, int, uint, long, ulongfloat, doubledecimalDateTime   (not a built-in C# type)

Reference Typesobjectstring

int x;Console.WriteLine(x.GetType());    // Prints System.Int32Console.WriteLine(typeof(int));      // Prints System.Int32

// Type conversion float d = 3.5f; int i = (int)d;   // set to 3  (truncates decimal)

VB.NET Constants C#

Const MAX_STUDENTS As Integer = const int MAX_STUDENTS = 25;

Page 153: Good+List+of+Questions+With+Answers

25

' Can set to a const or var; may be initialized in a constructorReadOnly MIN_DIAMETER As Single = 4.93

// Can set to a const or var; may be initialized in a constructor readonly float MIN_DIAMETER = 4.93f;

VB.NET Enumerat ions C#

Enum Action   Start   [Stop]   ' Stop is a reserved word  Rewind   Forward End Enum

Enum Status   Flunk = 50   Pass = 70   Excel = 90 End Enum

Dim a As Action = Action.Stop If a <> Action.Start Then _    Console.WriteLine(a.ToString & " is " & a)     ' Prints "Stop is 1"

Console.WriteLine(Status.Pass)     ' Prints 70 Console.WriteLine(Status.Pass.ToString())     ' Prints Pass

enum Action {Start, Stop, Rewind, Forward};enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;if (a != Action.Start)  Console.WriteLine(a + " is " + (int) a);    // Prints "Stop is 1"

Console.WriteLine((int) Status.Pass);    // Prints 70 Console.WriteLine(Status.Pass);      // Prints Pass

VB.NET Operators C#

Comparison=  <  >  <=  >=  <>

Arithmetic+  -  *  /Mod\  (integer division)^  (raise to a power)

Assignment=  +=  -=  *=  /=  \=  ^=  <<=  >>=  &=

Bitwise

Comparison==  <  >  <=  >=  !=

Arithmetic+  -  *  /%  (mod)/  (integer division if both operands are ints)Math.Pow(x, y)

Assignment=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --

Bitwise

Page 154: Good+List+of+Questions+With+Answers

And   Or   Not   <<   >>

LogicalAndAlso   OrElse   And   Or   Xor   Not

Note: AndAlso and OrElse perform short-circuit logical evaluations

String Concatenation&   +

&   |   ^   ~   <<   >>

Logical&&   ||   &   |   ^   !

Note: && and || perform short-circuit logical evaluations

String Concatenation+

VB.NET Choices C#

greeting = IIf(age < 20, "What's up?", "Hello")

' One line doesn't require "End If", no "Else"If language = "VB.NET" Then langType = "verbose"

' Use : to put two commands on same lineIf x <> 100 And y < 5 Then x *= 5 : y *= 2  

' PreferredIf x <> 100 And y < 5 Then  x *= 5   y *= 2End If

' or to break up any long single command use _If whenYouHaveAReally < longLine And itNeedsToBeBrokenInto2 > Lines Then _  UseTheUnderscore(charToBreakItUp)

'If x > 5 Then   x *= y ElseIf x = 5 Then   x += y ElseIf x < 10 Then   x -= y Else   x /= y End If

greeting = age < 20 ? "What's up?" : "Hello";

if (x != 100 && y < 5) {    // Multiple statements must be enclosed in {}  x *= 5;  y *= 2;}

No need for _ or : since ; is used to terminate each statement.

if (x > 5)   x *= y; else if (x == 5)   x += y; else if (x < 10)   x -= y; else   x /= y;

switch (color) {                          // Must be integer or string  case "pink":  case "red":    r++;    break;        // break is

Page 155: Good+List+of+Questions+With+Answers

Select Case color   ' Must be a primitive data type  Case "pink", "red"    r += 1   Case "blue"     b += 1   Case "green"     g += 1   Case Else     other += 1 End Select

mandatory; no fall-through  case "blue":   b++;   break;  case "green": g++;   break;  default:    other++;   break;       // break necessary on default}

VB.NET Loops C#

Pre-test Loops:

While c < 10   c += 1 End While

Do Until c = 10   c += 1 Loop

Do While c < 10   c += 1 Loop

For c = 2 To 10 Step 2   Console.WriteLine(c) Next

Post-test Loops:

Do   c += 1 Loop While c < 10

Do   c += 1 Loop Until c = 10

'  Array or collection loopingDim names As String() = {"Fred", "Sue", "Barney"} For Each s As String In names   Console.WriteLine(s) Next

' Breaking out of loopsDim i As Integer = 0While (True)  If (i = 5) Then Exit While

Pre-test Loops:  

// no "until" keywordwhile (c < 10)   c++;

for (c = 2; c < = 10; c += 2)   Console.WriteLine(c);

Post-test Loop:

do   c++; while (c < 10);

// Array or collection loopingstring[] names = {"Fred", "Sue", "Barney"};foreach (string s in names)  Console.WriteLine(s);

// Breaking out of loopsint i = 0;while (true) {  if (i == 5)    break;  i++;}

Page 156: Good+List+of+Questions+With+Answers

  i += 1End While

VB.NET Arrays C#

Dim nums() As Integer = {1, 2, 3} For i As Integer = 0 To nums.Length - 1

  Console.WriteLine(nums(i)) Next

' 4 is the index of the last element, so it holds 5 elementsDim names(4) As String names(0) = "David"names(5) = "Bobby"  ' Throws System.IndexOutOfRangeException

' Resize the array, keeping the existing values (Preserve is optional)ReDim Preserve names(6)

Dim twoD(rows-1, cols-1) As Single twoD(2, 0) = 4.5

Dim jagged()() As Integer = { _   New Integer(4) {}, New Integer(1) {}, New Integer(2) {} } jagged(0)(4) = 5

int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++)  Console.WriteLine(nums[i]);

// 5 is the size of the arraystring[] names = new string[5];names[0] = "David";names[5] = "Bobby";   // Throws System.IndexOutOfRangeException

// C# can't dynamically resize an array.  Just copy into new array.string[] names2 = new string[7]; Array.Copy(names, names2, names.Length);   // or names.CopyTo(names2, 0); 

float[,] twoD = new float[rows, cols];twoD[2,0] = 4.5f; 

int[][] jagged = new int[3][] {   new int[5], new int[2], new int[3] };jagged[0][4] = 5;

VB.NET Functions C#

' Pass by value (in, default), reference (in/out), and reference (out)  Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)  x += 1  y += 1   z = 5 End Sub

Dim a = 1, b = 1, c As Integer   ' c set to zero by default  TestFunc(a, b, c) Console.WriteLine("{0} {1} {2}", a, b,

// Pass by value (in, default), reference (in/out), and reference (out)void TestFunc(int x, ref int y, out int z) {  x++;    y++;  z = 5;}

int a = 1, b = 1, c;  // c doesn't need initializingTestFunc(a, ref b, out c);Console.WriteLine("{0} {1} {2}", a, b, c);  //

Page 157: Good+List+of+Questions+With+Answers

c)   ' 1 2 5

' Accept variable number of arguments

Function Sum(ByVal ParamArray nums As Integer()) As Integer   Sum = 0    For Each i As Integer In nums     Sum += i   Next End Function   ' Or use Return statement like C#

Dim total As Integer = Sum(4, 3, 2, 1)   ' returns 10

' Optional parameters must be listed last and must have a default value Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")  Console.WriteLine("Greetings, " & prefix & " " & name) End Sub

SayHello("Strangelove", "Dr.")SayHello("Madonna")

1 2 5

// Accept variable number of argumentsint Sum(params int[] nums) {  int sum = 0;  foreach (int i in nums)    sum += i;  return sum;}

int total = Sum(4, 3, 2, 1);   // returns 10

/* C# doesn't support optional arguments/parameters.  Just create two different versions of the same function. */  void SayHello(string name, string prefix) {  Console.WriteLine("Greetings, " + prefix + " " + name);} 

void SayHello(string name) {   SayHello(name, ""); }

VB.NET Str ings C#

Special character constantsvbCrLf, vbCr, vbLf, vbNewLine vbNullString vbTab vbBack vbFormFeed vbVerticalTab""

' String concatenation (use & or +) Dim school As String = "Harding" & vbTabschool = school & "University" ' school is "Harding (tab) University"

' CharsDim letter As Char = school.Chars(0)   ' letter is H letter = Convert.ToChar(65)                ' letter is A letter = Chr(65)                                 '

Escape sequences\n, \r\t\\\"

// String concatenationstring school = "Harding\t"; school = school + "University";   // school is "Harding (tab) University"

// Charschar letter = school[0];            // letter is H letter = Convert.ToChar(65);     // letter is A letter = (char)65;                    // same thing char[] word = school.ToCharArray();   // word

Page 158: Good+List+of+Questions+With+Answers

same thing Dim word() As Char = school.ToCharArray() ' word holds Harding

' No string literal operator  Dim msg As String = "File is c:\temp\x.dat" 

' String comparisonDim mascot As String = "Bisons"If (mascot = "Bisons") Then   ' trueIf (mascot.Equals("Bisons")) Then   ' trueIf (mascot.ToUpper().Equals("BISONS")) Then  ' trueIf (mascot.CompareTo("Bisons") = 0) Then   ' true

Console.WriteLine(mascot.Substring(2, 3)) ' Prints "son"

' String matchingIf ("John 3:16" Like "Jo[Hh]? #:*") Then 'true

Imports System.Text.RegularExpressions   ' More powerful than LikeDim r As New Regex("Jo[hH]. \d:*")If (r.Match("John 3:16").Success) Then   'true

' My birthday: Oct 12, 1973Dim dt As New DateTime(1973, 10, 12)Dim s As String = "My birthday: " & dt.ToString("MMM dd, yyyy")Console.WriteLine(s)

' Mutable string Dim buffer As New System.Text.StringBuilder("two ")buffer.Append("three ")buffer.Insert(0, "one ")buffer.Replace("two", "TWO")Console.WriteLine(buffer)         ' Prints "one TWO three"

holds Harding

// String literal string msg = @"File is c:\temp\x.dat"; // same as string msg = "File is c:\\temp\\x.dat";

// String comparisonstring mascot = "Bisons"; if (mascot == "Bisons")    // trueif (mascot.Equals("Bisons"))   // trueif (mascot.ToUpper().Equals("BISONS"))   // trueif (mascot.CompareTo("Bisons") == 0)    // true

Console.WriteLine(mascot.Substring(2, 3));    // Prints "son"

// String matching// No Like equivalent - use regular expressions

using System.Text.RegularExpressions;Regex r = new Regex(@"Jo[hH]. \d:*");if (r.Match("John 3:16").Success)   // true

// My birthday: Oct 12, 1973DateTime dt = new DateTime(1973, 10, 12);string s = "My birthday: " + dt.ToString("MMM dd, yyyy");

// Mutable string System.Text.StringBuilder buffer = new System.Text.StringBuilder("two "); buffer.Append("three "); buffer.Insert(0, "one "); buffer.Replace("two", "TWO"); Console.WriteLine(buffer);     // Prints "one TWO three"

Page 159: Good+List+of+Questions+With+Answers

VB.NET Exception Handl ing C#

' Throw an exceptionDim ex As New Exception("Something is really wrong.") Throw  ex 

' Catch an exceptionTry   y = 0  x = 10 / yCatch ex As Exception When y = 0 ' Argument and When is optional  Console.WriteLine(ex.Message) Finally   Beep() End Try

' Deprecated unstructured error handlingOn Error GoTo MyErrorHandler...MyErrorHandler: Console.WriteLine(Err.Description)

// Throw an exceptionException up = new Exception("Something is really wrong."); throw up;  // ha ha

// Catch an exceptiontry {   y = 0;   x = 10 / y; } catch (Exception ex) {   // Argument is optional, no "When" keyword   Console.WriteLine(ex.Message); } finally {   // Requires reference to the Microsoft.VisualBasic.dll   // assembly (pre .NET Framework v2.0)   Microsoft.VisualBasic.Interaction.Beep(); }

VB.NET Namespaces C#

Namespace Harding.Compsci.Graphics   ...End Namespace

' or

Namespace Harding   Namespace Compsci     Namespace Graphics       ...    End Namespace   End Namespace End Namespace

Imports Harding.Compsci.Graphics

namespace Harding.Compsci.Graphics {  ...}

// or

namespace Harding {  namespace Compsci {    namespace Graphics {      ...    }  }}

using Harding.Compsci.Graphics;

VB.NET Classes / Interfaces C#

Page 160: Good+List+of+Questions+With+Answers

Accessibility keywords PublicPrivateFriend                    ProtectedProtected FriendShared

' InheritanceClass FootballGame  Inherits Competition  ...End Class 

' Interface definitionInterface IAlarmClock   ...End Interface

// Extending an interface Interface IAlarmClock   Inherits IClock  ...End Interface

// Interface implementationClass WristWatch   Implements IAlarmClock, ITimer    ...End Class 

Accessibility keywords publicprivateinternalprotectedprotected internalstatic

// Inheritanceclass FootballGame : Competition {  ...}

// Interface definitioninterface IAlarmClock {  ...}

// Extending an interface interface IAlarmClock : IClock {  ...}

// Interface implementationclass WristWatch : IAlarmClock, ITimer {   ...}

VB.NET Constructors / Destructors C#

Class SuperHero  Private _powerLevel As Integer

  Public Sub New()     _powerLevel = 0   End Sub

  Public Sub New(ByVal powerLevel As Integer)     Me._powerLevel = powerLevel   End Sub

  Protected Overrides Sub Finalize()    ' Desctructor code to free unmanaged resources     MyBase.Finalize()

class SuperHero {  private int _powerLevel;

  public SuperHero() {     _powerLevel = 0;  }

  public SuperHero(int powerLevel) {    this._powerLevel= powerLevel;   }

  ~SuperHero() {    // Destructor code to free unmanaged resources.    // Implicitly creates a Finalize method

Page 161: Good+List+of+Questions+With+Answers

  End SubEnd Class   }

}

VB.NET Objects C#

Dim hero As SuperHero = New SuperHero' orDim hero As New SuperHeroWith hero   .Name = "SpamMan"   .PowerLevel = 3 End With

hero.Defend("Laura Jones") hero.Rest()     ' Calling Shared method' orSuperHero.Rest()

Dim hero2 As SuperHero = hero  ' Both reference the same object hero2.Name = "WormWoman" Console.WriteLine(hero.Name)   ' Prints WormWoman

hero = Nothing    ' Free the object

If hero Is Nothing Then _   hero = New SuperHero

Dim obj As Object = New SuperHero If TypeOf obj Is SuperHero Then _  Console.WriteLine("Is a SuperHero object.")

SuperHero hero = new SuperHero();

// No "With" constructhero.Name = "SpamMan"; hero.PowerLevel = 3;

hero.Defend("Laura Jones");SuperHero.Rest();   // Calling static method

SuperHero hero2 = hero;   // Both reference the same object hero2.Name = "WormWoman"; Console.WriteLine(hero.Name);   // Prints WormWoman

hero = null ;   // Free the object

if (hero == null)  hero = new SuperHero();

Object obj = new SuperHero(); if (obj is SuperHero)   Console.WriteLine("Is a SuperHero object.");

VB.NET Structs C#

Structure StudentRecord   Public name As String   Public gpa As Single

  Public Sub New(ByVal name As String, ByVal gpa As Single)     Me.name = name     Me.gpa = gpa   End Sub End Structure

struct StudentRecord {  public string name;  public float gpa;

  public StudentRecord(string name, float gpa) {    this.name = name;    this.gpa = gpa;  }}

Page 162: Good+List+of+Questions+With+Answers

Dim stu As StudentRecord = New StudentRecord("Bob", 3.5) Dim stu2 As StudentRecord = stu  

stu2.name = "Sue" Console.WriteLine(stu.name)    ' Prints Bob Console.WriteLine(stu2.name)  ' Prints Sue

StudentRecord stu = new StudentRecord("Bob", 3.5f);StudentRecord stu2 = stu;  

stu2.name = "Sue";Console.WriteLine(stu.name);    // Prints BobConsole.WriteLine(stu2.name);   // Prints Sue

VB.NET Propert ies C#

Private _size As Integer

Public Property Size() As Integer  Get     Return _size   End Get   Set (ByVal Value As Integer)     If Value < 0 Then       _size = 0     Else       _size = Value     End If   End Set End Property

foo.Size += 1

private int _size;

public int Size {   get {     return _size;   }   set {     if (value < 0)       _size = 0;     else       _size = value;   } }

foo.Size++;

VB.NET Delegates / Events C#

Delegate Sub MsgArrivedEventHandler(ByVal message As String)

Event MsgArrivedEvent As MsgArrivedEventHandler

' or to define an event which declares a delegate implicitlyEvent MsgArrivedEvent(ByVal message As String)

AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback ' Won't throw an exception if obj is Nothing

delegate void MsgArrivedEventHandler(string message);

event MsgArrivedEventHandler MsgArrivedEvent;

// Delegates must be used with events in C#

MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);MsgArrivedEvent("Test message");    // Throws exception if obj is nullMsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEven

Page 163: Good+List+of+Questions+With+Answers

RaiseEvent MsgArrivedEvent("Test message") RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

Imports System.Windows.Forms

Dim WithEvents MyButton As Button   ' WithEvents can't be used on local variableMyButton = New Button

Private Sub MyButton_Click(ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles MyButton.Click   MessageBox.Show(Me, "Button was clicked", "Info", _    MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub

tCallback);

using System.Windows.Forms;

Button MyButton = new Button(); MyButton.Click += new System.EventHandler(MyButton_Click);

private void MyButton_Click(object sender, System.EventArgs e) {   MessageBox.Show(this, "Button was clicked", "Info",     MessageBoxButtons.OK, MessageBoxIcon.Information); }

VB.NET Console I /O C#

Console.Write("What's your name? ") Dim name As String = Console.ReadLine() Console.Write("How old are you? ") Dim age As Integer = Val(Console.ReadLine()) Console.WriteLine("{0} is {1} years old.", name, age)  ' or Console.WriteLine(name & " is " & age & " years old.")

Dim c As Integer c = Console.Read()    ' Read single char Console.WriteLine(c)   ' Prints 65 if user enters "A"

Console.Write("What's your name? ");string name = Console.ReadLine();Console.Write("How old are you? ");int age = Convert.ToInt32(Console.ReadLine());Console.WriteLine("{0} is {1} years old.", name, age);// orConsole.WriteLine(name + " is " + age + " years old.");

int c = Console.Read();  // Read single charConsole.WriteLine(c);    // Prints 65 if user enters "A"

VB.NET Fi le I /O C#

Imports System.IO using System.IO;

Page 164: Good+List+of+Questions+With+Answers

' Write out to text fileDim writer As StreamWriter = File.CreateText("c:\myfile.txt") writer.WriteLine("Out to file.") writer.Close()

' Read all lines from text fileDim reader As StreamReader = File.OpenText("c:\myfile.txt") Dim line As String = reader.ReadLine()

While Not line Is Nothing   Console.WriteLine(line)   line = reader.ReadLine() End While reader.Close()

' Write out to binary fileDim str As String = "Text data" Dim num As Integer = 123 Dim binWriter As New BinaryWriter(File.OpenWrite("c:\myfile.dat"))  binWriter.Write(str)  binWriter.Write(num) binWriter.Close()

' Read from binary fileDim binReader As New BinaryReader(File.OpenRead("c:\myfile.dat")) str = binReader.ReadString() num = binReader.ReadInt32() binReader.Close()

// Write out to text fileStreamWriter writer = File.CreateText("c:\\myfile.txt"); writer.WriteLine("Out to file."); writer.Close();

// Read all lines from text fileStreamReader reader = File.OpenText("c:\\myfile.txt"); string line = reader.ReadLine(); while (line != null) {  Console.WriteLine(line);   line = reader.ReadLine(); } reader.Close();

// Write out to binary filestring str = "Text data"; int num = 123; BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat")); binWriter.Write(str); binWriter.Write(num); binWriter.Close();

// Read from binary fileBinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat")); str = binReader.ReadString(); num = binReader.ReadInt32(); binReader.Close();

Contrast .NET with J2EE. Vendor Neutrality

The .NET platform is not vendor neutral “so far”, it is tied to the Microsoft. However,

Microsoft has implemented an open-source policy for selected academic institutions.

Microsoft also introduced different levels of Partner Programs with different levels of

engagements with its business and technology.

There is on going progress that started on 2003 to port .NET to non-Microsoft platform,

e.g. Ximian.

Cross-vendor portability for J2EE is definitely not the imaginary "write once, run

anywhere" scenario. This is due in part to its organic growth model, where vendors add

their own features and other ex-tensions ahead of the J2EE specification process. J2EE

Page 165: Good+List+of+Questions+With+Answers

vendor portability can be achieved by focusing on the parts of J2EE that are fully covered

in the J2EE specification—such as servlets—but doing so is currently very constraining

and even impossible. For example, EJB deployment dimensions aren't completely

addressed in the J2EE specification.

Platform Maturity The first J2EE specification came out in 1998 and first beta product in 19994.

The first Microsoft .NET equivalent “Microsoft DNA and MTS” came out in 1996.

Microsoft .NET was the evolution of the Microsoft DNA, e.g. MTS to COM+ becomes an

important piece of the .NET Enterprise Services7.

Interoperability and Web Services Web services are rapidly becoming the unique solution for e-Collaboration. Exposing Web

services increases potential reach and exposure, creating new business. They offer a self-

describing, vendor- and technology-independent means of inter-application communication over

the Internet. Web services standards are defined under the umbrella term Universal

Description, Discovery, and Integration (UDDI). The UDDI standards are owned by a consortium

led by Ariba, IBM, and Microsoft, and includes more than 100 supporting companies, including

Sun. UDDI is based on an existing set of foundation standards, basically HTTP, XML and SOAP.

UDDI is independent of the .NET platform, however most of the UDDI related activity was

pioneered by Microsoft. Although that Sun is a member of UDDI consortium but UDDI standards

are not incorporated into J2EE including the most basic of UDDI, i.e. SOAP.7, 9

Sun's interoperability strategy for J2EE is based on the communications protocol called IIOP

which have the following problems: Only supports J2EE and CORBA, is not designed to transport

over the Internet and current specification of IIOP is inadequate to ensure interoperability.

The .NET platform has a much stronger technology neutral e-Collaboration strategy than does

J2EE.

In addition, the .NET platform have a set of application servers that supports other forms of e-

Collaboration such as SAP connector, EDI connector and others.

Scalability and Performance Scalability refers to the ability to add more workload and achieve maximum throughput. Its

measurement is a function of the software platform and not the underlying hardware.

Performance refers to the speed of a single unit of work under different workloads. Its

measurement is a function of the software platform and not the underlying hardware.

All existing J2EE benchmarks published by J2EE vendors are analytical results which real

systems may or may not be able to actually achieve. Because of the J2EE portability, it happens

to run on different sets of hardware that should not be a factor in measuring platform scalability.

If a unit of work costs 10 cents on .NET platform, that same unit of work will probably cost 50

cents to a dollar on J2EE/Unix.

Page 166: Good+List+of+Questions+With+Answers

Distributed transaction benchmark XML Web service benchmark called “PetShop” to be the blueprint of the J2EE platform, Microsoft

then released another version of the same application implemented on the .NET platform which

showed an extremely higher performance/scalability than the J2EE version. The Middleware

Company announced that it was not a fair comparison. Middleware re-wrote a second revised,

and fully optimized J2EE™ application and re-ran the comparison tests. The new results still

show .NET performance and scalability much higher than the J2EE implementation.

Framework Support & Productivity Tools Framework support decreases development time and increases productivity by providing

sets of libraries that takes care of system plumbing.

The .NET platform includes an eCommerce framework called Commerce Server[21], this

eCommerce platform helps developers to build solutions on top of a well defined and

tested eCommerce framework. The use of such a framework can dramatically reduce

development costs, probably by a factor of at least 10. There is no equivalent vendor-

neutral framework in the J2EE arena.

The .NET Frame includes a huge system libraries (called Namespaces) combined with

the unique development tool (Visual Studio .NET) dramatically reduce development time

and thus cost. J2EE’s best development tool IBM’s WebSphere is out of competition.

The Middleware Company benchmark tests mentioned above shows this superiority, see

table below for lines of code needed to develop same enterprise application using these

development tools.

Programming Language & Development Skills Required J2EE supports Java, and only Java. Although both IBM's WebSphere and BEA's

WebLogic support other languages, neither does it through their J2EE technology.

There are only two official ways in the J2EE platform to access other languages, one

through the Java Native Interface and the other through CORBA interoperability which

Sun recommends. Building any new code in CORBA architecture is a highly

questionable strategy. CORBA, is from 90's and considered as obsolete.

Microsoft .NET platform supports dozens of well known programming languages

including Java, and open to third-parties to add more .NET enabled programming

languages.

In general Java programmers are paid about 25% higher salaries than equivalent VB or

Cobol programmers. This will increase the development cost for J2EE solutions

over .NET. Also, retraining of existing VB or Cobol programmers on Java constitutes

very high cost, the other option will be outsourcing.

Page 167: Good+List+of+Questions+With+Answers

Portability J2EE server applications supports operating system portability, Microsoft .NET server

applications only run on Windows Server operating systems.

The path to achieve J2EE portability is to stick with a given J2EE vendor and a given

database vendor, this due to differences in vendor’s implementations extensions of the

J2EE specification.

It’s important to note that Portability is not the path to Scalability. The highest scalability is

achieved by writing for a highly scalable platform and then leveraging that platform using

the highest hardware possible.

Portability is only beneficial to Independent software vendors (ISVs), for other

organizations migrating application from one hardware platform to another is a very

remote probability.

Client Device Independence J2EE Java Applets are packaged code that run in browser and automatically installed on

client (if enabled by client), this is analogous to the Microsoft ActiveX packages. Both

have little usage because of client security restrictions that might be in place.

J2EE Java Servlets and Java Active Pages are analogous to the old Microsoft Active

Server Pages. Both makes the presentation tier the programmer's responsibility to

determine the ultimate destination browser (or other thin client system), what the

capabilities of that thin client system are, and how to generate HTML to best take

advantage of that thin client system.

This Java approach has problems:

It requires a lot of code on the presentation tier, since every possible thin client system

requires a different code path.

It is very difficult to test the code with every possible thin client system.

It is very difficult to add new thin clients to an existing application, since to do so involves

searching through, and modifying a tremendous amount of presentation tier logic.

The .NET approach is to write device independent code that interacts with visual controls.

It is the control, not the programmer, that is responsible for determining what HTML to

deliver, based on the capabilities of the client device. In the .NET Framework model, one

can forget that such a thing as HTML even exists!

Legacy Integration: J2EE provides legacy integration through multiple avenues:

o The Java Message Service (JMS) to integrate with existing messaging systems.

o Web services to integrate with any system.

Page 168: Good+List+of+Questions+With+Answers

o CORBA for interfacing with code written in other languages that may exist on

remote machines.

o JNI for loading native libraries and calling them locally.

o J2EE Connector Architecture (JCA). The JCA is a specification for plugging in

resource adapters that understand how to communicate with existing systems,

such as SAP R/3, CICS/COBOL, Siebel and others.

.NET provides legacy integration through multiple avenues:

o Host Integration Server 2000.

o COM Transaction Integrator (COM TI) can be used for collaborating transactions

across mainframe systems.

o Microsoft Message Queue (MSMQ) can integrate with legacy systems built using

IBM MQSeries.

o BizTalk Server 2000 can be used to integrate with systems based on B2B

protocols, such as Electronic Data Interchange (EDI). Also provides integration

connectors to SAP, Siebel, Onyx, and J.D. Edwards, and more.

What benefit do you have by implementing IDisposable interface in .NET? The Idisposable Interface in .Net defines a method to release allocated unmanaged resources.

The IDisposable interface can be used for far more than just clearing up resources. When

coupled with the 'using' keyword, it enables code to be called on exiting a code block.

The IDisposable interface has one method—Dispose(). This method is not called by the garbage

collector on destruction of an object. Its purpose is to provide a single interface in which code can

force an instance of a class to mark its resources for garbage collection. Any resources that can

be released immediately (for example, native handles or memory) are also to be freed. For

instance, all the GDI objects (System.Drawing.Graphics, System.Drawing.Pen, and so forth)

implement IDisposable and in MSDN it's common for example code to explicitly call the Dispose()

method after creating instances of these classes. GDI objects are a limited resource, and so

should be released as soon as possible to prevent the system from running out of them. Hence,

the inheritance from IDisposable.

The garbage collector automatically releases the memory allocated to a managed object when

that object is no longer used, however, it is not possible to predict when garbage collection will

occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as

window handles, or open files and streams.

Use the Dispose method of this interface to explicitly release unmanaged resources in

conjunction with the garbage collector. The consumer of an object can call this method when the

object is no longer needed.

Page 169: Good+List+of+Questions+With+Answers

Explain the difference between Application object and Session object in ASP.NET. The main difference between the two is that, where a single Application object is shared by all

pages and all clients that access your site, each client (browser) is assigned its own Session

object.

Explain the difference between User controls and Custom controls in ASP.NET. User controls encapsulate code and HTML into smaller more functional units. User controls are

built very similar to ASP.NET Web forms but are placed on the hosting page as objects. The

controls can then interact with each other. It is important to note that user controls are created

and edited just like any other page in ASP.NET. The HTML and code-behind files are freely

viewable and editable. But what if you want to sell your controls, or for some other reason, limit

access to the code the control contains? You may also want to encapsulate the control in a more

concise manner. You may want to distribute only one file, not the three files created with user

controls, to the other developers on your team. Or, you may want to distribute the control as a

single file that can be added to the IDE toolbox just like the built-in ASP.NET server controls.

Since user controls must contain an HTML based ascx file, and the codebehind must be compiled

in the assembly, user controls are not a viable option.

In contrast to a user control, a custom control is boiled down into one compiled class. The

interface (HTML and JavaScript) is written out programmatically instead of being visually created

in an IDE. You can blend the richness of the .NET programming model in your code with as

complex of an interface as need be. Because a custom control is contained in a class, you have

access to all the functionality of the .NET Framework, properties can be defined, and functions

can be implemented. In fact, the server controls that ship with ASP.NET and Visual Studio.NET

are in essence, custom controls. They are compiled classes that when placed on a page, interact

with each other, interact with the page (take advantage of events like OnLoad), emit HTML and

script, and provide the power behind the ASP.NET technology.

You create a Custom control when it is going to be used across different applications. If the

control you are going to create is only for a particular website then user control is the best option.

User controls have a visual interface and custom controls don't. Custom controls however can be

added to your tool bar and used in different applications without re-compiling.

Describe transaction control in ADO.NET. A transaction is an abstract unit of concurrent computation that execute automatically. The effect

of transaction does not interfere with other transactions that access the same data. Also a

transaction happens with all of its effects (In this case you will commit the changes) or it doesn't

happen none of its effects (In this case you will rollback the changes).

Page 170: Good+List+of+Questions+With+Answers

In the transaction control we generally define code in between a block where we perform mission

critical operation. If all operations get completed successfully then that part is committed in the

database otherwise what ever modification you might have done during the process is roll backed

from the database so that it never affect other user's operations.

In .NET environment we can define transaction boundary by Transaction object.

o If you are using SqlClient (namespace System.Data.SqlClient) Managed Provider you

can SqlTransaction object.

o If you are using Oledb (namespace System.Data.Oledb) Managed Provider you can

OledbTransaction object.

o If you are using Odbc (namespace Microsoft.Data.Odbc) Managed Provider you can

OdbcTransaction object

string connectionString = ".........";

SqlConnection myConnection = new SqlConnection(connectionString);

myConnection.Open();

// Start transaction.

SqlTransaction myTransaction = myConnection.BeginTransaction();

// Assign command in the current transaction.

SqlCommand myCommand = new SqlCommand();

myCommand.Transaction = myTransaction;

try

{

.........................

Database operations

........................

myTransaction.Commit();

Console.WriteLine("Records are modified in the database.");

}

catch(Exception e)

{

myTransaction.Rollback();

Console.WriteLine(e.ToString());

Console.WriteLine("Neither record was written to database.");

}

finally

{

myConnection.Close();

}

Page 171: Good+List+of+Questions+With+Answers

In Above Block

BeginTransaction method of the Connection object to mark the start of the transaction, which

returns a Transaction object. The newly created transaction object is assigned to

CommandObject so that what ever the database operation is performed by that commandObject

can be managed by Transaction Object. If anything gets wrong the Transaction object will raise

an Exception otherwise it will run through a normal process. Call the Commit method of the

Transaction object to complete the transaction if everything works fine otherwise call the Rollback

method to cancel the transaction.

Describe transaction control in SQL Server. There are two ways to control transactions through Microsoft SQL Server:

o setting isolation levels

o using transaction control methods

Setting Isolation LevelsYou can use the isolation() method of RWDBConnection to set the isolation level of the SQL

server. Table 5 shows the mapping between the IsolationType argument you pass and the

isolation level set by the SQL server. Take special care when setting isolation levels as this

effects all users of the SQL server.

Table 5: Setting the isolation levelRWDBConnection::IsolationType Microsoft SQL Server Isolation Level

Unknown Level 1 - SQL_TXN_READ_UNCOMMITTED

ANSILevel1 Level 1 - SQL_TXN_READ_UNCOMMITTED

ANSILevel2 Level 1 - SQL_TXN_READ_COMMITTED

ANSILevel3 Level 3 - SQL_TXN_REPEATABLE_READor: SQL_TXN_SERIALIZABLE

To determine the isolation level, call RWDBConnection::isolation() without an argument.

Using Transaction Control MethodsYou can explicitly control transactions through the following methods:

o RWDBConnection::beginTransaction()

o RWDBConnection::rollbackTransaction()

o RWDBConnection::rollbackTransaction(RWCString savepoint)

Page 172: Good+List+of+Questions+With+Answers

o RWDBConnection::commitTransaction()

o RWDBConnection::setSavepoint(RWCString savepoint)

These methods are implemented using the following Transact-SQL transaction statements:

o "begin transaction"

o "rollback transaction"

o "rollback transaction savepoint"

o "commit transaction"

o "save transaction savepoint"

An application can add the DB Interface Module transaction methods to its code to take explicit

control of its transaction blocks. Transactions may be nested and the savepoint feature is

supported. The savepoint feature allows a current transaction to be partially rolled back to a

marked point.

The example below demonstrates the use of the savepoint feature and the other transaction

processing methods of the DB Interface Module.

// Assume we have a table myTable(c int) with no rows in it.

RWDBInserter ins= myTable.inserter();

cn2.beginTransaction("outmost"); // Begin transaction.

// Transaction name is allowed.

// Note: unlike savepoint name,

// transaction name is not used

// by server.

(ins << 1 ).execute(cn2); // First insertion

cn2.beginTransaction("inner"); // Nested transaction begins

...

cn2.setSavepoint("svp1"); // Save first insertion

(ins << 2 ).execute(cn2); // Second insertion

(ins << 3 ).execute(cn2); // Third insertion

cn2.rollbackTransaction("svp1"); // Roll back second and

// third insertions.

cn2.commitTransaction("inner"); // Pairing inner transaction

Page 173: Good+List+of+Questions+With+Answers

cn2.commitTransaction("outmost"); // Commit transaction on

// part that is not rolled back.

// The above program results in myTable holding one row of data.

// Its value is 1.

In .NET, what is an application domain? Application domain is a construct in the CLR that is the unit of isolation for an application. The

isolation guarantees the following:

o An application can be independently stopped.

o An application cannot directly access code or resources in another application.

o A fault in an application cannot affect other applications.

Configuration information is scoped by application. This means that an application controls the

location from which code is loaded and the version of the code that is loaded.

In SQL Server, what is an index? An index is a list of sorted record pointers based on a column. Having indexes on your database

tables will speed up SELECT queries if it is properly applied. Indexes will take up some disk

space and will slow down INSERT and UPDATE queries.

What is optimistic vs. pessimistic locking?Optimistic locking is the default locking mechanism for the Enterprise Objects Framework. With

optimistic locking, database rows and objects are never actually locked. When an object is first

read from the database, EOF makes a snapshot of that object. Before the data represented by

the object is updated, the snapshot and database row are compared and if they are not the same,

the update fails. The advantages of optimistic locking are the following:

o All databases support optimistic locking.

o Optimistic locking is easy to use.

o Optimistic locking doesn't use any extra database resources.

The disadvantages of optimistic locking are:

o Users are not notified that someone else modified a record until they try to update it.

o Optimistic locking slows down updates.

o All applications that update a database must agree on the columns to lock on.

Pessimistic locking locks database rows at the database level. Locking can happen either when

the row is selected or on demand. Depending on the database, a select on a locked row either

fails or is blocked until the row is unlocked. Some databases support page-level locking. This

Page 174: Good+List+of+Questions+With+Answers

means that whenever any row in a page is locked, a group of other rows is also locked. The

advantages of pessimistic locking are:

o Pessimistic locking can prevent users and applications from reading data that is being

changed.

o Users are notified immediately if they cannot access a database row.

o Pessimistic locking is easy to use.

The disadvantages of pessimistic locking are:

o Not all databases support this mechanism and the databases that do support it do so

differently.

o Pessimistic locking uses extra database resources.

o Pessimistic locking can prevent other users from having read-only access to data.

o Pessimistic locking can cause deadlocks.

o Pessimistic locking can cause excessive locking.

What is the difference between a clustered and non-clustered index. Clustered indexes

o Physically stored in order (ascending or descending)

o Only one per table

o When a primary key is created a clustered index is automatically created as well.

o If the table is under heavy data modifications or the primary key is used for searches, a

clustered index on the primary key is recommended.

o Columns with values that will not change at all or very seldom, are the best choices.

Non-clustered indexeso Up to 249 nonclustered indexes are possible for each table or indexed view.

o The clustered index keys are used for searching therefore clustered index keys should be

chosen with a minimal length.

o Covered queries (all the columns used for joining, sorting or filtering are indexed) should

be non-clustered.

o Foreign keys should be non-clustered.

o If the table is under heavy data retrieval from fields other than the primary key, one

clustered index and/or one or more non-clustered indexes should be created for the

column(s) used to retrieve the data.

In terms of remoting what is CAO and SAO?

Page 175: Good+List+of+Questions+With+Answers

Server Activated Objects : Stateless - SinglecallThis object type is the most prevalent and is recommended by Microsoft for use as the primary

remoting type. Server activated Singlecall objects hold no state, which makes them ideal for use

with clustered web servers, object pooling, and all other sorts of useful things. Since there is no

state held in the object, you have to pass all the data that the object needs to do its work on every

call.

Server Activated Objects : Stateful - SingletonThese objects are used when you need both a stateful object AND you need that objects data to

persist over time and multiple instantiation. If 3 computers instance an SAO Singleton on a

server, they will all get a reference to that same object. Singletons are commonly used to direct

access to scarce resources and should generally be avoided when possible.

Client Activated Objects : StatefulCAO Objects are used when you need an object to be stateful throughout its lifetime to its caller.

CAO Objects persist data to their caller, however they are different from SAO Singletons in that

multiple instantiations of a CAO will get brand new instances of that CAO each time.

Can you prevent your class from being inherited by another class? Yes. Make the class sealed.

Explain the three tier or n-Tier model. The term n-tier refers to the number of logical levels or layers the various components of an

application occupy. An application consists of the following primary component layers:

Presentation layer, Application or Business Logic layer, and the Data layer. The presentation

layer incorporates user interface components. The user interface might include Graphical User

Interface (GUI) components or be completely text based. A user interacts with an application

through its presentation layer. The application layer or business logic layer houses the application

proper, this means any domain specific knowledge components needed to power the functionality

of the application reside at this layer. The data layer exists to allow the application layer to

capture and maintain application state data. The data layer might take the form of one or more

standalone or geographically distributed database servers. The "n" indicates the number of levels

these components are split into. This does not mean how many physical computers an

application is spread across, for example, a 3-tier application could very well reside on one

computer but you'll see shortly why this is not usually the case. Before diving deeper into the n-

tier discussion I'd like to talk a little about the term-application.

What is SOA?

Page 176: Good+List+of+Questions+With+Answers

The goal for Service Oriented Architecture (SOA) is a world-wide mesh of collaborating services

that are published and available for invocation on a Service Bus. Adopting SOA is essential to

delivering the business agility and IT flexibility promised by Web Services. These benefits are

delivered not just by viewing service architecture from a technology perspective or by adopting

Web Service protocols, but also by requiring the creation of a Service Oriented Environment that

is based on specific key principles.

Can you explain some differences between an ADO.NET Dataset and an ADO Recordset? o In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the

dataset. There are important differences between them.

o A recordset looks like a single table. If a recordset is to contain data from multiple

database tables, it must use a JOIN query, which assembles the data from the various

database tables into a single result table. In contrast, a dataset is a collection of one or

more tables. The tables within a dataset are called data tables; specifically, they are

DataTable objects. If a dataset contains data from multiple database tables, it will

typically contain multiple DataTable objects. That is, each DataTable object typically

corresponds to a single database table or view. In this way, a dataset can mimic the

structure of the underlying database.

o A dataset usually also contains relationships. A relationship within a dataset is analogous

to a foreign-key relationship in a database —that is, it associates rows of the tables with

each other. For example, if a dataset contains a table about investors and another table

about each investor's stock purchases, it could also contain a relationship connecting

each row of the investor table with the corresponding rows of the purchase table.

Because the dataset can hold multiple, separate tables and maintain information about

relationships between them, it can hold much richer data structures than a recordset,

including self-relating tables and tables with many-to-many relationships.

o In ADO you scan sequentially through the rows of the recordset using the ADO

MoveNext method. In ADO.NET, rows are represented as collections, so you can loop

through a table as you would through any collection, or access particular rows via ordinal

or primary key index. DataRelation objects maintain information about master and detail

records and provide a method that allows you to get records related to the one you are

working with. A cursor is a database element that controls record navigation, the ability

to update data, and the visibility of changes made to the database by other users.

ADO.NET does not have an inherent cursor object, but instead includes data classes that

provide the functionality of a traditional cursor. For example, the functionality of a

forward-only, read-only cursor is available in the ADO.NET DataReader object. For more

information about cursor functionality, see Data Access Technologies.

Page 177: Good+List+of+Questions+With+Answers

o In ADO.NET you open connections only long enough to perform a database operation,

such as a Select or Update. You can read rows into a dataset and then work with them

without staying connected to the data source. In ADO the recordset can provide

disconnected access, but ADO is designed primarily for connected access. There is one

significant difference between disconnected processing in ADO and ADO.NET. In ADO

you communicate with the database by making calls to an OLE DB provider. In ADO.NET

you communicate with the database through a data adapter (an OleDbDataAdapter,

SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to

an OLE DB provider or the APIs provided by the underlying data source. The important

difference is that in ADO.NET the data adapter allows you to control how the changes to

the dataset are transmitted to the database — by optimizing for performance, performing

data validation checks, or adding any other extra processing.

o Transmitting an ADO.NET dataset between applications is much easier than transmitting

an ADO disconnected recordset. To transmit an ADO disconnected recordset from one

component to another, you use COM marshalling. To transmit data in ADO.NET, you use

a dataset, which can transmit an XML stream.

Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched? Compare Validator Control

What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? You must set the DataSource property and call the DataBind method.

What is a satellite Assembly? Satellite assemblies are often used to deploy language-specific resources for an application.

These language-specific assemblies work in side-by-side execution because the application has

a separate product ID for each language and installs satellite assemblies in a language-specific

subdirectory for each language. When uninstalling, the application removes only the satellite

assemblies associated with a given language and .NET Framework version. No core .NET

Framework files are removed unless the last language for that .NET Framework version is being

removed.

In Object Oriented Programming, how would you describe encapsulation? Encapsulation (Information Hiding). A principle, used when developing an overall program

structure, that each component of a program should encapsulate or hide a single design

Page 178: Good+List+of+Questions+With+Answers

decision... The interface to each module is defined in such a way as to reveal as little as possible

about its inner workings.

Encapsulation is the ability to hide the internal workings of an object's behavior and its data. For

instance, let's say you have a object named Car and this object has a method (another word for

behavior) named start(). When you create an instance of a car object and call its start() method

you are not worried about what happens to accomplish this, you just want to make sure the state

of the car is changed to 'running' afterwards. This kind of behavior hiding is encapsulation and it

makes programming much easier. When you want your car object to be in a 'running' state,

instead of calling: fuel.on(), starter.on(), etc., you just call start(). This not only makes it easier to

work with, but if the internal workings of this start() method have to change, the results will be the

same.

Encapsulation goes hand in hand with placing your code into a component and using this

component when needed. By placing the logic we need for similar processes into a component,

we eliminate the need to rewrite that code throughout an application every time the process has

to be modified. When we need to make a change to that process, we simply modify that

component and the change is propagated throughout the application wherever you used the

component.

Can you store multiple data types in System.Array? No

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. A shallow copy of an

Array copies only the elements of the Array, whether they are reference types or value types, but

it does not copy the objects that the references refer to. The references in the new Array point to

the same objects that the references in the original Array point to. In contrast, a deep copy of an

Array copies the elements and everything directly or indirectly referenced by the elements.

How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.

What’s the .NET collection class that allows an element to be accessed using a unique key? Hash Table

What class is underneath the SortedList class? Sorted Hash Table.

Page 179: Good+List+of+Questions+With+Answers

Will the finally block get executed if an exception has not occurred? Yes

If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate

constructor) in the overloaded constructor definition inside the inherited class.

What’s a multicast delegate? Multicast delegates allow you to chain together several functions or subs that are all called

together when the delegate is invoked. For the current iteration of the framework, you can't

designate the order that the functions are run, only that they are all run, one after another. Let's

look at the code for the multicast delegate.

How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.

What debugging tools come with the .NET SDK? .CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using

the /debug switch. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.

What does assert() method do? Assert method declares that the calling code can access the resource protected by a permission

demand through the code that calls this method, even if callers higher in the stack have not been

granted permission to access the resource. Using Assert can create security vulnerabilities.

Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the

risk of overloading the machine and the hard drive. Five levels range from None to Verbose,

allowing you to fine-tune the tracing activities.

What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output).

2. Negative test cases (broken or missing data, proper handling).

Page 180: Good+List+of+Questions+With+Answers

3. Exception test cases (exceptions are thrown and caught properly).

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.

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 is 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.

ProsPerformance – there is no doubt that ADO.NET is extremely fast. The actual figures vary

depending on who performed the test and which benchmark was being used, but ADO.NET

performs much, much faster at the same tasks than its predecessor, ADO.

Optimized SQL Provider – in addition to performing well under general circumstances, ADO.NET

includes a SQL Server Data Provider that is highly optimized for interaction with SQL Server. It

uses SQL Server's own TDS (Tabular Data Stream) format for exchanging information. Without

question, your SQL Server 7 and above data access operations will run blazingly fast utilizing this

optimized Data Provider.

XML Support (and Reliance) – everything you do in ADO.NET at some point will boil down to the

use of XML. In fact, many of the classes in ADO.NET, such as the DataSet, are so intertwined

with XML that they simply cannot exist or function without utilizing the technology.

Disconnected Operation Model – the core ADO.NET class, the DataSet, operates in an entirely

disconnected fashion. This may be new to some programmers, but it is a remarkably efficient and

scalable architecture. Because the disconnected model allows for the DataSet class to be

unaware of the origin of its data, an unlimited number of supported data sources can be plugged

into code without any hassle in the future.

Rich Object Model – the entire ADO.NET architecture is built on a hierarchy of class inheritance

and interface implementation. Once you start looking for things you need within this namespace,

you'll find that the logical inheritance of features and base class support makes the entire system

extremely easy to use, and very customizable to suit your own needs.

ConsManaged-Only Access – for a few obvious reasons, and some far more technical, you cannot

utilize the ADO.NET architecture from anything but managed code. This means that there is no

Page 181: Good+List+of+Questions+With+Answers

COM interoperability allowed for ADO.NET. Therefore, in order to take advantage of the

advanced SQL Server Data Provider and any other feature like DataSets, XML internal data

storage, etc, your code must be running under the CLR.

Only Three Managed Data Providers (so far) – unfortunately, if you need to access any data that

requires a driver that cannot be used through either an OLEDB provider or the SQL Server Data

Provider, then you may be out of luck. However, the good news is that the OLEDB provider for

ODBC is available for download from Microsoft. At that point the down-side becomes one of

performance, in which you are invoking multiple layers of abstraction as well as crossing the

COM InterOp gap, incurring some initial overhead as well.

Learning Curve – despite the misleading name, ADO.NET is not simply a new version of ADO,

nor should it even be considered a direct successor. ADO.NET should be thought of more as the

data access class library for use with the .NET framework. The difficulty in learning to use

ADO.NET to its fullest is that a lot of it does seem familiar. It is this that causes some common

pitfalls. Programmers need to learn that even though some syntax may appear the same, there is

actually a considerable amount of difference in the internal workings of many classes

Explain ACID rule of thumb for transactions. In databases, ACID stands for Atomicity, Consistency, Isolation, and Durability. They are

considered to be the key transaction processing features/properties of a database management

system, or DBMS. Without them, the integrity of the database cannot be guaranteed. In practice,

these properties are often relaxed somewhat to provide better performance.

In the context of databases, a single logical operation on the data is called a transaction. An

example of a transaction is a transfer of funds from one account to another, even though it might

consist of multiple individual operations (such as debiting one account and crediting another). The

ACID properties guarantee that such transactions are processed reliably.

Atomicity refers to the ability of the DBMS to guarantee that either all of the tasks of a

transaction are performed or none of them are. The transfer of funds can be completed or it can

fail for a multitude of reasons, but atomicity guarantees that one account won't be debited if the

other is not credited as well.

Consistency refers to the database being in a legal state when the transaction begins and when

it ends. This means that a transaction can't break the rules, or integrity constraints, of the

database. If an integrity constraint states that all accounts must have a positive balance, then any

transaction violating this rule will be aborted.

Isolation refers to the ability of the application to make operations in a transaction appear

isolated from all other operations. This means that no operation outside the transaction can ever

see the data in an intermediate state; a bank manager can see the transferred funds on one

account or the other, but never on both—even if she ran her query while the transfer was still

Page 182: Good+List+of+Questions+With+Answers

being processed. More formally, isolation means the transaction history (or schedule) is

serializable. For performance reasons, this ability is the most often relaxed constraint. See the

isolation article for more details.

Durability refers to the guarantee that once the user has been notified of success, the

transaction will persist, and not be undone. This means it will survive system failure, and that the

database system has checked the integrity constraints and won't need to abort the transaction.

Typically, all transactions are written into a log that can be played back to recreate the system to

its state right before the failure. A transaction can only be deemed committed after it is safely in

the log.

Between Windows Authentication and SQL Server Authentication, 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.

What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.

What namespaces are necessary to create a localized application? System.Globalization and System.Resources.

What is the smallest unit of execution in .NET?Assembly

Remoting FAQWhat distributed process frameworks outside .NET do you know? Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed

Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and

Java Remote Method Invocation (RMI).

What are possible implementations of distributed applications in .NET? .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library,

noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

Page 183: Good+List+of+Questions+With+Answers

When would you use .NET Remoting and when Web services?Use remoting for more efficient exchange of information when you control both ends of the

application. Use Web services for open-protocol-based information exchange when you are

just a client or a server with the other end belonging to someone else.

What's a proxy of the server object in .NET Remoting? It's a fake copy of the server object that resides on the client side and behaves as if it was the

server. It handles the communication between real server object and the client object. This

process is also known as marshaling.

What are remotable objects in .NET Remoting? Remotable objects are the objects that can be marshaled across the application domains. You

can marshal by value, where a deep copy of the object is created and then passed to the

receiver. You can also marshal by reference, where just a reference to an existing object is

passed.

What are channels in .NET Remoting? Channels represent the objects that transfer the other serialized objects from one application

domain to another and from one computer to another, as well as one process to another on the

same box. A channel must exist before an object can be transferred.

What security measures exist for .NET Remoting in System.Runtime.Remoting?

None. Security should be taken care of at the application level. Cryptography and other security

techniques can be applied at application or server level.

What is a formatter? A formatter is an object that is responsible for encoding and serializing data into messages on

one end, and deserializing and decoding messages into data on the other end.

Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs? Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

What's SingleCall activation mode used for? If the server object is instantiated for responding to just one single request, the request should be

made in SingleCall mode.

Page 184: Good+List+of+Questions+With+Answers

What's Singleton activation mode? A single object is instantiated regardless of the number of clients accessing it. Lifetime of this

object is determined by lifetime lease.

How do you define the lease of the object?By implementing ILease interface when writing the class code.

Can you configure a .NET Remoting object via XML file? Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-

level XML settings take precedence over machine.config.

How can you automatically generate interface for the remotable object in .NET with Microsoft tools? Use the Soapsuds tool.

What are CAO's i.e. Client Activated Objects ?Client-activated objects are objects whose lifetimes are controlled by the calling application

domain, just as they would be if the object were local to the client. With client activation, a round

trip to the server occurs when the client tries to create an instance of the server object, and the

client proxy is created using an object reference (ObjRef) obtained on return from the creation of

the remote object on the server. Each time a client creates an instance of a client-activated type,

that instance will service only that particular reference in that particular client until its lease

expires and its memory is recycled. If a calling application domain creates two new instances of

the remote type, each of the client references will invoke only the particular instance in the server

application domain from which the reference was returned.

In COM, clients hold an object in memory by holding a reference to it. When the last client

releases its last reference, the object can delete itself. Client activation provides the same client

control over the server object's lifetime, but without the complexity of maintaining references or

the constant pinging to confirm the continued existence of the server or client. Instead, client-

activated objects use lifetime leases to determine how long they should continue to exist. When a

client creates a remote object, it can specify a default length of time that the object should exist. If

the remote object reaches its default lifetime limit, it contacts the client to ask whether it should

continue to exist, and if so, for how much longer. If the client is not currently available, a default

time is also specified for how long the server object should wait while trying to contact the client

before marking itself for garbage collection. The client might even request an indefinite default

lifetime, effectively preventing the remote object from ever being recycled until the server

application domain is torn down. The difference between this and a server-activated indefinite

Page 185: Good+List+of+Questions+With+Answers

lifetime is that an indefinite server-activated object will serve all client requests for that type,

whereas the client-activated instances serve only the client and the reference that was

responsible for their creation. For more information, see Lifetime Leases.

To create an instance of a client-activated type, clients either configure their application

programmatically (or using a configuration file) and call new (New in Visual Basic), or they pass

the remote object's configuration in a call to Activator.CreateInstance. The following code

example shows such a call, assuming a TcpChannel has been registered to listen on port 8080.

How many processes can listen on a single TCP/IP port? One.

What technology enables out-of-proc communication in .NET?Most usually Remoting;.NET remoting enables client applications to use objects in other

processes on the same computer or on any other computer available on its network.While you

could implement an out-of-proc component in any number of other ways, someone using the term

almost always means Remoting.

How can objects in two diff. App Doimains communicate with each other?.Net framework provides various ways to communicate with objects in different app domains.

First is XML Web Service on internet, its good method because it is built using HTTP protocol and

SOAP formatting.

If the performance is the main concern then go for second option which is .Net remoting because

it gives you the option of using binary encoding and the default TcpChannel, which offers the best

interprocess communication performance

What is the difference between .Net Remoting and Web Services?Although we can develop an application using both technologies, each of them has its distinct

advantages. Yes you can look at them in terms of performance but you need to consider your

need first. There are many other factors such authentications, authorizing in process that need to

be considered.

Point  Remoting  Webservices If your application needs interoperability with other platforms or operating systems

 No Yes, Choose Web Services because it is more flexible in that they are support SOAP.

 If performance is the main requirement with security

 You should use the TCP channel and the binary formatter

 No

Page 186: Good+List+of+Questions+With+Answers

 Complex Programming  Yes  No

 State Management

 Supports a range of state management, depending on what object lifetime scheme you choose (single call or singleton call).

 Its stateless service management (does not inherently correlate multiple calls from the same user) 

 Transport Protocol  It can access through TCP or HTTP channel.

 It can be access only through HTTP channel

Some important stuff as wellThe differences between architecture and design (design pattern and architecture pattern as well)

Here's my point of view : there are two main steps while designing a system. The first one is

architecture and the second one is designing.

Architecture : sets which functionality the system should perform, split the functionality between

components, set how components should behave and communicate in the system context, set

the physical location of components and finally choose the tools in order to create components.

Design : while architecture deals more with the wide picture, design should drill down in to the

details relating to implementing certain components. Designing of components end up with

classes, interfaces, abstract classes and other OO feature in order to fulfill the given component

tasks.

Both architecture and design got patterns available to solve given problem. While design pattern

are more about classes and interfaces needed in order to create component, architecture

patterns on the other hand are more about behavior of the system. For example Singleton, which

is well known design pattern, helps developers to create a class with single instance. Singleton

deals with implementation of certain class in component. Singleton doesn’t have any implication

on the system. Inversion of control (IOC), on the other hand, shapes the system behavior. IOC is

architecture design pattern that force classes that write in the system to be control (run) by other

mechanism rather then the code that class implementer wrote. IOC force Infrastructure in order to

enable the writing class to be control by other code rather then the one that write to implement

class. IOC doesn’t have any implication on class’s implementation but has direct influence on the

way system behaves.

Page 187: Good+List+of+Questions+With+Answers